text
stringlengths
14
6.51M
unit OKey; {$mode objfpc}{$H+} interface uses Classes, SysUtils, UPCDataTypes, UCrypto, UBaseTypes, UConst, UOpenSSL, UPCEncryption; Type TOKey = class private privateKeyRaw : TRawBytes; publicKeyRaw: TECDSA_Public_Raw; privateKey: TECPrivateKey; procedure ExtractRaws(); public procedure GenerateNewRandomPair(); procedure ImportPrivateKeyFromRaw(data: TRawBytes); procedure ImportPrivateKeyFromHex(data: String); function GetPrivateKey: TECPrivateKeyInfo; function PrivateKeyAsRaw() : TRawBytes; function GetPublicKey: TECDSA_Public; function PublicKeyAsRaw() : TECDSA_Public_Raw; function PrivateKeyAsHex(): String; function PublicKeyAsHex(): String; function Equals(key: TOKey): boolean; overload; procedure output; function SignTRawBytes(msg: TRawBytes): TECDSA_SIG; overload; function SignTRawBytes(privKey: TECPrivateKeyInfo ;msg: TRawBytes): TECDSA_SIG; overload; function SignAsHex(sign: TECDSA_SIG): String; function SignVerify(msg: TRawBytes; sign: TECDSA_SIG): boolean; overload; function SignVerify(pubKey: TECDSA_Public; msg: TRawBytes; sign: TECDSA_SIG): boolean; overload; function EncryptMessage(msg: TRawBytes): TRawBytes; overload; function EncryptMessage(pubKey: TECDSA_Public; msg: TRawBytes): TRawBytes; overload; function DecryptMessage(emsg: TRawBytes): TRawBytes; overload; function DecryptMessage(privKey: TECPrivateKeyInfo; emsg: TRawBytes): TRawBytes; overload; end; implementation function TOKey.DecryptMessage(privKey: TECPrivateKeyInfo; emsg: TRawBytes): TRawBytes; overload; var dmsg: TRawBytes; begin TPCEncryption.DoPascalCoinECIESDecrypt(privKey, emsg, dmsg); Result := dmsg; end; function TOKey.DecryptMessage(emsg: TRawBytes): TRawBytes; overload; var dmsg: TRawBytes; begin TPCEncryption.DoPascalCoinECIESDecrypt(GetPrivateKey, emsg, dmsg); Result := dmsg; end; function TOKey.EncryptMessage(pubKey: TECDSA_Public; msg: TRawBytes): TRawBytes; overload; var emsg: TRawBytes; begin TPCEncryption.DoPascalCoinECIESEncrypt(pubKey,msg, emsg); Result := emsg; end; function TOKey.EncryptMessage(msg: TRawBytes): TRawBytes; overload; var emsg: TRawBytes; begin TPCEncryption.DoPascalCoinECIESEncrypt(GetPublicKey,msg, emsg); Result := emsg; end; function TOKey.SignVerify(msg: TRawBytes; sign: TECDSA_SIG): boolean; begin Result := TCrypto.ECDSAVerify(GetPublicKey, msg, sign); end; function TOKey.SignVerify(pubKey: TECDSA_Public; msg: TRawBytes; sign: TECDSA_SIG): boolean; overload; begin Result := TCrypto.ECDSAVerify(pubKey, msg, sign); end; function TOKey.SignAsHex(sign: TECDSA_SIG): String; begin Result := TCrypto.EncodeSignature(sign).ToHexaString; end; function TOKey.SignTRawBytes(msg: TRawBytes): TECDSA_SIG; begin Result := TCrypto.ECDSASign(GetPrivateKey, msg); end; function TOKey.SignTRawBytes(privKey: TECPrivateKeyInfo ;msg: TRawBytes): TECDSA_SIG; overload; begin Result := TCrypto.ECDSASign(privKey, msg); end; function TOKey.GetPrivateKey: TECPrivateKeyInfo; begin Result := privateKey.PrivateKey; end; function TOkey.GetPublicKey: TECDSA_Public; begin Result := privateKey.PublicKey; end; function TOKey.Equals(key: TOKey): boolean; begin Result := True; if ( (key.PublicKeyAsHex() <> PublicKeyAsHex()) OR (key.PrivateKeyAsHex() <> PrivateKeyAsHex()) ) then begin Result := False; end; end; procedure TOKey.output; begin writeln('Public : ' +PublicKeyAsHex()); writeln('Private : ' +PrivateKeyAsHex()); end; procedure TOKey.GenerateNewRandomPair(); begin privateKey := TECPrivateKey.Create; privateKey.GenerateRandomPrivateKey(CT_Default_EC_OpenSSL_NID); ExtractRaws(); end; procedure TOKey.ImportPrivateKeyFromRaw(data: TRawBytes); begin privateKey := TECPrivateKey.ImportFromRaw(data); ExtractRaws(); end; procedure TOKey.ImportPrivateKeyFromHex(data: String); begin ImportPrivateKeyFromRaw(TCrypto.HexaToRaw(data)); end; function TOKey.PrivateKeyAsHex(): String; begin Result := privateKeyRaw.ToHexaString; end; function TOKey.PublicKeyAsHex(): String; begin Result := publicKeyRaw.ToHexaString; end; procedure TOKey.ExtractRaws(); begin privateKeyRaw := privateKey.ExportToRaw; privateKey.PublicKey.ToRaw(publicKeyRaw); end; function TOKey.PrivateKeyAsRaw(): TRawBytes; begin Result := privateKeyRaw; end; function TOKey.PublicKeyAsRaw() : TECDSA_Public_Raw; begin Result := publicKeyRaw; end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Consts; interface const HTTP_HEADERFIELD_AUTH = 'Authorization'; // do not localize REST_NO_FALLBACK_CHARSET = 'raw'; // do not localize resourcestring RNullableNoValue = 'Nullable type has no value'; sExecuteRequestNilClient = 'Can''t execute TCustomRESTRequest when Client property is nil.'; sParameterName = 'Name'; sParameterValue = 'Value'; sParameterKind = 'Kind'; sOperationNotAllowedOnActiveComponent = 'Operation not allowed on active %s'; sConfigureRESTComponent = 'Configure...'; sExecuteRESTComponent = 'Execute...'; sResetRESTClient = 'Reset Client'; sClearRESTRequest = 'Clear Request Data'; sClearRESTResponse = 'Clear Response Data'; sResetRESTClientQuestion = 'Are you sure that you want to reset this Client to its default settings?'; sClearRESTRequestQuestion ='Are you sure that you want to clear this Request''s data (including its Response)?'; sClearRESTResponseQuestion ='Are you sure that you want to clear this Response''s data?'; sInvalidRESTComponent = 'Invalid component-type: "%s"'; sRESTAdapterUpdateDS = 'Update DataSet'; sRESTAdapterClearDS = 'Clear DataSet'; sRESTUnsupportedAuthMethod = 'Unsupported Authentication Method!'; sRESTUnsupportedRequestMethod = 'Unsupported Request Method'; sRESTErrorEmptyURL = 'URL for a request must not be empty'; sRESTErrorEmptyParamName = 'Name of a parameter must not be empty'; sRESTViewerNoContent = 'There is no content available.'; sRESTViewerNotAvailable = 'The content-type is not recognized as text. The viewer cannot be opened.'; sRESTUnsupportedDateTimeFormat = 'Unsupported DateTime format'; sAdapterResponseComponentIsNil = 'Adapter does not have a Response component'; sResponseContentIsNotJSON = 'Response content is not valid JSON'; sResponseContentIsEmpty = 'Response content is empty'; sAdapterInvalidRootElement = 'Adapter RootElement, "%s", is not a valid path for the response JSON'; sResponseInvalidRootElement = 'Response RootElement, "%s", is not a valid path for the response JSON'; sResponseDidNotReturnArray = 'Response did not return an Array of %s'; SAuthorizationCodeNeeded = 'An authorization code is needed before it can be changed into an access token.'; sUnknownContentType = 'Unknown content type: %s'; sNoClientAttached = 'Request has no client component'; sUnknownRequestMethod = 'Unknown request-method. Cannot execute request.'; sRESTRequestFailed = 'REST request failed: %s'; sUnsupportedProtocol = 'Unsupported Protocol: %s'; implementation end.
unit TestOS.Version.Helper; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, OS.Version.Helper, Version; type // Test methods for class TWriteBufferSettingVerifier TWindowsList = record FWindows95: Boolean; FWindows98: Boolean; FWindows2000: Boolean; FWindowsXP: Boolean; FWindowsXPSP1: Boolean; FWindowsXPSP2: Boolean; FWindowsXPSP3: Boolean; FWindows2003: Boolean; FWindowsVista: Boolean; FWindows7: Boolean; FWindows8: Boolean; FWindows81: Boolean; FWindows10: Boolean; end; TFunctionToTest = reference to function (const Version: TVersion): Boolean; TestOSVersionHelper = class(TTestCase) strict private procedure TestAs(const TestContents: String; const WindowsList: TWindowsList; const TestFunction: TFunctionToTest); public procedure SetUp; override; procedure TearDown; override; published procedure TestIsBelowVista; procedure TestIsBelowWindows8; procedure TestIsAtLeastWindows10; end; implementation procedure TestOSVersionHelper.SetUp; begin end; procedure TestOSVersionHelper.TearDown; begin end; procedure TestOSVersionHelper.TestAs(const TestContents: String; const WindowsList: TWindowsList; const TestFunction: TFunctionToTest); const Windows95: TVersion = (FMajorVer: 4; FMinorVer: 0; FBuildVer: 0); Windows98: TVersion = (FMajorVer: 4; FMinorVer: 10; FBuildVer: 0); Windows2000: TVersion = (FMajorVer: 5; FMinorVer: 0; FBuildVer: 0); WindowsXP: TVersion = (FMajorVer: 5; FMinorVer: 1; FBuildVer: 0); WindowsXPSP1: TVersion = (FMajorVer: 5; FMinorVer: 1; FBuildVer: 1); WindowsXPSP2: TVersion = (FMajorVer: 5; FMinorVer: 1; FBuildVer: 2); WindowsXPSP3: TVersion = (FMajorVer: 5; FMinorVer: 1; FBuildVer: 3); Windows2003: TVersion = (FMajorVer: 5; FMinorVer: 2; FBuildVer: 0); WindowsVista: TVersion = (FMajorVer: 6; FMinorVer: 0; FBuildVer: 0); Windows7: TVersion = (FMajorVer: 6; FMinorVer: 1; FBuildVer: 0); Windows8: TVersion = (FMajorVer: 6; FMinorVer: 2; FBuildVer: 0); Windows81: TVersion = (FMajorVer: 6; FMinorVer: 3; FBuildVer: 0); Windows10: TVersion = (FMajorVer: 10; FMinorVer: 0; FBuildVer: 0); begin CheckEquals(WindowsList.FWindows95, TestFunction(Windows95), TestContents + ' Windows 95'); CheckEquals(WindowsList.FWindows98, TestFunction(Windows98), TestContents + ' Windows 98'); CheckEquals(WindowsList.FWindows2000, TestFunction(Windows2000), TestContents + ' Windows 2000'); CheckEquals(WindowsList.FWindowsXP, TestFunction(WindowsXP), TestContents + ' Windows XP'); CheckEquals(WindowsList.FWindowsXPSP1, TestFunction(WindowsXPSP1), TestContents + ' Windows XP SP1'); CheckEquals(WindowsList.FWindowsXPSP2, TestFunction(WindowsXPSP2), TestContents + ' Windows XP SP2'); CheckEquals(WindowsList.FWindowsXPSP3, TestFunction(WindowsXPSP3), TestContents + ' Windows XP SP3'); CheckEquals(WindowsList.FWindows2003, TestFunction(Windows2003), TestContents + ' Windows 2003'); CheckEquals(WindowsList.FWindowsVista, TestFunction(WindowsVista), TestContents + ' Windows Vista'); CheckEquals(WindowsList.FWindows7, TestFunction(Windows7), TestContents + ' Windows 7'); CheckEquals(WindowsList.FWindows8, TestFunction(Windows8), TestContents + ' Windows 8'); CheckEquals(WindowsList.FWindows81, TestFunction(Windows81), TestContents + ' Windows 8.1'); CheckEquals(WindowsList.FWindows10, TestFunction(Windows10), TestContents + ' Windows 10'); end; procedure TestOSVersionHelper.TestIsAtLeastWindows10; const AtLeastWindows10List: TWindowsList = ( FWindows95: false; FWindows98: false; FWindows2000: false; FWindowsXP: false; FWindowsXPSP1: false; FWindowsXPSP2: false; FWindowsXPSP3: false; FWindows2003: false; FWindowsVista: false; FWindows7: false; FWindows8: false; FWindows81: false; FWindows10: true); begin TestAs('IsAtLeastWindows10', AtLeastWindows10List, IsAtLeastWindows10); end; procedure TestOSVersionHelper.TestIsBelowVista; const BelowVistaList: TWindowsList = ( FWindows95: true; FWindows98: true; FWindows2000: true; FWindowsXP: true; FWindowsXPSP1: true; FWindowsXPSP2: true; FWindowsXPSP3: true; FWindows2003: true; FWindowsVista: false; FWindows7: false; FWindows8: false; FWindows81: false; FWindows10: false); begin TestAs('IsBelowVista', BelowVistaList, IsBelowVista); end; procedure TestOSVersionHelper.TestIsBelowWindows8; const BelowWin8List: TWindowsList = ( FWindows95: true; FWindows98: true; FWindows2000: true; FWindowsXP: true; FWindowsXPSP1: true; FWindowsXPSP2: true; FWindowsXPSP3: true; FWindows2003: true; FWindowsVista: true; FWindows7: true; FWindows8: false; FWindows81: false; FWindows10: false); begin TestAs('IsBelowWindows8', BelowWin8List, IsBelowWindows8); end; initialization // Register any test cases with the test runner RegisterTest(TestOSVersionHelper.Suite); end.
unit LLVM.Imports.Types; interface //based on Types.h uses LLVM.Imports; type TLLVMBool = packed record ResultCode: Integer; class operator Implicit(const AValue: TLLVMBool): Boolean; class operator Implicit(const AValue: Boolean): TLLVMBool; class operator LogicalNot(const AValue: TLLVMBool): TLLVMBool; end; TLLVMMemoryBufferRef = type TLLVMRef; TLLVMContextRef = type TLLVMRef; TLLVMModuleRef = type TLLVMRef; PLLVMModuleRef = ^TLLVMModuleRef; TLLVMTypeRef = type TLLVMRef; PLLVMTypeRef = ^TLLVMTypeRef; TLLVMValueRef = type TLLVMRef; PLLVMValueRef = ^TLLVMValueRef; TLLVMBasicBlockRef = type TLLVMRef; PLLVMBasicBlockRef = ^TLLVMBasicBlockRef; TLLVMMetadataRef = type TLLVMRef; (** * Represents an LLVM Named Metadata Node. * * This models llvm::NamedMDNode. *) TLLVMNamedMDNodeRef = type TLLVMRef; (** * Represents an entry in a Global Object's metadata attachments. * * This models std::pair<unsigned, MDNode *> *) TLLVMValueMetadataEntry = type TLLVMRef; PLLVMValueMetadataEntry = ^TLLVMValueMetadataEntry; TLLVMBuilderRef = type TLLVMRef; TLLVMDIBuilderRef = type TLLVMRef; TLLVMModuleProviderRef = type TLLVMRef; TLLVMPassManagerRef = type TLLVMRef; TLLVMPassRegistryRef = type TLLVMRef; TLLVMUseRef = type TLLVMRef; TLLVMAttributeRef = type TLLVMRef; PLLVMAttributeRef = ^TLLVMAttributeRef; TLLVMDiagnosticInfoRef = type TLLVMRef; (** * @see llvm::Comdat *) TLLVMComdatRef = type TLLVMRef; (** * @see llvm::Module::ModuleFlagEntry *) TLLVMModuleFlagEntry = type TLLVMRef; PLLVMModuleFlagEntry = ^TLLVMModuleFlagEntry; (** * @see llvm::JITEventListener *) TLLVMJITEventListenerRef = type TLLVMRef; (** * @see llvm::object::Binary *) TLLVMBinaryRef = type TLLVMRef; implementation class operator TLLVMBool.Implicit(const AValue: TLLVMBool): Boolean; begin Result := AValue.ResultCode = 0; end; class operator TLLVMBool.Implicit(const AValue: Boolean): TLLVMBool; begin if AValue then Result.ResultCode := 0 else Result.ResultCode := 1; end; class operator TLLVMBool.LogicalNot(const AValue: TLLVMBool): TLLVMBool; begin if AValue.ResultCode <> 0 then Result.ResultCode := 0 else Result.ResultCode := 1; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TfrmCommissionCalculator } TfrmCommissionCalculator = class(TForm) btnCalculate: TButton; edtSales: TEdit; gpbCommission: TGroupBox; lblSales: TLabel; lblTotalCommission: TLabel; procedure btnCalculateClick(Sender: TObject); private { private declarations } public { public declarations } end; var frmCommissionCalculator: TfrmCommissionCalculator; implementation {$R *.lfm} { TfrmCommissionCalculator } procedure TfrmCommissionCalculator.btnCalculateClick(Sender: TObject); var Sales, Commission: Double; begin try Sales:=StrToFloat(EdtSales.Text); except if MessageDlg('Unable to process sales value ' + edtSales.Text, mtError, [mbOK, mbAbort], 0) = mrOK then begin edtSales.SetFocus; //jump out of event handler Exit; end else //user clicked abort Close; end; if Sales > 80000.00 then Commission:=Sales*0.40 else if (Sales > 40000.00) AND (Sales <= 80000.00) then Commission:=Sales*0.20 else Commission:=Sales*0.10; lblTotalCommission.Caption:='R ' + FloatToStrF(Commission, ffNumber, 10, 2); end; end.
program oil_deposits; const OIL = -1; NO_OIL = 0; var input_file: text; output_file: text; rows, columns: integer; deposits: integer; grid: array [0..101, 0..101] of integer; procedure mark_deposit (i: integer; j: integer; marker: integer); begin grid[i,j] := marker; if grid[i-1, j ] = OIL then mark_deposit (i-1, j , marker); if grid[i-1, j+1] = OIL then mark_deposit (i-1, j+1, marker); if grid[i , j+1] = OIL then mark_deposit (i , j+1, marker); if grid[i+1, j+1] = OIL then mark_deposit (i+1, j+1, marker); if grid[i+1, j ] = OIL then mark_deposit (i+1, j , marker); if grid[i+1, j-1] = OIL then mark_deposit (i+1, j-1, marker); if grid[i , j-1] = OIL then mark_deposit (i , j-1, marker); if grid[i-1, j-1] = OIL then mark_deposit (i-1, j-1, marker); end; procedure count_deposits; var i,j: integer; begin deposits := 0; for i := 1 to rows do for j := 1 to columns do if grid[i,j] = OIL then begin deposits := deposits + 1; mark_deposit (i, j, deposits); end; end; procedure read_grid; var i,j: integer; ch: char; begin for i := 0 to 101 do begin grid[i,0] := NO_OIL; grid[i,101] := NO_OIL; grid[0,i] := NO_OIL; grid[101,i] := NO_OIL; end; for i := 1 to rows do begin for j := 1 to columns do begin read (input_file, ch); if ch = '*' then grid[i,j] := NO_OIL else grid[i,j] := OIL; end; readln (input_file); end; end; procedure write_grid; var i,j: integer; begin for i := 1 to rows do begin for j := 1 to columns do write (grid[i,j]:3, ' '); writeln; end; writeln; end; begin assign (input_file, 'oil.in'); reset (input_file); assign (output_file, 'oil.out'); rewrite (output_file); readln (input_file, rows, columns); while (rows > 0) do begin read_grid; count_deposits; write_grid; writeln (output_file, deposits); readln (input_file, rows, columns); end; close (input_file); close (output_file); end.
unit uGrammatik; {$mode delphi}{$H+} interface uses Classes, SysUtils,fgl, fpjson, jsonparser, jsonConf; type TRegelProduktionsseite = class produktion: String; zufaelligkeit: Real; constructor Create; destructor Destroy; override; end; type TRegelProduktionsseitenListe = TFPGList<TRegelProduktionsseite>; type TRegelDictionary = TFPGMap<String,TRegelProduktionsseitenListe>; type TVariableZuWert = TFPGMap<String,String>; type TGrammatik = class private { Aufgabe: Speichert das Axiom mit den Zahlenwerten als Einsetzung. } FRawAxiom: String; { Aufgabe: Speichert das Axiom mit Platzhaltervariablen. } FAxiom: String; // setter-Funktionen fuer properties procedure setzeAxiom(axiom:String); public { Aufgabe: Speichert den Wert einer Platzhaltervariable. } variableZuWert: TVariableZuWert; { Aufgaben: Speichert die Regel genau so, wie die eingegeben wurde ohne diese weiter zu verarbeiten. } rawRegeln: TRegelDictionary; { Aufgabe: Speichert die Regeln, wobei diese durch alternative Variablen ersetzt wurden. Diese Varieblen machen Ersetzugen einfacher. } regeln: TRegelDictionary; constructor Create; destructor Destroy; override; property axiom: String read FRawAxiom write setzeAxiom; property ersetztesAxiom: String read FAxiom; { -- Bezieht sich auf Funktionen in diesem Block -- Aufgabe: Fuegt Regeln zur Grammatik hinzu. Einsetzung der Platzhalter in "regeln". } procedure addRegel(links: String; rechts: String; zufaelligkeit: Real); overload; procedure addRegel(links: String; rechts: String); overload; function RegelTauschLinks(links: String) : String; function RegelTauschRechts(links: String; rechts: String) : String; procedure aendereParameter(para: TStringList); // getter-Funktion (public) function gibParameter : TStringList; { Aufgabe: Dies wird als statische Variable genutzt. Mit der Funktion (im Gegensatz zur Variable) wird sichergestellt, dass sie auch wirklich readonly ist. -> innerhalb, wie auch ausserhalb der Funktion Die tokenLaenge ist die Laenge der ersetzten Variablennamen in FAxiom. } class function tokenLaenge : Cardinal; static; function copy : TGrammatik; end; implementation constructor TRegelProduktionsseite.Create; begin produktion := ''; zufaelligkeit := 100; end; destructor TRegelProduktionsseite.Destroy; begin FreeAndNil(produktion); FreeAndNil(zufaelligkeit); end; constructor TGrammatik.Create; begin FAxiom := ''; FRawAxiom := ''; regeln := TRegelDictionary.Create; rawRegeln := TRegelDictionary.Create; end; destructor TGrammatik.Destroy; begin FreeAndNil(variableZuWert); FreeAndNil(FAxiom); FreeAndNil(FRawAxiom); FreeAndNil(regeln); FreeAndNil(rawRegeln); end; procedure TGrammatik.setzeAxiom(axiom:String); var parameterCount: Cardinal; insertLetter,axiomOutput: String; letter: Char; begin parameterCount := 1; FAxiom := ''; FRawAxiom := axiom; axiomOutput:=''; variableZuWert:=TVariableZuWert.Create; for letter in axiom do begin if (ord(letter) <= 47) or (ord(letter) > 57) then begin if (letter <> ';') and (letter <> ')') then begin FAxiom := FAxiom + letter; end else begin insertLetter:= IntToStr(parameterCount)+'ax'; while length(insertLetter) < tokenLaenge do insertLetter:='0'+insertLetter; variableZuWert.add(insertLetter,axiomOutput); FAxiom := FAxiom + insertLetter+letter; axiomOutput:=''; inc(parameterCount); end; end else axiomOutput := axiomOutput + letter; end; end; procedure TGrammatik.addRegel(links: String; rechts: String; zufaelligkeit: Real); var tmp_links: String; procedure zuRegelHinzufuegen(var regelDict: TRegelDictionary); var tmp_regel: TRegelProduktionsseite; data: TRegelProduktionsseitenListe; begin tmp_regel := TRegelProduktionsseite.Create; tmp_regel.produktion := rechts; tmp_regel.zufaelligkeit := zufaelligkeit; if regelDict.TryGetData(links,data) then regelDict[links].add(tmp_regel) else begin regelDict[links] := TRegelProduktionsseitenListe.Create; regelDict[links].add(tmp_regel); end; end; begin zuRegelHinzufuegen(rawRegeln); if (links[2] = '(') then begin tmp_links := links; links := RegelTauschLinks(links); rechts := RegelTauschRechts(tmp_links,rechts); end; zuRegelHinzufuegen(regeln); end; procedure TGrammatik.addRegel(links: String; rechts: String); begin addRegel(links,rechts,100); end; function TGrammatik.RegelTauschLinks(links: string) : String; var parameterCount,letterAsc:INTEGER; pter:CARDINAL; letter,smlLetter:string; begin result := ''; result += links[1]; result += links[2]; pter:=3; letterAsc:=Ord(links[1]); letterAsc:=letterAsc+32; smlLetter:=Chr(letterAsc); for parameterCount:=1 to 27 do begin letter := IntToStr(parameterCount)+smlLetter; while length(letter) < tokenLaenge do letter:='0'+letter; result := result + letter; if links[pter+1]=';' then begin result := result + ';'; pter:=pter+2; end else begin result := result + ')'; break; end end; end; function TGrammatik.RegelTauschRechts(links: String; rechts: String) : String; var parameterCount,letterAsc:INTEGER; pter:CARDINAL; toReplace,letter,smlLetter:string; { Grund: Wenn man genau den kleinen Buchstaben als Variable hat, so koennten bei der Ersetzung fehler auftreten, da der Platzhalter ebenfalls diesen Buchstaben enthalten. Aufgabe: Ersetzung des kleinen Buchstaben mit aktuellem Platzhalter, ohne "falsch" zu ersetzen. } function ersetzeSmlLetter : String; var i: Cardinal; tmp_string: String; letzterBuchstabe: Char; begin result := ''; letzterBuchstabe := ')'; for i := 1 to length(rechts) do begin if ((letzterBuchstabe = '(') or (letzterBuchstabe = ';')) and (rechts[i] = smlLetter) then result += letter else result += rechts[i]; letzterBuchstabe := rechts[i]; end; end; begin pter:=3; letterAsc:=Ord(links[1]); letterAsc:=letterAsc+32; smlLetter:=Chr(letterAsc); for parameterCount:=1 to 27 do begin letter := IntToStr(parameterCount) + smlLetter; while length(letter) < tokenLaenge do letter:='0'+letter; if links[pter] = smlLetter then rechts := ersetzeSmlLetter else rechts := StringReplace(rechts,links[pter],letter,[rfReplaceAll]); if links[pter+1]=';' then pter:=pter+2 else break; end; result := rechts; end; procedure TGrammatik.aendereParameter(para: TStringList); var paraCnt: Cardinal; varName: String; begin FRawAxiom := FAxiom; if para.Count <> variableZuWert.Count then exit; for paraCnt := 1 to para.Count do begin varName := IntToStr(paraCnt)+'ax'; while length(varName) < tokenLaenge do varName:='0'+varName; variableZuWert.AddOrSetData(varName,para[paraCnt - 1]); FRawAxiom := StringReplace(FRawAxiom,varName,para[paraCnt - 1],[rfReplaceAll]); end; end; function TGrammatik.gibParameter : TStringList; var paraCnt: Cardinal; varName: String; begin result := TStringList.Create; for paraCnt := 1 to variableZuWert.Count do begin varName := IntToStr(paraCnt)+'ax'; while length(varName) < tokenLaenge do varName:='0'+varName; result.add(variableZuWert[varName]); end; end; class function TGrammatik.tokenLaenge : Cardinal; begin result := 4; end; function TGrammatik.copy : TGrammatik; var regelIdx, produktionIdx: Cardinal; var gram: TGrammatik; begin gram := TGrammatik.Create; gram.axiom := FRawAxiom; for regelIdx := 0 to rawRegeln.Count - 1 do begin for produktionIdx := 0 to (rawRegeln.data[regelIdx]).Count - 1 do begin gram.addRegel( rawRegeln.keys[regelIdx], rawRegeln.data[regelIdx][produktionIdx].produktion, rawRegeln.data[regelIdx][produktionIdx].zufaelligkeit ); end; end; result := gram; end; end.
unit classe.MakePeriod; interface type TMakePeriod = class private // public procedure createPeriod(valMonth: String; valYear : Integer); procedure SearchPeriod(valSearch, valPeriod : String); end; implementation { TMakePeriod } uses classe.Period, System.sysUtils; procedure TMakePeriod.createPeriod(valMonth : String; valYear: Integer); var MyPeriod : TPeriod; begin MyPeriod := TPeriod.Create; try MyPeriod.Month := valMonth; MyPeriod.Year := IntToStr(valYear); MyPeriod.SaveInDatabase; finally MyPeriod.Free; end; end; procedure TMakePeriod.SearchPeriod(valSearch, valPeriod: String); var MyPeriod : TPeriod; begin MyPeriod := TPeriod.Create; try MyPeriod.SearchPeriod(valSearch, valPeriod); finally MyPeriod.Free; end; end; end.
unit UnitMeasurement; interface type TMeasurement = record public Time: TDateTime; Value: Double; ProductID: int64; PAramAddr: int64; class function Deserialize(var p: Pointer) : TArray<TMeasurement>; static; end; implementation uses myutils; class function TMeasurement.Deserialize(var p: Pointer): TArray<TMeasurement>; var I: Integer; measurementsCount: int64; begin measurementsCount := PInt64(p)^; Inc(PByte(p), 8); SetLength(Result, measurementsCount); if measurementsCount = 0 then exit; for I := 0 to measurementsCount - 1 do begin Result[i].Time := unixMillisToDateTime(PInt64(p)^); Inc(PByte(p), 8); Result[i].ProductID := PInt64(p)^; Inc(PByte(p), 8); Result[i].PAramAddr := PInt64(p)^; Inc(PByte(p), 8); Result[i].Value := PDouble(p)^; Inc(PByte(p), 8); end; end; end.
{ IsZSDOS: return TRUE if we're running ZSDOS (for file timestamps) } FUNCTION IsZSDOS : BOOLEAN; CONST GetDosVersion = 48; BEGIN IsZSDOS := ((BdosHL(GetDosVersion) AND $FF00) SHR 8) = Ord('S'); END; 
// GLPolyhedron {: Standard polyhedrons.<p> <b>History : </b><font size=-1><ul> <li>10/03/13 - PW - Added TGLTetrahedron and TGLOctahedron classes <li>23/08/10 - Yar - Added OpenGLTokens to uses <li>20/01/04 - SG - Added TGLIcosahedron <li>21/07/03 - EG - Creation from GLObjects split </ul></font> } unit GLPolyhedron; interface uses Classes, GLScene, GLVectorGeometry, GLRenderContextInfo; type // TGLDodecahedron // {: A Dodecahedron.<p> The dodecahedron has no texture coordinates defined, ie. without using a texture generation mode, no texture will be mapped. } TGLDodecahedron = class(TGLSceneObject) public { Public Declarations } procedure BuildList(var rci: TRenderContextInfo); override; end; // TGLIcosahedron // {: A Icosahedron.<p> The icosahedron has no texture coordinates defined, ie. without using a texture generation mode, no texture will be mapped. } TGLIcosahedron = class(TGLSceneObject) public { Public Declarations } procedure BuildList(var rci: TRenderContextInfo); override; end; // TGLOctahedron // {: A Octahedron.<p> The octahedron has no texture coordinates defined, ie. without using a texture generation mode, no texture will be mapped. } TGLOctahedron = class(TGLSceneObject) public { Public Declarations } procedure BuildList(var rci: TRenderContextInfo); override; end; // TGLTetrahedron // {: A Tetrahedron.<p> The tetrahedron has no texture coordinates defined, ie. without using a texture generation mode, no texture will be mapped. } TGLTetrahedron = class(TGLSceneObject) public { Public Declarations } procedure BuildList(var rci: TRenderContextInfo); override; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- uses GLObjects; // ------------------ // ------------------ TGLDodecahedron ------------------ // ------------------ // BuildList // procedure TGLDodecahedron.BuildList(var rci: TRenderContextInfo); begin DodecahedronBuildList; end; // ------------------ // ------------------ TGLIcosahedron ------------------ // ------------------ // BuildList // procedure TGLIcosahedron.BuildList(var rci: TRenderContextInfo); begin IcosahedronBuildList; end; //-------------------- //-------------------- TGLOctahedron ------------------------ //-------------------- // BuildList // procedure TGLOctahedron.BuildList(var rci: TRenderContextInfo); begin OctahedronBuildList; end; //-------------------- //-------------------- TGLTetrahedron ------------------------ //-------------------- // BuildList // procedure TGLTetrahedron.BuildList(var rci: TRenderContextInfo); begin TetrahedronBuildList; end; initialization //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- RegisterClasses([TGLDodecahedron, TGLIcosahedron, TGLOctahedron, TGLTetrahedron]); end.
unit BaseWM; {$mode objfpc}{$H+} interface uses Classes; type // A base window manager. this might be useful later TBaseWindowManager = class(TObject) public procedure InitWM(QueryWindows: Boolean = True); virtual; abstract; procedure MainLoop; virtual; abstract; end; { TBaseFrame } TBaseFrame = class(TObject) private fOwner: TBaseWindowManager; fCaption: String; public procedure SetCaption(const AValue: String); virtual; property Caption: String read fCaption write SetCaption; property Owner: TBaseWindowManager read fOwner write fOwner; end; implementation { TBaseFrame } procedure TBaseFrame.SetCaption(const AValue: String); begin fCaption := AValue; end; end.
unit UnModelo; interface uses SysUtils, Classes, SqlExpr, FMTBcd, DB, DBClient, Provider, { helsonsant } Util, DataUtil, Configuracoes, Dominio; type TModelo = class; Modelo = class of TModelo; TModelo = class(TDataModule) Sql: TSQLDataSet; ds: TSQLDataSet; dsp: TDataSetProvider; cds: TClientDataSet; dsr: TDataSource; procedure cdsAfterPost(DataSet: TDataSet); protected FDominio: TDominio; FDataUtil: TDataUtil; FParameters: TMap; FConfiguracoes: TConfiguracoes; FSql: TSQL; FUtil: TUtil; function RetornarComponente(const Prefixo, Nome: string): TComponent; function GetSQL: TSQL; virtual; abstract; public constructor Create(const Dominio: TDominio); reintroduce; function Util(const Util: TUtil): TModelo; function DataUtil(const DataUtil: TDataUtil): TModelo; function Configuracoes(const Configuracoes: TConfiguracoes): TModelo; function Incluir: TModelo; virtual; function Inativar: TModelo; virtual; function Salvar: TModelo; virtual; function EhValido: Boolean; virtual; function Excluir: TModelo; virtual; function DataSet(const DataSetName: string = ''): TClientDataSet; function DataSource(const DataSourceName: string = ''): TDataSource; function Preparar(const Conexao: TSQLConnection): TModelo; virtual; function Carregar: TModelo; virtual; function CarregarPor(const Criterio: string): TModelo; virtual; function Descarregar: TModelo; function Parametros: TMap; function OrdernarPor(const Campo: string): TModelo; virtual; end; var FConexao: TSQLConnection; FSql: TSQL; FDataUtil: TDataUtil; FUtil: TUtil; FConfiguracoes: TConfiguracoes; implementation {$R *.dfm} uses UnFabricaDeDominios; { TModel } function TModelo.Carregar: TModelo; begin Result := Self; Self.CarregarPor(''); end; function TModelo.CarregarPor(const Criterio: string): TModelo; var _dataSet: TClientDataSet; begin Result := Self; _dataSet := Self.cds; _dataSet.Active := False; if Criterio = '' then begin _dataSet.CommandText := Self.GetSQL().ObterSQL; end else begin _dataSet.CommandText := Self.GetSQL().obterSQLFiltrado(Criterio); end; _dataSet.Open(); end; procedure TModelo.cdsAfterPost(DataSet: TDataSet); begin if (Self.FDominio <> nil) and Assigned(Self.FDominio.EventoAntesDePostarRegistro) then begin Self.FDominio.EventoAntesDePostarRegistro(DataSet); end; end; function TModelo.Configuracoes(const Configuracoes: TConfiguracoes): TModelo; begin Result := Self; Self.FConfiguracoes := Configuracoes; end; constructor TModelo.Create(const Dominio: TDominio); begin inherited Create(nil); Self.FDominio := Dominio; end; function TModelo.DataSet(const DataSetName: string): TClientDataSet; begin if DataSetName <> '' then begin Result := Self.RetornarComponente('cds_', DataSetName) as TClientDataSet; end else begin Result := Self.cds; end; end; function TModelo.DataSource(const DataSourceName: string): TDataSource; begin if DataSourceName <> '' then begin Result := Self.RetornarComponente('dsr_', DataSourceName) as TDataSource; end else begin Result := Self.dsr; end; end; function TModelo.DataUtil(const DataUtil: TDataUtil): TModelo; begin Result := Self; Self.FDataUtil := DataUtil; end; function TModelo.Descarregar: TModelo; begin Result := Self; Self.FDataUtil := nil; Self.FParameters := nil; Self.FConfiguracoes := nil; Self.FSql := nil; Self.FUtil := nil; end; function TModelo.Excluir: TModelo; begin Result := Self; Self.cds.Edit; Self.cds.FieldByName('REC_STT').AsInteger := Ord(srExcluido); Self.cds.FieldByName('REC_DEL').AsDateTime := Now; Self.cds.Post; Self.Salvar; end; function TModelo.Parametros: TMap; begin if Self.FParameters = nil then begin Self.FParameters := TMap.Create; end; Result := Self.FParameters; end; function TModelo.Incluir: TModelo; begin Result := Self; Self.cds.Append; end; function TModelo.OrdernarPor(const Campo: string): TModelo; begin Result := Self; end; function TModelo.Preparar(const Conexao: TSQLConnection): TModelo; var _i: Integer; begin Result := Self; Self.GetSQL; if Self.FDominio <> nil then begin TFabricaDeDominio .Conexao(Conexao) .FabricarDominio(Self.FDominio, Self); end; for _i := 0 to Self.ComponentCount-1 do begin if (Self.Components[_i].Tag <> 0) and (Self.Components[_i] is TSQLDataSet) then begin (Self.Components[_i] as TSQLDataSet).SQLConnection := Conexao; end; end; for _i := 0 to Self.ComponentCount-1 do begin if (Self.Components[_i].Tag <> 0) and (Self.Components[_i] is TClientDataSet) then begin (Self.Components[_i] as TClientDataSet).Open(); end; end; end; function TModelo.RetornarComponente(const Prefixo, Nome: string): TComponent; begin Result := Self.FindComponent(Format('%s%s', [Prefixo, Nome])); end; function TModelo.Salvar: TModelo; begin Result := Self; Self.FDataUtil.PostChanges(Self.cds); if Self.cds.ChangeCount > 0 then begin Self.cds.ApplyUpdates(-1); end; end; function TModelo.Util(const Util: TUtil): TModelo; begin Result := Self; Self.FUtil := Util; end; function TModelo.EhValido: Boolean; begin Result := True; if Assigned(Self.FDominio.EventoRegraDeNegocioGerencial) then begin Result := Self.FDominio.EventoRegraDeNegocioGerencial(Self); end; end; function TModelo.Inativar: TModelo; begin Result := Self; Self.cds.Edit; Self.cds.FieldByName('REC_STT').AsInteger := Ord(srInativo); Self.cds.FieldByName('REC_UPD').AsDateTime := Now; Self.cds.Post; Self.Salvar; end; end.
unit Dialog; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, FMX.Forms, Card, FMX.StdCtrls; type TDialog = class(TCard) private { Private declarations } protected { Protected declarations } FPointerOnClickDefocus: TNotifyEvent; { Block focus on background } FButton1: TButton; FButton2: TButton; FDefocusBackgroundCard: TRectangle; FCloseOnClickDefocus: Boolean; procedure OnClickFDefocusBackgroundCard(Sender: TObject); procedure OnEnterButton2(Sender: TObject); function GetFCornerRoundBackgroud: Single; procedure SetFCornerRoundBackgroud(const Value: Single); function GetFCardAlign: TAlignLayout; function GetFCardHeight: Single; function GetFCardMargins: TBounds; function GetFCardWidth: Single; procedure SetFCardAlign(const Value: TAlignLayout); procedure SetFCardHeight(const Value: Single); procedure SetFCardMargins(const Value: TBounds); procedure SetFCardWidth(const Value: Single); function GetFDefocusBackgroundColor: TAlphaColor; function GetFDefocusBackgroundOpacity: Single; procedure SetFDefocusBackgroundColor(const Value: TAlphaColor); procedure SetFDefocusBackgroundOpacity(const Value: Single); function GetFOnClickDefocus: TNotifyEvent; procedure SetFOnClickDefocus(const Value: TNotifyEvent); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open(Duration: Single = 0.2); override; published { Published declarations } { Additional properties } property CloseOnClickDefocus: Boolean read FCloseOnClickDefocus write FCloseOnClickDefocus; property CardAlign: TAlignLayout read GetFCardAlign write SetFCardAlign; property CardMargins: TBounds read GetFCardMargins write SetFCardMargins; property CardHeight: Single read GetFCardHeight write SetFCardHeight; property CardWidth: Single read GetFCardWidth write SetFCardWidth; property DefocusBackgroundColor: TAlphaColor read GetFDefocusBackgroundColor write SetFDefocusBackgroundColor; property DefocusBackgroundOpacity: Single read GetFDefocusBackgroundOpacity write SetFDefocusBackgroundOpacity; property CornerRoundBackgroud: Single read GetFCornerRoundBackgroud write SetFCornerRoundBackgroud; { Mouse events } property OnClickDefocus: TNotifyEvent read GetFOnClickDefocus write SetFOnClickDefocus; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TDialog]); end; { TDialog } constructor TDialog.Create(AOwner: TComponent); begin inherited; Align := TAlignLayout.Client; CornerRound := 5; FCloseOnClickDefocus := True; FButton1 := TButton.Create(Self); Self.AddObject(FButton1); FButton1.SetSubComponent(True); FButton1.Stored := False; FButton1.Opacity := 0; FButton2 := TButton.Create(Self); Self.AddObject(FButton2); FButton2.SetSubComponent(True); FButton2.Stored := False; FButton2.Opacity := 0; FButton2.OnEnter := OnEnterButton2; FButton1.TabOrder := 32700; FButton2.TabOrder := 32701; { BackgroundCard } FBackgroundCard.Align := TAlignLayout.Center; { DefocusBackgroundCard } FDefocusBackgroundCard := TRectangle.Create(Self); Self.AddObject(FDefocusBackgroundCard); FDefocusBackgroundCard.Align := TAlignLayout.Contents; FDefocusBackgroundCard.Stroke.Kind := TBrushKind.None; FDefocusBackgroundCard.Fill.Color := TAlphaColor($FF000000); FDefocusBackgroundCard.Opacity := 0.4; FDefocusBackgroundCard.SetSubComponent(True); FDefocusBackgroundCard.Stored := False; FDefocusBackgroundCard.SendToBack; FDefocusBackgroundCard.OnClick := OnClickFDefocusBackgroundCard; end; destructor TDialog.Destroy; begin if Assigned(FDefocusBackgroundCard) then FDefocusBackgroundCard.Free; if Assigned(FButton1) then FButton1.Free; if Assigned(FButton2) then FButton2.Free; inherited; end; procedure TDialog.OnClickFDefocusBackgroundCard(Sender: TObject); begin if FCloseOnClickDefocus then Self.Close; if Assigned(FPointerOnClickDefocus) then FPointerOnClickDefocus(Sender); end; procedure TDialog.OnEnterButton2(Sender: TObject); begin TThread.CreateAnonymousThread( procedure begin TThread.Synchronize(TThread.CurrentThread, procedure begin FButton1.SetFocus; end); end).Start; end; procedure TDialog.Open(Duration: Single); begin inherited; FButton1.SetFocus; end; function TDialog.GetFCardAlign: TAlignLayout; begin Result := FBackgroundCard.Align; end; function TDialog.GetFCardHeight: Single; begin Result := FBackgroundCard.Height; end; function TDialog.GetFCardMargins: TBounds; begin Result := FBackgroundCard.Margins; end; function TDialog.GetFCardWidth: Single; begin Result := FBackgroundCard.Width; end; function TDialog.GetFCornerRoundBackgroud: Single; begin Result := FDefocusBackgroundCard.XRadius; end; function TDialog.GetFDefocusBackgroundColor: TAlphaColor; begin Result := FDefocusBackgroundCard.Fill.Color; end; function TDialog.GetFDefocusBackgroundOpacity: Single; begin Result := FDefocusBackgroundCard.Opacity; end; function TDialog.GetFOnClickDefocus: TNotifyEvent; begin Result := FPointerOnClickDefocus; end; procedure TDialog.SetFCardAlign(const Value: TAlignLayout); begin FBackgroundCard.Align := Value; end; procedure TDialog.SetFCardHeight(const Value: Single); begin FBackgroundCard.Height := Value; end; procedure TDialog.SetFCardMargins(const Value: TBounds); begin FBackgroundCard.Margins := Value; end; procedure TDialog.SetFCardWidth(const Value: Single); begin FBackgroundCard.Width := Value; end; procedure TDialog.SetFCornerRoundBackgroud(const Value: Single); begin FDefocusBackgroundCard.XRadius := Value; FDefocusBackgroundCard.YRadius := Value; end; procedure TDialog.SetFDefocusBackgroundColor(const Value: TAlphaColor); begin FDefocusBackgroundCard.Fill.Color := Value; end; procedure TDialog.SetFDefocusBackgroundOpacity(const Value: Single); begin FDefocusBackgroundCard.Opacity := Value; end; procedure TDialog.SetFOnClickDefocus(const Value: TNotifyEvent); begin FPointerOnClickDefocus := Value; end; end.
unit SystemUnit; interface {$i compilers.inc} uses Classes, SysUtils, NPCompiler, NPCompiler.Classes, NPCompiler.DataTypes, IL.Types, NPCompiler.Operators, NPCompiler.Utils, NPCompiler.Intf; // System type TSYSTEMUnit = class(TNPUnit) type TDataTypes = array[TDataTypeID] of TIDType; const SystemTypesCount = Ord(dtPointer) + 1; private var FDataTypes: TDataTypes; FTrueConstant: TIDBooleanConstant; FFalseConstant: TIDBooleanConstant; FFalseExpression: TIDExpression; FTrueExpression: TIDExpression; FZeroConstant: TIDIntConstant; FZeroExpression: TIDExpression; FMinusOneConstant: TIDIntConstant; FMinusOneExpression: TIDExpression; FOneConstant: TIDIntConstant; FOneExpression: TIDExpression; FNullPtrType: TIDType; FNullPtrConstatnt: TIDIntConstant; FNullPtrExpression: TIDExpression; FEmptyStrConstant: TIDStringConstant; FEmptyStrExpression: TIDExpression; FPointerType: TIDPointer; FUntypedReferenceType: TIDPointer; FArrayType: TIDArray; // служебный тип для функций Length/SetLength FRefType: TIDType; // служебный тип для функций SizeOf FGuidType: TIDStructure; FOrdinalType: TIDType; FTObject: TIDClass; FException: TIDClass; FEAssertClass: TIDClass; FDateTimeType: TIDType; FDateType: TIDType; FTimeType: TIDType; FTypeIDType: TIDType; FImplicitAnyToVariant: TIDInternalOpImplicit; FImplicitVariantToAny: TIDInternalOpImplicit; FExplicitEnumFromAny: TIDInternalOpImplicit; fExplicitTProcFromAny: TIDInternalOpImplicit; FCopyArrayOfObjProc: TIDProcedure; FCopyArrayOfStrProc: TIDProcedure; FFinalArrayOfObjProc: TIDProcedure; FFinalArrayOfStrProc: TIDProcedure; FFinalArrayOfVarProc: TIDProcedure; FAsserProc: TIDProcedure; FSysTStrDynArray: TIDDynArray; FSysTObjDynArray: TIDDynArray; FSysTVarDynArray: TIDDynArray; fDeprecatedDefaultStr: TIDStringConstant; procedure AddImplicists; procedure AddExplicists; procedure AddNegOperators; procedure AddAddOperators; procedure AddSubOperators; procedure AddMulOperators; procedure AddDivOperators; procedure AddIntDivOperators; procedure AddModOperators; procedure AddLogicalOperators; procedure AddBitwiseOperators; procedure AddCompareOperators; procedure AddArithmeticOperators; procedure RegisterBuiltinFunctions; procedure RegisterSystemRTBuiltinFunctions; procedure RegisterSystemCTBuiltinFunctions; procedure InsertToScope(Declaration: TIDDeclaration); function RegisterBuiltin(const Name: string; MacroID: TBuiltInFunctionID; ResultDataType: TIDType; Flags: TProcFlags = [pfPure]): TIDBuiltInFunction; function RegisterType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType; function RegisterRefType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType; function RegisterOrdinal(const TypeName: string; DataType: TDataTypeID; LowBound: Int64; HighBound: UInt64): TIDType; function RegisterTypeAlias(const TypeName: string; OriginalType: TIDType): TIDAliasType; function RegisterConstInt(const Name: string; DataType: TIDType; Value: Int64): TIDIntConstant; private procedure CreateCopyArrayOfObjProc; procedure CreateCopyArrayOfStrProc; procedure CreateFinalArrayOfObjProc; procedure CreateFinalArrayOfStrProc; procedure CreateFinalArrayOfVarProc; procedure CreateAsserProc; procedure CreateSystemRoutinsTypes; procedure SearchSystemTypes; procedure AddCustomExplicits(const Sources: array of TDataTypeID; Dest: TIDType); overload; function AddSysRTFunction(const SysFuncClass: TIDSysRuntimeFunctionClass; const Name: string; ResultType: TIDType): TIDSysRuntimeFunction; function AddSysCTFunction(const SysFuncClass: TIDSysCompileFunctionClass; const Name: string; ResultType: TIDType): TIDSysCompileFunction; public //////////////////////////////////////////////////////////////////////////////////////////////////// constructor Create(const Package: INPPackage; const Source: string); override; function Compile(RunPostCompile: Boolean = True): TCompilerResult; override; function CompileIntfOnly: TCompilerResult; override; //////////////////////////////////////////////////////////////////////////////////////////////////// procedure CreateSystemRoutins; property DataTypes: TDataTypes read FDataTypes; property _Int8: TIDType read FDataTypes[dtInt8] write FDataTypes[dtInt8]; property _Int16: TIDType read FDataTypes[dtInt16] write FDataTypes[dtInt16]; property _Int32: TIDType read FDataTypes[dtInt32] write FDataTypes[dtInt32]; property _Int64: TIDType read FDataTypes[dtInt64] write FDataTypes[dtInt64]; property _UInt8: TIDType read FDataTypes[dtUInt8] write FDataTypes[dtUInt8]; property _UInt16: TIDType read FDataTypes[dtUInt16] write FDataTypes[dtUInt16]; property _UInt32: TIDType read FDataTypes[dtUInt32] write FDataTypes[dtUInt32]; property _UInt64: TIDType read FDataTypes[dtUInt64] write FDataTypes[dtUInt64]; property _NativeInt: TIDType read FDataTypes[dtNativeInt] write FDataTypes[dtNativeInt]; property _NativeUInt: TIDType read FDataTypes[dtNativeUInt] write FDataTypes[dtNativeUInt]; property _Float32: TIDType read FDataTypes[dtFloat32] write FDataTypes[dtFloat32]; property _Float64: TIDType read FDataTypes[dtFloat64] write FDataTypes[dtFloat64]; property _Boolean: TIDType read FDataTypes[dtBoolean] write FDataTypes[dtBoolean]; property _AnsiChar: TIDType read FDataTypes[dtAnsiChar] write FDataTypes[dtAnsiChar]; property _Char: TIDType read FDataTypes[dtChar] write FDataTypes[dtChar]; property _AnsiString: TIDType read FDataTypes[dtAnsiString] write FDataTypes[dtAnsiString]; property _String: TIDType read FDataTypes[dtString] write FDataTypes[dtString]; property _Variant: TIDType read FDataTypes[dtVariant] write FDataTypes[dtVariant]; property _NilPointer: TIDType read FNullPtrType; property _TGuid: TIDStructure read FGuidType; property _True: TIDBooleanConstant read FTrueConstant; property _False: TIDBooleanConstant read FFalseConstant; property _TrueExpression: TIDExpression read FTrueExpression; property _FalseExpression: TIDExpression read FFalseExpression; property _ZeroConstant: TIDIntConstant read FZeroConstant; property _ZeroExpression: TIDExpression read FZeroExpression; property _MinusOneExpression: TIDExpression read FMinusOneExpression; property _OneConstant: TIDIntConstant read FOneConstant; property _OneExpression: TIDExpression read FOneExpression; property _NullPtrConstant: TIDIntConstant read FNullPtrConstatnt; property _NullPtrExpression: TIDExpression read FNullPtrExpression; property _EmptyStrExpression: TIDExpression read FEmptyStrExpression; property _Pointer: TIDPointer read FPointerType; property _UntypedReference: TIDPointer read FUntypedReferenceType; property _TObject: TIDClass read FTObject; property _Exception: TIDClass read FException; property _EAssert: TIDClass read FEAssertClass; property _DateTime: TIDType read FDateTimeType; property _Date: TIDType read FDateType; property _Time: TIDType read FTimeType; property _CopyArrayOfObjProc: TIDProcedure read FCopyArrayOfObjProc; property _CopyArrayOfStrProc: TIDProcedure read FCopyArrayOfStrProc; property _FinalArrayOfObjProc: TIDProcedure read FFinalArrayOfObjProc; property _FinalArrayOfStrProc: TIDProcedure read FFinalArrayOfStrProc; property _FinalArrayOfVarProc: TIDProcedure read FFinalArrayOfVarProc; property _ExplicitEnumFromAny: TIDInternalOpImplicit read FExplicitEnumFromAny; property _ExplicitTProcFromAny: TIDInternalOpImplicit read fExplicitTProcFromAny; property _AssertProc: TIDProcedure read FAsserProc; property _TypeID: TIDType read FTypeIDType; property _DeprecatedDefaultStr: TIDStringConstant read fDeprecatedDefaultStr; end; var SYSUnit: TSYSTEMUnit = nil; // модуль SYSYTEM _MetaType: TIDType = nil; // служебный мета-тип который является типом всех остальных типов данных. _Void: TIDType = nil; implementation { TSystemUnit } uses NPCompiler.Messages, IL.Instructions, NPCompiler.SysFunctions; procedure AddUnarOperator(Op: TOperatorID; Source, Destination: TIDType); inline; begin Source.OverloadUnarOperator(Op, Destination); end; procedure AddBinarOperator(Op: TOperatorID; Left, Right, Result: TIDType); overload; inline; begin Left.OverloadBinarOperator2(Op, Right, Result); end; procedure AddBinarOperator(Op: TOperatorID; Left: TIDType; const Rights: array of TIDType; Result: TIDType); overload; var i: Integer; Right: TIDType; begin for i := 0 to Length(Rights) - 1 do begin Right := Rights[i]; AddBinarOperator(Op, Left, Right, Result); if Left <> Right then AddBinarOperator(Op, Right, Left, Result); end; end; procedure TSYSTEMUnit.AddImplicists; procedure AddBaseImplicits(DataType: TIDType); var i: TDataTypeID; begin for i := dtInt8 to dtFloat64 do DataType.OverloadImplicitTo(DataTypes[i]); DataType.OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; var i: TDataTypeID; begin // signed: AddBaseImplicits(_Int8); AddBaseImplicits(_Int16); AddBaseImplicits(_Int32); AddBaseImplicits(_Int64); AddBaseImplicits(_UInt8); AddBaseImplicits(_UInt16); AddBaseImplicits(_UInt32); AddBaseImplicits(_UInt64); AddBaseImplicits(_NativeInt); AddBaseImplicits(_NativeUInt); // Variant for i := dtInt8 to dtVariant do _Variant.OverloadImplicitTo(DataTypes[i], FImplicitVariantToAny); // float32 with _Float32 do begin OverloadImplicitTo(_Float32); OverloadImplicitTo(_Float64); OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; // Float64 with _Float64 do begin OverloadImplicitTo(_Float32); OverloadImplicitTo(_Float64); OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; // Char with _Char do begin OverloadImplicitTo(_Char); //OverloadImplicitTo(_AnsiChar); //OverloadImplicitTo(_String); OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; // AnsiChar with _AnsiChar do begin //OverloadImplicitTo(_Char); OverloadImplicitTo(_AnsiChar); //OverloadImplicitTo(_String); //OverloadImplicitTo(_AnsiString); OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; // string _String.OverloadImplicitTo(_Variant, FImplicitAnyToVariant); // AnsiString _AnsiString.OverloadImplicitTo(_Variant, FImplicitAnyToVariant); _String.OverloadImplicitTo(_AnsiString, TIDOpImplicitStringToAnsiString.CreateInternal(_AnsiString)); _String.OverloadImplicitTo(_TGuid, TIDOpImplicitStringToGUID.CreateInternal(_TGuid)); _AnsiString.OverloadImplicitTo(_String, TIDOpImplicitAnsiStringToString.CreateInternal(_String)); _AnsiString.OverloadImplicitTo(_TGuid, TIDOpImplicitStringToGUID.CreateInternal(_TGuid)); _Char.OverloadImplicitTo(_String, TIDOpImplicitCharToString.CreateInternal(_String)); _Char.OverloadImplicitTo(_AnsiString, TIDOpImplicitCharToAnsiString.CreateInternal(_AnsiString)); _Char.OverloadImplicitTo(_AnsiChar, TIDOpImplicitCharToAnsiChar.CreateInternal(_AnsiChar)); _AnsiChar.OverloadImplicitTo(_AnsiString, TIDOpImplicitAnsiCharToAnsiString.CreateInternal(_AnsiString)); _AnsiChar.OverloadImplicitTo(_String, TIDOpImplicitAnsiCharToString.CreateInternal(_String)); _AnsiChar.OverloadImplicitTo(_Char, TIDOpImplicitAnsiCharToChar.CreateInternal(_Char)); _MetaType.OverloadImplicitTo(_TGuid, TIDOpImplicitMetaClassToGUID.CreateInternal(_TGuid)); // Boolean _Boolean.OverloadImplicitTo(_Boolean); _Boolean.OverloadImplicitTo(_Variant, FImplicitAnyToVariant); end; procedure TSYSTEMUnit.AddCustomExplicits(const Sources: array of TDataTypeID; Dest: TIDType); var i: Integer; begin for i := 0 to Length(Sources) - 1 do DataTypes[Sources[i]].OverloadExplicitTo(Dest); end; procedure TSYSTEMUnit.AddExplicists; procedure AddBaseExplicits(DataType: TIDType); var i: TDataTypeID; begin for i := dtInt8 to dtFloat64 do DataType.OverloadExplicitTo(DataTypes[i]); end; procedure AddExplicits(DataType: TIDType; LB, HB: TDataTypeID); var i: TDataTypeID; begin for i := LB to HB do DataType.OverloadExplicitTo(DataTypes[i]); end; begin AddBaseExplicits(_Int8); AddBaseExplicits(_Int16); AddBaseExplicits(_Int32); AddBaseExplicits(_Int64); AddBaseExplicits(_UInt8); AddBaseExplicits(_UInt16); AddBaseExplicits(_UInt32); AddBaseExplicits(_UInt64); AddBaseExplicits(_NativeInt); AddBaseExplicits(_NativeUInt); AddBaseExplicits(_Variant); AddBaseExplicits(_Boolean); AddBaseExplicits(_Char); AddBaseExplicits(_AnsiChar); AddExplicits(_Float32, dtFloat32, dtFloat64); AddExplicits(_Float64, dtFloat32, dtFloat64); _String.OverloadExplicitTo(_Pointer); _Pointer.OverloadExplicitTo(_NativeInt); _Pointer.OverloadExplicitTo(_NativeUInt); _AnsiString.OverloadExplicitTo(_Pointer); AddCustomExplicits([dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtBoolean], _Char); AddCustomExplicits([dtInt8, dtInt16, dtInt32, dtInt64, dtUInt8, dtUInt16, dtUInt32, dtUInt64, dtBoolean], _AnsiChar); end; procedure TSYSTEMUnit.AddIntDivOperators; begin AddBinarOperator(opIntDiv, _Int8, [_Int8, _UInt8], _Int8); AddBinarOperator(opIntDiv, _UInt8, _UInt8, _UInt8); AddBinarOperator(opIntDiv, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16); AddBinarOperator(opIntDiv, _UInt16, [_UInt8, _UInt16], _UInt16); AddBinarOperator(opIntDiv, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32); AddBinarOperator(opIntDiv, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32); AddBinarOperator(opIntDiv, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64); AddBinarOperator(opIntDiv, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64); end; procedure TSYSTEMUnit.AddLogicalOperators; begin AddUnarOperator(opNot, _Boolean, _Boolean); AddBinarOperator(opAnd, _Boolean, _Boolean, _Boolean); AddBinarOperator(opOr, _Boolean, _Boolean, _Boolean); AddBinarOperator(opXor, _Boolean, _Boolean, _Boolean); end; procedure TSYSTEMUnit.AddModOperators; begin AddBinarOperator(opModDiv, _Int8, [_Int8, _UInt8], _Int8); AddBinarOperator(opModDiv, _UInt8, _UInt8, _UInt8); AddBinarOperator(opModDiv, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16); AddBinarOperator(opModDiv, _UInt16, [_UInt8, _UInt16], _UInt16); AddBinarOperator(opModDiv, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32); AddBinarOperator(opModDiv, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32); AddBinarOperator(opModDiv, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64); AddBinarOperator(opModDiv, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64); end; procedure TSYSTEMUnit.AddMulOperators; begin AddBinarOperator(opMultiply, _Int8, [_Int8, _UInt8], _Int8); AddBinarOperator(opMultiply, _UInt8, _UInt8, _UInt8); AddBinarOperator(opMultiply, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16); AddBinarOperator(opMultiply, _UInt16, [_UInt8, _UInt16], _UInt16); AddBinarOperator(opMultiply, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32); AddBinarOperator(opMultiply, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32); AddBinarOperator(opMultiply, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64); AddBinarOperator(opMultiply, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64); // int * float AddBinarOperator(opMultiply, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64); AddBinarOperator(opMultiply, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64); // variant AddBinarOperator(opMultiply, _Variant, _Variant, _Variant); end; procedure TSYSTEMUnit.AddNegOperators; begin AddUnarOperator(opNegative, _Int8, _Int8); AddUnarOperator(opNegative, _UInt8, _Int8); AddUnarOperator(opNegative, _Int16, _Int16); AddUnarOperator(opNegative, _UInt16, _Int16); AddUnarOperator(opNegative, _Int32, _Int32); AddUnarOperator(opNegative, _UInt32, _Int32); AddUnarOperator(opNegative, _Int64, _Int64); AddUnarOperator(opNegative, _UInt64, _Int64); AddUnarOperator(opNegative, _NativeInt, _NativeInt); AddUnarOperator(opNegative, _NativeUInt, _NativeInt); AddUnarOperator(opNegative, _Float32, _Float32); AddUnarOperator(opNegative, _Float64, _Float64); end; procedure TSYSTEMUnit.AddSubOperators; begin // int - int AddBinarOperator(opSubtract, _Int8, [_Int8, _UInt8], _Int8); AddBinarOperator(opSubtract, _UInt8, _UInt8, _UInt8); AddBinarOperator(opSubtract, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16); AddBinarOperator(opSubtract, _UInt16, [_UInt8, _UInt16], _UInt16); AddBinarOperator(opSubtract, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32); AddBinarOperator(opSubtract, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32); AddBinarOperator(opSubtract, _NativeInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt); AddBinarOperator(opSubtract, _NativeUInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt); AddBinarOperator(opSubtract, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64); AddBinarOperator(opSubtract, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64); // int - float AddBinarOperator(opSubtract, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32], _Float32); AddBinarOperator(opSubtract, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64); AddBinarOperator(opSubtract, _Variant, _Variant, _Variant); AddUnarOperator(opPostDec, _Int8, _Int8); AddUnarOperator(opPostDec, _Int16, _Int16); AddUnarOperator(opPostDec, _Int32, _Int32); AddUnarOperator(opPostDec, _Int64, _Int64); AddUnarOperator(opPostDec, _UInt8, _UInt8); AddUnarOperator(opPostDec, _UInt16, _UInt16); AddUnarOperator(opPostDec, _UInt32, _UInt32); AddUnarOperator(opPostDec, _UInt64, _UInt64); end; function TSYSTEMUnit.AddSysCTFunction(const SysFuncClass: TIDSysCompileFunctionClass; const Name: string; ResultType: TIDType): TIDSysCompileFunction; begin Result := SysFuncClass.Create(IntfSection, Name, bf_sysctfunction); Result.DataType := ResultType; InsertToScope(Result); end; function TSYSTEMUnit.AddSysRTFunction(const SysFuncClass: TIDSysRuntimeFunctionClass; const Name: string; ResultType: TIDType): TIDSysRuntimeFunction; begin Result := SysFuncClass.Create(IntfSection, Name, bf_sysrtfunction); Result.DataType := ResultType; InsertToScope(Result); end; procedure TSYSTEMUnit.AddAddOperators; begin AddBinarOperator(opAdd, _Int8, [_Int8, _UInt8], _Int8); AddBinarOperator(opAdd, _UInt8, _UInt8, _UInt8); AddBinarOperator(opAdd, _Int16, [_Int8, _UInt8, _Int16, _UInt16], _Int16); AddBinarOperator(opAdd, _UInt16, [_UInt8, _UInt16], _UInt16); AddBinarOperator(opAdd, _Int32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _Int32); AddBinarOperator(opAdd, _UInt32, [_UInt8, _UInt16, _UInt32], _UInt32); AddBinarOperator(opAdd, _NativeInt, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32], _NativeInt); AddBinarOperator(opAdd, _NativeUInt, [_UInt8, _UInt16, _UInt32], _NativeUInt); AddBinarOperator(opAdd, _Int64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Int64); AddBinarOperator(opAdd, _UInt64, [_UInt8, _UInt16, _UInt32, _UInt64], _UInt64); // int + float AddBinarOperator(opAdd, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32], _Float32); AddBinarOperator(opAdd, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64); // strings AddBinarOperator(opAdd, _String, _String, _String); AddBinarOperator(opAdd, _Char, _Char, _Char); AddBinarOperator(opAdd, _AnsiString, _AnsiString, _AnsiString); AddBinarOperator(opAdd, _AnsiChar, _AnsiChar, _AnsiChar); AddBinarOperator(opAdd, _Variant, _Variant, _Variant); AddUnarOperator(opPostInc, _Int8, _Int8); AddUnarOperator(opPostInc, _Int16, _Int16); AddUnarOperator(opPostInc, _Int32, _Int32); AddUnarOperator(opPostInc, _Int64, _Int64); AddUnarOperator(opPostInc, _UInt8, _UInt8); AddUnarOperator(opPostInc, _UInt16, _UInt16); AddUnarOperator(opPostInc, _UInt32, _UInt32); AddUnarOperator(opPostInc, _UInt64, _UInt64); end; procedure TSYSTEMUnit.AddDivOperators; begin AddBinarOperator(opDivide, _Int8, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64); AddBinarOperator(opDivide, _Int16, [_Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64); AddBinarOperator(opDivide, _Int32, [_Int32, _UInt32, _Int64, _UInt64], _Float64); AddBinarOperator(opDivide, _Int64, [_Int64, _UInt64], _Float64); AddBinarOperator(opDivide, _Float32, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64, _Float32, _Float64], _Float64); AddBinarOperator(opDivide, _Float64, [_Int8, _UInt8, _Int16, _UInt16, _Int32, _UInt32, _Int64, _UInt64], _Float64); AddBinarOperator(opDivide, _Variant, _Variant, _Variant); end; procedure TSYSTEMUnit.AddArithmeticOperators; begin AddNegOperators; AddAddOperators; AddSubOperators; AddMulOperators; AddDivOperators; AddIntDivOperators; AddModOperators; end; procedure TSYSTEMUnit.AddBitwiseOperators; function GetMaxBitwiceOpType(DtLeft, DtRight: TIDType): TIDType; begin if DtLeft.DataTypeID in [dtInt8, dtUint8, dtInt16, dtUInt16, dtInt32, dtUint32] then Result := _UInt32 else Result := _Int64; end; procedure UnarOp(Op: TOperatorID); var i: TDataTypeID; begin for i := dtInt8 to dtUInt64 do AddUnarOperator(Op, DataTypes[i], DataTypes[i]); end; procedure BitwiseOp(Op: TOperatorID); var i, j: TDataTypeID; begin for i := dtInt8 to dtUInt64 do for j := dtInt8 to dtUInt64 do AddBinarOperator(Op, DataTypes[i], DataTypes[j], GetMaxBitwiceOpType(DataTypes[i], DataTypes[j])); end; begin UnarOp(opNot); BitwiseOp(opAnd); BitwiseOp(opOr); BitwiseOp(opXor); BitwiseOp(opShiftLeft); BitwiseOp(opShiftRight); end; procedure TSYSTEMUnit.AddCompareOperators; procedure AD(Op: TOperatorID); var i, j: TDataTypeID; begin for i := dtInt8 to dtNativeUInt do for j := dtInt8 to dtNativeUInt do AddBinarOperator(Op, DataTypes[i], DataTypes[j], _Boolean); for i := dtInt8 to dtUInt64 do begin AddBinarOperator(Op, DataTypes[i], _Float32, _Boolean); AddBinarOperator(Op, DataTypes[i], _Float64, _Boolean); AddBinarOperator(Op, _Float32, DataTypes[i], _Boolean); AddBinarOperator(Op, _Float64, DataTypes[i], _Boolean); end; AddBinarOperator(Op, _Float32, _Float32, _Boolean); AddBinarOperator(Op, _Float32, _Float64, _Boolean); AddBinarOperator(Op, _Float64, _Float32, _Boolean); AddBinarOperator(Op, _Float64, _Float64, _Boolean); AddBinarOperator(Op, _Boolean, _Boolean, _Boolean); AddBinarOperator(Op, _Variant, _Variant, _Boolean); end; begin AD(opEqual); AD(opNotEqual); AD(opLess); AD(opLessOrEqual); AD(opGreater); AD(opGreaterOrEqual); // char AddBinarOperator(opEqual, _Char, _Char, _Boolean); AddBinarOperator(opNotEqual, _Char, _Char, _Boolean); AddBinarOperator(opLess, _Char, _Char, _Boolean); AddBinarOperator(opLessOrEqual, _Char, _Char, _Boolean); AddBinarOperator(opGreater, _Char, _Char, _Boolean); AddBinarOperator(opGreaterOrEqual, _Char, _Char, _Boolean); // ansichar AddBinarOperator(opEqual, _AnsiChar, _AnsiChar, _Boolean); AddBinarOperator(opNotEqual, _AnsiChar, _AnsiChar, _Boolean); AddBinarOperator(opLess, _AnsiChar, _AnsiChar, _Boolean); AddBinarOperator(opLessOrEqual, _AnsiChar, _AnsiChar, _Boolean); AddBinarOperator(opGreater, _AnsiChar, _AnsiChar, _Boolean); AddBinarOperator(opGreaterOrEqual, _AnsiChar, _AnsiChar, _Boolean); // ansistring AddBinarOperator(opEqual, _AnsiString, _AnsiString, _Boolean); AddBinarOperator(opNotEqual, _AnsiString, _AnsiString, _Boolean); AddBinarOperator(opLess, _AnsiString, _AnsiString, _Boolean); AddBinarOperator(opLessOrEqual, _AnsiString, _AnsiString, _Boolean); AddBinarOperator(opGreater, _AnsiString, _AnsiString, _Boolean); AddBinarOperator(opGreaterOrEqual, _AnsiString, _AnsiString, _Boolean); // string AddBinarOperator(opEqual, _String, _String, _Boolean); AddBinarOperator(opNotEqual, _String, _String, _Boolean); AddBinarOperator(opLess, _String, _String, _Boolean); AddBinarOperator(opLessOrEqual, _String, _String, _Boolean); AddBinarOperator(opGreater, _String, _String, _Boolean); AddBinarOperator(opGreaterOrEqual, _String, _String, _Boolean); end; function TSYSTEMUnit.RegisterType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType; begin Result := TypeClass.Create(IntfSection, Identifier(TypeName)); Result.Elementary := True; Result.DataTypeID := DataType; Result.ItemType := itType; InsertToScope(Result); FDataTypes[DataType] := Result; AddType(Result); end; procedure TSYSTEMUnit.SearchSystemTypes; begin FTObject := GetPublicClass('TObject'); FException := GetPublicClass('Exception'); FEAssertClass := GetPublicClass('EAssert'); FTypeIDType := GetPublicType('TDataTypeID'); end; function TSYSTEMUnit.RegisterRefType(const TypeName: string; TypeClass: TIDTypeClass; DataType: TDataTypeID): TIDType; begin Result := RegisterType(TypeName, TypeClass, DataType); // äîáàâëÿåì implicit nullptr FNullPtrType.OverloadImplicitTo(Result); end; procedure TSYSTEMUnit.RegisterSystemCTBuiltinFunctions; var Fn: TIDSysCompileFunction; begin // StaticAssert Fn := AddSysCTFunction(TSF_StaticAssert, 'StaticAssert', _Void); Fn.AddParam('Expression', _Boolean, [VarConst]); Fn.AddParam('Text', _String, [VarConst], _EmptyStrExpression); end; procedure TSYSTEMUnit.RegisterSystemRTBuiltinFunctions; var Decl: TIDSysRuntimeFunction; begin // typeid Decl := AddSysRTFunction(TSF_typeid, 'typeid', _TypeID); Decl.AddParam('Value or Type', _Void, []); // now AddSysRTFunction(TSF_now, 'Now', _DateTime); end; function TSYSTEMUnit.RegisterBuiltin(const Name: string; MacroID: TBuiltInFunctionID; ResultDataType: TIDType; Flags: TProcFlags = [pfPure]): TIDBuiltInFunction; begin Result := TIDBuiltInFunction.Create(Self.IntfSection, Name, MacroID); Result.ResultType := ResultDataType; Result.Flags := Flags; InsertToScope(Result); end; procedure TSYSTEMUnit.RegisterBuiltinFunctions; var Decl: TIDBuiltInFunction; begin FArrayType := TIDArray.Create(nil, Identifier('<array type or string>')); FRefType := TIDType.Create(nil, Identifier('')); // assigned Decl := RegisterBuiltin('Assigned', bf_assigned, _Boolean); Decl.AddParam('Value', FRefType, [VarConst]); // inc Decl := RegisterBuiltin('inc', bf_inc, nil); Decl.AddParam('Value', FOrdinalType, [VarInOut]); Decl.AddParam('Increment', FOrdinalType, [VarConst, VarHasDefault], _OneExpression); // dec Decl := RegisterBuiltin('dec', bf_dec, nil); Decl.AddParam('Value', FOrdinalType, [VarInOut]); Decl.AddParam('Decrement', FOrdinalType, [VarConst, VarHasDefault], _OneExpression); // memset Decl := RegisterBuiltin('memset', bf_memset, nil); Decl.AddParam('Value', FRefType, [VarConstRef]); Decl.AddParam('FillChar', _UInt8, [VarConst, VarHasDefault], _ZeroExpression); // Length Decl := RegisterBuiltin('Length', bf_length, _UInt32); Decl.AddParam('S', FArrayType, [VarConst]); // SetLength Decl := RegisterBuiltin('SetLength', bf_setlength, FArrayType); Decl.AddParam('Str', FArrayType, [VarInOut]); Decl.AddParam('NewLength', _Int32); // Copy Decl := RegisterBuiltin('Copy', bf_copy, nil); Decl.AddParam('Str', FArrayType, [VarInOut]); Decl.AddParam('From', _Int32, [VarIn], _ZeroExpression); Decl.AddParam('Count', _Int32, [VarIn], _MinusOneExpression); // Move Decl := RegisterBuiltin('Move', bf_move, nil); Decl.AddParam('SrcArray', FArrayType, [VarInOut]); Decl.AddParam('SrcIndex', _Int32, [VarIn]); Decl.AddParam('DstArray', FArrayType, [VarInOut]); Decl.AddParam('DstIndex', _Int32, [VarIn]); Decl.AddParam('Count', _Int32, [VarIn]); // SizeOf Decl := RegisterBuiltin('SizeOf', bf_sizeof, _UInt32); Decl.AddParam('S', FRefType); // accert Decl := RegisterBuiltin('assert', bf_assert, nil); Decl.AddParam('Value', _Boolean); Decl.AddParam('ErrorText', _String, [], _EmptyStrExpression); // TypeName Decl := RegisterBuiltin('TypeName', bf_typename, _String); Decl.AddParam('S', FRefType); // New Decl := RegisterBuiltin('New', bf_new, nil); Decl.AddParam('Ptr', _Pointer, [VarOut]); // Free Decl := RegisterBuiltin('Free', bf_free, nil); Decl.AddParam('Ptr', _Pointer, [VarConst]); // GetRef Decl := RegisterBuiltin('GetRef', bf_getref, _Boolean); Decl.AddParam('WeakPtr', _Pointer, [VarConst]); Decl.AddParam('StrongPtr', _Pointer, [VarOut]); // TypeInfo Decl := RegisterBuiltin('TypeInfo', bf_typeinfo, _TObject); Decl.AddParam('Declaration', _Pointer, [VarConst]); // Low(const Ordinal/Array) Decl := RegisterBuiltin('Low', bf_LoBound, _Int64); Decl.AddParam('Value', _Void, [VarConst]); // High(const Ordinal/Array) Decl := RegisterBuiltin('High', bf_HiBound, _Int64); Decl.AddParam('Value', _Void, [VarConst]); // Ord(const Ordinal) Decl := RegisterBuiltin('Ord', bf_Ord, _Int64); Decl.AddParam('Value', _Void, [VarConst]); // include(var Set; const SubSet) Decl := RegisterBuiltin('include', bf_include, nil); Decl.AddParam('Set', _Void, [VarInOut]); Decl.AddParam('SubSet', _Void, [VarInOut]); // exclude(var Set; const SubSet) Decl := RegisterBuiltin('exclude', bf_exclude, nil); Decl.AddParam('Set', _Void, [VarInOut]); Decl.AddParam('SubSet', _Void, [VarInOut]); // GetBit(const Value; BitIndex: Int32): Boolean Decl := RegisterBuiltin('getbit', bf_getbit, _Boolean); Decl.AddParam('Value', _Void, [VarIn, VarConst]); Decl.AddParam('BitIndex', _UInt32, [VarIn]); // SetBit(const Value; BitIndex: Int32; BitValue: Boolean); Decl := RegisterBuiltin('setbit', bf_setbit, nil); Decl.AddParam('Value', _Void, [VarIn, VarConst]); Decl.AddParam('BitIndex', _UInt32, [VarIn]); Decl.AddParam('BitValue', _Boolean, [VarIn]); RegisterBuiltin('current_unit', bf_current_unit, _String); RegisterBuiltin('current_function', bf_current_function, _String); RegisterBuiltin('current_line', bf_current_line, _UInt32); // refcount(reference) Decl := RegisterBuiltin('RefCount', bf_refcount, _Int32); Decl.AddParam('Reference', _Void, [VarConst]); end; function TSYSTEMUnit.RegisterOrdinal(const TypeName: string; DataType: TDataTypeID; LowBound: Int64; HighBound: UInt64): TIDType; begin Result := RegisterType(TypeName, TIDOrdinal, DataType); TIDOrdinal(Result).LowBound := LowBound; TIDOrdinal(Result).HighBound := HighBound; end; function TSYSTEMUnit.Compile(RunPostCompile: Boolean = True): TCompilerResult; begin Result := CompileFail; try Result := inherited Compile(False); if Result = CompileSuccess then begin Result := CompileFail; SearchSystemTypes; CreateSystemRoutins; PostCompileProcessUnit; end; Result := CompileSuccess; except on e: ECompilerStop do Exit; on e: ECompilerSkip do Exit(CompileSkip); on e: ECompilerAbort do PutMessage(ECompilerAbort(e).CompilerMessage^); on e: Exception do PutMessage(cmtInteranlError, e.Message); end; end; constructor TSYSTEMUnit.Create(const Package: INPPackage; const Source: string); begin inherited Create(Package, Source); //_ID := 'system'; // nil constant FNullPtrType := TIDNullPointerType.CreateAsSystem(IntfSection, 'null ptr'); FNullPtrConstatnt := TIDIntConstant.Create(IntfSection, Identifier('nil'), FNullPtrType, 0); FNullPtrExpression := TIDExpression.Create(FNullPtrConstatnt); IntfSection.InsertID(FNullPtrConstatnt); FUntypedReferenceType := TIDPointer.CreateAsSystem(IntfSection, 'Untyped reference'); IntfSection.InsertID(FUntypedReferenceType); FOrdinalType := TIDOrdinal.CreateAsSystem(nil, 'ordinal'); FExplicitEnumFromAny := TIDOpExplicitIntToEnum.CreateAsIntOp; fExplicitTProcFromAny := TIDOpExplicitTProcFromAny.CreateAsIntOp; {!!! Ïîðÿäîê ðåãèñòðàöèè òèïîâ ñîîòâåòñòâóåò ïîðÿäêîâîìó íîìåðó êîíñòàíòû DataTypeID !!!} //=============================================================== RegisterOrdinal('Int8', dtInt8, MinInt8, MaxInt8); RegisterOrdinal('Int16', dtInt16, MinInt16, MaxInt16); RegisterOrdinal('Int32', dtInt32, MinInt32, MaxInt32); RegisterOrdinal('Int64', dtInt64, MinInt64, MaxInt64); RegisterOrdinal('UInt8', dtUInt8, 0, MaxUInt8); RegisterOrdinal('UInt16', dtUInt16, 0, MaxUInt16); RegisterOrdinal('UInt32', dtUInt32, 0, MaxUInt32); RegisterOrdinal('UInt64', dtUInt64, 0, MaxUInt64); RegisterOrdinal('NativeInt', dtNativeInt, MinInt64, MaxInt64); RegisterOrdinal('NativeUInt', dtNativeUInt, 0, MaxUInt64); RegisterType('Float32', TIDType, dtFloat32); RegisterType('Float64', TIDType, dtFloat64); //=============================================================== RegisterOrdinal('Boolean', dtBoolean, 0, 1); RegisterOrdinal('AnsiChar', dtAnsiChar, 0, MaxUInt8); RegisterOrdinal('Char', dtChar, 0, MaxUInt16); //=============================================================== RegisterType('AnsiString', TIDString, dtAnsiString); TIDString(_AnsiString).ElementDataType := _AnsiChar; TIDString(_AnsiString).AddBound(TIDOrdinal(_NativeUInt)); //=============================================================== RegisterType('String', TIDString, dtString); TIDString(_String).ElementDataType := _Char; TIDString(_String).AddBound(TIDOrdinal(_NativeUInt)); //=============================================================== RegisterType('Variant', TIDVariant, dtVariant); FImplicitAnyToVariant := TIDOpImplicitAnyToVariant.CreateInternal(_Variant); FImplicitVariantToAny := TIDOpImplicitVariantToAny.CreateInternal(nil); // TObject ======================================================== {FTObject := TIDClass.CreateAsSystem(UnitInterface, 'TObject'); FTObject.NeedForward := True; // forward declaration InsertToScope(FTObject);} // TGUID ======================================================== FGuidType := TIDStructure.CreateAsSystem(IntfSection, 'TGUID'); FGuidType.DataTypeID := dtGuid; FGuidType.AddField('LoDWord', _Int64); FGuidType.AddField('HiDWord', _Int64); FGuidType.OverloadBinarOperator2(opEqual, FGuidType, _Boolean); FGuidType.OverloadBinarOperator2(opNotEqual, FGuidType, _Boolean); FGuidType.DataType := _MetaType; InsertToScope(FGuidType); AddType(FGuidType); //=============================================================== FDateTimeType := TIDAliasType.CreateAliasAsSystem(IntfSection, 'DateTime', _Float64); FDateType := TIDAliasType.CreateAliasAsSystem(IntfSection, 'Date', _Float64); FTimeType := TIDAliasType.CreateAliasAsSystem(IntfSection, 'Time', _Float64); InsertToScope(FDateTimeType); InsertToScope(FDateType); InsertToScope(FTimeType); AddType(FDateTimeType); AddType(FDateType); AddType(FTimeType); //=============================================================== FPointerType := RegisterRefType('Pointer', TIDPointer, dtPointer) as TIDPointer; FPointerType.OverloadBinarOperator2(opEqual, FPointerType, _Boolean); // ñòàíäàðòíûå îïåðàòîðû FPointerType.OverloadBinarOperator2(opNotEqual, FPointerType, _Boolean); FPointerType.OverloadBinarOperator2(opEqual, _NilPointer, _Boolean); FPointerType.OverloadBinarOperator2(opNotEqual, _NilPointer, _Boolean); FPointerType.OverloadBinarOperator2(opAdd, FPointerType, FPointerType); FPointerType.OverloadBinarOperator2(opSubtract, FPointerType, FPointerType); FPointerType.OverloadBinarOperator2(opAdd, _Int32, FPointerType); FPointerType.OverloadBinarOperator2(opSubtract, _Int32, FPointerType); //=============================================================== // constant "True" FTrueConstant := TIDBooleanConstant.Create(IntfSection, Identifier('TRUE'), _Boolean, True); FTrueExpression := TIDExpression.Create(FTrueConstant); IntfSection.InsertID(FTrueConstant); // constant "False" FFalseConstant := TIDBooleanConstant.Create(IntfSection, Identifier('FALSE'), _Boolean, False); FFalseExpression := TIDExpression.Create(FFalseConstant); IntfSection.InsertID(FFalseConstant); // constant "0" FZeroConstant := TIDIntConstant.CreateAnonymous(IntfSection, _UInt8, 0); FZeroExpression := TIDExpression.Create(FZeroConstant); // constant "1" FOneConstant := TIDIntConstant.CreateAnonymous(IntfSection, _UInt8, 1); FOneExpression := TIDExpression.Create(FOneConstant); // constant "-1" FMinusOneConstant := TIDIntConstant.CreateAnonymous(IntfSection, _Int32, -1); FMinusOneExpression := TIDExpression.Create(FMinusOneConstant); // constant "" FEmptyStrConstant := TIDStringConstant.CreateAnonymous(IntfSection, _String, ''); FEmptyStrExpression := TIDExpression.Create(FEmptyStrConstant); // constant for deprecated fDeprecatedDefaultStr := TIDStringConstant.CreateAsSystem(IntfSection, 'The declaration is deprecated'); AddImplicists; AddExplicists; AddArithmeticOperators; AddLogicalOperators; AddBitwiseOperators; AddCompareOperators; RegisterBuiltinFunctions; end; procedure TSYSTEMUnit.CreateAsserProc; var Proc: TIDProcedure; IL: TIL; EAssertCtor: TIDProcedure; Code: TILInstruction; EExpr: TIDExpression; StrParam: TIDParam; StrArg: TIDExpression; begin Proc := CreateSysProc('$assert'); StrParam := Proc.AddParam('Str', _String, [VarConst]); IL := Proc.IL as TIL; // ñîçäàåì ýêçåìïëÿð êëàññà EAssert EExpr := TIDExpression.Create(Proc.GetTMPVar(SYSUnit._EAssert, [VarTmpResOwner])); Code := TIL.IL_DNew(EExpr, TIDExpression.Create(SYSUnit._EAssert)); IL.Write(Code); // âûçûâàåì êîíñòðóêòîð êëàññà EAssert StrArg := TIDExpression.Create(StrParam); EAssertCtor := _EAssert.FindMethod('Create'); Code := TIL.IL_ProcCall(TIDExpression.Create(EAssertCtor), nil, EExpr, [StrArg]); IL.Write(Code); // âûáðàñûâàåì èñêëþ÷åíèå IL.Write(TIL.IL_EThrow(cNone, EExpr)); FAsserProc := Proc; end; procedure TSYSTEMUnit.CreateCopyArrayOfStrProc; var Param: TIDVariable; Ctx: TLoopCodeContext; begin FCopyArrayOfStrProc := CreateArraySysProc(FSysTStrDynArray, FSysTStrDynArray.Name + '$copy', Param); Ctx := TLoopCodeContext.Create(FCopyArrayOfStrProc, Param); // ãåíåðèðóåì êîä öèêëà ïðîõîäà ïî ìàññèâó MakeLoopBodyBegin(Ctx); // òåëî öèêëà Ctx.IL.Write(TIL.IL_IncRef(Ctx.ItemExpr)); // êîíåö öèêëà MakeLoopBodyEnd(Ctx); end; procedure TSYSTEMUnit.CreateCopyArrayOfObjProc; var Param: TIDVariable; Ctx: TLoopCodeContext; begin FCopyArrayOfObjProc := CreateArraySysProc(FSysTObjDynArray, FSysTObjDynArray.Name + '$copy', Param); Ctx := TLoopCodeContext.Create(FCopyArrayOfObjProc, Param); // ãåíåðèðóåì êîä öèêëà ïðîõîäà ïî ìàññèâó MakeLoopBodyBegin(Ctx); // òåëî öèêëà Ctx.IL.Write(TIL.IL_IncRef(Ctx.ItemExpr)); // êîíåö öèêëà MakeLoopBodyEnd(Ctx); end; procedure TSYSTEMUnit.CreateFinalArrayOfStrProc; var Param: TIDVariable; Ctx: TLoopCodeContext; begin FFinalArrayOfStrProc := CreateArraySysProc(FSysTStrDynArray, FSysTStrDynArray.Name + '$final', Param); Ctx := TLoopCodeContext.Create(FFinalArrayOfStrProc, Param); // ãåíåðèðóåì êîä öèêëà ïðîõîäà ïî ìàññèâó MakeLoopBodyBegin(Ctx); // òåëî öèêëà Ctx.IL.Write(TIL.IL_DecRef(Ctx.ItemExpr)); // êîíåö öèêëà MakeLoopBodyEnd(Ctx); end; procedure TSYSTEMUnit.CreateFinalArrayOfVarProc; var Param: TIDVariable; Ctx: TLoopCodeContext; begin FFinalArrayOfVarProc := CreateArraySysProc(FSysTVarDynArray, FSysTVarDynArray.Name + '$final', Param); Ctx := TLoopCodeContext.Create(FFinalArrayOfVarProc, Param); // ãåíåðèðóåì êîä öèêëà ïðîõîäà ïî ìàññèâó MakeLoopBodyBegin(Ctx); // òåëî öèêëà Ctx.IL.Write(TIL.IL_DecRef(Ctx.ItemExpr)); // êîíåö öèêëà MakeLoopBodyEnd(Ctx); end; procedure TSYSTEMUnit.CreateFinalArrayOfObjProc; var Param: TIDVariable; Ctx: TLoopCodeContext; begin FFinalArrayOfObjProc := CreateArraySysProc(FSysTObjDynArray, FSysTObjDynArray.Name + '$final', Param); Ctx := TLoopCodeContext.Create(FFinalArrayOfObjProc, Param); // ãåíåðèðóåì êîä öèêëà ïðîõîäà ïî ìàññèâó MakeLoopBodyBegin(Ctx); // òåëî öèêëà Ctx.IL.Write(TIL.IL_DecRef(Ctx.ItemExpr)); // êîíåö öèêëà MakeLoopBodyEnd(Ctx); end; procedure TSYSTEMUnit.CreateSystemRoutins; begin RegisterSystemCTBuiltinFunctions; RegisterSystemRTBuiltinFunctions; CreateSystemRoutinsTypes; CreateCopyArrayOfObjProc; CreateCopyArrayOfStrProc; CreateFinalArrayOfObjProc; CreateFinalArrayOfStrProc; CreateFinalArrayOfVarProc; CreateAsserProc; end; procedure TSYSTEMUnit.CreateSystemRoutinsTypes; begin FSysTStrDynArray := TIDDynArray.CreateAsSystem(ImplSection, '$TStrDynArray'); FSysTStrDynArray.ElementDataType := _String; AddType(FSysTStrDynArray); FSysTObjDynArray := TIDDynArray.CreateAsSystem(ImplSection, '$TObjDynArray'); FSysTObjDynArray.ElementDataType := _TObject; AddType(FSysTObjDynArray); FSysTVarDynArray := TIDDynArray.CreateAsSystem(ImplSection, '$TVarDynArray'); FSysTVarDynArray.ElementDataType := _Variant; AddType(FSysTVarDynArray); end; procedure TSYSTEMUnit.InsertToScope(Declaration: TIDDeclaration); begin if Assigned(IntfSection.InsertNode(Declaration.Name, Declaration)) then raise Exception.CreateFmt('Unit SYSTEM: ' + msgIdentifierRedeclaredFmt, [Declaration.Name]); end; function TSYSTEMUnit.CompileIntfOnly: TCompilerResult; begin Result := Compile(); end; function TSYSTEMUnit.RegisterTypeAlias(const TypeName: string; OriginalType: TIDType): TIDAliasType; begin Result := TIDAliasType.CreateAliasAsSystem(IntfSection, TypeName, OriginalType); Result.Elementary := True; InsertToScope(Result); AddType(Result); end; function TSYSTEMUnit.RegisterConstInt(const Name: string; DataType: TIDType; Value: Int64): TIDIntConstant; begin Result := TIDIntConstant.CreateAsSystem(IntfSection, Name); Result.DataType := DataType; Result.Value := Value; InsertToScope(Result); end; initialization _Void := TIDType.CreateAsSystem(nil, 'Void'); _Void.DataTypeID := TDataTypeID(dtUnknown); _MetaType := TIDType.CreateAsSystem(nil, 'MetaType'); _MetaType.DataTypeID := dtClass; finalization end.
unit IdNNTPServer; interface uses Classes, IdGlobal, IdTCPServer; const KnownCommands: array[1..26] of string = ('ARTICLE', 'BODY', 'HEAD', 'STAT', 'GROUP', 'LIST', 'HELP', 'IHAVE', 'LAST', 'NEWGROUPS', 'NEWNEWS', 'NEXT', 'POST', 'QUIT', 'SLAVE', 'AUTHINFO', 'XOVER', 'XHDR', 'DATE', {returns "111 YYYYMMDDHHNNSS"} 'LISTGROUP', {returns all the article numbers for specified group} 'MODE', {for the MODE command} 'TAKETHIS', {streaming nntp} 'CHECK', {streaming nntp need this to go with takethis} 'XTHREAD', {Useful mainly for the TRN newsreader } 'XGTITLE', {legacy support} 'XPAT' {Header Pattern matching} ); type TGetEvent = procedure(AThread: TIdPeerThread) of object; TOtherEvent = procedure(AThread: TIdPeerThread; ACommand: string; AParm: string; var AHandled: Boolean) of object; TDoByIDEvent = procedure(AThread: TIdPeerThread; AActualID: string) of object; TDoByNoEvent = procedure(AThread: TIdPeerThread; AActualNumber: Cardinal) of object; TGroupEvent = procedure(AThread: TIdPeerThread; AGroup: string) of object; TNewsEvent = procedure(AThread: TIdPeerThread; AParm: string) of object; TDataEvent = procedure(AThread: TIdPeerThread; AData: TObject) of object; TIdNNTPServer = class(TIdTCPServer) protected fOnCommandAuthInfo: TOtherEvent; fOnCommandArticleID: TDoByIDEvent; fOnCommandArticleNO: TDoByNoEvent; fOnCommandBodyID: TDoByIDEvent; fOnCommandBodyNO: TDoByNoEvent; fOnCommandHeadID: TDoByIDEvent; fOnCommandHeadNO: TDoByNoEvent; fOnCommandStatID: TDoByIDEvent; fOnCommandStatNO: TDoByNoEvent; fOnCommandGroup: TGroupEvent; fOnCommandList: TNewsEvent; fOnCommandHelp: TGetEvent; fOnCommandIHave: TDoByIDEvent; fOnCommandLast: TGetEvent; fOnCommandMode: TNewsEvent; fOnCommandNewGroups: TNewsEvent; fOnCommandNewNews: TNewsEvent; fOnCommandNext: TGetEvent; fOnCommandPost: TGetEvent; fOnCommandQuit: TGetEvent; fOnCommandSlave: TGetEvent; fOnCommandXOver: TNewsEvent; fOnCommandXHDR: TNewsEvent; fOnCommandDate: TGetEvent; fOnCommandListgroup: TNewsEvent; fOnCommandTakeThis: TDoByIDEvent; fOnCommandCheck: TDoByIDEvent; fOnCommandXThread: TNewsEvent; fOnCommandXGTitle: TNewsEvent; fOnCommandXPat: TNewsEvent; fOnCommandOther: TOtherEvent; // function DoExecute(AThread: TIdPeerThread): boolean; override; public constructor Create(AOwner: TComponent); override; published property OnCommandAuthInfo: TOtherEvent read fOnCommandAuthInfo write fOnCommandAuthInfo; property OnCommandArticleID: TDoByIDEvent read fOnCommandArticleID write fOnCommandArticleID; property OnCommandArticleNo: TDoByNoEvent read fOnCommandArticleNo write fOnCommandArticleNo; property OnCommandBodyID: TDoByIDEvent read fOnCommandBodyID write fOnCommandBodyID; property OnCommandBodyNo: TDoByNoEvent read fOnCommandBodyNo write fOnCommandBodyNo; property OnCommandCheck: TDoByIDEvent read fOnCommandCheck write fOnCommandCheck; property OnCommandHeadID: TDoByIDEvent read fOnCommandHeadID write fOnCommandHeadID; property OnCommandHeadNo: TDoByNoEvent read fOnCommandHeadNo write fOnCommandHeadNo; property OnCommandStatID: TDoByIDEvent read fOnCommandStatID write fOnCommandStatID; property OnCommandStatNo: TDoByNoEvent read fOnCommandStatNo write fOnCommandStatNo; property OnCommandGroup: TGroupEvent read fOnCommandGroup write fOnCommandGroup; property OnCommandList: TNewsEvent read fOnCommandList write fOnCommandList; property OnCommandHelp: TGetEvent read fOnCommandHelp write fOnCommandHelp; property OnCommandIHave: TDoByIDEvent read fOnCommandIHave write fOnCommandIHave; property OnCommandLast: TGetEvent read fOnCommandLast write fOnCommandLast; property OnCommandMode: TNewsEvent read fOnCommandMode write fOnCommandMode; property OnCommandNewGroups: TNewsEvent read fOnCommandNewGroups write fOnCommandNewGroups; property OnCommandNewNews: TNewsEvent read fOnCommandNewNews write fOnCommandNewNews; property OnCommandNext: TGetEvent read fOnCommandNext write fOnCommandNext; property OnCommandPost: TGetEvent read fOnCommandPost write fOnCommandPost; property OnCommandQuit: TGetEvent read fOnCommandQuit write fOnCommandQuit; property OnCommandSlave: TGetEvent read fOnCommandSlave write fOnCommandSlave; property OnCommandTakeThis: TDoByIDEvent read fOnCommandTakeThis write fOnCommandTakeThis; property OnCommandXOver: TNewsEvent read fOnCommandXOver write fOnCommandXOver; property OnCommandXHDR: TNewsEvent read fOnCommandXHDR write fOnCommandXHDR; property OnCommandDate: TGetEvent read fOnCommandDate write fOnCommandDate; property OnCommandListgroup: TNewsEvent read fOnCommandListGroup write fOnCommandListGroup; property OnCommandXThread: TNewsEvent read fOnCommandXThread write fOnCommandXThread; property OnCommandXGTitle: TNewsEvent read fOnCommandXGTitle write fOnCommandXGTitle; property OnCommandXPat: TNewsEvent read fOnCommandXPat write fOnCommandXPat; property OnCommandOther: TOtherEvent read fOnCommandOther write fOnCommandOther; property DefaultPort default IdPORT_NNTP; end; implementation uses IdTCPConnection, IdResourceStrings, SysUtils; constructor TIdNNTPServer.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultPort := IdPORT_NNTP; end; function TIdNNTPServer.DoExecute(AThread: TIdPeerThread): boolean; var i: integer; s, sCmd: string; WasHandled: Boolean; procedure NotHandled(CMD: string); begin AThread.Connection.Writeln('500 ' + Format(RSNNTPServerNotRecognized, [CMD])); end; function isNumericString(Str: string): Boolean; begin if Length(str) = 0 then Result := False else Result := IsNumeric(Str[1]); end; begin result := true; with AThread.Connection do begin while Connected do begin try s := ReadLn; except exit; end; sCmd := Fetch(s, ' '); i := Succ(PosInStrArray(UpperCase(sCmd), KnownCommands)); case i of 1: {article} if isNumericString(s) then begin if Assigned(OnCommandArticleNo) then OnCommandArticleNo(AThread, StrToCard(S)) else NotHandled(sCmd); end else begin if Assigned(OnCommandArticleID) then OnCommandArticleID(AThread, S) else NotHandled(sCmd); end; 2: {body} if isNumericString(s) then begin if assigned(OnCommandBodyNo) then OnCommandBodyNo(AThread, StrToCard(S)) else NotHandled(sCmd); end else begin if assigned(OnCommandBodyID) then OnCommandBodyID(AThread, S) else NotHandled(sCmd); end; 3: {head} if isNumericString(s) then begin if assigned(OnCommandHeadNo) then OnCommandHeadNo(AThread, StrToCard(S)) else NotHandled(sCmd); end else begin if assigned(OnCommandHeadID) then OnCommandHeadID(AThread, S) else NotHandled(sCmd); end; 4: {stat} if isNumericString(s) then begin if assigned(OnCommandStatNo) then OnCommandStatNo(AThread, StrToCard(S)) else NotHandled(sCmd); end else begin if assigned(OnCommandStatID) then OnCommandStatID(AThread, S) else NotHandled(sCmd); end; 5: {group} if assigned(OnCommandGroup) then OnCommandGroup(AThread, S) else NotHandled(sCmd); 6: {list} if assigned(OnCommandList) then OnCommandList(AThread, S) else NotHandled(sCmd); 7: {help} if assigned(OnCommandHelp) then OnCommandHelp(AThread) else NotHandled(sCmd); 8: {ihave} if assigned(OnCommandIHave) then OnCommandIHave(AThread, S) else NotHandled(sCmd); 9: {last} if assigned(OnCommandLast) then OnCommandLast(AThread) else NotHandled(sCmd); 10: {newgroups} if assigned(OnCommandNewGroups) then OnCommandNewGroups(AThread, S) else NotHandled(sCmd); 11: {newsgroups} if assigned(OnCommandNewNews) then OnCommandNewNews(AThread, S) else NotHandled(sCmd); 12: {next} if assigned(OnCommandNext) then OnCommandNext(AThread) else NotHandled(sCmd); 13: {post} if assigned(OnCommandPost) then OnCommandPost(AThread) else NotHandled(sCmd); 14: {quit} begin if assigned(OnCommandQuit) then OnCommandQuit(AThread) else AThread.Connection.WriteLn('205 ' + RSNNTPServerGoodBye); AThread.Connection.Disconnect; end; 15: {slave} if assigned(OnCommandSlave) then OnCommandSlave(AThread) else NotHandled(sCmd); 16: {authinfo} if assigned(OnCommandAuthInfo) then begin sCmd := UpperCase(Fetch(s, ' ')); WasHandled := False; OnCommandAuthInfo(AThread, SCmd, S, WasHandled); if not WasHandled then NotHandled(sCmd); end else NotHandled(sCmd); 17: {xover} if assigned(OnCommandXOver) then OnCommandXOver(AThread, S) else NotHandled(sCmd); 18: {xhdr} if assigned(OnCommandXHDR) then OnCommandXHDR(AThread, S) else NotHandled(sCmd); 19: {date} if assigned(OnCommandDate) then OnCommandDate(AThread) else NotHandled(sCmd); 20: {listgroup} if assigned(OnCommandListGroup) then OnCommandListGroup(AThread, S) else NotHandled(sCmd); 21: {mode} if assigned(OnCommandMode) then OnCommandMode(AThread, S) else NotHandled(sCmd); 22: {takethis} if assigned(OnCommandTakeThis) then OnCommandTakeThis(AThread, S) else NotHandled(sCmd); 23: {check} if assigned(OnCommandCheck) then OnCommandCheck(AThread, S) else NotHandled(sCmd); 24: {XThread} if assigned(OnCommandXThread) then OnCommandXThread(AThread, S) else NotHandled(sCmd); 25: {XGTitle} if assigned(OnCommandXGTitle) then OnCommandXGTitle(AThread, S) else NotHandled(sCmd); else begin if assigned(OnCommandOther) then begin WasHandled := False; OnCommandOther(AThread, sCmd, S, WasHandled); if not WasHandled then NotHandled(sCmd); end else NotHandled(sCmd); end; end; end; end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Vcl.Touch.Keyboard; interface uses Vcl.Touch.KeyboardTypes, System.Generics.Collections, Vcl.Controls, System.Classes, Winapi.Messages, Winapi.Windows, Vcl.ExtCtrls, Vcl.Graphics, System.Types; type TCustomTouchKeyboard = class; TCustomKeyboardButton = class public type {$SCOPEDENUMS ON} TDrawState = (dsNormal, dsPressed, dsDisabled); {$SCOPEDENUMS OFF} strict private FCaption: string; FState: TDrawState; FKey: TVirtualKey; FModifier: Boolean; FDown: Boolean; FID: Integer; FKeyImage: TKeyImage; private FBottomMargin: Integer; FTopMargin: Integer; FLeft: Integer; FTop: Integer; FHeight: Integer; FWidth: Integer; FParent: TCustomTouchKeyboard; procedure SetCaption(const Value: string); private procedure SetState(const Value: TDrawState; Delay: Boolean); function GetBoundsRect: TRect; procedure SetBoundsRect(const Value: TRect); function GetClientRect: TRect; public constructor Create(const AKey: TVirtualKey); procedure Paint(Canvas: TCustomCanvas = nil); virtual; property BottomMargin: Integer read FBottomMargin; property BoundsRect: TRect read GetBoundsRect write SetBoundsRect; property Caption: string read FCaption write SetCaption; property ClientRect: TRect read GetClientRect; property Down: Boolean read FDown write FDown; property Height: Integer read FHeight; property ID: Integer read FID write FID; property Key: TVirtualKey read FKey; property KeyImage: TKeyImage read FKeyImage write FKeyImage; property Left: Integer read FLeft; property Modifier: Boolean read FModifier write FModifier; property Parent: TCustomTouchKeyboard read FParent; property State: TDrawState read FState; property Top: Integer read FTop; property TopMargin: Integer read FTopMargin; property Width: Integer read FWidth; end; TKeyboardButton = class(TCustomKeyboardButton); TButtonList = class(TList<TCustomKeyboardButton>); TCustomKeyboardButtonClass = class of TCustomKeyboardButton; TKeyCaptions = class sealed public type TKeyCaption = record Name, Value, Language: string; end; TKeyCaptionArray = array of TKeyCaption; function KeyCaption(const AName, AValue, ALanguage: string): TKeyCaption; private FItems: TKeyCaptionArray; function GetCount: Integer; function GetItems(const Index: Integer): TKeyCaption; procedure SetItems(const Index: Integer; const Value: TKeyCaption); public function HasCaption(const AName: string; const ALanguage: string = ''): Boolean; procedure Clear; procedure Add(const AName, AValue: string; const ALanguage: string = ''); procedure Delete(const AName: string; const ALanguage: string = ''); function GetCaption(const AName: string; const ALanguage: string = ''): string; procedure SetCaption(const AName, AValue: string; const ALanguage: string = ''); property Count: Integer read GetCount; property Items[const Index: Integer]: TKeyCaption read GetItems write SetItems; default; end; TKeyboardLayouts = class sealed strict private class var FKeyboardLayouts: TVirtualKeyLayouts; private class constructor Create; class destructor Destroy; class function GetLayoutNames: TStringDynArray; static; class function GetCount: Integer; static; class function Find(const Layout, Language: string): TVirtualKeyLayout; overload; class function Find(const Layout: string): TVirtualKeyLayout; overload; class property Layouts: TVirtualKeyLayouts read FKeyboardLayouts; public class procedure LoadFromResourceName(const ResourceName: string); class procedure LoadFromStream(Stream: TStream); class property Count: Integer read GetCount; class property LayoutNames: TStringDynArray read GetLayoutNames; end; TCustomTouchKeyboard = class(TCustomControl) strict private type TChangeState = record Button: TCustomKeyboardButton; State: TCustomKeyboardButton.TDrawState; class function ChangeState(AButton: TCustomKeyboardButton; const AState: TCustomKeyboardButton.TDrawState): TChangeState; static; end; TChangeStates = class(TList<TChangeState>); public type {$SCOPEDENUMS ON} TDrawingStyle = (dsNormal, dsGradient); {$SCOPEDENUMS OFF} private FLayout: TKeyboardLayout; FCurrentLayout: TVirtualKeyLayout; FKeyCaptions: TKeyCaptions; FInitialized: Boolean; FLanguage: string; FChangeTimer: TTimer; FRepeat: TTimer; FRepeatDelay: Cardinal; FRepeatRate: Cardinal; FGradientEnd: TColor; FGradientStart: TColor; FDefaultButtonClass: TCustomKeyboardButtonClass; FChangeStates: TChangeStates; FDeadKey: TKeyData; FButtons: TButtonList; FUnclick: TButtonList; // Keys that apply modifications to the current key. FPressedKeys: TButtonList; // Keys that are currently held down. FDeadKeyUnclick: TButtonList; // Modification keys that apply to dead keys. FDrawingStyle: TDrawingStyle; procedure ToggleKeys(AButton: TCustomKeyboardButton; KeyState: TKeyState; Immediate: Boolean = False); procedure Initialize; procedure OnRepeat(Sender: TObject); procedure OnChange(Sender: TObject); procedure KeyClick(Button: TCustomKeyboardButton); function GetShiftState(const VirtualKey: TVirtualKey): TModifierState; procedure ProcessKeyPress(const Msg: TWmMouse; ID: Integer); function GetModifiedKey(const Key: TVirtualKey; const Language: string): TKey; function GetLanguageKey(const Key: TVirtualKey; const Language: string): TVirtualKey; procedure SetLayout(const Value: TKeyboardLayout); procedure ReadCustomCaptionOverrides(Stream: TStream); procedure WriteCustomCaptionOverrides(Stream: TStream); procedure AddChangeState(Button: TCustomKeyboardButton; const State: TCustomKeyboardButton.TDrawState); function GetOverrideCaption(const Key: TVirtualKey; var Caption: string): Boolean; procedure SetGradientEnd(const Value: TColor); procedure SetGradientStart(const Value: TColor); function GetPrimaryLanguage(const Language: string): string; function GetCurrentInputLanguage: string; procedure WMInputLangChange(var Message: TMessage); message CM_INPUTLANGCHANGE; procedure WMTouch(var Message: TMessage); message WM_TOUCH; function GetButtons(Index: Integer): TCustomKeyboardButton; procedure SetDrawingStyle(const Value: TDrawingStyle); protected procedure Paint; override; procedure Resize; override; procedure SetEnabled(Value: Boolean); override; function GetPropertyNames: TStringDynArray; procedure WndProc(var Message: TMessage); override; procedure CreateWnd; override; procedure DefineProperties(Filer: TFiler); override; function CreateKeyboard(const Language: string = ''): Boolean; procedure Loaded; override; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; property Buttons[Index: Integer]: TCustomKeyboardButton read GetButtons; function ButtonsCount: Integer; procedure ClearState; procedure UpdateCaptions; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Redraw; property CaptionOverrides: TKeyCaptions read FKeyCaptions; property DefaultButtonClass: TCustomKeyboardButtonClass read FDefaultButtonClass write FDefaultButtonClass; public property DrawingStyle: TDrawingStyle read FDrawingStyle write SetDrawingStyle default TDrawingStyle.dsNormal; property GradientEnd: TColor read FGradientEnd write SetGradientEnd default clDkGray; property GradientStart: TColor read FGradientStart write SetGradientStart default clLtGray; property Layout: TKeyboardLayout read FLayout write SetLayout; property RepeatRate: Cardinal read FRepeatRate write FRepeatRate default 50; property RepeatDelay: Cardinal read FRepeatDelay write FRepeatDelay default 300; end; TTouchKeyboard = class(TCustomTouchKeyboard) published property Anchors; property Align; property Color; property DrawingStyle; property Enabled; property GradientEnd; property GradientStart; property Height; property Left; property Layout; property ParentColor; property ParentShowHint; property RepeatRate; property RepeatDelay; property ShowHint; property Top; property Tag; property Width; property Visible; end; procedure SendKeys(const Keys: array of TKeyData); overload; procedure SendKeys(const Keys: array of TKeyData; KeyState: TKeyState); overload; procedure SendKey(const Key: TKeyData; KeyState: TKeyState); implementation uses System.SysUtils, Vcl.GraphUtil, Winapi.UxTheme, Vcl.Consts; {$R KeyboardLayouts.res} type TState = class(TList<TKeyData>); var GlobalKeyboardLayouts: TVirtualKeyLayouts; procedure SendKeys(const Keys: array of TKeyData); function GetState(const Key: TKeyData; State: TState): Integer; var Index: Integer; begin Result := 0; for Index := 0 to State.Count - 1 do begin if (State[Index].Vk = Key.Vk) and (State[Index].ScanCode = Key.ScanCode) then begin Result := KEYEVENTF_KEYUP; State.Delete(Index); Break; end; end; end; var Index: Integer; State: TState; Key: TKeyData; begin State := TState.Create; try for Index := 0 to Length(Keys) - 1 do begin Key := Keys[Index]; if GetState(Key, State) = 0 then begin SendKey(Key, ksDown); State.Add(Key); end else SendKey(Key, ksUp); end; finally State.Free; end; end; procedure SendKeys(const Keys: array of TKeyData; KeyState: TKeyState); var Index: Integer; Key: TKeyData; begin for Index := 0 to Length(Keys) - 1 do begin Key := Keys[Index]; SendKey(Key, KeyState); end; end; procedure SendKey(const Key: TKeyData; KeyState: TKeyState); var KeyFlag: Integer; LKey: TKeyData; Msg: UINT; begin LKey := GetVirtualKey(Key); case LKey.Vk of VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN: begin if KeyState = ksDown then Msg := WM_KEYDOWN else Msg := WM_KEYUP; SendMessage(GetFocus, Msg, LKey.Vk, 0); end else begin if KeyState = ksDown then KeyFlag := 0 else KeyFlag := KEYEVENTF_KEYUP; keybd_event(LKey.Vk, LKey.ScanCode, KeyFlag, 0); end; end; end; procedure PlayKey(const Key: TKey; KeyState: TKeyState); begin if Length(Key.ComboKeys) > 0 then SendKeys(Key.ComboKeys, KeyState) else SendKey(Key, KeyState); end; function TouchInputToWmMouse(Control: TWinControl; const TouchInput: TouchInput): TWMMouse; var P: TPoint; begin Result.Msg := WM_NULL; if (TouchInput.dwFlags and TOUCHEVENTF_DOWN <> 0) then Result.Msg := WM_LBUTTONDOWN else if (TouchInput.dwFlags and TOUCHEVENTF_UP <> 0) then Result.Msg := WM_LBUTTONUP else if (TouchInput.dwFlags and TOUCHEVENTF_MOVE <> 0) then Result.Msg := WM_MOUSEMOVE; P := Point(TouchInput.X div 100, TouchInput.Y div 100); PhysicalToLogicalPoint(Control.Handle, P); Result.Pos := PointToSmallPoint(Control.ScreenToClient(P)); end; { TCustomKeyboardButton } function TCustomKeyboardButton.GetBoundsRect: TRect; begin Result.Left := Left; Result.Top := Top; Result.Right := Left + Width; Result.Bottom := Top + Height; end; function TCustomKeyboardButton.GetClientRect: TRect; begin Result.Left := Left + Key.LeftMargin; Result.Top := Top + TopMargin; Result.Right := Left + Width - Key.RightMargin; Result.Bottom := Top + Height - BottomMargin; end; constructor TCustomKeyboardButton.Create(const AKey: TVirtualKey); begin inherited Create; FState := TDrawState.dsNormal; FHeight := 45; FWidth := 45; FModifier := False; FID := -1; FKey := AKey; FKeyImage := AKey.KeyImage; end; procedure TCustomKeyboardButton.Paint(Canvas: TCustomCanvas); const ICON_TOP_OFFSET = 8; ICON_LEFT_OFFSET = 4; procedure PaintTab(Canvas: TCustomCanvas; Rect: TRect); const ICON_WIDTH = 36; ICON_HEIGHT = 12; begin // Top line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_TOP_OFFSET); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_TOP_OFFSET); // Top vertical line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_TOP_OFFSET - 5); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_TOP_OFFSET + 5); // Top arrow Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_TOP_OFFSET - 1); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_TOP_OFFSET + 2); Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 3, Rect.Top + ICON_TOP_OFFSET - 2); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 3, Rect.Top + ICON_TOP_OFFSET + 3); // Bottom line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH + 1, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT); // Bottom vertical line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT - 5); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT + 5); // Bottom arrow Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH - 2, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT - 1); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH - 2, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT + 2); Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH - 3, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT - 2); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH - 3, Rect.Top + ICON_TOP_OFFSET + ICON_HEIGHT + 3); end; procedure PaintEnter(Canvas: TCustomCanvas; Rect: TRect); const ICON_WIDTH = 36; ICON_HEIGHT = 12; begin // Horizontal line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT - 6); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT + 1); // Vertical line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_HEIGHT); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT); // Arrow Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_HEIGHT - 1); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_HEIGHT + 2); Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_HEIGHT - 2); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_HEIGHT + 3); end; procedure PaintTallEnter(Canvas: TCustomCanvas; Rect: TRect); const ICON_WIDTH = 24; ICON_HEIGHT = 12; begin // Horizontal line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT - 6); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT + 1); // Vertical line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_HEIGHT); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_HEIGHT); // Arrow Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_HEIGHT - 1); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_HEIGHT + 2); Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_HEIGHT - 2); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_HEIGHT + 3); end; procedure PaintBackspace(Canvas: TCustomCanvas; Rect: TRect); const ICON_WIDTH = 24; ICON_HEIGHT = 24; begin // Vertical line Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + ICON_TOP_OFFSET); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + ICON_WIDTH, Rect.Top + ICON_TOP_OFFSET); // Arrow Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_TOP_OFFSET - 1); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 1, Rect.Top + ICON_TOP_OFFSET + 2); Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_TOP_OFFSET - 2); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 2, Rect.Top + ICON_TOP_OFFSET + 3); end; procedure PaintShift(Canvas: TCustomCanvas; Rect: TRect); begin Canvas.MoveTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + 4 + 12); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 10, Rect.Top + 6); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 20, Rect.Top + 4 + 12); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 14, Rect.Top + 4 + 12); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 14, Rect.Top + 4 + 18); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 6, Rect.Top + 4 + 18); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET + 6, Rect.Top + 4 + 12); Canvas.LineTo(Rect.Left + ICON_LEFT_OFFSET, Rect.Top + 4 + 12); end; procedure PaintArrow(Canvas: TCustomCanvas; Rect: TRect; Direction: TKeyImage); const ICON_WIDTH = 8; ICON_HEIGHT = 8; var X, Y: Integer; begin X := (Rect.Left + Rect.Right) div 2; Y := (Rect.Top + Rect.Bottom) div 2; case Direction of kiUp: begin // Vertical line Canvas.MoveTo(X, Y - ICON_HEIGHT); Canvas.LineTo(X, Y + ICON_HEIGHT); // Arrow Canvas.MoveTo(X - 1, Y - 7); Canvas.LineTo(X + 2, Y - 7); Canvas.MoveTo(X - 2, Y - 6); Canvas.LineTo(X + 3, Y - 6); end; kiDown: begin // Vertical line Canvas.MoveTo(X, Y - ICON_HEIGHT); Canvas.LineTo(X, Y + ICON_HEIGHT); // Arrow Canvas.MoveTo(X - 1, Y + 6); Canvas.LineTo(X + 2, Y + 6); Canvas.MoveTo(X - 2, Y + 5); Canvas.LineTo(X + 3, Y + 5); end; kiLeft: begin // Vertical line Canvas.MoveTo(X - ICON_WIDTH, Y); Canvas.LineTo(X + ICON_WIDTH, Y); // Arrow Canvas.MoveTo(X - 6, Y - 1); Canvas.LineTo(X - 6, Y + 2); Canvas.MoveTo(X - 5, Y - 2); Canvas.LineTo(X - 5, Y + 3); end; kiRight: begin // Vertical line Canvas.MoveTo(X - ICON_WIDTH, Y); Canvas.LineTo(X + ICON_WIDTH, Y); // Arrow Canvas.MoveTo(X + 6, Y - 1); Canvas.LineTo(X + 6, Y + 2); Canvas.MoveTo(X + 5, Y - 2); Canvas.LineTo(X + 5, Y + 3); end; end; end; function GetModifier(const Key: TVirtualKey; var Value: TKeyModifier): Boolean; var Index, UnclickIndex: Integer; Modifier: TKeyModifier; begin Result := False; if FParent = nil then Exit; for Index := 0 to Length(Key.Modifiers) - 1 do begin Modifier := Key.Modifiers[Index]; for UnclickIndex := 0 to FParent.FUnclick.Count - 1 do begin if Modifier.ModifierName = Fparent.FUnclick[UnclickIndex].Key.ModifierName then begin Value := Modifier; Result := True; Break; end; end; end; end; const Rounding = 5; OuterEdgeColors: array[TDrawState] of TColor = (clBlack, clCream, clCream); InnerEdgeColors: array[TDrawState] of TColor = (clGray, clDkGray, clGray); BkStartColors: array[TDrawState] of TColor = (clDkGray, clCream, clGray); BkEndColors: array[TDrawState] of TColor = (clBlack, clLtGray, clCream); TextColors: array[TDrawState] of TColor = (clWhite, clBlack, clGray); var LRgn: HRGN; LRect: TRect; LCanvas: TCanvas; LCaption: string; Modifier: TKeyModifier; begin if Canvas <> nil then LCanvas := Canvas as TCanvas else LCanvas := Parent.Canvas; LRect := ClientRect; Inc(LRect.Right, 1); Inc(LRect.Bottom, 1); LRgn := CreateRoundRectRgn(LRect.Left, LRect.Top, LRect.Right, LRect.Bottom, Rounding, Rounding); if LRgn = 0 then Exit; try if SelectClipRgn(LCanvas.Handle, LRgn) = ERROR then Exit; try GradientFillCanvas(LCanvas, BkStartColors[FState], BkEndColors[FState], LRect, gdVertical); LCanvas.Brush.Style := bsClear; LCanvas.Pen.Color := OuterEdgeColors[FState]; Dec(LRect.Right, 1); Dec(LRect.Bottom, 1); LCanvas.RoundRect(LRect, Rounding, Rounding); LCanvas.Pen.Color := InnerEdgeColors[FState]; LCanvas.Brush.Style := bsClear; InflateRect(LRect, -1, -1); LCanvas.RoundRect(LRect, Rounding - 1, Rounding - 1); LCanvas.Pen.Color := TextColors[FState]; LCanvas.Font.Color := TextColors[FState]; if GetModifier(Key, Modifier) then LCanvas.Font.Size := Modifier.FontSize else LCanvas.Font.Size := Key.FontSize; case KeyImage of kiOverride: begin if not Parent.GetOverrideCaption(Key, LCaption) then LCaption := Caption; LCanvas.TextOut(LRect.Left + 4, LRect.Top + 4, LCaption); end; kiText: LCanvas.TextOut(LRect.Left + 4, LRect.Top + 4, Caption); kiTab: PaintTab(LCanvas, LRect); kiShift: PaintShift(LCanvas, LRect); kiEnter: PaintEnter(LCanvas, LRect); kiBackspace: PaintBackspace(LCanvas, LRect); kiUp, kiDown,kiLeft, kiRight: PaintArrow(LCanvas, LRect, KeyImage); kiTallEnter: PaintTallEnter(LCanvas, LRect); end; finally SelectClipRgn(LCanvas.Handle, 0); end; finally DeleteObject(LRgn); end; end; procedure TCustomKeyboardButton.SetBoundsRect(const Value: TRect); begin FTop := Value.Top; FLeft := Value.Left; FWidth := Value.Right; FHeight := Value.Bottom; end; procedure TCustomKeyboardButton.SetCaption(const Value: string); begin if Value <> FCaption then FCaption := Value; end; procedure TCustomKeyboardButton.SetState(const Value: TDrawState; Delay: Boolean); begin case Value of TDrawState.dsNormal: begin if Delay and (Parent <> nil) then Parent.AddChangeState(Self, Value) else FState := Value; end; TDrawState.dsPressed, TDrawState.dsDisabled: FState := Value; end; end; { TCustomTouchKeyboard } procedure TCustomTouchKeyboard.AddChangeState(Button: TCustomKeyboardButton; const State: TCustomKeyboardButton.TDrawState); begin FChangeStates.Add(TChangeState.ChangeState(Button, State)); FChangeTimer.Enabled := True; end; function TCustomTouchKeyboard.ButtonsCount: Integer; begin Result := FButtons.Count; end; procedure TCustomTouchKeyboard.ClearState; var Index: Integer; Button: TCustomKeyboardButton; begin FDeadKey := VKey(-1, -1); FUnclick.Clear; FDeadKeyUnclick.Clear; for Index := 0 to FPressedKeys.Count - 1 do begin Button := FPressedKeys[Index]; Button.Down := False; Button.SetState(TCustomKeyboardButton.TDrawState.dsNormal, False); if Button.Modifier then PlayKey(GetLanguageKey(Button.Key, FLanguage), ksUp); end; FPressedKeys.Clear; end; constructor TCustomTouchKeyboard.Create(AOwner: TComponent); begin inherited; FRepeatDelay := 300; FRepeatRate := 50; FLayout := 'Standard'; FUnclick := TButtonList.Create; FPressedKeys := TButtonList.Create; FDeadKeyUnclick := TButtonList.Create; FButtons := TButtonList.Create; FDeadKey := VKey(-1, -1); BevelOuter := bvNone; FInitialized := False; FRepeat := TTimer.Create(Self); FRepeat.Enabled := False; FRepeat.OnTimer := OnRepeat; FLanguage := GetCurrentInputLanguage; DoubleBuffered := False; ParentDoubleBuffered := False; Touch.TabletOptions := []; FDefaultButtonClass := TKeyboardButton; FKeyCaptions := TKeyCaptions.Create; FChangeStates := TChangeStates.Create; FChangeTimer := TTimer.Create(Self); FChangeTimer.Enabled := False; FChangeTimer.OnTimer := OnChange; FChangeTimer.Interval := 100; FGradientEnd := clLtGray; FGradientStart := clDkGray; ControlStyle := ControlStyle - [csGestures]; FDrawingStyle := TDrawingStyle.dsNormal; end; procedure TCustomTouchKeyboard.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('CustomCaptionOverrides', ReadCustomCaptionOverrides, WriteCustomCaptionOverrides, CaptionOverrides.Count > 0); // do not localize end; function TCustomTouchKeyboard.CreateKeyboard(const Language: string): Boolean; var Index, RowIndex, ColIndex: Integer; Button: TCustomKeyboardButton; LeftPosition, TopPosition: Integer; KeyboardState: TKeyboardState; KeyboardLayout: TVirtualKeyLayout; Row: TVirtualKeys; FoundCaps: Boolean; begin Result := False; FoundCaps := False; for Index := 0 to FButtons.Count - 1 do FButtons[Index].Free; FButtons.Clear; FDeadKey := VKey(-1, -1); TopPosition := 0; if Language <> '' then FLanguage := Language; KeyboardLayout := TKeyboardLayouts.Find(Layout, Language); if KeyboardLayout = nil then KeyboardLayout := TKeyboardLayouts.Find(Layout, GetPrimaryLanguage(Language)); if KeyboardLayout = nil then KeyboardLayout := TKeyboardLayouts.Find(Layout); if KeyboardLayout = nil then Exit; FCurrentLayout := KeyboardLayout; for RowIndex := 0 to KeyboardLayout.Keys.Count - 1 do begin LeftPosition := 0; Row := KeyboardLayout.Keys[RowIndex]; for ColIndex := 0 to Row.Count - 1 do begin Button := DefaultButtonClass.Create(Row[ColIndex]); Button.FParent := Self; Button.FTopMargin := Row.TopMargin; Button.FBottomMargin := Row.BottomMargin; Button.BoundsRect := Rect(LeftPosition, TopPosition, Button.Key.Width, Button.Key.Height); FButtons.Add(Button); if Button.Key.ModifierName <> '' then begin Button.Modifier := True; // Special case for Caps Lock where the state is checked. if ((Button.Key.Vk = VK_CAPITAL) or (Button.Key.ScanCode = 58)) then begin ZeroMemory(@KeyboardState[0], Length(KeyboardState)); GetKeyboardState(KeyboardState); if KeyboardState[VK_CAPITAL] = 1 then begin FoundCaps := True; Button.Down := True; Button.SetState(TCustomKeyboardButton.TDrawState.dsPressed, False); FPressedKeys.Add(Button); FUnclick.Add(Button); end; end; end; Inc(LeftPosition, Button.Width); end; Inc(TopPosition, KeyboardLayout.RowHeight); end; Constraints.MinWidth := KeyboardLayout.MinWidth; Constraints.MinHeight := KeyboardLayout.MinHeight; Constraints.MaxWidth := KeyboardLayout.MaxWidth; Constraints.MaxHeight := KeyboardLayout.MaxHeight; Resize; Result := True; if FoundCaps then UpdateCaptions; end; procedure TCustomTouchKeyboard.CreateWnd; begin inherited; if not (csLoading in ComponentState) then begin Initialize; CreateKeyboard(FLanguage); Redraw; end; end; destructor TCustomTouchKeyboard.Destroy; var Index: Integer; Button: TCustomKeyboardButton; begin for Index := 0 to FUnclick.Count - 1 do begin Button := FUnclick[Index]; case Button.Key.ScanCode of 29: SendKey(VKey(-1, 29), ksUp); 42: SendKey(VKey(-1, 42), ksUp); 56: SendKey(VKey(-1, 56), ksUp); else begin if Button.Key.Caption = 'AltGr' then begin SendKey(VKey(-1, 56), ksUp); SendKey(VKey(-1, 29), ksUp); end; end; end; end; FUnclick.Free; FPressedKeys.Free; FDeadKeyUnclick.Free; for Index := 0 to FButtons.Count - 1 do FButtons[Index].Free; FButtons.Free; FRepeat.Free; FKeyCaptions.Free; FChangeStates.Free; FChangeTimer.Free; inherited; end; procedure TCustomTouchKeyboard.SetDrawingStyle(const Value: TDrawingStyle); begin if Value <> FDrawingStyle then begin FDrawingStyle := Value; Invalidate; end; end; procedure TCustomTouchKeyboard.SetEnabled(Value: Boolean); var Index: Integer; DrawState: TCustomKeyboardButton.TDrawState; begin inherited; if Value then DrawState := TCustomKeyboardButton.TDrawState.dsNormal else DrawState := TCustomKeyboardButton.TDrawState.dsDisabled; for Index := 0 to FButtons.Count - 1 do FButtons[Index].SetState(DrawState, True); end; procedure TCustomTouchKeyboard.SetGradientEnd(const Value: TColor); begin FGradientEnd := Value; Invalidate; end; procedure TCustomTouchKeyboard.SetGradientStart(const Value: TColor); begin FGradientStart := Value; Invalidate; end; procedure TCustomTouchKeyboard.SetLayout(const Value: TKeyboardLayout); begin if FLayout <> Value then begin FLayout := Value; if not (csLoading in ComponentState) then begin CreateKeyboard(FLanguage); Redraw; end; end; end; function TCustomTouchKeyboard.GetButtons(Index: Integer): TCustomKeyboardButton; begin Result := FButtons[Index]; end; function TCustomTouchKeyboard.GetCurrentInputLanguage: string; var LocaleID: cardinal; Size: Integer; Success: Boolean; Layout: HKL; SubLanguage, PrimaryLanguage: string; begin Success := False; Layout := GetKeyboardLayout(0); LocaleID := LoWord(Layout); Size := GetLocaleInfo(LocaleID, LOCALE_SISO639LANGNAME, nil, 0); SetLength(PrimaryLanguage, Size); if GetLocaleInfo(LocaleID, LOCALE_SISO639LANGNAME, @PrimaryLanguage[1], Size) <> 0 then begin SetLength(PrimaryLanguage, Size - 1); Size := GetLocaleInfo(LocaleID, LOCALE_SISO3166CTRYNAME, nil, 0); SetLength(SubLanguage, Size); if GetLocaleInfo(LocaleID, LOCALE_SISO3166CTRYNAME, @SubLanguage[1], Size) <> 0 then begin SetLength(SubLanguage, Size - 1); Result := Format('%s-%s', [PrimaryLanguage, SubLanguage]); Success := True; end; end; if not Success then raise Exception.CreateRes(@SKeyboardLocaleInfo); end; // Returns a key that has taken all the modified keys, languages and // overrides into account. function TCustomTouchKeyboard.GetModifiedKey(const Key: TVirtualKey; const Language: string): TKey; function GetLanguageModifier(const Key: TVirtualKey; const Languages: TKeyLanguages; const Language: string; var Value: TKey): Boolean; var Index: Integer; KeyLanguage: TKeyLanguage; begin Result := False; for Index := 0 to Length(Languages) - 1 do begin KeyLanguage := Languages[Index]; if KeyLanguage.Language = Language then begin if KeyLanguage.Caption = '' then Value.Caption := Key.Caption else Value.Caption := KeyLanguage.Caption; if KeyLanguage.KeyImage <> kiText then Value.KeyImage := Key.KeyImage else Value.KeyImage := KeyLanguage.KeyImage; if Length(KeyLanguage.ComboKeys) > 0 then begin Value.ComboKeys := KeyLanguage.ComboKeys; Value.ScanCode := -1; Value.Vk := -1; end else begin if KeyLanguage.Vk <> -1 then Value.Vk := KeyLanguage.Vk else Value.Vk := Key.Vk; if KeyLanguage.ScanCode <> -1 then Value.ScanCode := KeyLanguage.ScanCode else Value.ScanCode := Key.ScanCode; end; Result := True; Break; end; end; end; function GetModifier(const Key: TVirtualKey; const Keys: TButtonList; Modifier: TKeyModifier; const Language: string; var Value: TKey): Boolean; var Index: Integer; begin Result := False; for Index := 0 to Keys.Count - 1 do begin if (Modifier.ModifierName = Keys[Index].Key.ModifierName) and ((Modifier.Language = '') or (Modifier.Language = FLanguage) or (Modifier.Language = GetPrimaryLanguage(FLanguage))) then begin if GetLanguageModifier(Key, Modifier.Languages, FLanguage, Value) or GetLanguageModifier(Key, Modifier.Languages, GetPrimaryLanguage(FLanguage), Value) then begin Result := True; Break; end; Value := Modifier; Result := True; Break; end; end; end; var Index: Integer; Modifier: TKeyModifier; LKey: TVirtualKey; begin LKey := GetLanguageKey(Key, Language); try for Index := 0 to Length(Key.Modifiers) - 1 do begin Modifier := LKey.Modifiers[Index]; if GetModifier(LKey, FUnclick, Modifier, Language, Result) then Exit; end; if GetLanguageModifier(LKey, Key.Languages, Language, Result) then Exit else if GetLanguageModifier(LKey, LKey.Languages, GetPrimaryLanguage(Language), Result) then Exit; Result := LKey; finally if (LKey.PublishedName <> '') and GetOverrideCaption(LKey, Result.Caption) then Result.KeyImage := kiOverride; end; end; function TCustomTouchKeyboard.GetLanguageKey(const Key: TVirtualKey; const Language: string): TVirtualKey; function InternalGetLanguageKey(var Key: TVirtualKey; const Language: string): Boolean; var Index: Integer; KeyLanguage: TKeyLanguage; begin Result := False; for Index := 0 to Length(Key.Languages) - 1 do begin KeyLanguage := Key.Languages[Index]; if KeyLanguage.Language = Language then begin if KeyLanguage.Caption <> '' then begin Key.Caption := KeyLanguage.Caption; KeyLanguage.KeyImage := kiText; end; if Length(KeyLanguage.ComboKeys) > 0 then begin Key.ComboKeys := KeyLanguage.ComboKeys; Key.Vk := -1; Key.ScanCode := -1; end else begin if KeyLanguage.Vk <> -1 then Key.Vk := KeyLanguage.Vk; if KeyLanguage.ScanCode <> -1 then Key.ScanCode := KeyLanguage.ScanCode; end; Result := True; Break; end; end; end; begin Result := Key; if not InternalGetLanguageKey(Result, Language) then InternalGetLanguageKey(Result, GetPrimaryLanguage(Language)); end; function TCustomTouchKeyboard.GetPrimaryLanguage(const Language: string): string; var P: PChar; begin Result := ''; P := @Language[1]; while P^ <> #0 do begin case P^ of '-': Break; end; Result := Result + P^; Inc(P); end; end; function TCustomTouchKeyboard.GetPropertyNames: TStringDynArray; var Index: Integer; Button: TCustomKeyboardButton; begin for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Key.PublishedName <> '' then begin SetLength(Result, Length(Result) + 1); Result[Length(Result) - 1] := Button.Key.PublishedName; end; end; end; function TCustomTouchKeyboard.GetShiftState(const VirtualKey: TVirtualKey): TModifierState; var Index, ModifierIndex: Integer; Button: TCustomKeyboardButton; Modifier: TKeyModifier; FoundCaps, FoundShift: Boolean; begin Result := []; FoundCaps := False; FoundShift := False; for Index := 0 to FUnclick.Count - 1 do begin Button := FUnclick[Index]; case Button.Key.ScanCode of 54 {Right Shift}, 42 {Left Shift}: begin FoundShift := True; Include(Result, msShift); end; 285 {Right CTRL}, 29 {Left CTRL}: Include(Result, msCtrl); 312 {Right ALT}, 56 {Left ALT}: Include(Result, msAlt); end; case VirtualKey.Vk of VK_SHIFT: begin FoundShift := True; Include(Result, msShift); end; VK_CONTROL: Include(Result, msCtrl); VK_MENU: Include(Result, msAlt); end; if (Button.Key.Vk = VK_CAPITAL) or (Button.Key.ScanCode = 58) then begin for ModifierIndex := 0 to Length(VirtualKey.Modifiers) - 1 do begin Modifier := VirtualKey.Modifiers[ModifierIndex]; if (Button.Key.ModifierName = Modifier.ModifierName) and ((Modifier.Language = '') or (Modifier.Language = FLanguage) or (Modifier.Language = GetPrimaryLanguage(FLanguage))) then begin FoundCaps := True; Include(Result, msShift); Break; end; end; end; end; if FoundShift and FoundCaps then Exclude(Result, msShift); end; procedure TCustomTouchKeyboard.Initialize; begin if not FInitialized and CheckWin32Version(6, 1) and RegisterTouchWindow(Handle, 0) then FInitialized := True; end; procedure TCustomTouchKeyboard.ReadCustomCaptionOverrides(Stream: TStream); function ReadInteger: Integer; begin Stream.Read(Result, SizeOf(Result)); end; function ReadString: string; var Count: Byte; Bytes: TBytes; begin Stream.Read(Count, SizeOf(Count)); if Count > 0 then begin SetLength(Bytes, Count); ZeroMemory(@Bytes[0], Length(Bytes)); Stream.Read(Bytes[0], Count); Result := TEncoding.Unicode.GetString(Bytes); end else Result := ''; end; var Index: Integer; Count, ItemCount: Integer; Name, Value, Language: string; begin ReadInteger; // Version Count := ReadInteger; for Index := 0 to Count - 1 do begin ItemCount := ReadInteger; Name := ReadString; Value := ReadString; if ItemCount = 3 then Language := ReadString; CaptionOverrides.Add(Name, Value, Language); end; end; procedure TCustomTouchKeyboard.Redraw; begin UpdateCaptions; Paint; end; procedure TCustomTouchKeyboard.Resize; var Index: Integer; Button: TCustomKeyboardButton; WidthLeftoverIndex: Integer; WidthLeftover: array of Integer; OriginalWidthsIndex: Integer; OriginalWidths: array of Integer; RowCount, ButtonHeight, Row, TopRemainder, TopPosition: Integer; TallButton: TCustomKeyboardButton; begin if FCurrentLayout = nil then Exit; // Resize all non-stretchy buttons. WidthLeftoverIndex := -1; // Find the widths of all stretchy buttons on each row. Store them in // the array OriginalWidths. OriginalWidthsIndex := -1; for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Left = 0 then begin Inc(WidthLeftoverIndex); SetLength(WidthLeftover, Length(WidthLeftover) + 1); WidthLeftover[WidthLeftoverIndex] := Width + 1; Inc(OriginalWidthsIndex); SetLength(OriginalWidths, Length(OriginalWidths) + 1); end; if kfStretch in Button.Key.Flags then Inc(OriginalWidths[OriginalWidthsIndex], Button.Key.Width) else begin Button.FWidth := (Button.Key.Width * Width) div FCurrentLayout.Width; Dec(WidthLeftover[WidthLeftoverIndex], Button.Width); end; end; // Resize all stretchy buttons using OriginalWidths as the width size. OriginalWidthsIndex := -1; WidthLeftoverIndex := -1; for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Left = 0 then begin Inc(OriginalWidthsIndex); Inc(WidthLeftoverIndex); end; if kfStretch in Button.Key.Flags then begin Button.FWidth := ((Button.Key.Width * WidthLeftover[WidthLeftoverIndex]) div OriginalWidths[OriginalWidthsIndex]); end else if Index = FButtons.Count - 1 then Button.FWidth := Button.Width - 1; end; // Orient all buttons horizontally. for Index := 1 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Left <> 0 then Button.FLeft := FButtons[Index - 1].Left + FButtons[Index - 1].Width; end; // Resize and orient all buttons vertically. RowCount := 0; for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Left = 0 then Inc(RowCount); end; if RowCount > 0 then ButtonHeight := (Height - 1) div RowCount else ButtonHeight := 0; TopPosition := 0; Row := 0; TopRemainder := (Height - (ButtonHeight * RowCount)); TallButton := nil; for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; if Button.Key.Height <> FCurrentLayout.RowHeight then TallButton := Button; if Button.Top <> Row then begin Row := Button.Top; if TopRemainder > 0 then TopPosition := TopPosition + ButtonHeight + 1 else TopPosition := TopPosition + ButtonHeight; Dec(TopRemainder); if (TallButton <> nil) and (TallButton.Key.Height <> FCurrentLayout.RowHeight) then begin // Note: Because tall buttons are on the previous row they contain the margin // of that row (top and bottom). This is why Button.TopMargin is not added // to the hight of the tall button. TallButton.FHeight := TallButton.Height + ButtonHeight + TallButton.BottomMargin; if TopRemainder > 0 then TallButton.FHeight := TallButton.Height + 1; TallButton := nil; end; end; Button.FTop := TopPosition; if TopRemainder > 0 then Button.FHeight := ButtonHeight + 1 else Button.FHeight := ButtonHeight; end; inherited; end; procedure TCustomTouchKeyboard.ToggleKeys(AButton: TCustomKeyboardButton; KeyState: TKeyState; Immediate: Boolean = False); procedure SetButtonState(Button: TCustomKeyboardButton; State: TCustomKeyboardButton.TDrawState); begin if Button.State <> State then begin if Immediate then begin Button.SetState(State, False); Button.Paint; end else Button.SetState(State, True); end; end; var Index: Integer; LButton: TCustomKeyboardButton; Key: TVirtualKey; State: TCustomKeyboardButton.TDrawState; begin if KeyState = ksUp then State := TCustomKeyboardButton.TDrawState.dsNormal else State := TCustomKeyboardButton.TDrawState.dsPressed; Key := GetLanguageKey(AButton.Key, FLanguage); if Length(Key.ComboKeys) > 0 then SetButtonState(AButton, State) else begin // Toggle/Untoggle all keys with the same Vk or ScanCode. for Index := 0 to FButtons.Count - 1 do begin LButton := FButtons[Index]; if Key.Equals(GetLanguageKey(LButton.Key, FLanguage)) then SetButtonState(LButton, State); end; end; end; procedure TCustomTouchKeyboard.UpdateCaptions; var Index: Integer; Button: TCustomKeyboardButton; Key: TKey; begin for Index := 0 to FButtons.Count - 1 do begin Button := FButtons[Index]; Key := GetModifiedKey(Button.Key, FLanguage); if Key.KeyImage <> kiText then Button.KeyImage := Key.KeyImage else begin if Key.Caption = '' then Button.Caption := Key.ToString(GetShiftState(Button.Key)) else Button.Caption := Key.Caption; end; if not Button.Modifier then Button.SetState(TCustomKeyboardButton.TDrawState.dsNormal, False); end; end; procedure TCustomTouchKeyboard.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin Message.Result := 0; end; procedure TCustomTouchKeyboard.WMInputLangChange(var Message: TMessage); var LLanguage: string; Success: Boolean; begin Success := False; LLanguage := GetCurrentInputLanguage; if LLanguage <> '' then begin FLanguage := LLanguage; if CreateKeyboard(FLanguage) then begin Invalidate; Redraw; Paint; Success := True; end; end; if not Success then raise Exception.CreateRes(@SKeyboardLangChange); end; procedure TCustomTouchKeyboard.WMTouch(var Message: TMessage); var TouchInputs: array of TouchInput; LTouchInput: TouchInput; Index, TouchCount: Integer; begin try TouchCount := LoWord(Message.WParam); SetLength(TouchInputs, TouchCount); if GetTouchInputInfo(Message.LParam, TouchCount, @TouchInputs[0], SizeOf(TouchInput)) then begin for Index := 0 to Length(TouchInputs) - 1 do begin LTouchInput := TouchInputs[Index]; ProcessKeyPress(TouchInputToWmMouse(Self, LTouchInput), LTouchInput.dwID); end; end; finally CloseTouchInputHandle(Message.LParam); end; end; procedure TCustomTouchKeyboard.WndProc(var Message: TMessage); begin if not ((ssTouch in MouseOriginToShiftState) and CheckWin32Version(6, 1)) then begin if Message.Msg = WM_LBUTTONDBLCLK then Dec(Message.Msg, WM_LBUTTONDBLCLK - WM_LBUTTONDOWN); ProcessKeyPress(TWMMouse(Message), 0); end; if (Message.Msg = WM_DESTROY) and FInitialized then begin UnregisterTouchWindow(Handle); FInitialized := False; end; inherited; end; procedure TCustomTouchKeyboard.WriteCustomCaptionOverrides(Stream: TStream); procedure WriteInteger(Value: Integer); begin Stream.Write(Value, SizeOf(Value)); end; procedure WriteString(const Value: string); var Bytes: TBytes; Count: Byte; begin Bytes := TEncoding.Unicode.GetBytes(Value); Count := Length(Bytes); Stream.Write(Count, SizeOf(Count)); if Count > 0 then Stream.Write(Bytes[0], Count); end; var Index: Integer; Version: Integer; KeyItem: TKeyCaptions.TKeyCaption; begin Version := 1; WriteInteger(Version); WriteInteger(CaptionOverrides.Count); for Index := 0 to CaptionOverrides.Count - 1 do begin KeyItem := CaptionOverrides[Index]; if KeyItem.Language = '' then begin WriteInteger(2); WriteString(KeyItem.Name); WriteString(KeyItem.Value); end else begin WriteInteger(2); WriteString(KeyItem.Name); WriteString(KeyItem.Value); WriteString(KeyItem.Language); end; end; end; procedure TCustomTouchKeyboard.KeyClick(Button: TCustomKeyboardButton); var ModifierButton: TCustomKeyboardButton; Index: Integer; Key: TKey; begin Key := GetModifiedKey(Button.Key, FLanguage); if Key.IsDeadKey then begin FDeadKey := VKey(Key.Vk, Key.ScanCode); // Move all the modifier keys that are not held down to the dead key. Index := 0; while Index < FUnclick.Count do begin ModifierButton := FUnclick[Index]; if (not (kfToggle in ModifierButton.Key.Flags)) and (ModifierButton.ID = -1) then begin FDeadKeyUnclick.Add(ModifierButton); ToggleKeys(ModifierButton, ksUp, True); PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksUp); ModifierButton.Down := False; FUnclick.Delete(Index); enD else Inc(Index); end; Redraw; Exit; end; if (FDeadKey.Vk >= 0) or (FDeadKey.ScanCode >= 0) then begin for Index := 0 to FUnclick.Count - 1 do begin ModifierButton := FUnclick[Index]; if ((ModifierButton.Key.Vk <> VK_CAPITAL) and (ModifierButton.Key.ScanCode <> 58)) then PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksUp); end; for Index := 0 to FDeadKeyUnclick.Count - 1 do begin ModifierButton := FDeadKeyUnclick[Index]; PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksDown); end; SendKey(FDeadKey, ksDown); for Index := 0 to FDeadKeyUnclick.Count - 1 do begin ModifierButton := FDeadKeyUnclick[Index]; PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksUp); end; SendKey(FDeadKey, ksUp); for Index := 0 to FUnclick.Count - 1 do begin ModifierButton := FUnclick[Index]; if (ModifierButton.ID = -1) and ((ModifierButton.Key.Vk <> VK_CAPITAL) and (ModifierButton.Key.ScanCode <> 58)) then begin PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksDown); end; end; end; PlayKey(Key, ksDown); PlayKey(Key, ksUp); if FUnclick.Count > 0 then begin // Untoggle all keys that are currently toggled and not held down. Index := 0; while Index < FUnclick.Count do begin ModifierButton := FUnclick[Index]; if ModifierButton.Modifier and not (kfToggle in ModifierButton.Key.Flags) and (ModifierButton.ID <> -1) then ModifierButton.Down := False; if (not (kfToggle in ModifierButton.Key.Flags)) and ((ModifierButton.ID = -1) or (ModifierButton.ID = 0)) then begin PlayKey(GetLanguageKey(ModifierButton.Key, FLanguage), ksUp); ToggleKeys(ModifierButton, ksUp, True); ModifierButton.Down := False; FUnclick.Delete(Index); end else Inc(Index); end; Redraw; end; FDeadKey := VKey(-1, -1); FDeadKeyUnclick.Clear; end; procedure TCustomTouchKeyboard.Loaded; begin inherited; end; function TCustomTouchKeyboard.GetOverrideCaption(const Key: TVirtualKey; var Caption: string): Boolean; begin Result := False; if CaptionOverrides.HasCaption(Key.PublishedName, FLanguage) then begin Caption := CaptionOverrides.GetCaption(Key.PublishedName, FLanguage); Result := True; end else if CaptionOverrides.HasCaption(Key.PublishedName) then begin Caption := CaptionOverrides.GetCaption(Key.PublishedName); Result := True; end; end; procedure TCustomTouchKeyboard.OnChange(Sender: TObject); var ChangeState: TChangeState; begin while FChangeStates.Count > 0 do begin ChangeState := FChangeStates[0]; ChangeState.Button.SetState(ChangeState.State, False); ChangeState.Button.Paint; FChangeStates.Delete(0); end; FChangeTimer.Enabled := False; end; procedure TCustomTouchKeyboard.OnRepeat(Sender: TObject); var Index: Integer; PressedKey: TCustomKeyboardButton; Key: TKey; begin if FPressedKeys.Count > 0 then begin for Index := 0 to FPressedKeys.Count - 1 do begin PressedKey := FPressedKeys[Index]; if not PressedKey.Modifier then begin Key := GetModifiedKey(PressedKey.Key, FLanguage); PlayKey(Key, ksDown); end; end; FRepeat.Interval := RepeatRate; end; end; procedure TCustomTouchKeyboard.Paint; var MemDC: HDC; LCanvas: TCanvas; Bitmap: TBitmap; Index: Integer; begin MemDC := CreateCompatibleDC(Canvas.Handle); try Bitmap := TBitmap.Create; try Bitmap.Width := Width; Bitmap.Height := Height; SelectObject(MemDC, Bitmap.Handle); LCanvas := TCanvas.Create; try LCanvas.Handle := MemDC; if DrawingStyle = TDrawingStyle.dsGradient then GradientFillCanvas(LCanvas, GradientStart, GradientEnd, ClientRect, gdVertical) else begin LCanvas.Brush.Color := Color; LCanvas.FillRect(ClientRect); end; for Index := 0 to FButtons.Count - 1 do FButtons[Index].Paint(LCanvas); Canvas.CopyRect(ClientRect, LCanvas, ClientRect); finally LCanvas.Free; end; finally Bitmap.Free; end; finally DeleteDC(MemDC); end; end; procedure TCustomTouchKeyboard.ProcessKeyPress(const Msg: TWmMouse; ID: Integer); function FindButton(Point: TPoint): TCustomKeyboardButton; overload; var Index: Integer; begin Result := nil; for Index := 0 to FButtons.Count - 1 do begin if PtInRect(FButtons[Index].BoundsRect, Point) then begin Result := FButtons[Index]; Break; end; end; end; function FindButton(ID: Integer): TCustomKeyboardButton; overload; var Index: Integer; begin Result := nil; if ID <> -1 then begin for Index := 0 to FButtons.Count - 1 do begin if FButtons[Index].ID = ID then begin Result := FButtons[Index]; Break; end; end; end; end; function FindLastKey(Button: TCustomKeyboardButton): TCustomKeyboardButton; var Index: Integer; begin Result := nil; if Button <> nil then begin for Index := 0 to FPressedKeys.Count - 1 do begin if FPressedKeys[Index] = Button then begin Result := FPressedKeys[Index]; Break; end; end; end; end; procedure DeleteLastKey(Button: TCustomKeyboardButton); var Index: Integer; begin for Index := 0 to FPressedKeys.Count - 1 do begin if FPressedKeys[Index] = Button then begin FPressedKeys.Delete(Index); Break; end; end; end; procedure DeleteUnclickKey(Button: TCustomKeyboardButton); var Index: Integer; begin for Index := 0 to FUnclick.Count - 1 do begin if FUnclick[Index] = Button then begin FUnclick.Delete(Index); Break; end; end; end; procedure AddLastKey(Button: TCustomKeyboardButton); var Index: Integer; begin for Index := 0 to FPressedKeys.Count - 1 do begin if FPressedKeys[Index] = Button then Exit; end; FPressedKeys.Add(Button); end; procedure AddOrDelete(List: TButtonList; Button: TCustomKeyboardButton); var Index: Integer; begin for Index := 0 to List.Count - 1 do begin if List[Index].Key.Equals(Button.Key) then begin List.Delete(Index); Exit; end; end; Index := 0; while Index < List.Count - 1 do begin if (List[Index].Key.GroupIndex = Button.Key.GroupIndex) then List.Delete(Index) else Inc(Index); end; List.Add(Button); end; var Button, LastKey: TCustomKeyboardButton; Point: TPoint; begin if not Enabled or (csDesigning in ComponentState) then Exit; Point:= SmallPointToPoint(Msg.Pos); case Msg.Msg of WM_LBUTTONDOWN: begin Button := FindButton(Point); if Button <> nil then begin Button.ID := ID; AddLastKey(Button); if Button.Modifier then begin if kfToggle in Button.Key.Flags then begin if not Button.Down then ToggleKeys(Button, ksDown, True); AddOrDelete(FUnclick, Button); Button.Down := not Button.Down; Redraw; end else if Button.Modifier then begin if not Button.Down then begin PlayKey(GetLanguageKey(Button.Key, FLanguage), ksDown); if Button.State = TCustomKeyboardButton.TDrawState.dsPressed then ToggleKeys(Button, ksUp, True) else ToggleKeys(Button, ksDown, True); end; AddOrDelete(FUnclick, Button); Button.Down := not Button.Down; Redraw; end; end else begin ToggleKeys(Button, ksDown, True); if (RepeatRate <> 0) and (RepeatDelay <> 0) then begin FRepeat.Interval := RepeatDelay; FRepeat.Enabled := True; end; end; end; end; WM_LBUTTONUP: begin Button := FindButton(Point); if Button <> nil then begin FRepeat.Enabled := False; LastKey := FindLastKey(Button); if LastKey <> nil then DeleteLastKey(LastKey); if (LastKey = Button) and Button.Modifier then begin if (Button.ID <> -1) and (Button.ID = ID) then begin Button.ID := -1; if kfToggle in Button.Key.Flags then begin PlayKey(GetLanguageKey(Button.Key, FLanguage), ksDown); PlayKey(GetLanguageKey(Button.Key, FLanguage), ksUp); if not Button.Down then ToggleKeys(Button, ksUp, True); end else if not Button.Down then begin PlayKey(GetLanguageKey(Button.Key, FLanguage), ksUp); ToggleKeys(Button, ksUp, True); if FUnclick.Count > 0 then AddOrDelete(FUnclick, Button); Redraw; end; end; end else if (LastKey = Button) and not Button.Modifier then begin ToggleKeys(Button, ksUp); Button.ID := -1; KeyClick(Button); end else if LastKey <> nil then begin ToggleKeys(LastKey, ksUp); DeleteLastKey(LastKey); end; end; end; WM_MOUSELEAVE: begin if FPressedKeys.Count > 0 then begin ClearState; Redraw; end; end; WM_MOUSEMOVE: begin if (ID <> -1) and (FPressedKeys.Count > 0) then begin Button := FindButton(Point); LastKey := FindButton(ID); if (LastKey <> nil) and (Button <> nil) and (LastKey <> Button) then begin FRepeat.Enabled := False; Button.ID := ID; LastKey.ID := -1; if LastKey.Modifier then begin if kfToggle in LastKey.Key.Flags then begin LastKey.Down := not LastKey.Down; ToggleKeys(LastKey, ksUp, True); DeleteLastKey(LastKey); DeleteUnclickKey(LastKey); end else begin LastKey.Down := not LastKey.Down; ToggleKeys(LastKey, ksUp, True); DeleteLastKey(LastKey); ToggleKeys(Button, ksDown, True); AddLastKey(Button); end; end else begin ToggleKeys(LastKey, ksUp, True); ToggleKeys(Button, ksDown, True); DeleteLastKey(LastKey); AddLastKey(Button); end; end; end; end; end; end; { TCustomTouchKeyboard.TChangeState } class function TCustomTouchKeyboard.TChangeState.ChangeState(AButton: TCustomKeyboardButton; const AState: TCustomKeyboardButton.TDrawState): TChangeState; begin Result.Button := AButton; Result.State := AState; end; { TKeyCaptions } procedure TKeyCaptions.Add(const AName, AValue: string; const ALanguage: string = ''); begin SetLength(FItems, Length(FItems) + 1); FItems[Length(FItems) - 1] := KeyCaption(AName, AValue, ALanguage); end; procedure TKeyCaptions.Clear; begin SetLength(FItems, 0); end; procedure TKeyCaptions.Delete(const AName: string; const ALanguage: string = ''); var Index, CopyIndex: Integer; Items: TKeyCaptionArray; begin SetLength(Items, Length(FItems) - 1); Index := 0; CopyIndex := 0; while Index < Length(Items) do begin if (FItems[CopyIndex].Name = AName) and (FItems[CopyIndex].Language = ALanguage) then Inc(CopyIndex); Items[Index] := FItems[CopyIndex]; Inc(Index); Inc(CopyIndex); end; FItems := Items; end; function TKeyCaptions.GetCaption(const AName, ALanguage: string): string; var Index: Integer; KeyCaption: TKeyCaption; begin for Index := 0 to Length(FItems) - 1 do begin KeyCaption := FItems[Index]; if (KeyCaption.Name = AName) and (KeyCaption.Language = ALanguage) then Exit(KeyCaption.Value); end; end; function TKeyCaptions.GetCount: Integer; begin Result := Length(FItems); end; function TKeyCaptions.GetItems(const Index: Integer): TKeyCaption; begin Result := FItems[Index]; end; function TKeyCaptions.HasCaption(const AName: string; const ALanguage: string = ''): Boolean; var Index: Integer; begin Result := False; for Index := 0 to Length(FItems) - 1 do begin if (FItems[Index].Name = AName) and (FItems[Index].Language = ALanguage) then begin Result := True; Break; end; end; end; function TKeyCaptions.KeyCaption(const AName, AValue, ALanguage: string): TKeyCaption; begin Result.Name := AName; Result.Value := AValue; Result.Language := ALanguage; end; procedure TKeyCaptions.SetCaption(const AName, AValue: string; const ALanguage: string = ''); var Index: Integer; Found: Boolean; begin Found := False; for Index := 0 to Length(FItems) - 1 do begin if (FItems[Index].Name = AName) and (FItems[Index].Language = ALanguage) then begin FItems[Index].Value := AValue; Found := True; Break; end; end; if not Found then Add(AName, AValue, ALanguage); end; procedure TKeyCaptions.SetItems(const Index: Integer; const Value: TKeyCaption); begin FItems[Index] := Value; end; { TKeyboardLayouts } function EnumResNames(Module: HMODULE; ResType, ResName: PChar; Nothing: Pointer): Integer; stdcall; const sResourceName = 'KEYBOARD'; var Layout: TVirtualKeyLayout; Stream: TResourceStream; begin if Pos(sResourceName, ResName) > 0 then begin Stream := TResourceStream.Create(HInstance, ResName, RT_RCDATA); try Layout := TVirtualKeyLayout.Create; Layout.LoadFromStream(Stream); GlobalKeyboardLayouts.Add(Layout); finally Stream.Free; end; end; Result := 1; end; class constructor TKeyboardLayouts.Create; begin FKeyboardLayouts := TVirtualKeyLayouts.Create; GlobalKeyboardLayouts := FKeyboardLayouts; EnumResourceNames(HInstance, RT_RCDATA, @EnumResNames, 0); end; class destructor TKeyboardLayouts.Destroy; begin FKeyboardLayouts.Free; end; class function TKeyboardLayouts.Find(const Layout: string): TVirtualKeyLayout; var Index: Integer; begin Result := nil; for Index := 0 to TKeyboardLayouts.Count - 1 do begin if Layouts[Index].KeyboardType = Layout then begin Result := TKeyboardLayouts.Layouts[Index]; Exit; end; end; end; class function TKeyboardLayouts.Find(const Layout, Language: string): TVirtualKeyLayout; var Index, LanguageIndex: Integer; KeyboardLayout: TVirtualKeyLayout; begin Result := nil; for Index := TKeyboardLayouts.Count - 1 downto 0 do begin KeyboardLayout := Layouts[Index]; for LanguageIndex := 0 to KeyboardLayout.Languages.Count - 1 do begin if (KeyboardLayout.KeyboardType = Layout) and (KeyboardLayout.Languages[LanguageIndex].Language = Language) then begin Result := KeyboardLayout; Exit; end; end; end; end; class function TKeyboardLayouts.GetCount: Integer; begin Result := Layouts.Count; end; class function TKeyboardLayouts.GetLayoutNames: TStringDynArray; function FindItem(const Strings: TStringDynArray; const Value: string): Boolean; var Index: Integer; begin Result := False; for Index := 0 to Length(Strings) - 1 do begin if Strings[Index] = Value then begin Result := True; Break; end; end; end; var Index: Integer; begin SetLength(Result, FKeyboardLayouts.Count); for Index := 0 to FKeyboardLayouts.Count - 1 do if not FindItem(Result, FKeyboardLayouts[Index].KeyboardType) then Result[Index] := FKeyboardLayouts[Index].KeyboardType; end; class procedure TKeyboardLayouts.LoadFromResourceName( const ResourceName: string); var Stream: TResourceStream; begin Stream := TResourceStream.Create(HInstance, ResourceName, RT_RCDATA); try LoadFromStream(Stream); finally Stream.Free; end; end; class procedure TKeyboardLayouts.LoadFromStream(Stream: TStream); var Layout: TVirtualKeyLayout; begin Layout := TVirtualKeyLayout.Create; Layout.LoadFromStream(Stream); FKeyboardLayouts.Add(Layout); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC FireMonkey Error dialog } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.FMXUI.Error; interface {$SCOPEDENUMS ON} uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, FMX.Forms, FMX.Controls, FMX.ListBox, FMX.Layouts, FMX.Memo, FMX.Edit, FMX.TabControl, FMX.Objects, FMX.Types, FMX.ExtCtrls, FMX.Grid, FMX.StdCtrls, FMX.Header, FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.FMXUI.OptsBase; type TfrmFDGUIxFMXError = class(TfrmFDGUIxFMXOptsBase) pcAdvanced: TTabControl; tsAdvanced: TTabItem; tsQuery: TTabItem; NativeLabel: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; edtErrorCode: TEdit; edtServerObject: TEdit; edtMessage: TMemo; edtErrorKind: TEdit; edtCommandTextOffset: TEdit; Label9: TLabel; Label5: TLabel; lvCommandParams: TListBox; tsOther: TTabItem; Label6: TLabel; Label7: TLabel; edtClassName: TEdit; edtADCode: TEdit; Label8: TLabel; Label10: TLabel; Label11: TLabel; pnlMsg: TPanel; memMsg: TMemo; pnlAdvanced: TPanel; btnCopy: TButton; pnlCopy: TPanel; Panel1: TPanel; mmCommandText: TMemo; Panel3: TPanel; Header1: THeader; HeaderItem1: THeaderItem; HeaderItem2: THeaderItem; Label12: TLabel; edtADObjName: TEdit; btnPrior: TButton; btnNext: TButton; procedure FormActivate(Sender: TObject); procedure BackClick(Sender: TObject); procedure NextClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DetailsBtnClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure btnCopyClick(Sender: TObject); private FError: EFDDBEngineException; FDetailsHeight, CurItem: Integer; FDetails: string; FPrevWidth: Integer; FOnHide: TFDGUIxErrorDialogEvent; FOnShow: TFDGUIxErrorDialogEvent; procedure UpdateLayout(ASwitching: Boolean); procedure ShowError; procedure ShowCommand; protected procedure Execute(AExc: EFDDBEngineException); end; var frmFDGUIxFMXError: TfrmFDGUIxFMXError; implementation uses System.UITypes, FMX.Platform, FireDAC.Stan.Consts, FireDAC.Stan.Factory, FireDAC.Stan.Util, FireDAC.Stan.ResStrs, FireDAC.UI; {$R *.fmx} { --------------------------------------------------------------------------- } { TfrmFDGUIxFMXError } { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.FormCreate(Sender: TObject); begin Caption := S_FD_ErrorDialogDefCaption; FDetailsHeight := ClientHeight; FDetails := btnCancel.Text; pnlAdvanced.Visible := True; DetailsBtnClick(nil); ActiveControl := btnOk; Visible := False; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.FormDestroy(Sender: TObject); begin if frmFDGUIxFMXError = Self then frmFDGUIxFMXError := nil; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkEscape then begin ModalResult := mrCancel; Key := 0; end else if (ssCtrl in Shift) and ((KeyChar = 'C') or (Key = vkInsert)) then begin btnCopyClick(nil); Key := 0; end; inherited; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.btnCopyClick(Sender: TObject); const C_Delim: String = '-------------------------------------------'; var oStrs: TFDStringList; i: Integer; oLI: TListBoxItem; oName, oValue: TText; oClpSrv: IFMXClipboardService; begin oStrs := TFDStringList.Create; try oStrs.Add(Caption); oStrs.Add(lblPrompt.Text); oStrs.Add(C_Delim); oStrs.Add(Label4.Text + ' ' + edtMessage.Text); oStrs.Add(NativeLabel.Text + ' ' + edtErrorCode.Text); oStrs.Add(Label2.Text + ' ' + edtErrorKind.Text); oStrs.Add(Label1.Text + ' ' + edtServerObject.Text); oStrs.Add(Label3.Text + ' ' + edtCommandTextOffset.Text); oStrs.Add(C_Delim); oStrs.Add(Label9.Text + ' ' + mmCommandText.Text); oStrs.Add(Label5.Text); // Start from 1/skip the header for i := 1 to lvCommandParams.Items.Count - 1 do begin oLI := lvCommandParams.ListItems[i]; oName := TText(oLI.FindStyleResource('Name')); oValue := TText(oLI.FindStyleResource('Value')); if (oName <> nil) and (oValue <> nil) then oStrs.Add(' ' + oName.Text + '=' + oValue.Text); end; oStrs.Add(C_Delim); oStrs.Add(Label6.Text + ' ' + edtClassName.Text); oStrs.Add(Label7.Text + ' ' + edtADCode.Text); oStrs.Add(Label12.Text + ' ' + edtADObjName.Text); if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, IInterface(oClpSrv)) then oClpSrv.SetClipboard(oStrs.Text); finally FDFree(oStrs); end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.UpdateLayout(ASwitching: Boolean); const DetailsOn: array [Boolean] of string = ('%s >>', '<< %s'); begin if pnlAdvanced.Visible then ClientHeight := FDetailsHeight else begin FDetailsHeight := ClientHeight; ClientHeight := ClientHeight - Trunc(pnlAdvanced.Height); end; btnCancel.Text := Format(DetailsOn[pnlAdvanced.Visible], [FDetails]); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.ShowError; const ErrorKinds: array [TFDCommandExceptionKind] of String = ('Other', 'NoDataFound', 'TooManyRows', 'RecordLocked', 'UKViolated', 'FKViolated', 'ObjNotExists', 'UserPwdInvalid', 'UserPwdExpired', 'UserPwdWillExpire', 'CmdAborted', 'ServerGone', 'ServerOutput', 'ArrExecMalfunc', 'InvalidParams'); var oError: TFDDBError; s: String; i: Integer; begin btnPrior.Enabled := CurItem > 0; btnNext.Enabled := CurItem < FError.ErrorCount - 1; if CurItem > FError.ErrorCount - 1 then CurItem := FError.ErrorCount - 1 else if CurItem < 0 then CurItem := 0; if FError.ErrorCount > 0 then begin oError := FError.Errors[CurItem]; s := IntToStr(oError.ErrorCode); if oError.ErrorCode > 0 then for i := 1 to 5 - Length(s) do s := '0' + s; edtErrorCode.Text := s; edtErrorKind.Text := ErrorKinds[oError.Kind]; edtMessage.Text := AdjustLineBreaks(oError.Message, tlbsCRLF); edtServerObject.Text := oError.ObjName; if oError.CommandTextOffset = -1 then edtCommandTextOffset.Text := '' else edtCommandTextOffset.Text := IntToStr(oError.CommandTextOffset); end else begin edtErrorCode.Text := ''; edtErrorKind.Text := ''; edtMessage.Text := ''; edtServerObject.Text := ''; edtCommandTextOffset.Text := ''; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.ShowCommand; var i: Integer; oParams: TStrings; oLI: TListBoxItem; oText: TText; begin mmCommandText.Text := FError.SQL; lvCommandParams.Clear; oParams := FError.Params; for i := 0 to oParams.Count - 1 do begin oLI := TListBoxItem.Create(Self); oLI.Parent := lvCommandParams; oLI.StyleLookup := 'LBReportStyle'; oText := TText(oLI.FindStyleResource('Name')); if oText <> nil then oText.Text := oParams.KeyNames[i]; oText := TText(oLI.FindStyleResource('Value')); if oText <> nil then oText.Text := oParams.ValueFromIndex[i]; end; tsQuery.Visible := (Trim(mmCommandText.Text) <> '') or (lvCommandParams.Items.Count > 0); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.FormActivate(Sender: TObject); begin memMsg.Text := AdjustLineBreaks(FError.Message, tlbsCRLF); edtClassName.Text := FError.ClassName; edtADCode.Text := IntToStr(FError.FDCode); edtADObjName.Text := FError.FDObjName; CurItem := 0; ShowError; ShowCommand; FPrevWidth := ClientWidth; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.BackClick(Sender: TObject); begin Dec(CurItem); ShowError; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.NextClick(Sender: TObject); begin Inc(CurItem); ShowError; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.DetailsBtnClick(Sender: TObject); begin pnlAdvanced.Visible := not pnlAdvanced.Visible; UpdateLayout(True); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.Execute(AExc: EFDDBEngineException); var oPrevForm: TCommonCustomForm; i: Integer; begin if Assigned(FOnShow) then FOnShow(Self, AExc); FError := AExc; oPrevForm := nil; for i := 0 to Screen.FormCount - 1 do if Screen.Forms[i].Active then begin oPrevForm := Screen.Forms[i]; Break; end; if Application.MainForm <> nil then Application.MainForm.BringToFront; ShowModal; if oPrevForm <> nil then oPrevForm.BringToFront; FError := nil; if Assigned(FOnHide) then FOnHide(Self, AExc); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFMXError.FormResize(Sender: TObject); begin FPrevWidth := ClientWidth; end; { --------------------------------------------------------------------------- } { TFDGUIxErrorDialogImpl } { --------------------------------------------------------------------------- } type TFDGUIxErrorDialogImpl = class(TFDGUIxObject, IFDGUIxErrorDialog) private FPrevOnException: TExceptionEvent; FHandlingException: Boolean; function GetForm: TfrmFDGUIxFMXError; procedure HandleException(Sender: TObject; E: Exception); protected // IFDGUIxErrorDialog function GetOnShow: TFDGUIxErrorDialogEvent; procedure SetOnShow(const AValue: TFDGUIxErrorDialogEvent); function GetOnHide: TFDGUIxErrorDialogEvent; procedure SetOnHide(const AValue: TFDGUIxErrorDialogEvent); function GetCaption: String; procedure SetCaption(const AValue: String); function GetEnabled: Boolean; procedure SetEnabled(const AValue: Boolean); function GetStayOnTop: Boolean; procedure SetStayOnTop(const AValue: Boolean); procedure Execute(AExc: EFDDBEngineException); public procedure Initialize; override; destructor Destroy; override; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.Initialize; begin inherited Initialize; frmFDGUIxFMXError := nil; SetEnabled(True); end; { --------------------------------------------------------------------------- } destructor TFDGUIxErrorDialogImpl.Destroy; begin SetEnabled(False); FDFreeAndNil(frmFDGUIxFMXError); inherited Destroy; end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetForm: TfrmFDGUIxFMXError; begin if frmFDGUIxFMXError = nil then frmFDGUIxFMXError := TfrmFDGUIxFMXError.Create(Application); Result := frmFDGUIxFMXError; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.HandleException(Sender: TObject; E: Exception); begin if (E is EFDDBEngineException) and not Application.Terminated and not FHandlingException then begin FHandlingException := True; try Execute(EFDDBEngineException(E)) finally FHandlingException := False; end; end else if Assigned(FPrevOnException) then FPrevOnException(Sender, E) else Application.ShowException(E); end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.Execute(AExc: EFDDBEngineException); begin if not FDGUIxSilent() then GetForm.Execute(AExc); end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetOnHide: TFDGUIxErrorDialogEvent; begin Result := GetForm.FOnHide; end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetOnShow: TFDGUIxErrorDialogEvent; begin Result := GetForm.FOnShow; end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetCaption: String; begin Result := GetForm.Caption; end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetEnabled: Boolean; var oHndlExc: TExceptionEvent; begin oHndlExc := HandleException; Result := (Application <> nil) and (TMethod(Application.OnException).Code = TMethod(oHndlExc).Code) and (TMethod(Application.OnException).Data = TMethod(oHndlExc).Data); end; { --------------------------------------------------------------------------- } function TFDGUIxErrorDialogImpl.GetStayOnTop: Boolean; begin Result := GetForm.FormStyle = TFormStyle.StayOnTop; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.SetOnHide(const AValue: TFDGUIxErrorDialogEvent); begin if Assigned(AValue) or Assigned(frmFDGUIxFMXError) then GetForm.FOnHide := AValue; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.SetOnShow(const AValue: TFDGUIxErrorDialogEvent); begin if Assigned(AValue) or Assigned(frmFDGUIxFMXError) then GetForm.FOnShow := AValue; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.SetCaption(const AValue: String); begin if (AValue <> '') or Assigned(frmFDGUIxFMXError) then GetForm.Caption := AValue; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.SetEnabled(const AValue: Boolean); begin if GetEnabled <> AValue then if AValue then begin FPrevOnException := Application.OnException; Application.OnException := HandleException; end else begin if Application <> nil then Application.OnException := FPrevOnException; FPrevOnException := nil; end; end; { --------------------------------------------------------------------------- } procedure TFDGUIxErrorDialogImpl.SetStayOnTop(const AValue: Boolean); begin if AValue then GetForm.FormStyle := TFormStyle.StayOnTop else GetForm.FormStyle := TFormStyle.Normal; end; { --------------------------------------------------------------------------- } var oFact: TFDFactory; initialization oFact := TFDSingletonFactory.Create(TFDGUIxErrorDialogImpl, IFDGUIxErrorDialog, C_FD_GUIxFMXProvider); finalization FDReleaseFactory(oFact); end.
Unit GetField; Interface uses Crt, KeyCodes; CONST IgnoreStr = 0; BlankStr = 1; TrimStr = 2; BlankNTrim = 3; NoStr = ''; type BoxToggle = (NOBOX, BOX); Alignment = (LEFT,TOP); procedure AddExitKey(NewKey : Integer); { The pre-existing default is ESC } (* automatically called procedure ForgetExitKeys; { You must call this upon exit even if you did not add any beyond the default } *) procedure DrawBox(x,y,wide,high : integer); procedure Field_Str( Xpos, Ypos, Len, Opts : Byte; Lab : String; Var UserStr : String; Format : Char; DoBox : BoxToggle; RelPos : Alignment); procedure SetUp_Field(ActiveFColor,InactiveFColor : Byte; ActiveBColor,InactiveBColor : Byte; ClearChar : Char); procedure Release_Fields; procedure CleanString(var S : String); procedure GetString(Ypos,Xpos,Attr,Len,Opts : Byte; Var UserStr : String; Legal : Char; Var Keyval : Integer); procedure Do_Fields(Var KeyVal : Integer); { KeyVal is key code of last key pressed } function Get_Key : Integer; { ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} implementation Type Field_IO = Record Xpos,Ypos,Len,Exit,Opts : Byte; Format : Char; UserStr : ^String; end; KeyPtr = ^Node; Node = Record Key : integer; Next : KeyPtr; END; Var Field_Array : Array[1..256] of ^Field_IO; Max_Field : Byte; Active_Fcolor : Byte; Inactive_Fcolor : Byte; Active_Bcolor : Byte; Inactive_Bcolor : Byte; Clear_Char : Char; KeyList, LastNode, KeyNode : KeyPtr; ExitSave : POINTER; procedure AddExitKey(NewKey : Integer); { dynamically allocate a linked list of keys that trigger loop exit } begin new(KeyNode); IF KeyList <> NIL THEN LastNode^.Next := KeyNode ELSE KeyList := KeyNode; KeyNode^.Key := NewKey; KeyNode^.Next := NIL; LastNode := KeyNode; end; function ExitKey(KeyVal : integer) : BOOLEAN; { check if KeyVal matches any exit keys } VAR position : KeyPtr; begin position := KeyList; ExitKey := FALSE; WHILE (position <> NIL) AND (position^.Key <> KeyVal) DO position := position^.Next; IF position <> NIL then ExitKey := TRUE; end; {ExitKey} procedure ForgetExitKeys; { release memory used by KeyList } VAR position : KeyPtr; begin WHILE (KeyList <> NIL) DO BEGIN position := KeyList; KeyList := KeyList^.next; Dispose(position); END; end; {ForgetExitKeys} function RepeatStr(fill:string; times:integer) : string; var temp : string; i : integer; begin temp := ''; for i := 1 to times do temp := temp + fill; RepeatStr := temp; end; {REPEATSTR} procedure DrawBox(x,y,wide, high : integer); { x,y is character position WITHIN box at upper left. } var i : integer; begin for i := 0 to high DO BEGIN gotoXY(x-1,y+i); write(char(179)); gotoXY(x+wide,y+i); write(char(179)); END; gotoXY(x-1,y+high); write(char(192),RepeatStr(char(196),wide),char(217)); gotoXY(x-1,y-1); write(char(218),RepeatStr(char(196),wide),char(191)); end; {drawbox} procedure Field_Str; VAR StartLabel : INTEGER; begin inc(Max_Field,1); New(Field_Array[Max_Field]); Field_Array[Max_Field]^.Xpos := Xpos; Field_Array[Max_Field]^.Ypos := Ypos; Field_Array[Max_Field]^.Len := Len; Field_Array[Max_Field]^.Opts := Opts; If Opts > 2 then UserStr := ''; Field_Array[Max_Field]^.UserStr := @UserStr; Field_Array[Max_Field]^.Format := Format; IF NOT (Lab = NoStr) THEN IF RelPos = LEFT THEN begin StartLabel := Xpos - Length(Lab) - 1; IF StartLabel > 0 THEN begin GotoXY(StartLabel,YPos); Write(Lab); end; end else begin StartLabel := trunc(XPos + Len/2 - Length(Lab)/2); IF StartLabel < 1 THEN StartLabel := 1; GotoXY(StartLabel,YPos-1-ORD(DoBox)); Write(Lab); end; IF DoBox = BOX THEN DrawBox(Xpos,Ypos,Len,1); end; procedure SetUp_Field; begin Active_FColor := ActiveFColor; Inactive_Fcolor := InactiveFColor; Active_BColor := ActiveBColor; Inactive_Bcolor := InactiveBColor; Clear_Char := ClearChar; Max_Field := 0; end; procedure Release_Fields; Var X : Byte; begin For X := 1 to Max_Field do Release(Field_Array[Max_Field]); Max_Field := 0; end; procedure CleanString; Var X : Byte; Begin If Length(S) > 0 then begin X := 1; While (s[x] = ' ') and (Length(s) > 0) do Delete(S,x,1); X := Length(S); While (s[x] = ' ') and (x > 0) do dec(x); S[0] := Char(x); end; end; function Get_Key : Integer; Var CH : Char; Int : Integer; begin CH := ReadKey; If CH = #0 then begin CH := ReadKey; int := Ord(CH); inc(int,256); end else Int := Ord(CH); Get_Key := Int; end; procedure GetString(Ypos,Xpos,Attr,Len,Opts : Byte; Var UserStr : String; Legal : Char; Var Keyval : Integer); Var Position : Byte; Ins,Exit : Boolean; Str255 : String; procedure WriteString; Var X : Byte; begin GotoXY(Xpos,Ypos); If Length(Str255) > Len then Str255[0] := Char(Len); Write(Str255); If Length(Str255) < Len then For X := Length(Str255) to Len-1 do Write(Clear_Char); end; procedure BackSpaceChar; Begin delete(Str255,Position-1,1); dec(Position); WriteString; end; procedure DeleteChar; Begin inc(Position); BackSpaceChar; end; procedure WriteChar; Var DoWrite : Boolean; Begin If Position <= Len then begin DoWrite := True; case Legal of 'U' : Char(KeyVal) := UpCase(Chr(KeyVal)); 'L' : DoWrite := True; 'N' : If Pos(Char(KeyVal),'1234567890.-') = 0 then DoWrite := False; else DoWrite := False; end; If DoWrite then begin If Ins then Insert(Char(Keyval),Str255,Position) else Str255[Position] := Char(KeyVal); if Position > Length(Str255) then Str255[0] := Char(Position); WriteString; Inc(Position); GotoXY(Xpos+Position-1,Ypos); end; end; End; procedure EditString; Begin KeyVal := Get_Key; Case KeyVal of {Back} 8 : If Position > 1 then BackSpaceChar; {Return} 13 : Exit := True; {Home} 327 : Position := 1; {Up} 328 : Exit := True; {PgUp} 329 : Exit := True; {Left} 331 : If Position > 1 then dec(Position); {Right} 333 : If Position < Len then inc(Position); {End} 335 : Position := Length(Str255)+1; {Down} 336 : Exit := True; {PgDn} 337 : Exit := True; {Ins} 338 : If Ins then Ins := False else Ins := True; {Del} 339 : DeleteChar; end; IF ExitKey(KeyVal) THEN Exit := TRUE; If (KeyVal < 256) and (Keyval > 27) then WriteChar else GotoXY(Xpos+Position-1,Ypos); end; begin Exit := false; Ins := False; TextAttr := Attr; Position := 1; FillChar(Str255,SizeOf(Str255),Clear_Char); Insert(UserStr,Str255,1); Str255[0] := Char(Length(UserStr)); WriteString; GotoXY(Xpos+Position-1,Ypos); repeat EditString until Exit; TextAttr := Inactive_FColor + Inactive_BColor * 16; If Opts > 1 then CleanString(Str255); WriteString; UserStr := Str255; end; procedure Do_Fields; Var Exit : Boolean; Field_Id : Byte; begin Field_Id := 1; Repeat With Field_Array[Field_Id]^ do GetString(Ypos,Xpos, Active_Fcolor + Active_Bcolor * 16, Len,Opts,UserStr^,Format,KeyVal); If ExitKey(KeyVal) THEN Exit := True ELSE Exit := False; Case KeyVal of CR,DownArrow : If Field_Id = Max_Field then Field_Id := 1 else inc(Field_Id); UpArrow: If Field_Id = 1 then Field_Id := Max_Field else dec(Field_Id,1); end; Until Exit; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} {$F+} procedure TerminateClean; {$F-} { This should automatically get called no matter how we exit } BEGIN IF Max_Field > 0 Then Release_Fields; IF KeyList <> NIL THEN ForgetExitKeys; ExitProc := ExitSave; END; {TerminateClean} {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} begin SetUp_Field($70,$07,$00,$00,' '); KeyList := NIL; AddExitKey(ESC); ExitSave := ExitProc; ExitProc := @TerminateClean; end. 
unit NtUtils.Tokens; interface uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntseapi, NtUtils.Exceptions, NtUtils.Objects, NtUtils.Security.Sid, NtUtils.Security.Acl; { ------------------------------ Creation ---------------------------------- } const // Now supported everywhere on all OS versions NtCurrentProcessToken: THandle = THandle(-4); NtCurrentThreadToken: THandle = THandle(-5); NtCurrentEffectiveToken: THandle = THandle(-6); // Open a token of a process function NtxOpenProcessToken(out hxToken: IHandle; hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; function NtxOpenProcessTokenById(out hxToken: IHandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Open a token of a thread function NtxOpenThreadToken(out hxToken: IHandle; hThread: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; InverseOpenLogic: Boolean = False): TNtxStatus; function NtxOpenThreadTokenById(out hxToken: IHandle; TID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; InverseOpenLogic: Boolean = False): TNtxStatus; // Open an effective token of a thread function NtxOpenEffectiveTokenById(out hxToken: IHandle; const ClientId: TClientId; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; InverseOpenLogic: Boolean = False): TNtxStatus; // Convert a pseudo-handle to an actual token handle function NtxOpenPseudoToken(out hxToken: IHandle; Handle: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; InverseOpenLogic: Boolean = False): TNtxStatus; // Make sure to convert a pseudo-handle to an actual token handle if necessary // NOTE: Do not save the handle returned from this function function NtxExpandPseudoToken(out hxToken: IHandle; hToken: THandle; DesiredAccess: TAccessMask): TNtxStatus; // Copy an effective security context of a thread via direct impersonation function NtxDuplicateEffectiveToken(out hxToken: IHandle; hThread: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; function NtxDuplicateEffectiveTokenById(out hxToken: IHandle; TID: NativeUInt; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; // Duplicate existing token function NtxDuplicateToken(out hxToken: IHandle; hExistingToken: THandle; DesiredAccess: TAccessMask; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel = SecurityImpersonation; HandleAttributes: Cardinal = 0; EffectiveOnly: Boolean = False): TNtxStatus; // Open anonymous token function NtxOpenAnonymousToken(out hxToken: IHandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Filter a token function NtxFilterToken(out hxNewToken: IHandle; hToken: THandle; Flags: Cardinal; SidsToDisable: TArray<ISid>; PrivilegesToDelete: TArray<TLuid>; SidsToRestrict: TArray<ISid>): TNtxStatus; // Create a new token from scratch. Requires SeCreateTokenPrivilege. function NtxCreateToken(out hxToken: IHandle; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; AuthenticationId: TLuid; ExpirationTime: TLargeInteger; User: TGroup; Groups: TArray<TGroup>; Privileges: TArray<TPrivilege>; Owner: ISid; PrimaryGroup: ISid; DefaultDacl: IAcl; const TokenSource: TTokenSource; DesiredAccess: TAccessMask = TOKEN_ALL_ACCESS; HandleAttributes: Cardinal = 0) : TNtxStatus; // Create an AppContainer token, Win 8+ function NtxCreateLowBoxToken(out hxToken: IHandle; hExistingToken: THandle; Package: PSid; Capabilities: TArray<TGroup> = nil; Handles: TArray<THandle> = nil; HandleAttributes: Cardinal = 0): TNtxStatus; { --------------------------- Other operations ---------------------------- } // Adjust privileges function NtxAdjustPrivilege(hToken: THandle; Privilege: TSeWellKnownPrivilege; NewAttribute: Cardinal): TNtxStatus; function NtxAdjustPrivileges(hToken: THandle; Privileges: TArray<TLuid>; NewAttribute: Cardinal): TNtxStatus; // Adjust groups function NtxAdjustGroups(hToken: THandle; Sids: TArray<ISid>; NewAttribute: Cardinal; ResetToDefault: Boolean): TNtxStatus; implementation uses Ntapi.ntstatus, Ntapi.ntpsapi, NtUtils.Tokens.Misc, NtUtils.Processes, NtUtils.Tokens.Impersonate, NtUtils.Threads, NtUtils.Ldr, Ntapi.ntpebteb; { Creation } function NtxOpenProcessToken(out hxToken: IHandle; hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hToken: THandle; begin Result.Location := 'NtOpenProcessTokenEx'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @TokenAccessType; Result.LastCall.Expects(PROCESS_QUERY_LIMITED_INFORMATION, @ProcessAccessType); Result.Status := NtOpenProcessTokenEx(hProcess, DesiredAccess, HandleAttributes, hToken); if Result.IsSuccess then hxToken := TAutoHandle.Capture(hToken); end; function NtxOpenProcessTokenById(out hxToken: IHandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hxProcess: IHandle; begin Result := NtxOpenProcess(hxProcess, PID, PROCESS_QUERY_LIMITED_INFORMATION); if Result.IsSuccess then Result := NtxOpenProcessToken(hxToken, hxProcess.Handle, DesiredAccess, HandleAttributes); end; function NtxOpenThreadToken(out hxToken: IHandle; hThread: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; InverseOpenLogic: Boolean): TNtxStatus; var hToken: THandle; begin Result.Location := 'NtOpenThreadTokenEx'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @TokenAccessType; Result.LastCall.Expects(THREAD_QUERY_LIMITED_INFORMATION, @ThreadAccessType); // By default, when opening other thread's token use our effective (thread) // security context. When reading a token from the current thread use the // process' security context. Result.Status := NtOpenThreadTokenEx(hThread, DesiredAccess, (hThread = NtCurrentThread) xor InverseOpenLogic, HandleAttributes, hToken); if Result.IsSuccess then hxToken := TAutoHandle.Capture(hToken); end; function NtxOpenThreadTokenById(out hxToken: IHandle; TID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; InverseOpenLogic: Boolean): TNtxStatus; var hxThread: IHandle; begin Result := NtxOpenThread(hxThread, TID, THREAD_QUERY_LIMITED_INFORMATION); if Result.IsSuccess then Result := NtxOpenThreadToken(hxToken, hxThread.Handle, DesiredAccess, HandleAttributes, InverseOpenLogic); end; function NtxOpenEffectiveTokenById(out hxToken: IHandle; const ClientId: TClientId; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; InverseOpenLogic: Boolean): TNtxStatus; begin // When querying effective token we read thread token first, and then fall // back to process token if it's not available. Result := NtxOpenThreadTokenById(hxToken, ClientId.UniqueThread, DesiredAccess, HandleAttributes, InverseOpenLogic); if Result.Status = STATUS_NO_TOKEN then Result := NtxOpenProcessTokenById(hxToken, ClientId.UniqueProcess, DesiredAccess, HandleAttributes); end; function NtxOpenPseudoToken(out hxToken: IHandle; Handle: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; InverseOpenLogic: Boolean): TNtxStatus; begin if Handle = NtCurrentProcessToken then Result := NtxOpenProcessToken(hxToken, NtCurrentProcess, DesiredAccess, HandleAttributes) else if Handle = NtCurrentThreadToken then Result := NtxOpenThreadToken(hxToken, NtCurrentThread, DesiredAccess, HandleAttributes, InverseOpenLogic) else if Handle = NtCurrentEffectiveToken then Result := NtxOpenEffectiveTokenById(hxToken, NtCurrentTeb.ClientId, DesiredAccess, HandleAttributes, InverseOpenLogic) else begin Result.Location := 'NtxOpenPseudoToken'; Result.Status := STATUS_INVALID_HANDLE; end; end; function NtxExpandPseudoToken(out hxToken: IHandle; hToken: THandle; DesiredAccess: TAccessMask): TNtxStatus; begin if hToken > MAX_HANDLE then Result := NtxOpenPseudoToken(hxToken, hToken, DesiredAccess) else begin // Not a pseudo-handle. Capture, but do not close automatically. // Do not save this handle outside of the function since we // don't maintain its lifetime. Result.Status := STATUS_SUCCESS; hxToken := TAutoHandle.Capture(hToken); hxToken.AutoRelease := False; end; end; function NtxDuplicateEffectiveToken(out hxToken: IHandle; hThread: THandle; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var hxOldToken: IHandle; QoS: TSecurityQualityOfService; begin // Backup our impersonation token hxOldToken := NtxBackupImpersonation(NtCurrentThread); InitializaQoS(QoS, ImpersonationLevel, EffectiveOnly); // Direct impersonation makes the server thread to impersonate the effective // security context of the client thread. We use our thead as a server and the // target thread as a client, and then read the token from our thread. Result.Location := 'NtImpersonateThread'; Result.LastCall.Expects(THREAD_IMPERSONATE, @ThreadAccessType); // Server Result.LastCall.Expects(THREAD_DIRECT_IMPERSONATION, @ThreadAccessType); // Client // No access checks are performed on the client's token, we obtain a copy Result.Status := NtImpersonateThread(NtCurrentThread, hThread, QoS); if not Result.IsSuccess then Exit; // Read it back from our thread Result := NtxOpenThreadToken(hxToken, NtCurrentThread, DesiredAccess, HandleAttributes); // Restore our previous impersonation NtxRestoreImpersonation(NtCurrentThread, hxOldToken); end; function NtxDuplicateEffectiveTokenById(out hxToken: IHandle; TID: NativeUInt; ImpersonationLevel: TSecurityImpersonationLevel; DesiredAccess: TAccessMask; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var hxThread: IHandle; begin Result := NtxOpenThread(hxThread, TID, THREAD_DIRECT_IMPERSONATION); if Result.IsSuccess then Result := NtxDuplicateEffectiveToken(hxToken, hxThread.Handle, ImpersonationLevel, DesiredAccess, HandleAttributes, EffectiveOnly); end; function NtxDuplicateToken(out hxToken: IHandle; hExistingToken: THandle; DesiredAccess: TAccessMask; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; HandleAttributes: Cardinal; EffectiveOnly: Boolean): TNtxStatus; var hxExistingToken: IHandle; hToken: THandle; ObjAttr: TObjectAttributes; QoS: TSecurityQualityOfService; begin // Manage support for pseudo-handles Result := NtxExpandPseudoToken(hxExistingToken, hExistingToken, TOKEN_DUPLICATE); if not Result.IsSuccess then Exit; InitializaQoS(QoS, ImpersonationLevel, EffectiveOnly); InitializeObjectAttributes(ObjAttr, nil, HandleAttributes, 0, @QoS); Result.Location := 'NtDuplicateToken'; Result.LastCall.Expects(TOKEN_DUPLICATE, @TokenAccessType); Result.Status := NtDuplicateToken(hxExistingToken.Handle, DesiredAccess, @ObjAttr, EffectiveOnly, TokenType, hToken); if Result.IsSuccess then hxToken := TAutoHandle.Capture(hToken); end; function NtxOpenAnonymousToken(out hxToken: IHandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hxOldToken: IHandle; begin // Backup our impersonation context hxOldToken := NtxBackupImpersonation(NtCurrentThread); // Set our thread to impersonate anonymous token Result.Location := 'NtImpersonateAnonymousToken'; Result.LastCall.Expects(THREAD_IMPERSONATE, @ThreadAccessType); Result.Status := NtImpersonateAnonymousToken(NtCurrentThread); // Read the token from the thread if Result.IsSuccess then Result := NtxOpenThreadToken(hxToken, NtCurrentThread, DesiredAccess, HandleAttributes); // Restore previous impersonation NtxRestoreImpersonation(NtCurrentThread, hxOldToken); end; function NtxFilterToken(out hxNewToken: IHandle; hToken: THandle; Flags: Cardinal; SidsToDisable: TArray<ISid>; PrivilegesToDelete: TArray<TLuid>; SidsToRestrict: TArray<ISid>): TNtxStatus; var hxToken: IHandle; hNewToken: THandle; DisableSids, RestrictSids: PTokenGroups; DeletePrivileges: PTokenPrivileges; begin // Manage pseudo-tokens Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_DUPLICATE); if not Result.IsSuccess then Exit; DisableSids := NtxpAllocGroups(SidsToDisable, 0); RestrictSids := NtxpAllocGroups(SidsToRestrict, 0); DeletePrivileges := NtxpAllocPrivileges(PrivilegesToDelete, 0); Result.Location := 'NtFilterToken'; Result.LastCall.Expects(TOKEN_DUPLICATE, @TokenAccessType); Result.Status := NtFilterToken(hxToken.Handle, Flags, DisableSids, DeletePrivileges, RestrictSids, hNewToken); if Result.IsSuccess then hxNewToken := TAutoHandle.Capture(hNewToken); FreeMem(DisableSids); FreeMem(RestrictSids); FreeMem(DeletePrivileges); end; function NtxCreateToken(out hxToken: IHandle; TokenType: TTokenType; ImpersonationLevel: TSecurityImpersonationLevel; AuthenticationId: TLuid; ExpirationTime: TLargeInteger; User: TGroup; Groups: TArray<TGroup>; Privileges: TArray<TPrivilege>; Owner: ISid; PrimaryGroup: ISid; DefaultDacl: IAcl; const TokenSource: TTokenSource; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var hToken: THandle; QoS: TSecurityQualityOfService; ObjAttr: TObjectAttributes; TokenUser: TSidAndAttributes; TokenGroups: PTokenGroups; TokenPrivileges: PTokenPrivileges; TokenOwner: TTokenOwner; pTokenOwnerRef: PTokenOwner; TokenPrimaryGroup: TTokenPrimaryGroup; TokenDefaultDacl: TTokenDefaultDacl; pTokenDefaultDaclRef: PTokenDefaultDacl; begin InitializaQoS(QoS, ImpersonationLevel); InitializeObjectAttributes(ObjAttr, nil, HandleAttributes, 0, @QoS); // Prepare user Assert(Assigned(User.SecurityIdentifier)); TokenUser.Sid := User.SecurityIdentifier.Sid; TokenUser.Attributes := User.Attributes; // Prepare groups and privileges TokenGroups := NtxpAllocGroups2(Groups); TokenPrivileges:= NtxpAllocPrivileges2(Privileges); // Owner is optional if Assigned(Owner) then begin TokenOwner.Owner := Owner.Sid; pTokenOwnerRef := @TokenOwner; end else pTokenOwnerRef := nil; // Prepare primary group Assert(Assigned(PrimaryGroup)); TokenPrimaryGroup.PrimaryGroup := PrimaryGroup.Sid; // Default Dacl is optional if Assigned(DefaultDacl) then begin TokenDefaultDacl.DefaultDacl := DefaultDacl.Acl; pTokenDefaultDaclRef := @TokenDefaultDacl; end else pTokenDefaultDaclRef := nil; Result.Location := 'NtCreateToken'; Result.LastCall.ExpectedPrivilege := SE_CREATE_TOKEN_PRIVILEGE; Result.Status := NtCreateToken(hToken, DesiredAccess, @ObjAttr, TokenType, AuthenticationId, ExpirationTime, TokenUser, TokenGroups, TokenPrivileges, pTokenOwnerRef, TokenPrimaryGroup, pTokenDefaultDaclRef, TokenSource); if Result.IsSuccess then hxToken := TAutoHandle.Capture(hToken); // Clean up FreeMem(TokenGroups); FreeMem(TokenPrivileges); end; function NtxCreateLowBoxToken(out hxToken: IHandle; hExistingToken: THandle; Package: PSid; Capabilities: TArray<TGroup>; Handles: TArray<THandle>; HandleAttributes: Cardinal): TNtxStatus; var hxExistingToken: IHandle; hToken: THandle; ObjAttr: TObjectAttributes; CapArray: TArray<TSidAndAttributes>; i: Integer; begin Result := LdrxCheckNtDelayedImport('NtCreateLowBoxToken'); if not Result.IsSuccess then Exit; // Manage pseudo-handles on input Result := NtxExpandPseudoToken(hxExistingToken, hExistingToken, TOKEN_DUPLICATE); if not Result.IsSuccess then Exit; InitializeObjectAttributes(ObjAttr, nil, HandleAttributes); // Prepare capabilities SetLength(CapArray, Length(Capabilities)); for i := 0 to High(CapArray) do begin CapArray[i].Sid := Capabilities[i].SecurityIdentifier.Sid; CapArray[i].Attributes := Capabilities[i].Attributes; end; Result.Location := 'NtCreateLowBoxToken'; Result.LastCall.Expects(TOKEN_DUPLICATE, @TokenAccessType); Result.Status := NtCreateLowBoxToken(hToken, hxExistingToken.Handle, TOKEN_ALL_ACCESS, @ObjAttr, Package, Length(CapArray), CapArray, Length(Handles), Handles); if Result.IsSuccess then hxToken := TAutoHandle.Capture(hToken); end; { Other operations } function NtxAdjustPrivileges(hToken: THandle; Privileges: TArray<TLuid>; NewAttribute: Cardinal): TNtxStatus; var hxToken: IHandle; Buffer: PTokenPrivileges; begin // Manage working with pseudo-handles Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_ADJUST_PRIVILEGES); if not Result.IsSuccess then Exit; Buffer := NtxpAllocPrivileges(Privileges, NewAttribute); Result.Location := 'NtAdjustPrivilegesToken'; Result.LastCall.Expects(TOKEN_ADJUST_PRIVILEGES, @TokenAccessType); Result.Status := NtAdjustPrivilegesToken(hxToken.Handle, False, Buffer, 0, nil, nil); FreeMem(Buffer); end; function NtxAdjustPrivilege(hToken: THandle; Privilege: TSeWellKnownPrivilege; NewAttribute: Cardinal): TNtxStatus; var Privileges: TArray<TLuid>; begin SetLength(Privileges, 1); Privileges[0] := TLuid(Privilege); Result := NtxAdjustPrivileges(hToken, Privileges, NewAttribute); end; function NtxAdjustGroups(hToken: THandle; Sids: TArray<ISid>; NewAttribute: Cardinal; ResetToDefault: Boolean): TNtxStatus; var hxToken: IHandle; Buffer: PTokenGroups; begin // Manage working with pseudo-handles Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_ADJUST_GROUPS); if not Result.IsSuccess then Exit; Buffer := NtxpAllocGroups(Sids, NewAttribute); Result.Location := 'NtAdjustGroupsToken'; Result.LastCall.Expects(TOKEN_ADJUST_GROUPS, @TokenAccessType); Result.Status := NtAdjustGroupsToken(hxToken.Handle, ResetToDefault, Buffer, 0, nil, nil); FreeMem(Buffer); end; end.
unit fmAuthTest; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, pVDLogger, pVDEtc, Vcl.StdCtrls, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.CategoryButtons, Vcl.ExtCtrls, Vcl.WinXPanels, Vcl.ComCtrls, System.UITypes; type TfAuthTest = class(TForm) etcMain: TVDEtc; logMain: TVDLogger; cbMain: TCategoryButtons; amMain: TActionManager; aShowLogFileName: TAction; aShowLogFilePath: TAction; aAddLines: TAction; spMain: TStackPanel; Label1: TLabel; eFirstLine: TEdit; Label2: TLabel; eSecondLine: TEdit; Label3: TLabel; meAddLines: TMemo; aAddStringList: TAction; aDisplayLogfile: TAction; StatusBar1: TStatusBar; aCycleLogFile: TAction; procedure aShowLogFileNameExecute(Sender: TObject); procedure aShowLogFilePathExecute(Sender: TObject); procedure aAddLinesExecute(Sender: TObject); procedure aAddStringListExecute(Sender: TObject); procedure aDisplayLogfileExecute(Sender: TObject); procedure aCycleLogFileExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var fAuthTest: TfAuthTest; implementation {$R *.dfm} procedure TfAuthTest.aAddLinesExecute(Sender: TObject); begin logMain.LogLine(TLogSource.lsUtility, [eFirstLine.Text, eSecondLine.Text]); end; procedure TfAuthTest.aAddStringListExecute(Sender: TObject); begin logMain.LogStrings(TLogSource.lsUtility, meAddLines.Lines); end; procedure TfAuthTest.aCycleLogFileExecute(Sender: TObject); begin if logMain.CycleLogfile then ShowMessage('Logfile Cycle Successful') else ShowMessage('Logfile Cycle Failed'); end; procedure TfAuthTest.aDisplayLogfileExecute(Sender: TObject); begin logMain.ShowLog; end; procedure TfAuthTest.aShowLogFileNameExecute(Sender: TObject); begin MessageDlg(logMain.GetLogFileName, mtInformation, [mbOK], 0); end; procedure TfAuthTest.aShowLogFilePathExecute(Sender: TObject); begin MessageDlg(logMain.GetLogFilePath, mtInformation, [mbOK], 0); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Login dialog } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.VCLUI.Login; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Dialogs, Vcl.ImgList, FireDAC.Stan.Intf, FireDAC.UI.Intf, FireDAC.UI, FireDAC.VCLUI.OptsBase; type TFDGUIxFormsLoginDialogImpl = class; TfrmFDGUIxFormsLogin = class; TFDGUIxFormsLoginDialogImpl = class(TFDGUIxLoginDialogImplBase) private function CreateDlg: TfrmFDGUIxFormsLogin; protected function ExecuteLogin: Boolean; override; function ExecuteChngPwd: Boolean; override; end; TfrmFDGUIxFormsLogin = class(TfrmFDGUIxFormsOptsBase) pnlLogin: TPanel; pnlControls: TPanel; pnlHistory: TPanel; Label1: TLabel; SpeedButton1: TSpeedButton; cbxProfiles: TComboBox; Bevel1: TBevel; pnlChngPwd: TPanel; Label2: TLabel; Label3: TLabel; edtNewPassword: TEdit; edtNewPassword2: TEdit; OpenDialog1: TOpenDialog; ImageList1: TImageList; procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure cbxProfilesClick(Sender: TObject); procedure edtNewPasswordChange(Sender: TObject); procedure cbxProfilesChange(Sender: TObject); procedure FileEditClick(Sender: TObject); private FDlg: TFDGUIxFormsLoginDialogImpl; FAddToOptionsHeight: Integer; public function ExecuteLogin: Boolean; function ExecuteChngPwd: Boolean; end; var frmFDGUIxFormsLogin: TfrmFDGUIxFormsLogin; implementation uses FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs, FireDAC.Phys.Intf, FireDAC.VCLUI.Controls; {$R *.dfm} {-------------------------------------------------------------------------------} { TfrmFDGUIxFormsLogin } {-------------------------------------------------------------------------------} type __TControl = class(TControl) end; {-------------------------------------------------------------------------------} function TfrmFDGUIxFormsLogin.ExecuteLogin: Boolean; var i, j: Integer; rTmp: TFDLoginItem; oPanel: TPanel; oLabel: TLabel; oCombo: TComboBox; oEdit: TEdit; oChk: TCheckBox; oBEdit: TButtonedEdit; oCtrl: TControl; oActiveCtrl: TWinControl; M: TMonitor; begin pnlChngPwd.Visible := False; pnlLogin.Align := alClient; pnlLogin.Visible := True; lblPrompt.Caption := S_FD_LoginCredentials; M := Application.MainForm.Monitor; while pnlControls.ControlCount > 0 do FDFree(pnlControls.Controls[0]); for i := 0 to Length(FDlg.FParams) - 1 do for j := i to Length(FDlg.FParams) - 2 do if FDlg.FParams[j].FOrder > FDlg.FParams[j + 1].FOrder then begin rTmp := FDlg.FParams[j + 1]; FDlg.FParams[j + 1] := FDlg.FParams[j]; FDlg.FParams[j] := rTmp; end; oActiveCtrl := nil; for i := 0 to Length(FDlg.FParams) - 1 do begin oPanel := TPanel.Create(Self); oPanel.BevelInner := bvNone; oPanel.BevelOuter := bvNone; oPanel.BorderStyle := bsNone; oPanel.Top := i * 26; oPanel.Height := 26; oPanel.Left := 3; oPanel.Width := pnlControls.ClientWidth; oPanel.Parent := pnlControls; oLabel := TLabel.Create(Self); oLabel.Top := 5; oLabel.Left := 3; oLabel.Parent := oPanel; oLabel.Caption := '&' + FDlg.FParams[i].FCaption + ':'; if (FDlg.FParams[i].FType = '@L') or (FDlg.FParams[i].FType = '@Y') then begin oChk := TCheckBox.Create(Self); oChk.Top := 4; oChk.Left := 70; oChk.Tag := i; oChk.Checked := (CompareText(FDlg.FParams[i].FValue, S_FD_True) = 0) or (CompareText(FDlg.FParams[i].FValue, S_FD_Yes) = 0); oChk.Parent := oPanel; oLabel.FocusControl := oChk; end else if Copy(FDlg.FParams[i].FType, 1, 2) = '@F' then begin oBEdit := TButtonedEdit.Create(Self); oBEdit.Top := 2; oBEdit.Left := 70; oBEdit.Width := 166; oBEdit.Parent := oPanel; oBEdit.Tag := i; oBEdit.Images := ImageList1; oBEdit.RightButton.ImageIndex := 0; oBEdit.RightButton.Visible := True; oBEdit.OnRightButtonClick := FileEditClick; FDGUIxSetupEditor(nil, nil, oBEdit, OpenDialog1, FDlg.FParams[i].FType); oBEdit.Text := FDlg.FParams[i].FValue; if (oBEdit.Text = '') and (oActiveCtrl = nil) then oActiveCtrl := oBEdit; oLabel.FocusControl := oBEdit; end else if (FDlg.FParams[i].FType <> '@S') and (FDlg.FParams[i].FType <> '@I') and (FDlg.FParams[i].FType <> '@P') then begin oCombo := TComboBox.Create(Self); oCombo.Top := 2; oCombo.Left := 70; oCombo.Width := 166; oCombo.Parent := oPanel; oCombo.Tag := i; FDGUIxSetupEditor(oCombo, nil, nil, nil, FDlg.FParams[i].FType); oCombo.Text := FDlg.FParams[i].FValue; if (oCombo.Text = '') and (oActiveCtrl = nil) then oActiveCtrl := oCombo; oLabel.FocusControl := oCombo; end else begin oEdit := TEdit.Create(Self); if FDlg.FParams[i].FType = '@P' then oEdit.PasswordChar := '#'; oEdit.Top := 2; oEdit.Left := 70; oEdit.Width := 166; oEdit.Parent := oPanel; oEdit.Tag := i; oEdit.Text := FDlg.FParams[i].FValue; if (oEdit.Text = '') and (oActiveCtrl = nil) then oActiveCtrl := oEdit; oLabel.FocusControl := oEdit; end; end; ClientHeight := FAddToOptionsHeight + Length(FDlg.FParams) * Muldiv(26, M.PixelsPerInch, 96); ClientWidth := Muldiv(250, M.PixelsPerInch, 96); if oActiveCtrl = nil then ActiveControl := btnOk else ActiveControl := oActiveCtrl; if FDlg.FHistoryEnabled then begin cbxProfiles.Items := FDlg.FHistory; cbxProfiles.ItemIndex := FDlg.FHistoryIndex; {$IFDEF MSWINDOWS} SendMessage(cbxProfiles.Handle, CB_SETDROPPEDWIDTH, Width, 0); {$ENDIF} cbxProfiles.OnChange(nil); end else begin cbxProfiles.Items.Clear; Height := Height - pnlHistory.Height; pnlHistory.Visible := False; end; Result := (ShowModal = mrOK); if Result then begin for i := 0 to pnlControls.ControlCount - 1 do begin oCtrl := TPanel(pnlControls.Controls[i]).Controls[1]; if oCtrl is TCheckBox then if FDlg.FParams[oCtrl.Tag].FType = '@Y' then FDlg.FConnectionDef.AsYesNo[FDlg.FParams[oCtrl.Tag].FParam] := TCheckBox(oCtrl).Checked else FDlg.FConnectionDef.AsBoolean[FDlg.FParams[oCtrl.Tag].FParam] := TCheckBox(oCtrl).Checked else FDlg.FConnectionDef.AsString[FDlg.FParams[oCtrl.Tag].FParam] := __TControl(oCtrl).Caption; end; end; Application.ProcessMessages; end; {-------------------------------------------------------------------------------} function TfrmFDGUIxFormsLogin.ExecuteChngPwd: Boolean; begin ClientHeight := pnlButtons.Height + pnlTop.Height + pnlChngPwd.Height; Width := 250; pnlLogin.Visible := False; pnlChngPwd.Align := alClient; pnlChngPwd.Visible := True; lblPrompt.Caption := S_FD_LoginNewPassword; btnOk.Enabled := False; ActiveControl := edtNewPassword; Result := (ShowModal = mrOK); if Result then FDlg.FConnectionDef.Params.NewPassword := edtNewPassword.Text; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.FormCreate(Sender: TObject); begin FAddToOptionsHeight := pnlButtons.Height + pnlTop.Height + pnlHistory.Height; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.SpeedButton1Click(Sender: TObject); begin if cbxProfiles.ItemIndex = -1 then Exit; FDlg.RemoveHistory(cbxProfiles.Text); cbxProfiles.Items.Delete(cbxProfiles.ItemIndex); cbxProfiles.ItemIndex := -1; cbxProfiles.Text := ''; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.cbxProfilesClick(Sender: TObject); var i: Integer; oCtrl: TControl; oList: TStrings; begin oList := TFDStringList.Create; try FDlg.ReadHistory(cbxProfiles.Text, oList); for i := 0 to pnlControls.ControlCount - 1 do begin oCtrl := TPanel(pnlControls.Controls[i]).Controls[1]; __TControl(oCtrl).Caption := oList.Values[FDlg.FParams[oCtrl.Tag].FParam]; end; finally FDFree(oList); end; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.cbxProfilesChange(Sender: TObject); begin SpeedButton1.Enabled := cbxProfiles.Text <> ''; end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.edtNewPasswordChange(Sender: TObject); begin btnOk.Enabled := (edtNewPassword.Text = edtNewPassword2.Text); end; {-------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsLogin.FileEditClick(Sender: TObject); begin OpenDialog1.FileName := TCustomEdit(Sender).Text; if OpenDialog1.Execute then TCustomEdit(Sender).Text := OpenDialog1.FileName; end; {-------------------------------------------------------------------------------} { TFDGUIxFormsLoginDialogImpl } {-------------------------------------------------------------------------------} function TFDGUIxFormsLoginDialogImpl.CreateDlg: TfrmFDGUIxFormsLogin; begin Result := TfrmFDGUIxFormsLogin.Create(Application); Result.FDlg := Self; Result.Caption := FCaption; end; {-------------------------------------------------------------------------------} function TFDGUIxFormsLoginDialogImpl.ExecuteLogin: Boolean; var oLogin: TfrmFDGUIxFormsLogin; begin oLogin := CreateDlg; Result := oLogin.ExecuteLogin; end; {-------------------------------------------------------------------------------} function TFDGUIxFormsLoginDialogImpl.ExecuteChngPwd: Boolean; var oLogin: TfrmFDGUIxFormsLogin; begin oLogin := CreateDlg; Result := oLogin.ExecuteChngPwd; end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization oFact := TFDMultyInstanceFactory.Create(TFDGUIxFormsLoginDialogImpl, IFDGUIxLoginDialog, C_FD_GUIxFormsProvider); finalization FDReleaseFactory(oFact); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2015-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.JSON.BSON; interface {$SCOPEDENUMS ON} uses System.SysUtils, System.Classes, System.Generics.Collections, System.Rtti, System.JSON.Types, System.JSON.Writers, System.JSON.Readers; type /// <summary> /// Code of each bson type. See http://bsonspec.org/spec.html /// </summary> TBsonType = ( BsonDocument = 0, Float = 1, &String = 2, &Object = 3, &Array = 4, Binary = 5, Undefined = 6, Oid = 7, Boolean = 8, DateTime = 9, Null = 10, Regex = 11, Reference = 12, Code = 13, Symbol = 14, CodeWScope = 15, Integer = 16, TimeStamp = 17, Long = 18, MinKey = 255, MaxKey = 127 ); /// <summary> /// Writer to serialize data into Bson. See http://bsonspec.org/ /// </summary> TBsonWriter = class(TJsonWriter) private type TBsonContainer = class abstract private [Weak] FParent: TBsonContainer; FPosition: Integer; FValuesSize: Integer; FChildren: TObjectList<TBsonContainer>; public constructor Create(AParent: TBsonContainer; SizePos: Integer); destructor Destroy; override; property Children: TObjectList<TBsonContainer> read FChildren; property ValuesSize: Integer read FValuesSize write FValuesSize; property Position: Integer read FPosition write FPosition; property Parent: TBsonContainer read FParent write FParent; end; TBsonObject = class(TBsonContainer) end; TBsonArray = class(TBsonContainer) private FIndex: Integer; public property &Index: Integer read FIndex write FIndex; end; private FEncoding: TEncoding; FWriter: TBinaryWriter; FWriterOwner: Boolean; FRoot: TBsonContainer; FParent: TBsonContainer; FPropertyName: string; procedure AddContainer(const Token: TBsonContainer); procedure AddSize(Size: Integer); inline; function WriteContainerSize(Container: TBsonContainer): Integer; procedure WriteType(BsonType: TBsonType); procedure WriteKey; procedure WriteInteger(const Value: Integer); procedure WriteInt64(const Value: Int64); procedure WriteDouble(const Value: Double); procedure WriteString(const Value: string); procedure WriteCString(const Value: string); procedure WriteBytes(const Value: TBytes; BinaryType: TJsonBinaryType); procedure WriteBoolean(const Value: Boolean); procedure WriteOid(const Value: TJsonOid); procedure InternalWriteStartObject(Inlined: Boolean); protected /// <summary> Write the end token based on the token, this method does not updates the internal state </summary> /// <remarks> When the token to be written is the last end token, the document it will be flushed. See <see cref="Flush">Flush</see></remarks> procedure WriteEnd(const Token: TJsonToken); override; public constructor Create(const ABinaryWriter: TBinaryWriter); overload; constructor Create(const Stream: TStream); overload; destructor Destroy; override; /// <sumary> Resets the internal state allowing write from the begining </sumary> procedure Rewind; override; /// <summary> Close the writer and flushes the document. See <see cref="Flush">Flush</see>.</summary> procedure Close; override; /// <summary> /// Calculates and writes the preceding size of each object/array written in the underliying stream/BinaryWriter. /// If the document is not finished (the last end token is not written yet) the containers will be closed by written /// the end token but without updating the internal writer state /// </summary> procedure Flush; override; /// <summary> Writes a comment</summary> procedure WriteComment(const Comment: string); override; /// <summary> Writes the start of a json object </summary> procedure WriteStartObject; override; /// <summary> Writes the end of a json object </summary> procedure WriteEndObject; override; /// <summary> Writes the start of a json array </summary> procedure WriteStartArray; override; /// <summary> Writes the end of a json array </summary> procedure WriteEndArray; override; /// <summary> Writes the start of a javascript constructor </summary> procedure WriteStartConstructor(const Name: string); override; /// <summary> Writes a property name </summary> procedure WritePropertyName(const Name: string); override; /// <summary> Writes a null value </summary> procedure WriteNull; override; /// <summary> Writes a raw json, it does not update the internal state </summary> procedure WriteRaw(const Json: string); override; /// <summary> Writes a raw json, it updates the internal state </summary> procedure WriteRawValue(const Json: string); override; /// <summary> Writes an undefined value </summary> procedure WriteUndefined; override; /// <summary> Writes an string value </summary> procedure WriteValue(const Value: string); override; /// <summary> Writes an Integer value </summary> procedure WriteValue(Value: Integer); override; /// <summary> Writes an UInt32 value </summary> procedure WriteValue(Value: UInt32); override; /// <summary> Writes an Int64 value </summary> procedure WriteValue(Value: Int64); override; /// <summary> Writes an UInt64 value value </summary> procedure WriteValue(Value: UInt64); override; /// <summary> Writes a Single value </summary> procedure WriteValue(Value: Single); override; /// <summary> Writes a Double value </summary> procedure WriteValue(Value: Double); override; /// <summary> Writes an Extended value </summary> procedure WriteValue(Value: Extended); override; /// <summary> Writes a Boolean value </summary> procedure WriteValue(Value: Boolean); override; /// <summary> Writes a Char value </summary> procedure WriteValue(Value: Char); override; /// <summary> Writes a Byte value </summary> procedure WriteValue(Value: Byte); override; /// <summary> Writes a TDateTime value </summary> procedure WriteValue(Value: TDateTime); override; /// <summary> Writes a <see cref="TGUID">TGUID</see> value </summary> procedure WriteValue(const Value: TGUID); override; /// <summary> Writes a Binary value. See http://bsonspec.org/spec.html </summary> procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); override; /// <summary> Writes a <see cref="TJsonOid">TJsonOid</see> value. See http://bsonspec.org/spec.html </summary> procedure WriteValue(const Value: TJsonOid); override; /// <summary> Writes a <see cref="TJsonRegEx">TJsonRegEx</see> value. See http://bsonspec.org/spec.html </summary> procedure WriteValue(const Value: TJsonRegEx); override; /// <summary> Writes a <see cref="TJsonDBRef">TJsonDBRef</see> value. See http://bsonspec.org/spec.html </summary> procedure WriteValue(const Value: TJsonDBRef); override; /// <summary> Writes a <see cref="TJsonCodeWScope">TJsonCodeWScope</see> value. See http://bsonspec.org/spec.html </summary> procedure WriteValue(const Value: TJsonCodeWScope); override; /// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary> procedure WriteMinKey; override; /// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary> procedure WriteMaxKey; override; // BSON specific extensions procedure WriteCode(const Code: string); /// <summary> Gets the underliying binary Writer </summary> /// <remarks> When the TStream overload constructor is used the returned Writer is owned by this class </remarks> property Writer: TBinaryWriter read FWriter; end; /// <summary> /// Reader to access Bson data. See http://bsonspec.org/ /// </summary> TBsonReader = class(TJsonReader) private const MaxCharBytesSize = 128; CodeWScopeKey = '$code'; // do not localize type TContainerContext = class public &Type: TBsonType; Length: Integer; Position: Integer; constructor Create(AType: TBsonType); end; private FEncoding: TEncoding; FCurrentElementType: TBsonType; FReadRootValueAsArray: Boolean; FReader: TBinaryReader; FStack: TObjectStack<TContainerContext>; FCurrentContext: TContainerContext; FByteBuffer: TBytes; FCharBuffer: TCharArray; function ReadElement: string; function ReadCodeWScope: TJsonCodeWScope; function ReadRegEx: TJsonRegEx; function ReadDBRef: TJsonDBRef; function ReadDouble: Double; function ReadInteger: Integer; function ReadInt64: Int64; function ReadByte: Byte; function ReadString: string; overload; function ReadString(ALength: Integer): string; overload; function ReadCString: string; function ReadType: TBsonType; procedure ReadByType(AType: TBsonType); function ReadBinary(out BinaryType: TJsonBinaryType): TBytes; function ReadBytes(Count: Integer): TBytes; procedure MovePosition(Count: Integer); inline; procedure PopContext(FreeContext: Boolean); procedure PushContext(const Context: TContainerContext); protected function ReadInternal: Boolean; override; public constructor Create(const AStream: TStream; AReadAsRootValuesArray: Boolean = False); destructor Destroy; override; /// <summary> Changes the <see cref="TJsonReader.TState"/> to Closed. </summary> procedure Close; override; /// <summary> Skips the children of the current token </summary> procedure Skip; override; /// <summary> Resets the reader state to start read again </summary> procedure Rewind; override; /// <summary> Indicating whether the root object will be read as JSON array </summary> property ReadRootValueAsArray: Boolean read FReadRootValueAsArray write FReadRootValueAsArray; /// <summary> Gets the current bson type element </summary> property CurrentElementType: TBsonType read FCurrentElementType; /// <summary> Gets the underlying reader </summary> property Reader: TBinaryReader read FReader; end; implementation uses System.TypInfo, System.DateUtils, System.Math, System.JSONConsts, System.JSON.Utils; { Helpers } function GetName(Value: TJsonToken): string; overload; begin Result := GetEnumName(TypeInfo(TJsonToken), Integer(Value)); end; { TBsonWriter } constructor TBsonWriter.Create(const ABinaryWriter: TBinaryWriter); begin inherited Create; FEncoding := TEncoding.UTF8; FWriter := ABinaryWriter; DateTimeZoneHandling := TJsonDateTimeZoneHandling.Utc; end; constructor TBsonWriter.Create(const Stream: TStream); begin Create(TBinaryWriter.Create(Stream)); FWriterOwner := True; end; procedure TBsonWriter.AddSize(Size: Integer); begin FParent.ValuesSize := FParent.ValuesSize + Size; end; procedure TBsonWriter.AddContainer(const Token: TBsonContainer); begin if FParent <> nil then FParent.Children.Add(Token) else FRoot := Token; FParent := Token; end; destructor TBsonWriter.Destroy; begin if FCurrentState <> TState.Closed then Close; if FRoot <> nil then FreeAndNil(FRoot); if FWriterOwner then FWriter.Free; inherited Destroy; end; function TBsonWriter.WriteContainerSize(Container: TBsonContainer): Integer; var ChildContainer: TBsonContainer; begin // Size + ValuesSize + EndSize Result := SizeOf(Integer) + Container.ValuesSize + SizeOf(Byte); for ChildContainer in Container.Children do Result := Result + WriteContainerSize(ChildContainer) ; FWriter.BaseStream.Position := Container.Position; FWriter.Write(Result); end; procedure TBsonWriter.Close; begin inherited Close; FreeAndNil(FRoot); end; procedure TBsonWriter.Flush; var LastPosition, I, ValuesSize: Integer; begin if FCurrentState = TState.Start then Exit; LastPosition := FWriter.BaseStream.Position; // if we are in a property write it as null if FCurrentState = TState.Property then begin ValuesSize := FParent.ValuesSize; WriteType(TBsonType.Null); WriteKey; end else ValuesSize := 0; // close all opened containers for I := 1 to Top do FWriter.Write(Byte(0)); WriteContainerSize(FRoot); // restore the property size if FCurrentState = TState.Property then FParent.ValuesSize := ValuesSize; FWriter.BaseStream.Position := LastPosition; end; procedure TBsonWriter.Rewind; begin inherited Rewind; FParent := nil; FPropertyName := ''; FreeAndNil(FRoot); end; procedure TBsonWriter.WriteBoolean(const Value: Boolean); begin FWriter.Write(Value); AddSize(SizeOf(Boolean)); end; procedure TBsonWriter.WriteBytes(const Value: TBytes; BinaryType: TJsonBinaryType); begin FWriter.Write(Integer(Length(Value))); FWriter.Write(Byte(BinaryType)); FWriter.Write(Value); AddSize(SizeOf(Integer) + SizeOf(Byte) + Length(Value)); end; procedure TBsonWriter.WriteString(const Value: string); var Bytes: TBytes; begin Bytes := FEncoding.GetBytes(Value); FWriter.Write(Integer(Length(Bytes) + SizeOf(Byte))); // string byte size + null termination FWriter.Write(Bytes); FWriter.Write(Byte(0)); AddSize(SizeOf(Integer) + Length(Bytes) + SizeOf(Byte)); end; procedure TBsonWriter.WriteCString(const Value: string); var Bytes: TBytes; begin Bytes := FEncoding.GetBytes(Value); FWriter.Write(Bytes); FWriter.Write(Byte(0)); AddSize(Length(Bytes) + SizeOf(Byte)); end; procedure TBsonWriter.WriteDouble(const Value: Double); begin FWriter.Write(Value); AddSize(SizeOf(Double)); end; procedure TBsonWriter.WriteOid(const Value: TJsonOid); var Bytes: TBytes; begin Bytes := BytesOf(@Value.bytes[0], SizeOf(Value.bytes)); FWriter.Write(Bytes); AddSize(Length(Bytes)); end; procedure TBsonWriter.WriteEnd(const Token: TJsonToken); begin inherited WriteEnd(Token); if Top = 0 then Flush; end; procedure TBsonWriter.WriteInt64(const Value: Int64); begin FWriter.Write(Value); AddSize(SizeOf(Int64)); end; procedure TBsonWriter.WriteInteger(const Value: Integer); begin FWriter.Write(Value); AddSize(SizeOf(Integer)); end; procedure TBsonWriter.WriteKey; begin if FParent is TBsonObject then WriteCString(FPropertyName) else if FParent is TBsonArray then begin WriteCString(TBsonArray(FParent).Index.ToString); TBsonArray(FParent).Index := TBsonArray(FParent).Index + 1; end; end; procedure TBsonWriter.WriteType(BsonType: TBsonType); begin FWriter.Write(Byte(BsonType)); AddSize(SizeOf(Byte)); end; procedure TBsonWriter.WriteComment(const Comment: string); begin raise EJsonWriterException.Create(SUnsupportedCommentBson); end; procedure TBsonWriter.WriteNull; begin inherited WriteNull; WriteType(TBsonType.Null); WriteKey; end; procedure TBsonWriter.WriteStartConstructor(const Name: string); begin raise EJsonWriterException.Create(SUnsupportedBsonConstructor); end; procedure TBsonWriter.WriteRaw(const Json: string); begin raise EJsonWriterException.Create(SUnsupportedBsonRaw); end; procedure TBsonWriter.WriteRawValue(const Json: string); begin raise EJsonWriterException.Create(SUnsupportedBsonRaw); end; procedure TBsonWriter.WriteStartArray; begin inherited WriteStartArray; if FParent <> nil then begin WriteType(TBsonType.Array); WriteKey; end; // the size is only knowed after end it (WriteEndArray) so the position is saved to fill it at the end AddContainer(TBsonArray.Create(FParent, FWriter.BaseStream.Position)); FWriter.Write(Integer(0)); end; procedure TBsonWriter.InternalWriteStartObject(Inlined: Boolean); begin inherited WriteStartObject; if (FParent <> nil) and not Inlined then begin WriteType(TBsonType.Object); WriteKey; end; // the size is only knowed after end it (WriteEndObject) so the position is saved to fill it at the end AddContainer(TBsonObject.Create(FParent, FWriter.BaseStream.Position)); FWriter.Write(Integer(0)); end; procedure TBsonWriter.WriteStartObject; begin InternalWriteStartObject(False); end; procedure TBsonWriter.WriteEndArray; begin inherited WriteEndArray; FWriter.Write(Byte(0)); FParent := FParent.Parent; end; procedure TBsonWriter.WriteEndObject; begin inherited WriteEndObject; FWriter.Write(Byte(0)); FParent := FParent.Parent; end; procedure TBsonWriter.WriteUndefined; begin inherited WriteUndefined; WriteType(TBsonType.Undefined); WriteKey; end; procedure TBsonWriter.WriteValue(Value: UInt64); begin inherited WriteValue(Value); WriteType(TBsonType.Long); WriteKey; WriteInt64(PInt64(@Value)^); end; procedure TBsonWriter.WriteValue(Value: Single); begin inherited WriteValue(Value); WriteType(TBsonType.Float); WriteKey; WriteDouble(Value); end; procedure TBsonWriter.WriteValue(Value: Double); begin inherited WriteValue(Value); WriteType(TBsonType.Float); WriteKey; WriteDouble(Value); end; procedure TBsonWriter.WriteValue(Value: Int64); begin inherited WriteValue(Value); WriteType(TBsonType.Long); WriteKey; WriteInt64(Value); end; procedure TBsonWriter.WriteValue(const Value: string); begin inherited WriteValue(Value); if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then Exit; WriteType(TBsonType.String); WriteKey; WriteString(Value); end; procedure TBsonWriter.WriteValue(Value: Integer); begin inherited WriteValue(Value); WriteType(TBsonType.Integer); WriteKey; WriteInteger(Value); end; procedure TBsonWriter.WriteValue(Value: UInt32); begin inherited WriteValue(Value); WriteType(TBsonType.Integer); WriteKey; WriteInteger(PInteger(@Value)^); end; procedure TBsonWriter.WriteValue(Value: Extended); begin inherited WriteValue(Value); WriteType(TBsonType.Float); WriteKey; WriteDouble(Value); end; procedure TBsonWriter.WriteValue(const Value: TGUID); begin inherited WriteValue(Value); WriteType(TBsonType.Binary); WriteKey; WriteBytes(Value.ToByteArray, TJsonBinaryType.Uuid); end; procedure TBsonWriter.WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); begin inherited WriteValue(Value); if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then Exit; WriteType(TBsonType.Binary); WriteKey; WriteBytes(Value, BinaryType); end; procedure TBsonWriter.WriteValue(const Value: TJsonOid); begin inherited WriteValue(Value); WriteType(TBsonType.Oid); WriteKey; WriteOid(Value); end; procedure TBsonWriter.WriteValue(Value: TDateTime); begin inherited WriteValue(Value); WriteType(TBsonType.DateTime); WriteKey; if DateTimeZoneHandling = TJsonDateTimeZoneHandling.Local then Value := TTimeZone.Local.ToUniversalTime(Value); WriteInt64(DateTimeToMilliseconds(Value) - DateTimeToMilliseconds(UnixDateDelta)); end; procedure TBsonWriter.WriteValue(Value: Boolean); begin inherited WriteValue(Value); WriteType(TBsonType.Boolean); WriteKey; WriteBoolean(Value); end; procedure TBsonWriter.WriteValue(Value: Char); begin inherited WriteValue(Value); WriteType(TBsonType.String); WriteKey; WriteString(Value); end; procedure TBsonWriter.WriteValue(Value: Byte); begin inherited WriteValue(Value); WriteType(TBsonType.Integer); WriteKey; WriteInteger(Value); end; procedure TBsonWriter.WriteValue(const Value: TJsonRegEx); begin inherited WriteValue(Value); WriteType(TBsonType.Regex); WriteKey; WriteCString(Value.RegEx); WriteCString(Value.Options); end; procedure TBsonWriter.WriteValue(const Value: TJsonDBRef); begin inherited WriteValue(Value); WriteType(TBsonType.Reference); WriteKey; WriteString(Value.Ref); WriteOid(Value.Id); end; procedure TBsonWriter.WriteValue(const Value: TJsonCodeWScope); var LPrevPos: Int64; I: Integer; LCurPos: Int64; begin inherited WriteValue(Value); WriteType(TBsonType.CodeWScope); WriteKey; LPrevPos := FWriter.BaseStream.Position; WriteInteger(0); WriteString(Value.Code); WritePropertyName(''); InternalWriteStartObject(True); for I := 0 to Length(Value.Scope) - 1 do begin WritePropertyName(Value.Scope[I].Ident); WriteValue(Value.Scope[I].value); end; WriteEndObject; LCurPos := FWriter.BaseStream.Position; FWriter.BaseStream.Position := LPrevPos; FWriter.Write(Integer(LCurPos - LPrevPos)); FWriter.BaseStream.Position := LCurPos; end; procedure TBsonWriter.WriteMinKey; begin inherited WriteMaxKey; WriteType(TBsonType.MinKey); WriteKey; end; procedure TBsonWriter.WriteMaxKey; begin inherited WriteMaxKey; WriteType(TBsonType.MaxKey); WriteKey; end; procedure TBsonWriter.WriteCode(const Code: string); begin inherited WriteValue(Code); WriteType(TBsonType.Code); WriteKey; WriteString(Code); end; procedure TBsonWriter.WritePropertyName(const Name: string); begin inherited WritePropertyName(Name); FPropertyName := Name; end; { TBsonReader.TContainerContext } constructor TBsonReader.TContainerContext.Create(AType: TBsonType); begin &Type := AType; end; { TBsonReader } procedure TBsonReader.Close; begin inherited Close; FStack.Clear; end; constructor TBsonReader.Create(const AStream: TStream; AReadAsRootValuesArray: Boolean); begin inherited Create; FEncoding := TEncoding.UTF8; FReader := TBinaryReader.Create(AStream); FStack := TObjectStack<TContainerContext>.Create; FReadRootValueAsArray := AReadAsRootValuesArray; SetLength(FByteBuffer, MaxCharBytesSize); SetLength(FCharBuffer, FEncoding.GetMaxCharCount(MaxCharBytesSize)); DateTimeZoneHandling := TJsonDateTimeZoneHandling.Utc; end; destructor TBsonReader.Destroy; begin inherited Destroy; FReader.Free; FStack.Free; end; procedure TBsonReader.MovePosition(Count: Integer); begin Inc(FCurrentContext.Position, Count); end; procedure TBsonReader.PopContext(FreeContext: Boolean); var LOwnsObjects: Boolean; begin LOwnsObjects := FStack.OwnsObjects; try FStack.OwnsObjects := FreeContext; FStack.Pop; if FStack.Count > 0 then FCurrentContext := FStack.Peek else FCurrentContext := nil; finally FStack.OwnsObjects := LOwnsObjects; end; end; procedure TBsonReader.PushContext(const Context: TContainerContext); begin FStack.Push(Context); FCurrentContext := Context; end; function TBsonReader.ReadBinary(out BinaryType: TJsonBinaryType): TBytes; var LLength: Integer; begin LLength := ReadInteger; BinaryType := TJsonBinaryType(ReadByte); // the old binary has been obsolte, this is only for compatibility (and it has the length repeated in the data) if BinaryType = TJsonBinaryType.BinaryOld then LLength := ReadInteger; Result := ReadBytes(LLength); end; function TBsonReader.ReadByte: Byte; begin Result := FReader.ReadByte; MovePosition(1); end; function TBsonReader.ReadBytes(Count: Integer): TBytes; begin Result := FReader.ReadBytes(Count); MovePosition(Count); end; procedure TBsonReader.ReadByType(AType: TBsonType); var Context: TContainerContext; BinaryType: TJsonBinaryType; LDate: TDateTime; begin case AType of // TBsonType.BsonDocument: ; TBsonType.Float: SetToken(TJsonToken.Float, ReadDouble); TBsonType.String, TBsonType.Symbol: SetToken(TJsonToken.String, ReadString); TBsonType.Object: begin SetToken(TJsonToken.StartObject); Context := TContainerContext.Create(TBsonType.Object); PushContext(Context); Context.Length := ReadInteger; end; TBsonType.Array: begin SetToken(TJsonToken.StartArray); Context := TContainerContext.Create(TBsonType.Array); PushContext(Context); Context.Length := ReadInteger; end; TBsonType.Binary: SetToken(TJsonToken.Bytes, TValue.From<TBytes>(ReadBinary(BinaryType))); TBsonType.Undefined: SetToken(TJsonToken.Undefined); TBsonType.Oid: SetToken(TJsonToken.Oid, TValue.From<TJsonOid>(TJsonOid.Create(ReadBytes(12)))); TBsonType.Boolean: SetToken(TJsonToken.Boolean, ReadByte <> 0); TBsonType.DateTime: begin LDate := IncMilliSecond(UnixDateDelta, ReadInt64); if DateTimeZoneHandling = TJsonDateTimeZoneHandling.Local then LDate := TTimeZone.Local.ToLocalTime(LDate); SetToken(TJsonToken.Date, LDate); end; TBsonType.Null: SetToken(TJsonToken.Null); TBsonType.Regex: SetToken(TJsonToken.RegEx, TValue.From<TJsonRegEx>(ReadRegEx)); TBsonType.Reference: SetToken(TJsonToken.DBRef, TValue.From<TJsonDBRef>(ReadDBRef)); TBsonType.Code: SetToken(TJsonToken.String, ReadString); TBsonType.CodeWScope: SetToken(TJsonToken.CodeWScope, TValue.From<TJsonCodeWScope>(ReadCodeWScope)); TBsonType.Integer: SetToken(TJsonToken.Integer, ReadInteger); TBsonType.TimeStamp, TBsonType.Long: SetToken(TJsonToken.Integer, ReadInt64); TBsonType.MinKey: SetToken(TJsonToken.MinKey); TBsonType.MaxKey: SetToken(TJsonToken.MaxKey); end; end; function TBsonReader.ReadCodeWScope: TJsonCodeWScope; procedure Error; begin raise EJsonReaderException.Create(Self, Format(SUnexpectedTokenCodeWScope, [GetName(TokenType)])); end; var I: Integer; begin ReadInteger; Result.Code := ReadString; ReadByType(TBsonType.Object); while ReadInternal and (TokenType <> TJsonToken.EndObject) do begin I := Length(Result.Scope); SetLength(Result.Scope, I + 1); if TokenType <> TJsonToken.PropertyName then Error; Result.Scope[I].ident := Value.AsString; ReadInternal; if not IsPrimitiveToken(TokenType) then Error; Result.Scope[I].value := Value.AsString; end; end; function TBsonReader.ReadDouble: Double; begin Result := FReader.ReadDouble; MovePosition(8); end; function TBsonReader.ReadElement: string; begin FCurrentElementType := ReadType; Result := ReadCString; end; function TBsonReader.ReadInt64: Int64; begin Result := FReader.ReadInt64; MovePosition(8); end; function TBsonReader.ReadInteger: Integer; begin Result := FReader.ReadInteger; MovePosition(4); end; function TBsonReader.ReadInternal: Boolean; var JsonToken: TJsonToken; BsonType: TBsonType; Context: TContainerContext; LengthMinusEnd: Integer; begin try case CurrentState of TState.Start: begin if FReadRootValueAsArray then begin JsonToken := TJsonToken.StartArray; BsonType := TBsonType.&Array; end else begin JsonToken := TJsonToken.StartObject; BsonType := TBsonType.&Object; end; SetToken(JsonToken); Context := TContainerContext.Create(BsonType); PushContext(Context); Context.Length := ReadInteger; Result := True; end; TState.Property: begin ReadByType(FCurrentElementType); Result := True; end; TState.ObjectStart, TState.ArrayStart, TState.PostValue: begin if FCurrentContext <> nil then begin Context := FCurrentContext; LengthMinusEnd := Context.Length - 1; if Context.Position < LengthMinusEnd then begin if Context.&Type = TBsonType.&Array then begin ReadElement; ReadByType(FCurrentElementType); end else SetToken(TJsonToken.PropertyName, ReadElement); end else if Context.Position = LengthMinusEnd then begin if ReadByte <> 0 then raise EJsonReaderException.Create(Self, SUnexpectedObjectByteEnd); PopContext(False); try if FCurrentContext <> nil then MovePosition(Context.Length); if Context.&Type = TBsonType.&Object then SetToken(TJsonToken.EndObject) else SetToken(TJsonToken.EndArray); finally Context.Free; end; end else raise EJsonReaderException.Create(SReadErrorContainerEnd); Result := True; end else Result := False; end; TState.Complete, TState.Closed, TState.ConstructorStart, TState.Constructor, TState.Error, TState.Finished: Result := False; else raise EArgumentOutOfRangeException.Create(''); end; if not Result then SetToken(TJsonToken.None); except on E: EStreamError do begin SetToken(TJsonToken.None); Result := False; end; end; end; function TBsonReader.ReadRegEx: TJsonRegEx; begin Result.RegEx := ReadCString; Result.Options := ReadCString; end; function TBsonReader.ReadDBRef: TJsonDBRef; begin Result.DB := ''; Result.Ref := ReadString; Result.Id.AsBytes := ReadBytes(12); end; function TBsonReader.ReadString: string; var LLength: Integer; begin LLength := ReadInteger; Result := ReadString(LLength - 1); FReader.ReadByte; MovePosition(LLength); end; function TBsonReader.ReadString(ALength: Integer): string; var LLength: Integer; begin // Ensure the buffer size if ALength > Length(FByteBuffer) then begin LLength := Length(FByteBuffer); while ALength > LLength do LLength := LLength * 2; SetLength(FByteBuffer, LLength); end; if FReader.Read(FByteBuffer, 0, ALength) = ALength then Result := FEncoding.GetString(FByteBuffer, 0, ALength) else raise EJsonReaderException.Create(''); end; function TBsonReader.ReadCString: string; var I: Integer; begin I := -1; repeat Inc(I); // Ensure the buffer size if Length(FByteBuffer) < I then SetLength(FByteBuffer, Length(FByteBuffer) * 2); if FReader.Read(FByteBuffer, I, 1) = 0 then raise EJsonReaderException.Create(''); until FByteBuffer[I] = 0; Result := FEncoding.GetString(FByteBuffer, 0, I); MovePosition(I + 1); end; function TBsonReader.ReadType: TBsonType; begin Result := TBsonType(FReader.ReadSByte); MovePosition(1); end; procedure TBsonReader.Rewind; begin inherited Rewind; FStack.Clear; FCurrentContext := nil; end; procedure TBsonReader.Skip; // skip string, binary or code_w_s function SkipValue: string; var LOffset: Integer; begin LOffset := ReadInteger; FReader.BaseStream.Position := FReader.BaseStream.Position + LOffset; MovePosition(LOffset); end; var LOffset: Integer; begin if TokenType = TJsonToken.PropertyName then begin // optimized for string and binary data case FCurrentElementType of TBsonType.String, TBsonType.Symbol, TBsonType.Code: begin SkipValue; SetToken(TJsonToken.String, ''); end; TBsonType.Binary: begin SkipValue; SetToken(TJsonToken.Bytes, ''); end; TBsonType.CodeWScope: begin SkipValue; SetToken(TJsonToken.CodeWScope, ''); end; else Read; end; end; if IsStartToken(TokenType) then begin LOffset := FStack.Peek.Length - SizeOf(Integer) - 1; FReader.BaseStream.Position := FReader.BaseStream.Position + LOffset; MovePosition(LOffset); // Read the final byte to autoset the state to EndToken Read; end end; { TBsonContainer } constructor TBsonWriter.TBsonContainer.Create(AParent: TBsonContainer; SizePos: Integer); begin FParent := AParent; FPosition := SizePos; FChildren := TObjectList<TBsonContainer>.Create; end; destructor TBsonWriter.TBsonContainer.Destroy; begin FChildren.Free; inherited Destroy; end; end.
unit UtilsU_FMX; interface // uses FMX.Graphics,System.Classes, System.NetEncoding, sysUtils; uses FMX.Graphics; // function StringToComponentProc(Value: string): TComponent; // function ComponentToStringProc(Component: TComponent): string; procedure BitmapFromBase64(Base64: string; Bitmap: TBitmap); function Base64FromBitmap(Bitmap: TBitmap): string; function CalcMd5(valeur: string): string; implementation uses System.Classes, System.NetEncoding, System.SysUtils, System.Hash; function CalcMd5(valeur: string): string; var Hash: THashMD5; begin Hash := THashMD5.Create; Hash.Update(valeur); Result := Hash.HashAsString; end; // function ComponentToStringProc(Component: TComponent): string; // var // BinStream:TMemoryStream; // StrStream: TStringStream; // s: string; // begin // BinStream := TMemoryStream.Create; // try // StrStream := TStringStream.Create(s); // try // BinStream.WriteComponent(Component); // BinStream.Seek(0, soFromBeginning); // ObjectBinaryToText(BinStream, StrStream); // StrStream.Seek(0, soFromBeginning); // Result:= StrStream.DataString; // finally // StrStream.Free; // end; // finally // BinStream.Free // end; // end; // // function StringToComponentProc(Value: string): TComponent; // var // StrStream:TStringStream; // BinStream: TMemoryStream; // begin // StrStream := TStringStream.Create(Value); // try // BinStream := TMemoryStream.Create; // try // ObjectTextToBinary(StrStream, BinStream); // BinStream.Seek(0, soFromBeginning); // Result:= BinStream.ReadComponent(nil); // finally // BinStream.Free; // end; // finally // StrStream.Free; // end; // end; // function Base64FromBitmap(Bitmap: TBitmap): string; // var // Input: TBytesStream; // Output: TStringStream; // Encoding: TBase64Encoding; // begin // Input := TBytesStream.Create; // try // Bitmap.SaveToStream(Input); // Input.Position := 0; // Output := TStringStream.Create('', TEncoding.ASCII); // try // Encoding := TBase64Encoding.Create(0); // try // Encoding.Encode(Input, Output); // Result := Output.DataString; // finally // Encoding.Free; // end; // finally // Output.Free; // end; // finally // Input.Free; // end; // end; // // procedure BitmapFromBase64(Base64: string; Bitmap: TBitmap); // var // Input: TStringStream; // Output: TBytesStream; // Encoding: TBase64Encoding; // begin // Input := TStringStream.Create(Base64, TEncoding.ASCII); // try // Output := TBytesStream.Create; // try // Encoding := TBase64Encoding.Create(0); // try // Encoding.Decode(Input, Output); // Output.Position := 0; // Bitmap.LoadFromStream(Output); // finally // Encoding.Free; // end; // finally // Output.Free; // end; // finally // Input.Free; // end; // end; // function Base64FromBitmap(Bitmap: TBitmap): string; var Stream: TBytesStream; Encoding: TBase64Encoding; begin Stream := TBytesStream.Create; try Bitmap.SaveToStream(Stream); Encoding := TBase64Encoding.Create(0); try Result := Encoding.EncodeBytesToString(Copy(Stream.Bytes, 0, Stream.Size)); finally Encoding.Free; end; finally Stream.Free; end; end; procedure BitmapFromBase64(Base64: string; Bitmap: TBitmap); var Stream: TBytesStream; Bytes: TBytes; Encoding: TBase64Encoding; begin Stream := TBytesStream.Create; try Encoding := TBase64Encoding.Create(0); try Bytes := Encoding.DecodeStringToBytes(Base64); Stream.WriteData(Bytes, Length(Bytes)); Stream.Position := 0; Bitmap.LoadFromStream(Stream); finally Encoding.Free; end; finally Stream.Free; end; end; end.
unit uload; {Membaca file-file csv yang dibutuhkan program utama dan memuatnya ke dalam array of ADT masing-masing, contoh: array of ADT Buku} {REFERENSI : http://wiki.freepascal.org/File_Handling_In_Pascal https://www.youtube.com/watch?v=AOYbfHHh4bE (Reading & Writing to CSV Files in Pascal by Holly Billinghurst)} interface uses k03_kel3_utils, ucsvwrapper, ubook, uuser, udate; {PUBLIC VARIABLE, CONST, ADT} const LOAD_MAXWORD = 1000; {PUBLIC FUNCTIONS, PROCEDURE} procedure loadbook(filename: string; ptr: pbook); procedure loaduser(filename: string; ptr: puser); procedure loadborrow(filename: string; ptr: pborrow); procedure loadreturn(filename: string; ptr: preturn); procedure loadmissing(filename: string; ptr: pmissing); implementation {PRIVATE VARIABLE, CONST, ADT} type {Definisi ADT input dari file} inputStream = array[1..LOAD_MAXWORD] of string; {pointer dari array inputStream} pinput = ^inputStream; var wordcnt: integer; {FUNGSI dan PROSEDUR} procedure parserow(str: string; ptr: pinput); {DESKRIPSI : Mencari cell yang memuat koma, kemudian mengubahnya menjadi string yang dapat digunakan pada program} {I.S. : sembarang} {F.S. : string kompatibel dengan program dan dapat dimasukkan ke array of ADT} {Proses : mencari kombinasi char ' ,"x ' (menandakan awal cell yang dibungkus) dan char ' x", ' (menandakan akhir cell yang dibungkus) dengan x karakter sembarang bukan quote ' " ' lalu membuka cell yang dibungkus, dan tidak mengubah cell yang tidak dibungkus} {KAMUS LOKAL} var i : integer; wrappedtext : string; {ALGORITMA} begin i := 1; wordcnt += 1; ptr^[wordcnt] := ''; while (i <= length(str)) do begin {cell dibungkus wrapper} if (((i = 1) or ((i - 1 >= 1) and (str[i - 1] = delimiter))) and (str[i] = wrapper) and ((i = length(str)) or ((i + 1 <= length(str)) and (str[i + 1] <> wrapper)))) then begin wrappedtext := ''; repeat wrappedtext += str[i]; i += 1; until (((i = 1) or ((i - 1 >= 1) and (str[i - 1] <> wrapper))) and (str[i] = wrapper) and ((i = length(str)) or ((i + 1 <= length(str)) and (str[i + 1] = delimiter)))); wrappedtext += str[i]; ptr^[wordcnt] := unwraptext(wrappedtext); {cell tidak dibungkus wrapper} end else begin if (str[i] = delimiter) then begin wordcnt += 1; ptr^[wordcnt] := ''; end else begin ptr^[wordcnt] += str[i]; end; end; i += 1; end; end; function readInput(filename: string; delimiter: char): pinput; {DESKRIPSI : membaca file teks dan memuat ke dalam array agar dapat digunakan program/unit lain} {PARAMETER : nama file (beserta extensionnya) dan karakter delimiter (pemisah masing-masing kolom), pada kasus ini (CSV), adalah koma ','} {RETURN : pointer dari ADT inputStream} {KAMUS LOKAL} var f : text; readline : string; filetext : inputStream; i : integer; ptr : pinput; {ALGORITMA} begin {KONSTRUKTOR, set isi array menjadi string '-', sebagai penanda end of file, sehingga dapat dihitung N-efektifnya} for i:= 1 to LOAD_MAXWORD do begin filetext[i] := '-'; end; new(ptr); ptr^ := filetext; {memuat file ke variabel f} system.assign(f, filename); system.reset(f); {membaca isi file csv} wordcnt := 0; while not EOF(f) do begin {ulangi selama belum EOF/EndOfFile} readln(f, readline); parserow(readline, ptr); end; close(f); readInput := ptr; end; procedure loadbook(filename: string; ptr: pbook); {DESKRIPSI : Memuat file csv berisi data buku ke dalam ADT array of Book} {I.S. : pointer pbook terdefinisi, array tbook terdefinisi, filename ada di direktori} {F.S. : array tbook terisi sesuai isi filename,} {Proses : meminta input nama file, lalu memisah masing-masing kolom menjadi beberapa type dari buku, mengisi variabel bookNeff sesuai jumlah baris dari file csv} {KAMUS LOKAL} var ploadedcsv : pinput; i, row : integer; column : integer; {ALGORITMA} begin ploadedcsv := readInput(filename, ','); column := BOOK_COLUMN; {6} {memisah-misah file loadedcsv ke beberapa array} {row : counter indeks array yang sudah diolah} {i : counter indeks array yang belum diolah} {menggunakan modulo karena kolom berulang setiap n data} i := column; row := (i div column) - 1; while not (ploadedcsv^[i + 1] = '-') do begin i += 1; if ((i mod column) = 1) then begin row += 1; ptr^[row].id := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 2) then begin ptr^[row].title := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 3) then begin ptr^[row].author := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 4) then begin ptr^[row].qty := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 5) then begin ptr^[row].year := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 0) then begin ptr^[row].category := ploadedcsv^[i]; end; end; bookNeff := row; end; procedure loaduser(filename: string; ptr: puser); {DESKRIPSI : Memuat file csv berisi data buku ke dalam ADT array of User} {I.S. : pointer puser terdefinisi, array tuser terdefinisi, filename ada di direktori} {F.S. : array tuser terisi sesuai isi filename,} {Proses : meminta input nama file, lalu memisah masing-masing kolom menjadi beberapa type dari user, mengisi variabel userNeff sesuai jumlah baris dari file csv} {KAMUS LOKAL} var ploadedcsv : pinput; i, row : integer; column : integer; {ALGORITMA} begin ploadedcsv := readInput(filename, ','); column := USER_COLUMN; {5} {memisah-misah file loadedcsv ke beberapa array} {row : counter indeks array yang sudah diolah} {i : counter indeks array yang belum diolah} {menggunakan modulo karena kolom berulang setiap n data} i := column; row := (i div column) - 1; while not (ploadedcsv^[i + 1] = '-') do begin i += 1; if ((i mod column) = 1) then begin row += 1; ptr^[row].fullname := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 2) then begin ptr^[row].address := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 3) then begin ptr^[row].username := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 4) then begin ptr^[row].password := ploadedcsv^[i]; end else if ((i mod column) = 0) then begin ptr^[row].isAdmin := ploadedcsv^[i] = 'Admin'; end; end; userNeff := row; end; procedure loadborrow(filename: string; ptr: pborrow); {DESKRIPSI : Memuat file csv berisi data buku ke dalam ADT array of BorrowHistory} {I.S. : pointer pBorrowHistory terdefinisi, array tBorrowHistory terdefinisi, filename ada di direktori} {F.S. : array tBorrowHistory terisi sesuai isi filename,} {Proses : meminta input nama file, lalu memisah masing-masing kolom menjadi beberapa type dari BorrowHistory, mengisi variabel BorrowNeff sesuai jumlah baris dari file csv} {KAMUS LOKAL} var ploadedcsv : pinput; i, row : integer; column : integer; {ALGORITMA} begin ploadedcsv := readInput(filename, ','); column := BORROW_COLUMN; {5} {memisah-misah file loadedcsv ke beberapa array} {row : counter indeks array yang sudah diolah} {i : counter indeks array yang belum diolah} {menggunakan modulo karena kolom berulang setiap n data} i := column; row := (i div column) - 1; while not (ploadedcsv^[i + 1] = '-') do begin i += 1; if ((i mod column) = 1) then begin row += 1; ptr^[row].username := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 2) then begin ptr^[row].id := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 3) then begin ptr^[row].borrowDate := StrToDate(ploadedcsv^[i]); end else if ((i mod column) = 4) then begin ptr^[row].returnDate := StrToDate(ploadedcsv^[i]); end else if ((i mod column) = 0) then begin ptr^[row].isBorrowed := ploadedcsv^[i] = 'belum'; end; end; borrowNeff := row; end; procedure loadreturn(filename: string; ptr: preturn); {DESKRIPSI : Memuat file csv berisi data buku ke dalam ADT array of ReturnHistory} {I.S. : pointer pReturnHistory terdefinisi, array tReturnHistory terdefinisi, filename ada di direktori} {F.S. : array tReturnHistory terisi sesuai isi filename,} {Proses : meminta input nama file, lalu memisah masing-masing kolom menjadi beberapa type dari ReturnHistory, mengisi variabel ReturnNeff sesuai jumlah baris dari file csv} {KAMUS LOKAL} var ploadedcsv : pinput; i, row : integer; column : integer; {ALGORITMA} begin ploadedcsv := readInput(filename, ','); column := RETURN_COLUMN; {3} {memisah-misah file loadedcsv ke beberapa array} {row : counter indeks array yang sudah diolah} {i : counter indeks array yang belum diolah} {menggunakan modulo karena kolom berulang setiap n data} i := column; row := (i div column) - 1; while not (ploadedcsv^[i + 1] = '-') do begin i += 1; if ((i mod column) = 1) then begin row += 1; ptr^[row].username := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 2) then begin ptr^[row].id := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 0) then begin ptr^[row].returnDate := StrToDate(ploadedcsv^[i]); end; end; returnNeff := row; end; procedure loadmissing(filename: string; ptr: pmissing); {DESKRIPSI : Memuat file csv berisi data buku ke dalam ADT array of MissingBook} {I.S. : pointer pMissingBook terdefinisi, array tMissingBook terdefinisi, filename ada di direktori} {F.S. : array tMissingBook terisi sesuai isi filename,} {Proses : meminta input nama file, lalu memisah masing-masing kolom menjadi beberapa type dari MissingBook, mengisi variabel MissingNeff sesuai jumlah baris dari file csv} {KAMUS LOKAL} var ploadedcsv : pinput; i, row : integer; column : integer; {ALGORITMA} begin ploadedcsv := readInput(filename, ','); column := MISSING_COLUMN; {3} {memisah-misah file loadedcsv ke beberapa array} {row : counter indeks array yang sudah diolah} {i : counter indeks array yang belum diolah} {menggunakan modulo karena kolom berulang setiap n data} i := column; row := (i div column) - 1; while not (ploadedcsv^[i + 1] = '-') do begin i += 1; if ((i mod column) = 1) then begin row += 1; ptr^[row].username := wraptext(ploadedcsv^[i]); end else if ((i mod column) = 2) then begin ptr^[row].id := StrToInt(ploadedcsv^[i]); end else if ((i mod column) = 0) then begin ptr^[row].reportDate := StrToDate(ploadedcsv^[i]); end; end; missingNeff := row; end; end.
unit uMovimentacaoAlunoDsiciplina; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uCadastroBase, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Mask; type TfrmMovimentacaoAlunoDisciplina = class(TfrmCadBase) qrAluno: TFDQuery; qrDisciplina: TFDQuery; dsAluno: TDataSource; dsDisciplina: TDataSource; qrDadosDISCIPLINA_ID: TIntegerField; qrDadosALUNO_ID: TIntegerField; qrDadosALUNO: TStringField; qrDadosDISCIPLINA: TStringField; Label1: TLabel; Label2: TLabel; lkAluno: TDBLookupComboBox; lkDisciplina: TDBLookupComboBox; qrProfessor: TFDQuery; dsProfessor: TDataSource; qrDadosPROFESSOR_ID: TIntegerField; qrDadosPROFESSOR: TStringField; Label3: TLabel; lkProfessor: TDBLookupComboBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMovimentacaoAlunoDisciplina: TfrmMovimentacaoAlunoDisciplina; implementation {$R *.dfm} uses udmPrincipal; procedure TfrmMovimentacaoAlunoDisciplina.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; qrAluno.Close; qrDisciplina.Close; frmMovimentacaoAlunoDisciplina := nil; end; procedure TfrmMovimentacaoAlunoDisciplina.FormShow(Sender: TObject); begin inherited; qrAluno.Open; qrDisciplina.Open; qrProfessor.Open; 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 XmlTextReader; interface uses classes, sysutils, libxml2; type EArgumentNullException = class(Exception); EArgumentOutOfRangeException = class(Exception); EXmlException = class(Exception); TXmlParserProperties = set of xmlParserProperties; TIntegerAttribAccessFunc = function(reader: xmlTextReaderPtr): Longint; cdecl; TXmlNodeType = ( ntNone, // = 0, ntElement, // = 1, ntAttribute, // = 2, ntText, // = 3, ntCDATA, // = 4, ntEntityReference, // = 5, ntEntity, // = 6, ntProcessingInstruction, // = 7, ntComment, // = 8, ntDocument, // = 9, ntDocumentType, // = 10, ntDocumentFragment, // = 11, ntNotation, // = 12, ntWhitespace, // = 13, ntSignificantWhitespace, // = 14, ntEndElement, // = 15, ntEndEntity, // = 16, ntXmlDeclaration // = 17 ); TXmlTextReader = class private FStream: TStream; FXmlTextReaderPtr: xmlTextReaderPtr; FXmlParserInputBufferPtr: xmlParserInputBufferPtr; FLastError: string; FEof: boolean; FInternalStream: TFileStream; private procedure InitLibxml2Objects; procedure FreeLibxml2Objects; function GetStream: TStream; procedure SetLastError(const ErrorMessage: string); function PXmlCharToStr(xmlChar: PXmlChar): string; function GetIntegerAttribute(IntegerAttribAccessFunc: TIntegerAttribAccessFunc): Integer; function GetBooleanAttribute(IntegerAttribAccessFunc: TIntegerAttribAccessFunc): boolean; function CheckError(FunctionResult: Integer): boolean; private function GetName: string; function GetLocalName: string; function GetPrefix: string; function GetNameSpaceUri: string; function GetAttributeCount: Integer; function GetDepth: Integer; function GetHasAttributes: boolean; function GetHasValue: boolean; function GetValue: string; function GetIsEmptyElement: boolean; function GetTmlParserProperties: TXmlParserProperties; function GetNodeType: TXmlNodeType; procedure SetXmlParserProperties(const Value: TXmlParserProperties); public constructor Create(Stream: TStream); overload; constructor Create(FileName: string); overload; destructor Destroy; override; public function Read: boolean; procedure Reset; function GetAttribute(const Name: string): string; overload; function GetAttribute(No: Integer): string; overload; function GetAttribute(const LocalName: string; const NamespaceUri: string): string; overload; function MoveToAttribute(const Name: string): boolean; overload; procedure MoveToAttribute(No: Integer); overload; function MoveToAttribute(const LocalName: string; const NamespaceUri: string): boolean; overload; function MoveToFirstAttribute: boolean; function MoveToNextAttribute: boolean; function MoveToElement: boolean; function LookupNamespace(const Prefix: string): string; function ReadInnerXml: string; function ReadOuterXml: string; function ReadString: string; procedure Skip; public property Name: string read GetName; property LocalName: string read GetLocalName; property Prefix: string read GetPrefix; property NamespaceUri: string read GetNameSpaceUri; property AttributeCount: Integer read GetAttributeCount; property Depth: Integer read GetDepth; property HasAttributes: boolean read GetHasAttributes; property HasValue: boolean read GetHasValue; property Value: string read GetValue; property IsEmptyElement: boolean read GetIsEmptyElement; property ParserProperties : TXmlParserProperties read GetTmlParserProperties write SetXmlParserProperties; property NodeType: TXmlNodeType read GetNodeType; end; implementation function ReadCallback(context: Pointer; buffer: PChar; len: Integer): Longint; cdecl; begin Result := TXmlTextReader(context).GetStream.Read(buffer^, len); end; procedure xmlTextReaderErrorFunc(arg: Pointer; const msg: PChar; severity: xmlParserSeverities; locator: xmlTextReaderLocatorPtr); cdecl; begin TXmlTextReader(arg).SetLastError(Utf8ToAnsi(PAnsiChar(msg))); end; constructor TXmlTextReader.Create(Stream: TStream); begin if not assigned(Stream) then raise EArgumentNullException.Create('Stream'); FStream := Stream; InitLibxml2Objects; end; destructor TXmlTextReader.Destroy; begin FreeLibxml2Objects; FInternalStream.Free; inherited; end; procedure TXmlTextReader.FreeLibxml2Objects; begin if assigned(FXmlTextReaderPtr) then libxml2.xmlFreeTextReader(FXmlTextReaderPtr); FXmlTextReaderPtr := nil; if assigned(FXmlParserInputBufferPtr) then libxml2.xmlFreeParserInputBuffer(FXmlParserInputBufferPtr); FXmlParserInputBufferPtr := nil; end; function TXmlTextReader.GetStream: TStream; begin Result := FStream; end; procedure TXmlTextReader.InitLibxml2Objects; begin FXmlParserInputBufferPtr := xmlAllocParserInputBuffer(XML_CHAR_ENCODING_NONE); if assigned(FXmlParserInputBufferPtr) then begin FXmlParserInputBufferPtr.context := self; FXmlParserInputBufferPtr.ReadCallback := ReadCallback; end else raise Exception.Create('libxml2: error creating xmlParserInputBuffer'); FXmlTextReaderPtr := xmlNewTextReader(FXmlParserInputBufferPtr, ''); if assigned(FXmlTextReaderPtr) then xmlTextReaderSetErrorHandler(FXmlTextReaderPtr, xmlTextReaderErrorFunc, self) else raise Exception.Create('libxml2: error creating xmlTextReader'); end; function TXmlTextReader.Read: boolean; begin if FEof then Result := False else Result := CheckError(XmlTextReaderRead(FXmlTextReaderPtr)); FEof := not Result; end; procedure TXmlTextReader.Reset; begin FLastError := ''; FEof := False; FreeLibxml2Objects; InitLibxml2Objects; end; procedure TXmlTextReader.SetLastError(const ErrorMessage: string); begin FLastError := ErrorMessage; end; function TXmlTextReader.GetName: string; begin Result := PXmlCharToStr(xmlTextReaderName(FXmlTextReaderPtr)); end; function TXmlTextReader.GetLocalName: string; begin Result := PXmlCharToStr(xmlTextReaderLocalName(FXmlTextReaderPtr)); end; function TXmlTextReader.GetPrefix: string; begin Result := PXmlCharToStr(xmlTextReaderPrefix(FXmlTextReaderPtr)); end; function TXmlTextReader.GetNameSpaceUri: string; begin Result := PXmlCharToStr(xmlTextReaderNameSpaceUri(FXmlTextReaderPtr)); end; function TXmlTextReader.GetAttributeCount: Integer; begin Result := GetIntegerAttribute(xmlTextReaderAttributeCount); end; function TXmlTextReader.GetDepth: Integer; begin Result := GetIntegerAttribute(xmlTextReaderDepth); end; function TXmlTextReader.GetIntegerAttribute (IntegerAttribAccessFunc: TIntegerAttribAccessFunc): Integer; begin Result := IntegerAttribAccessFunc(FXmlTextReaderPtr); CheckError(Result); end; function TXmlTextReader.GetHasAttributes: boolean; begin Result := GetBooleanAttribute(xmlTextReaderHasAttributes); end; function TXmlTextReader.GetHasValue: boolean; begin Result := GetBooleanAttribute(xmlTextReaderHasValue); end; function TXmlTextReader.GetValue: string; begin Result := PXmlCharToStr(xmlTextReaderValue(FXmlTextReaderPtr)); end; function TXmlTextReader.GetIsEmptyElement: boolean; begin Result := GetBooleanAttribute(xmlTextReaderisEmptyElement); end; function TXmlTextReader.GetBooleanAttribute (IntegerAttribAccessFunc: TIntegerAttribAccessFunc): boolean; begin Result := (GetIntegerAttribute(IntegerAttribAccessFunc) = 1); end; function TXmlTextReader.GetAttribute(const Name: string): string; begin Result := PXmlCharToStr(XmlTextReaderGetAttribute(FXmlTextReaderPtr, PAnsiChar(AnsiToUtf8(Name)))); end; function TXmlTextReader.GetAttribute(No: Integer): string; begin Result := PXmlCharToStr(XmlTextReaderGetAttributeNo(FXmlTextReaderPtr, No)); end; function TXmlTextReader.GetAttribute(const LocalName, NamespaceUri: string) : string; begin Result := PXmlCharToStr(XmlTextReaderGetAttributeNs(FXmlTextReaderPtr, PAnsiChar(AnsiToUtf8(LocalName)), PAnsiChar(AnsiToUtf8(NamespaceUri)))); end; function TXmlTextReader.MoveToAttribute(const Name: string): boolean; begin Result := CheckError(XmlTextReaderMoveToAttribute(FXmlTextReaderPtr, PAnsiChar(AnsiToUtf8(Name)))); end; function TXmlTextReader.CheckError(FunctionResult: Integer): boolean; begin if FunctionResult < 0 then if FLastError <> '' then raise EXmlException.Create(FLastError) else Result := False else Result := (FunctionResult = 1); end; procedure TXmlTextReader.MoveToAttribute(No: Integer); begin if not CheckError(XmlTextReaderMoveToAttributeNo(FXmlTextReaderPtr, No)) then raise EArgumentOutOfRangeException.Create(''); end; function TXmlTextReader.MoveToAttribute(const LocalName, NamespaceUri: string): boolean; begin Result := CheckError(XmlTextReaderMoveToAttributeNs(FXmlTextReaderPtr, PAnsiChar(AnsiToUtf8(LocalName)), PAnsiChar(AnsiToUtf8(NamespaceUri)))); end; function TXmlTextReader.MoveToFirstAttribute: boolean; begin Result := CheckError(XmlTextReaderMoveToFirstAttribute(FXmlTextReaderPtr)); end; function TXmlTextReader.MoveToNextAttribute: boolean; begin Result := CheckError(XmlTextReaderMoveToNextAttribute(FXmlTextReaderPtr)); end; function TXmlTextReader.MoveToElement: boolean; begin Result := CheckError(XmlTextReaderMoveToElement(FXmlTextReaderPtr)); end; function TXmlTextReader.PXmlCharToStr(xmlChar: PXmlChar): string; begin if assigned(xmlChar) then begin Result := Utf8ToAnsi(xmlChar); xmlFree(xmlChar); end else begin Result := ''; end; end; function TXmlTextReader.LookupNamespace(const Prefix: string): string; begin Result := PXmlCharToStr(XmlTextReaderLookupNamespace(FXmlTextReaderPtr, PAnsiChar(AnsiToUtf8(Prefix)))); end; function TXmlTextReader.ReadInnerXml: string; begin Result := PXmlCharToStr(XmlTextReaderReadInnerXml(FXmlTextReaderPtr)); end; function TXmlTextReader.ReadOuterXml: string; var node: xmlNodePtr; buffer: xmlBufferPtr; begin node := XmlTextReaderExpand(FXmlTextReaderPtr); Result := ''; if assigned(node) then begin buffer := xmlBufferCreate; try if xmlNodeDump(buffer, node.doc, node, 0, 0) > 0 then Result := Utf8ToAnsi(buffer.content); finally xmlBufferFree(buffer); end; end; // Result := PXmlCharToStr(XmlTextReaderReadOuterXml(FXmlTextReaderPtr)); end; function TXmlTextReader.ReadString: string; begin Result := PXmlCharToStr(XmlTextReaderReadString(FXmlTextReaderPtr)); end; function TXmlTextReader.GetTmlParserProperties: TXmlParserProperties; begin if CheckError(XmlTextReaderGetParserProp(FXmlTextReaderPtr, ord(XML_PARSER_LOADDTD))) then Result := [XML_PARSER_LOADDTD] else Result := []; end; procedure TXmlTextReader.SetXmlParserProperties(const Value: TXmlParserProperties); var prop: xmlParserProperties; propIsSet: Integer; begin for prop := LOW(prop) to HIGH(prop) do begin if prop in Value then propIsSet := 1 else propIsSet := 0; CheckError(XmlTextReaderSetParserProp(FXmlTextReaderPtr, ord(prop), propIsSet)) end; end; constructor TXmlTextReader.Create(FileName: string); begin FXmlTextReaderPtr := libxml2.xmlNewTextReaderFilename (PChar(AnsiString(FileName))); if assigned(FXmlTextReaderPtr) then xmlTextReaderSetErrorHandler(FXmlTextReaderPtr, xmlTextReaderErrorFunc, self) else raise EXmlException.Create('Error opening XML file'); end; function TXmlTextReader.GetNodeType: TXmlNodeType; begin case xmlTextReaderNodeType(FXmlTextReaderPtr) of 1: Result := ntElement; 2: Result := ntAttribute; 3: Result := ntText; 4: Result := ntCDATA; 5: Result := ntEntityReference; 6: Result := ntEntity; 7: Result := ntProcessingInstruction; 8: Result := ntComment; 9: Result := ntDocument; 10: Result := ntDocumentType; 11: Result := ntDocumentFragment; 12: Result := ntNotation; 13: Result := ntWhitespace; 14: Result := ntSignificantWhitespace; 15: Result := ntEndElement; 16: Result := ntEndEntity; 17: Result := ntXmlDeclaration; else Result := ntNone; end; end; procedure TXmlTextReader.Skip; begin CheckError(xmlTextReaderNext(FXmlTextReaderPtr)); end; initialization // required for thread safety since 2.4.7 see: http://xmlsoft.org/threads.html xmlInitParser(); end.
unit PhisicsControllerUnit; interface uses Test1Unit, TestsUnit, ControllersUnit, System.Generics.Collections, MainUnit, MenuUnit; type PhisicsController = class(TInterfacedObject, Controllers) private Test: Tests; /// <link>aggregation</link> Menu1: Main; public procedure setTest(Caption: string); function getMenu: TList<string>; function getQuest: TList<string>; function getAnswer: TList<string>; function getCorrect: TDictionary<integer, integer>; end; implementation function PhisicsController.getAnswer: TList<string>; begin result := TList<string>.create; result := Test.getAnswer; end; function PhisicsController.getCorrect: TDictionary<integer, integer>; begin result := TDictionary<integer, integer>.create; // result := TList<string>.create; result := Test.getCorrect; end; function PhisicsController.getMenu: TList<string>; begin result := TList<string>.create; Menu1 := Menu.create; result := Menu1.getMenu; end; function PhisicsController.getQuest: TList<string>; begin result := TList<string>.create; result := Test.getQuest; end; procedure PhisicsController.setTest(Caption: string); begin Test := Test1.create; Test.setTest(Caption); end; end.
//Ejercicio 10 // Escribir un programa que ingrese de la entrada un entero de hasta cuatro cifras y lo despliegue con el punto de la manera habitual, esto es: separando la cifra de los // millares (si la hay) de la cifra de las centenas. // // Ejemplos // // Entrada Salida // 1234 1.234 // 567 567 // 23 23 // 5678 5.678 program ejercicio10; var entrada, m, c, d, u : integer; begin writeln('Ingrese un numero de maximo 4 cifras.'); read(entrada); m := entrada div 1000; c := (entrada - (m*1000)) div 100; d := (entrada - (m*1000) - (c*100)) div 10; u := (entrada - (m*1000) - (c*100) - (d*10)) mod 10; if (m = 0) and (c = 0) and (d = 0) then writeln(u); if (m = 0) and (c = 0) and (d <> 0) then writeln(d,u); if (m = 0) and (c <> 0) then writeln(c,d,u); if (m <> 0) then writeln(m,'.',c,d,u); end.
unit UnMovimentoDeContaCorrenteImpressaoView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, JvExControls, JvButton, JvTransparentButton, StdCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvCheckedMaskEdit, JvDatePickerEdit, { helsonsant } Util, DataUtil, UnModelo, UnAplicacao, UnMovimentoDeContaCorrenteListaRegistrosModelo; type TMovimentoDeContaCorrenteImpressaoView = class(TForm, ITela) Panel1: TPanel; btnGravar: TJvTransparentButton; txtInicio: TJvDatePickerEdit; Label1: TLabel; Label2: TLabel; txtFim: TJvDatePickerEdit; Label3: TLabel; txtTipo: TComboBox; private FControlador: IResposta; FMovimentoDeContaCorrenteListaRegistrosModelo: TMovimentoDeContaCorrenteListaRegistrosModelo; public function Descarregar: ITela; function Controlador(const Controlador: IResposta): ITela; function Modelo(const Modelo: TModelo): ITela; function Preparar: ITela; function ExibirTela: Integer; end; var MovimentoDeContaCorrenteImpressaoView: TMovimentoDeContaCorrenteImpressaoView; implementation {$R *.dfm} { TForm1 } function TMovimentoDeContaCorrenteImpressaoView.Controlador(const Controlador: IResposta): ITela; begin Self.FControlador := Controlador; Result := Self; end; function TMovimentoDeContaCorrenteImpressaoView.Descarregar: ITela; begin Self.FControlador := nil; Self.FMovimentoDeContaCorrenteListaRegistrosModelo := nil; Result := Self; end; function TMovimentoDeContaCorrenteImpressaoView.ExibirTela: Integer; begin Result := Self.ShowModal; end; function TMovimentoDeContaCorrenteImpressaoView.Modelo(const Modelo: TModelo): ITela; begin Self.FMovimentoDeContaCorrenteListaRegistrosModelo := (Modelo as TMovimentoDeContaCorrenteListaRegistrosModelo); Result := Self; end; function TMovimentoDeContaCorrenteImpressaoView.Preparar: ITela; var _parametros: TMap; _inicio, _fim: TDateTime; begin _parametros := Self.FMovimentoDeContaCorrenteListaRegistrosModelo.Parametros; _inicio := StrToDate(_parametros.Ler('inicio').ComoTexto); _fim := StrToDate(_parametros.Ler('fim').ComoTexto); Self.txtInicio.Date := _inicio; Self.txtFim.Date := _fim; Result := Self; end; end.
namespace RemObjects.SDK.CodeGen4; uses RemObjects.Elements.RTL; type RodlRole = public class public constructor; empty; constructor(aRole: String; aNot: Boolean); begin Role := aRole; &Not := aNot; end; property Role: String; property &Not: Boolean; end; RodlRoles = public class private fRoles: List<RodlRole> := new List<RodlRole>; public method LoadFromXmlNode(node: XmlElement); begin var el := node.FirstElementWithName("Roles") as XmlElement; if (el = nil) or (el.Elements.Count = 0) then exit; for each lItem in el.Elements do begin if (lItem.LocalName = "DenyRole") then fRoles.Add(new RodlRole(lItem.Value, true)) else if (lItem.LocalName = "AllowRole") then fRoles.Add(new RodlRole(lItem.Value, false)); end; end; method LoadFromJsonNode(node: JsonNode); begin for each lItem in node['DenyRoles'] as JsonArray do fRoles.Add(new RodlRole(lItem:StringValue, true)); for each lItem in node['AllowRoles'] as JsonArray do fRoles.Add(new RodlRole(lItem:StringValue, false)); end; method Clear; begin fRoles.RemoveAll; end; property Roles:List<RodlRole> read fRoles; property Role[index : Integer]: RodlRole read fRoles[index]; end; end.
unit Main; interface uses System.SysUtils, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Edit, FMX.ScrollBox, FMX.Memo, FMX.Platform.Win, Windows, DriversAPI, RegistryUtils, System.Classes, FMX.Controls.Presentation; type TMainForm = class(TForm) DriverPathEdit: TEdit; DriverNameEdit: TEdit; InstallDriverButton: TButton; DeleteDriverButton: TButton; Label2: TLabel; SelectDriverPathButton: TButton; Label1: TLabel; IOCTLEdit: TEdit; Label4: TLabel; SendIRPButton: TButton; Label5: TLabel; InputEdit: TEdit; StatusMemo: TMemo; SaveSettingsButton: TButton; StyleBook: TStyleBook; procedure SelectDriverPathButtonClick(Sender: TObject); procedure InstallDriverButtonClick(Sender: TObject); procedure DeleteDriverButtonClick(Sender: TObject); procedure SendIRPButtonClick(Sender: TObject); procedure SaveSettingsButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure ShowErrorMessage(const Text: string); procedure SaveSettings; procedure LoadSettings; private const RegistryPath: string = 'DriversAPI'; end; var MainForm: TMainForm; implementation {$R *.fmx} // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.SaveSettings; begin SaveStringToRegistry(RegistryPath, 'Path' , DriverPathEdit.Text); SaveStringToRegistry(RegistryPath, 'Name' , DriverNameEdit.Text); SaveStringToRegistry(RegistryPath, 'IOCTL', IOCTLEdit.Text); SaveStringToRegistry(RegistryPath, 'Input', InputEdit.Text); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.LoadSettings; begin DriverPathEdit.Text := ReadStringFromRegistry(RegistryPath, 'Path', ''); DriverNameEdit.Text := ReadStringFromRegistry(RegistryPath, 'Name', ''); IOCTLEdit.Text := ReadStringFromRegistry(RegistryPath, 'IOCTL', '$800'); InputEdit.Text := ReadStringFromRegistry(RegistryPath, 'Input', '$00000000'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.SaveSettingsButtonClick(Sender: TObject); begin StatusMemo.Lines.Clear; SaveSettings; StatusMemo.Lines.Add('Настройки сохранены!'); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - function LastError: string; var Buffer: PChar; ErrorCode: LongWord; const BufferSize = 512; begin ErrorCode := GetLastError; GetMem(Buffer, BufferSize); FillChar(Buffer^, BufferSize, #0); FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode, LANG_NEUTRAL, Buffer, BufferSize, nil ); Result := '(0x' + IntToHex(ErrorCode, 8) + ') ' + Copy(Buffer, 1, Length(Buffer) - 2); FreeMem(Buffer); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - function GetFmxWND(const WindowHandle: TWindowHandle): THandle; inline; begin Result := WindowHandleToPlatform(WindowHandle).Wnd end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.SelectDriverPathButtonClick(Sender: TObject); var OpenDialog: TOpenDialog; begin OpenDialog := TOpenDialog.Create(Self); OpenDialog.Filter := '*.sys|*.sys'; if OpenDialog.Execute then DriverPathEdit.Text := OpenDialog.FileName; FreeAndNil(OpenDialog); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.ShowErrorMessage(const Text: string); begin MessageBox(GetFmxWND(Handle), PChar(Text), 'Ошибка!', MB_ICONERROR); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.FormCreate(Sender: TObject); begin LoadSettings; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.InstallDriverButtonClick(Sender: TObject); var Status: INSTALL_DRIVER_STATUS; begin StatusMemo.Lines.Clear; if not FileExists(DriverPathEdit.Text) then begin ShowErrorMessage('Файл не найден!'); Exit; end; Status := InstallDriver(DriverPathEdit.Text, DriverNameEdit.Text); case Status of INSTALL_DRIVER_SUCCESS : StatusMemo.Lines.Add('Драйвер успешно установлен!'); INSTALL_DRIVER_ERROR_OPEN_SC_MANAGER : StatusMemo.Lines.Add('Не удалось открыть SCManager!' + #13#10 + ' # ' + LastError); INSTALL_DRIVER_ERROR_CREATE_SERVICE : StatusMemo.Lines.Add('Не удалось создать сервис!' + #13#10 + ' # ' + LastError); INSTALL_DRIVER_ERROR_START_SERVICE : StatusMemo.Lines.Add('Не удалось запустить сервис!' + #13#10 + ' # ' + LastError); end; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.DeleteDriverButtonClick(Sender: TObject); var Status: DELETE_DRIVER_STATUS; begin StatusMemo.Lines.Clear; Status := DeleteDriver(DriverNameEdit.Text); case Status of DELETE_DRIVER_SUCCESS : StatusMemo.Lines.Add('Драйвер успешно удалён!'); DELETE_DRIVER_ERROR_OPEN_SC_MANAGER : StatusMemo.Lines.Add('Не удалось открыть SCManager!' + #13#10 + ' # ' + LastError); DELETE_DRIVER_ERROR_OPEN_SERVICE : StatusMemo.Lines.Add('Не удалось открыть сервис!' + #13#10 + ' # ' + LastError); DELETE_DRIVER_ERROR_CONTROL_SERVICE : StatusMemo.Lines.Add('Не удалось остановить запущенный сервис!' + #13#10 + ' # ' + LastError); DELETE_DRIVER_ERROR_DELETE_SERVICE : StatusMemo.Lines.Add('Не удалось удалить сервис!' + #13#10 + ' # ' + LastError); end; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TMainForm.SendIRPButtonClick(Sender: TObject); function PtrToHex(Ptr: Pointer): string; inline; begin Result := '0x' + IntToHex(NativeUInt(Ptr), SizeOf(Pointer) * 2); end; var Input, Output: LongWord; BytesReturned: LongWord; IOCTL: LongWord; Status: IRP_STATUS; const BuffersSize = SizeOf(LongWord); begin StatusMemo.Lines.Clear; Input := StrToInt(InputEdit.Text); IOCTL := StrToInt(IOCTLEdit.Text); Output := 0; Status := SendIOCTL(DriverNameEdit.Text, IOCTL, @Input, BuffersSize, @Output, BuffersSize, BytesReturned); case Status of IRP_SUCCESS: StatusMemo.Lines.Add( 'Запрос успешно отправлен!' + #13#10 + ' - IOCTL : 0x' + IntToHex(IOCTL, 8) + #13#10 + ' - Input : ' + PtrToHex(@Input) + ' in 4 bytes equals ' + IntToStr(Input) + #13#10 + ' - Output : ' + PtrToHex(@Output) + ' in 4 bytes equals ' + IntToStr(Output) ); IRP_ERROR_OPEN_DEVICE : StatusMemo.Lines.Add('Устройство не найдено!' + #13#10 + ' # ' + LastError); IRP_ERROR_DEVICE_IO_CONTROL : StatusMemo.Lines.Add('Не получилось отправить IRP!' + #13#10 + ' # ' + LastError); end; end; end.
unit uOpstellingPlayer; interface uses uHTPredictor, uRatingBijdrage; type TOpstellingPlayer = class private FDEF_R_Bijdrage: double; FAANV_R_Bijdrage: double; FMID_Bijdrage: double; FAANV_C_Bijdrage: double; FDEF_L_Bijdrage: double; FAANV_L_Bijdrage: double; FDEF_C_Bijdrage: double; FRating: TRatingBijdrage; FPositie: TPlayerPosition; FPlayerOrder: TPlayerOrder; FPlayer: TObject; FOpstelling: TObject; procedure SetAANV_C_Bijdrage(const Value: double); procedure SetAANV_L_Bijdrage(const Value: double); procedure SetAANV_R_Bijdrage(const Value: double); procedure SetDEF_C_Bijdrage(const Value: double); procedure SetDEF_L_Bijdrage(const Value: double); procedure SetDEF_R_Bijdrage(const Value: double); procedure SetMID_Bijdrage(const Value: double); public property Player: TObject read FPlayer; property Opstelling: TObject read FOpstelling; property MID_Bijdrage: double read FMID_Bijdrage write SetMID_Bijdrage; property DEF_R_Bijdrage: double read FDEF_R_Bijdrage write SetDEF_R_Bijdrage; property DEF_C_Bijdrage: double read FDEF_C_Bijdrage write SetDEF_C_Bijdrage; property DEF_L_Bijdrage: double read FDEF_L_Bijdrage write SetDEF_L_Bijdrage; property AANV_R_Bijdrage: double read FAANV_R_Bijdrage write SetAANV_R_Bijdrage; property AANV_L_Bijdrage: double read FAANV_L_Bijdrage write SetAANV_L_Bijdrage; property AANV_C_Bijdrage: double read FAANV_C_Bijdrage write SetAANV_C_Bijdrage; procedure RecalculateRatings; procedure CalculateRatings(aRating: TRatingBijdrage; aPositie: TPlayerPosition; aPlayerOrder: TPlayerOrder); constructor Create(aPlayer, aOpstelling: TObject); end; implementation uses uSelectie, Math, uPlayer; procedure TOpstellingPlayer.RecalculateRatings; begin if (FRating <> nil) then begin CalculateRatings(FRating, FPositie, FPlayerOrder); end; end; procedure TOpstellingPlayer.CalculateRatings(aRating: TRatingBijdrage; aPositie: TPlayerPosition; aPlayerOrder: TPlayerOrder); var vPlayer: TPlayer; begin FRating := aRating; FPositie := aPositie; FPlayerOrder := aPlayerOrder; vPlayer := TPlayer(FPlayer); //MID_Bijdrage MID_Bijdrage := (aRating.MID_PM * vPlayer.PM); //DEF_R_Bijdrage if (aPositie in [pCV, pCM]) then begin DEF_R_Bijdrage := (aRating.WB_DEF * vPlayer.DEF / 2) + (aRating.WB_GK * vPlayer.GK); end else if (aPositie in [pLB, pLCV, pLW, pLCM]) then begin DEF_R_Bijdrage := 0; end else begin DEF_R_Bijdrage := (aRating.WB_DEF * vPlayer.DEF) + (aRating.WB_GK * vPlayer.GK); end; //DEF_L_Bijdrage if (aPositie in [pCV, pCM]) then begin DEF_L_Bijdrage := (aRating.WB_DEF * vPlayer.DEF / 2) + (aRating.WB_GK * vPlayer.GK); end else if (aPositie in [pRB, pRCV, pRW, pRCM]) then begin DEF_L_Bijdrage := 0; end else begin DEF_L_Bijdrage := (aRating.WB_DEF * vPlayer.DEF) + (aRating.WB_GK * vPlayer.GK); end; //DEF_C_Bijdrage DEF_C_Bijdrage := (aRating.CD_DEF * vPlayer.DEF) + (aRating.CD_GK * vPlayer.GK); //AANV_R_Bijdrage if (aPositie in [pCM]) then begin AANV_R_Bijdrage := (aRating.WA_PASS * vPlayer.PAS / 2) + (aRating.WA_WING * vPlayer.WNG) + (aRating.WA_SC * vPlayer.SCO); end else if (aPositie in [pLW, pLCM, pLB, pLCV]) then begin AANV_R_Bijdrage := 0; end else if (aPositie = pLCA) and (aPlayerOrder = oNaarVleugel) then begin AANV_R_Bijdrage := (aRating.WA_SC_OTHER * vPlayer.SCO); end else begin AANV_R_Bijdrage := (aRating.WA_PASS * vPlayer.PAS) + (aRating.WA_WING * vPlayer.WNG) + (aRating.WA_SC * vPlayer.SCO); end; //AANV_L_Bijdrage if (aPositie in [pCM]) then begin AANV_L_Bijdrage := (aRating.WA_PASS * vPlayer.PAS / 2) + (aRating.WA_WING * vPlayer.WNG) + (aRating.WA_SC * vPlayer.SCO); end else if (aPositie in [pRW, pRCM, pRB, pRCV]) then begin AANV_L_Bijdrage := 0; end else if (aPositie = pRCA) and (aPlayerOrder = oNaarVleugel) then begin AANV_L_Bijdrage := (aRating.WA_SC_OTHER * vPlayer.SCO); end else begin AANV_L_Bijdrage := (aRating.WA_PASS * vPlayer.PAS) + (aRating.WA_WING * vPlayer.WNG) + (aRating.WA_SC * vPlayer.SCO); end; //AANV_C_Bijdrage AANV_C_Bijdrage := (aRating.CA_PASS * vPlayer.PAS) + (aRating.CA_SC * vPlayer.SCO); end; procedure TOpstellingPlayer.SetAANV_C_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FAANV_C_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetAANV_L_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FAANV_L_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetAANV_R_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FAANV_R_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetDEF_C_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FDEF_C_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetDEF_L_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FDEF_L_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetDEF_R_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FDEF_R_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; procedure TOpstellingPlayer.SetMID_Bijdrage(const Value: double); var vPlayer: TPlayer; begin vPlayer := TPlayer(FPlayer); FMID_Bijdrage := Value * vPlayer.GetConditieFactor * vPlayer.GetFormFactor * vPlayer.GetXPFactor; end; constructor TOpstellingPlayer.Create(aPlayer, aOpstelling: TObject); begin FPlayer := aPlayer; FOpstelling := aOpstelling; end; end.
namespace RemObjects.Elements.System; uses Foundation; type ParallelLoopState = public class private public property IsStopped: Boolean read private write; method &Break; begin if not IsStopped then IsStopped := True; end; end; &Parallel = static public class public class method &For(fromInclusive: Integer; toExclusive: Integer; body: block(aSource: Integer; aState: ParallelLoopState)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m: Integer := fromInclusive to toExclusive - 1 do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; new Task(-> begin body.Invoke(temp, ls); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; class method &For(fromInclusive: Int64; toExclusive: Int64; body: block(aSource: Int64; aState: ParallelLoopState)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m: Int64 := fromInclusive to toExclusive - 1 do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; new Task(-> begin body.Invoke(temp, ls); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; class method ForEach<TSource>(source: INSFastEnumeration<TSource>; body: block(aSource: TSource; aState: ParallelLoopState; aIndex: Int64)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m in source index n do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; var tempi := n; new Task(-> begin body.Invoke(temp, ls, tempi); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 JclBase.pas. } { } { The Initial Developer of the Original Code is documented in the accompanying } { help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. } { } {**************************************************************************************************} { } { This unit contains generic JCL base classes and routines to support earlier } { versions of Delphi as well as FPC. } { } { Unit owner: Marcel van Brakel } { Last modified: March 15, 2002 } { } {**************************************************************************************************} unit JclBase; {$I jcl.inc} {$WEAKPACKAGEUNIT ON} interface uses {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} Classes, SysUtils; //-------------------------------------------------------------------------------------------------- // Version //-------------------------------------------------------------------------------------------------- const JclVersionMajor = 1; // 0=pre-release|beta/1, 2, ...=final JclVersionMinor = 20; // Forth minor release JCL 1.20 JclVersionRelease = 1; // 0=pre-release|beta/1=release JclVersionBuild = 779; // build number, days since march 1, 2000 JclVersion = (JclVersionMajor shl 24) or (JclVersionMinor shl 16) or (JclVersionRelease shl 15) or (JclVersionBuild shl 0); //-------------------------------------------------------------------------------------------------- // FreePascal Support //-------------------------------------------------------------------------------------------------- {$IFDEF FPC} type PResStringRec = ^string; function SysErrorMessage(ErrNo: Integer): string; {$IFDEF MSWINDOWS} procedure RaiseLastWin32Error; procedure QueryPerformanceCounter(var C: Int64); function QueryPerformanceFrequency(var Frequency: Int64): Boolean; {$ENDIF MSWINDOWS} var Default8087CW: Word; {$ENDIF FPC} //-------------------------------------------------------------------------------------------------- // EJclError //-------------------------------------------------------------------------------------------------- type EJclError = class (Exception) public constructor CreateResRec(ResStringRec: PResStringRec); constructor CreateResRecFmt(ResStringRec: PResStringRec; const Args: array of const); end; //-------------------------------------------------------------------------------------------------- // EJclWin32Error //-------------------------------------------------------------------------------------------------- {$IFDEF MSWINDOWS} type EJclWin32Error = class (EJclError) private FLastError: DWORD; FLastErrorMsg: string; public constructor Create(const Msg: string); constructor CreateFmt(const Msg: string; const Args: array of const); constructor CreateRes(Ident: Integer); constructor CreateResRec(ResStringRec: PResStringRec); property LastError: DWORD read FLastError; property LastErrorMsg: string read FLastErrorMsg; end; {$ENDIF MSWINDOWS} //-------------------------------------------------------------------------------------------------- // Types //-------------------------------------------------------------------------------------------------- type {$IFDEF MATH_EXTENDED_PRECISION} Float = Extended; {$ENDIF MATH_EXTENDED_PRECISION} {$IFDEF MATH_DOUBLE_PRECISION} Float = Double; {$ENDIF MATH_DOUBLE_PRECISION} {$IFDEF MATH_SINGLE_PRECISION} Float = Single; {$ENDIF MATH_SINGLE_PRECISION} PFloat = ^Float; {$IFDEF FPC} type LongWord = Cardinal; TSysCharSet = set of Char; {$ENDIF FPC} type PPointer = ^Pointer; //-------------------------------------------------------------------------------------------------- // Int64 support //-------------------------------------------------------------------------------------------------- procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal); procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal); // Redefinition of TLargeInteger to relieve dependency on Windows.pas type PLargeInteger = ^TLargeInteger; TLargeInteger = record case Integer of 0: ( LowPart: LongWord; HighPart: Longint); 1: ( QuadPart: Int64); end; // Redefinition of TULargeInteger to relieve dependency on Windows.pas type PULargeInteger = ^TULargeInteger; TULargeInteger = record case Integer of 0: ( LowPart: LongWord; HighPart: LongWord); 1: ( QuadPart: Int64); end; //-------------------------------------------------------------------------------------------------- // Dynamic Array support //-------------------------------------------------------------------------------------------------- type TDynByteArray = array of Byte; TDynShortintArray = array of Shortint; TDynSmallintArray = array of Smallint; TDynWordArray = array of Word; TDynIntegerArray = array of Integer; TDynLongintArray = array of Longint; TDynCardinalArray = array of Cardinal; TDynInt64Array = array of Int64; TDynExtendedArray = array of Extended; TDynDoubleArray = array of Double; TDynSingleArray = array of Single; TDynFloatArray = array of Float; TDynPointerArray = array of Pointer; //-------------------------------------------------------------------------------------------------- // TObjectList //-------------------------------------------------------------------------------------------------- {$IFNDEF DELPHI5_UP} type TObjectList = class (TList) private FOwnsObjects: Boolean; function GetItems(Index: Integer): TObject; procedure SetItems(Index: Integer; const Value: TObject); public procedure Clear; override; constructor Create(AOwnsObjects: Boolean = False); property Items[Index: Integer]: TObject read GetItems write SetItems; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; {$ENDIF DELPHI5_UP} //-------------------------------------------------------------------------------------------------- // Cross-Platform Compatibility //-------------------------------------------------------------------------------------------------- {$IFNDEF DELPHI6_UP} procedure RaiseLastOSError; {$ENDIF DELPHI6_UP} //-------------------------------------------------------------------------------------------------- // Interface compatibility //-------------------------------------------------------------------------------------------------- {$IFDEF SUPPORTS_INTERFACE} {$IFNDEF COMPILER6_UP} type IInterface = IUnknown; {$ENDIF COMPILER6_UP} {$ENDIF SUPPORTS_INTERFACE} //-------------------------------------------------------------------------------------------------- // TStringList.CustomSort compatibility //-------------------------------------------------------------------------------------------------- {$IFDEF DELPHI4} type TStringListCustomSortCompare = function(List: TStringList; Index1, Index2: Integer): Integer; procedure StringListCustomSort(StringList: TStringList; SortFunc: TStringListCustomSortCompare); {$ENDIF DELPHI4} implementation uses JclResources; //================================================================================================== // EJclError //================================================================================================== constructor EJclError.CreateResRec(ResStringRec: PResStringRec); begin {$IFDEF FPC} inherited Create(ResStringRec^); {$ELSE FPC} inherited Create(LoadResString(ResStringRec)); {$ENDIF FPC} end; constructor EJclError.CreateResRecFmt(ResStringRec: PResStringRec; const Args: array of const); begin {$IFDEF FPC} inherited CreateFmt(ResStringRec^, Args); {$ELSE FPC} inherited CreateFmt(LoadResString(ResStringRec), Args); {$ENDIF FPC} end; //================================================================================================== // FreePascal support //================================================================================================== {$IFDEF FPC} {$IFDEF MSWINDOWS} function SysErrorMessage(ErrNo: Integer): string; var Size: Integer; Buffer: PChar; begin GetMem(Buffer, 4000); Size := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ARGUMENT_ARRAY, nil, ErrNo, 0, Buffer, 4000, nil); SetString(Result, Buffer, Size); end; //-------------------------------------------------------------------------------------------------- procedure RaiseLastWin32Error; begin end; //-------------------------------------------------------------------------------------------------- function QueryPerformanceFrequency(var Frequency: Int64): Boolean; var T: TLargeInteger; begin Windows.QueryPerformanceFrequency(@T); CardinalsToI64(Frequency, T.LowPart, T.HighPart); end; //-------------------------------------------------------------------------------------------------- procedure QueryPerformanceCounter(var C: Int64); var T: TLargeInteger; begin Windows.QueryPerformanceCounter(@T); CardinalsToI64(C, T.LowPart, T.HighPart); end; {$ELSE MSWINDOWS} function SysErrorMessage(ErrNo: Integer): string; begin Result := Format(RsSysErrorMessageFmt, [ErrNo, ErrNo]); end; {$ENDIF MSWINDOWS} {$ENDIF FPC} //================================================================================================== // EJclWin32Error //================================================================================================== {$IFDEF MSWINDOWS} constructor EJclWin32Error.Create(const Msg: string); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(Msg + #13 + RsWin32Prefix, [FLastErrorMsg, FLastError]); end; //-------------------------------------------------------------------------------------------------- constructor EJclWin32Error.CreateFmt(const Msg: string; const Args: array of const); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(Msg + #13 + Format(RsWin32Prefix, [FLastErrorMsg, FLastError]), Args); end; //-------------------------------------------------------------------------------------------------- constructor EJclWin32Error.CreateRes(Ident: Integer); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); inherited CreateFmt(LoadStr(Ident) + #13 + RsWin32Prefix, [FLastErrorMsg, FLastError]); end; //-------------------------------------------------------------------------------------------------- constructor EJclWin32Error.CreateResRec(ResStringRec: PResStringRec); begin FLastError := GetLastError; FLastErrorMsg := SysErrorMessage(FLastError); {$IFDEF FPC} inherited CreateFmt(ResStringRec^ + #13 + RsWin32Prefix, [FLastErrorMsg, FLastError]); {$ELSE FPC} inherited CreateFmt(LoadResString(ResStringRec) + #13 + RsWin32Prefix, [FLastErrorMsg, FLastError]); {$ENDIF FPC} end; {$ENDIF MSWINDOWS} //================================================================================================== // Int64 support //================================================================================================== procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal); begin LowPart := TULargeInteger(I).LowPart; HighPart := TULargeInteger(I).HighPart; end; //-------------------------------------------------------------------------------------------------- procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal); begin TULargeInteger(I).LowPart := LowPart; TULargeInteger(I).HighPart := HighPart; end; //================================================================================================== // TObjectList //================================================================================================== {$IFNDEF DELPHI5_UP} procedure TObjectList.Clear; var I: Integer; begin if OwnsObjects then for I := 0 to Count - 1 do Items[I].Free; inherited; end; //-------------------------------------------------------------------------------------------------- constructor TObjectList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; //-------------------------------------------------------------------------------------------------- function TObjectList.GetItems(Index: Integer): TObject; begin Result := TObject(Get(Index)); end; //-------------------------------------------------------------------------------------------------- procedure TObjectList.SetItems(Index: Integer; const Value: TObject); begin Put(Index, Value); end; {$ENDIF DELPHI5_UP} //================================================================================================== // Cross=Platform Compatibility //================================================================================================== {$IFNDEF DELPHI6_UP} procedure RaiseLastOSError; begin RaiseLastWin32Error; end; {$ENDIF DELPHI6_UP} //================================================================================================== // TStringList.CustomSort compatibility //================================================================================================== {$IFDEF DELPHI4} procedure StringListCustomSort(StringList: TStringList; SortFunc: TStringListCustomSortCompare); procedure QuickSort(L, R: Integer); var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while SortFunc(StringList, I, P) < 0 do Inc(I); while SortFunc(StringList, J, P) > 0 do Dec(J); if I <= J then begin StringList.Exchange(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; begin QuickSort(0, StringList.Count - 1); end; {$ENDIF DELPHI4} end.
unit frm_CalculoAvancesPaquetes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, utilerias, frm_connection, DBCtrls, StdCtrls, Buttons, DB, Global, ComCtrls, math, ZAbstractRODataset, ZDataset, Gauges, masUtilerias, UnitValidaTexto,unitexcepciones, DBDateTimePicker; type TfrmCalculoAvancesPaquetes = class(TForm) Label1: TLabel; btnOk: TBitBtn; btnExit: TBitBtn; tsNumeroOrden: TDBLookupComboBox; ds_ordenesdetrabajo: TDataSource; grPeriodo: TGroupBox; Inicio: TLabel; Final: TLabel; ordenesdetrabajo: TZReadOnlyQuery; Progress: TGauge; dFechaInicial: TDBDateTimePicker; dFechaFinal: TDBDateTimePicker; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure tsNumeroOrdenExit(Sender: TObject); procedure tsNumeroOrdenKeyPress(Sender: TObject; var Key: Char); procedure btnExitClick(Sender: TObject); procedure tsNumeroOrdenEnter(Sender: TObject); procedure dFechaInicialEnter(Sender: TObject); procedure dFechaInicialExit(Sender: TObject); procedure dFechaFinalEnter(Sender: TObject); procedure dFechaFinalExit(Sender: TObject); procedure procAjustaBitacoraActividades (sParamContrato, sParamOrden, sParamConvenio : String ; dParamFecha : tDate) ; procedure dFechaFinalKeyPress(Sender: TObject; var Key: Char); procedure dFechaInicialKeyPress(Sender: TObject; var Key: Char); procedure dFechaFinalChange(Sender: TObject); procedure dFechaInicialChange(Sender: TObject); // procedure procAjustacontrato (sParamContrato, sParamConvenio : String ; dParamFecha : tDate) ; private { Private declarations } public { Public declarations } end; var frmCalculoAvancesPaquetes: TfrmCalculoAvancesPaquetes; lBorraPaquetes : Boolean; TotalPaquetes : integer; implementation {$R *.dfm} procedure TfrmCalculoAvancesPaquetes.FormClose(Sender: TObject; var Action: TCloseAction); begin action := cafree ; end; procedure TfrmCalculoAvancesPaquetes.procAjustaBitacoraActividades (sParamContrato, sParamOrden, sParamConvenio : String ; dParamFecha : tDate) ; Var qryBitacora : tzReadOnlyQuery ; iRecord : Word ; begin qryBitacora := tzReadOnlyQuery.Create(self) ; qryBitacora.Connection := connection.zConnection ; // Primero los avances de la orden de trabajo ... // Inicializo la Bitacora Principal qryBitacora.Active := False ; qryBitacora.SQL.Clear ; qryBitacora.SQL.Add('select b.sWbs, sum(b.dAvance * a.dPonderado) as dAvanceReal from bitacoradeactividades b ' + 'INNER JOIN actividadesxorden a ON (b.sContrato = a.sContrato And a.sIdConvenio = :Convenio And b.sNumeroOrden = a.sNumeroOrden And ' + 'b.sWbs = a.sWbs And b.sNumeroActividad = a.sNumeroActividad) ' + 'where b.sContrato = :contrato and b.dIdFecha = :fecha And b.sNumeroOrden = :Orden ' + 'Group by b.sWbs order by a.iItemOrden ') ; qryBitacora.Params.ParamByName('contrato').DataType := ftString ; qryBitacora.Params.ParamByName('contrato').Value := sPAramContrato ; qryBitacora.Params.ParamByName('convenio').DataType := ftString ; qryBitacora.Params.ParamByName('convenio').Value := sParamConvenio ; qryBitacora.Params.ParamByName('Orden').DataType := ftString ; qryBitacora.Params.ParamByName('Orden').Value := sParamOrden ; qryBitacora.Params.ParamByName('fecha').DataType := ftDate ; qryBitacora.Params.ParamByName('fecha').Value := dParamFecha ; qryBitacora.Open ; If QryBitacora.RecordCount > 0 then Begin Progress.Visible := True ; Progress.Progress := 1 ; Progress.MinValue := 1 ; Progress.MaxValue := QryBitacora.RecordCount ; QryBitacora.First ; For iRecord := 1 to Progress.MaxValue Do Begin try connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'UPDATE bitacoradepaquetes SET dAvance = dAvance + :Avance ' + 'Where sContrato = :Contrato And sNumeroOrden = :Orden And dIdFecha = :Fecha And sIdConvenio = :convenio And InStr(:wbs, concat(sWbs,".")) > 0') ; connection.zCommand.Params.ParamByName('contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('contrato').value := sParamContrato ; connection.zCommand.Params.ParamByName('Orden').DataType := ftString ; connection.zCommand.Params.ParamByName('Orden').value := sParamOrden ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').value := sParamConvenio ; connection.zCommand.Params.ParamByName('fecha').DataType := ftDate ; connection.zCommand.Params.ParamByName('fecha').value := dParamFecha ; connection.zCommand.Params.ParamByName('wbs').DataType := ftString ; connection.zCommand.Params.ParamByName('wbs').value := QryBitacora.FieldValues['sWbs'] ; connection.zCommand.Params.ParamByName('Avance').DataType := ftFloat ; connection.zCommand.Params.ParamByName('Avance').value := QryBitacora.FieldValues['dAvanceReal'] ; connection.zCommand.ExecSQL ; Except MessageDlg('Ocurrio un error al actualizar el registro en la bitacora de actividades', mtWarning, [mbOk], 0); End ; Progress.Progress := iRecord ; QryBitacora.Next ; End ; Progress.Visible := False ; End ; QryBitacora.Destroy ; end ; procedure TfrmCalculoAvancesPaquetes.btnOkClick(Sender: TObject); Var lRegenera : Boolean ; strAux : String ; sPaqueteBusqueda, sPartidaOriginal : String ; lProcesoValido : Boolean ; dFactorAjuste : Currency ; dIdFecha : tDate ; //****************************BRITO 09/02/11******************************** sRangoKardex : String ; myYear, myMonth, myDay : Word; //****************************BRITO 09/02/11******************************** nombres, cadenas: TStringList; begin //empieza validacion nombres:=TStringList.Create;cadenas:=TStringList.Create; nombres.Add('Frente'); cadenas.Add(tsNumeroOrden.Text); if not validaTexto(nombres, cadenas, '','') then begin MessageDlg(UnitValidaTexto.errorValidaTexto, mtInformation, [mbOk], 0); exit; end; //continuainserccion de datos if tsNumeroOrden.text='' then begin ShowMessage('Selecciones un frente de trabajo'); tsNumeroOrden.SetFocus; abort end; //Verifica que la fecha final no sea menor que la fecha inicio if dFechaFinal.Date<dFechaInicial.Date then begin showmessage('la fecha final es menor a la fecha inicial' ); dFechaFinal.SetFocus; exit; end; try if lBorraPaquetes then begin connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'Delete from bitacoradepaquetes where sContrato = :contrato And sIdConvenio = :convenio ') ; connection.zCommand.Params.ParamByName('Contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('Contrato').Value := Global_Contrato ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').Value := global_convenio ; connection.zCommand.ExecSQL ; lBorraPaquetes := False; end; Inc(totalPaquetes); dIdFecha := dFechaInicial.Date ; While dIdFecha <= dFechaFinal.Date Do Begin // Inserccion de todos los paquetes para los frentes de trabajo.. try connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'insert into bitacoradepaquetes (sContrato, sIdConvenio, dIdFecha, sNumeroOrden, sWbs, sNumeroActividad, dAvance) ' + 'select sContrato, sIdConvenio, :fecha, sNumeroOrden, sWbs, sNumeroActividad, 0 from actividadesxorden ' + 'Where sContrato = :contrato And sIdConvenio =:convenio And sNumeroOrden =:orden And sTipoActividad = "Paquete" ') ; connection.zCommand.Params.ParamByName('Contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('Contrato').Value := Global_Contrato ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').Value := global_convenio ; connection.zCommand.Params.ParamByName('Orden').DataType := ftString ; connection.zCommand.Params.ParamByName('Orden').Value := tsNumeroOrden.Text ; connection.zCommand.Params.ParamByName('Fecha').DataType := ftDate ; connection.zCommand.Params.ParamByName('Fecha').Value := dIdFecha ; connection.zCommand.ExecSQL () ; Except end; procAjustaBitacoraActividades (global_contrato, tsNumeroOrden.Text, global_convenio, dIdFecha) ; connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'UPDATE bitacoradepaquetes SET dAvance = dAvance / 100 ' + 'Where sContrato = :Contrato And dIdFecha = :Fecha And sIdConvenio = :convenio And sNumeroOrden = :Orden') ; connection.zCommand.Params.ParamByName('contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('contrato').value := global_contrato ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').value := global_convenio ; connection.zCommand.Params.ParamByName('fecha').DataType := ftDate ; connection.zCommand.Params.ParamByName('fecha').value := dIdFecha ; connection.zCommand.Params.ParamByName('Orden').DataType := ftString ; connection.zCommand.Params.ParamByName('Orden').value := tsNumeroOrden.Text ; connection.zCommand.ExecSQL ; // Avances del Contrato .... try connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'insert into bitacoradepaquetes (sContrato, sIdConvenio, dIdFecha, sNumeroOrden, sWbs, sNumeroActividad, dAvance) ' + 'select sContrato, sIdConvenio, :fecha, "", sWbs, sNumeroActividad, 0 from actividadesxanexo ' + 'Where sContrato = :contrato And sIdConvenio = :convenio And sTipoActividad = "Paquete" ') ; connection.zCommand.Params.ParamByName('Contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('Contrato').Value := Global_Contrato ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').Value := global_convenio ; connection.zCommand.Params.ParamByName('Fecha').DataType := ftDate ; connection.zCommand.Params.ParamByName('Fecha').Value := dIdFecha ; connection.zCommand.ExecSQL () ; except end; procAjustaContrato (global_contrato, global_convenio, dIdFecha, frmCalculoAvancesPaquetes) ; connection.zCommand.Active := False ; connection.zCommand.SQL.Clear ; connection.zCommand.SQL.Add ( 'UPDATE bitacoradepaquetes SET dAvance = dAvance / 100 ' + 'Where sContrato = :Contrato And dIdFecha = :Fecha And sIdConvenio = :convenio And sNumeroOrden = :Orden') ; connection.zCommand.Params.ParamByName('contrato').DataType := ftString ; connection.zCommand.Params.ParamByName('contrato').value := global_contrato ; connection.zCommand.Params.ParamByName('convenio').DataType := ftString ; connection.zCommand.Params.ParamByName('convenio').value := global_convenio ; connection.zCommand.Params.ParamByName('fecha').DataType := ftDate ; connection.zCommand.Params.ParamByName('fecha').value := dIdFecha ; connection.zCommand.Params.ParamByName('Orden').DataType := ftString ; connection.zCommand.Params.ParamByName('Orden').value := '' ; connection.zCommand.ExecSQL ; dIdFecha := dIdFecha + 1 End ; //****************************BRITO 09/02/11******************************** //registrar la operacion en el kardex DecodeDate(dFechaInicial.Date, myYear, myMonth, myDay); sRangoKardex := inttostr(myDay) + '/' + inttostr(myMonth) + '/' + inttostr(myYear); DecodeDate(dFechaFinal.Date, myYear, myMonth, myDay); sRangoKardex := sRangoKardex + ' - ' + inttostr(myDay) + '/' + inttostr(myMonth) + '/' + inttostr(myYear); Kardex('Regeneraciones', 'Regenera entregables', sRangoKardex, 'Rango de Fechas', tsNumeroOrden.Text, '', '' ); //****************************BRITO 09/02/11******************************** MessageDlg('Proceso Terminado con Exito.', mtInformation, [mbOk], 0); except on e : exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'frm_CalculoAvancesPaquetes', 'Al regenerar el avance entregable', 0); end; end; end; procedure TfrmCalculoAvancesPaquetes.FormShow(Sender: TObject); begin try lBorraPaquetes := True; TotalPaquetes := 0; dFechaFinal.Date := Date ; connection.configuracion.refresh ; OrdenesdeTrabajo.Active := False ; OrdenesdeTrabajo.Params.ParamByName('Contrato').DataType := ftString ; OrdenesdeTrabajo.Params.ParamByName('Contrato').Value := Global_Contrato ; ordenesdetrabajo.Params.ParamByName('status').DataType := ftString ; ordenesdetrabajo.Params.ParamByName('status').Value := connection.configuracion.FieldValues [ 'cStatusProceso' ]; OrdenesdeTrabajo.Open ; Progress.Visible := False ; tsNumeroOrden.SetFocus except on e : exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'frm_CalculoAvancesPaquetes', 'Al hacer las consultas de inicio', 0); end; end; end; procedure TfrmCalculoAvancesPaquetes.tsNumeroOrdenExit(Sender: TObject); begin if tsNumeroOrden.Text='' then begin ShowMessage('Seleccione un frente de trabajo'); tsNumeroOrden.SetFocus; abort; end; dFechaInicial.Date := OrdenesdeTrabajo.FieldValues ['dFiProgramado'] ; tsNumeroOrden.Color := global_color_salida end; procedure TfrmCalculoAvancesPaquetes.tsNumeroOrdenKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dfechainicial.SetFocus end; procedure TfrmCalculoAvancesPaquetes.btnExitClick(Sender: TObject); begin if totalPaquetes = 0 then close else begin if TotalPaquetes < ordenesdeTrabajo.RecordCount then If MessageDlg('No se regeneraron Todos los Frentes de Trabajo, por lo tanto los avances fisicos del Contrato puede que no esten Correctos. '+#13+ ' Realmente desea salir ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then close else exit else close end; end; procedure TfrmCalculoAvancesPaquetes.tsNumeroOrdenEnter(Sender: TObject); begin tsNumeroOrden.Color := global_color_entrada end; procedure TfrmCalculoAvancesPaquetes.dFechaInicialChange(Sender: TObject); begin dFechaFinal.Date:=dFechainicial.Date; end; procedure TfrmCalculoAvancesPaquetes.dFechaInicialEnter(Sender: TObject); begin dFechaInicial.Color := global_color_entrada end; procedure TfrmCalculoAvancesPaquetes.dFechaInicialExit(Sender: TObject); begin dFechaInicial.Color := global_color_salida end; procedure TfrmCalculoAvancesPaquetes.dFechaInicialKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then dfechafinal.SetFocus end; procedure TfrmCalculoAvancesPaquetes.dFechaFinalChange(Sender: TObject); begin // dFechaFinal.MinDate:=dFechainicial.Date; end; procedure TfrmCalculoAvancesPaquetes.dFechaFinalEnter(Sender: TObject); begin dFechaFinal.Color := global_color_entrada end; procedure TfrmCalculoAvancesPaquetes.dFechaFinalExit(Sender: TObject); begin dFechaFInal.Color := global_color_salida end; procedure TfrmCalculoAvancesPaquetes.dFechaFinalKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then btnOk.SetFocus end; end.
{ "RTC Image Decoder" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcXImgDecode; interface {$INCLUDE rtcDefs.inc} uses Classes, Types, SysUtils, rtcTypes, rtcZLib, rtcXCompressRLE, rtcXImgConst, rtcXBmpUtils, rtcXJPEGConst, rtcXJPEGDecode; type TRtcImageDecoder=class(TObject) private JPGHeadStore:RtcByteArray; OldBmpInfo, NewBmpInfo: TRtcBitmapInfo; FIMGBlockX: integer; FIMGBlockY: integer; FMotionDebug: boolean; FMouseCursor: TRtcMouseCursorInfo; procedure ImageItemCopy(left, right: integer); procedure SetBlockColor(left:integer; right:LongWord); procedure SetMotionDebug(const Value: boolean); public constructor Create; destructor Destroy; override; function DecodeMouse(const Data:RtcByteArray):boolean; function DecodeSize(const Data:RtcByteArray; var SizeX,SizeY:integer; var Clear:boolean):boolean; function Decompress(const Data:RtcByteArray; var BmpInfo:TRtcBitmapInfo):boolean; property MotionDebug:boolean read FMotionDebug write SetMotionDebug default False; property Cursor:TRtcMouseCursorInfo read FMouseCursor; end; implementation { TRtcImageDecoder } constructor TRtcImageDecoder.Create; begin inherited Create; SetLength(JPGHeadStore,0); FMotionDebug:=False; FMouseCursor:=TRtcMouseCursorInfo.Create; end; destructor TRtcImageDecoder.Destroy; begin SetLength(JPGHeadStore,0); RtcFreeAndNil(FMouseCursor); inherited; end; function TRtcImageDecoder.DecodeSize(const Data: RtcByteArray; var SizeX,SizeY:integer; var Clear:boolean):boolean; var FDIF, FRLE, FJPG, FMOT, FCUR:boolean; haveBmp: boolean; begin Result:=False; Clear:=False; if length(Data)<5 then Exit; // no data FRLE:=(Data[0] and img_RLE)=img_RLE; FJPG:=(Data[0] and img_JPG)=img_JPG; FMOT:=(Data[0] and img_MOT)=img_MOT; FCUR:=(Data[0] and img_CUR)=img_CUR; FDIF:=(Data[0] and img_DIF)=img_DIF; if FJPG then begin if length(Data)<11 then Exit; // data error if FRLE then begin if length(Data)<15 then Exit; // data error end; haveBmp:=True; end else if FRLE then begin if length(Data)<9 then Exit; // data error haveBmp:=True; end else if FMOT then begin if length(Data)<9 then Exit; // data error haveBmp:=True; end else if FCUR then begin haveBmp:=False; end else Exit; // no data if haveBmp then begin SizeX:=Data[1]; SizeX:=SizeX shl 8 + Data[2]; SizeY:=Data[3]; SizeY:=SizeY shl 8 + Data[4]; Clear:=not FDIF; Result:=True; end; end; function TRtcImageDecoder.DecodeMouse(const Data: RtcByteArray):boolean; begin Result:=False; if length(Data)<5 then Exit; // no data Result:=(Data[0] and img_CUR)=img_CUR; end; function TRtcImageDecoder.Decompress(const Data: RtcByteArray; var BmpInfo: TRtcBitmapInfo):boolean; var FLZW, FRLE, FJPG, FDIF, FMOT, FCUR:boolean; SizeX,SizeY,HeadSize, JPGSize,RLESize,MOTSize,CurSize,DataStart,bsize:integer; jpgStore, rleStore, motStore, lzwStore, curStore: RtcByteArray; haveBmp: boolean; procedure MotionDecompensation; var i,chg,chgLeft,chgRight,chgColor, lastLeftID,lastRightID,lastColorID, xLeft,yLeft,xRight,yRight,xColor,yColor:integer; oldLeftID,oldRightID, fromColorID, fromLeftID,toLeftID, fromRightID,toRightID, myLastLeft,myLastRight:integer; myLastColor,toColorID, myFinalColor:LongWord; myBlockLine, myBlockX,myBlockY, myBlockID, maxBlockID, maxToBlockID:integer; colorBGR:colorBGR32; colorRGB:colorRGB32; begin i:=0; FIMGBlockX:=motStore[i]; Inc(i); FIMGBlockY:=motStore[i]; Inc(i); chgLeft:=motStore[i]; Inc(i); chgLeft:=chgLeft shl 8 + motStore[i]; Inc(i); chgLeft:=chgLeft shl 8 + motStore[i]; Inc(i); // chgLeft:=chgLeft shl 8 + motStore[i]; Inc(i); chgRight:=motStore[i]; Inc(i); chgRight:=chgRight shl 8 + motStore[i]; Inc(i); chgRight:=chgRight shl 8 + motStore[i]; Inc(i); // chgRight:=chgRight shl 8 + motStore[i]; Inc(i); chg:=(length(motStore)-i) div 6; if chgLeft>chg then Exit; // data error! if chgRight>chg then Exit; // data error! if chgLeft+chgRight>chg then Exit; // data error! chgColor:=chg-chgLeft-chgRight; lastLeftID:=0; lastRightID:=0; lastColorID:=0; myLastColor:=0; myLastLeft:=0; myLastRight:=0; myBlockLine:=(NewBmpInfo.Width div FIMGBlockX)+1; maxBlockID:=(NewBmpInfo.Height div FIMGBLockY)+1; maxBlockID:=maxBlockID*myBLockLine; maxToBlockID:=NewBmpInfo.Width*(NewBmpInfo.Height-FIMGBlockY) + NewBmpInfo.Width - FIMGBLockX; xLeft:=i; yLeft:=xLeft+chgLeft*3; xRight:=yLeft+chgLeft*3; yRight:=xRight+chgRight*3; xColor:=yRight+chgRight*3; yColor:=xColor+chgColor*3; if (chgLeft>0) or (chgRight>0) then begin OldBmpInfo:=DuplicateBitmapInfo(NewBmpInfo); try for i:=1 to chgRight do begin fromRightID:=motStore[xRight]; fromRightID:=fromRightID shl 8 + motStore[xRight+1]; fromRightID:=fromRightID shl 8 + motStore[xRight+2]; // fromRightID:=fromRightID shl 8 + motStore[xRight+3]; Inc(lastRightID,fromRightID+1); myBlockID:=lastRightID-1; if myBlockID>=maxBlockID then Exit; // data error! myBlockY:=myBlockID div myBlockLine; myBlockX:=myBlockID mod myBlockLine; myBlockID:=1 + myBlockX*FIMGBLockX + myBlockY*FIMGBlockY*NewBmpInfo.Width; toRightID:=motStore[yRight]; toRightID:=toRightID shl 8 + motStore[yRight+1]; toRightID:=toRightID shl 8 + motStore[yRight+2]; // toRightID:=toRightID shl 8 + motStore[yRight+3]; myLastRight:=myLastRight xor toRightID; oldRightID:=myBlockID-myLastRight-1; if oldRightID>=maxToBlockID then Exit; // data error! ImageItemCopy(-myBlockID,oldRightID); Inc(xRight,3); Inc(yRight,3); end; for i:=1 to chgLeft do begin fromLeftID:=motStore[xLeft]; fromLeftID:=fromLeftID shl 8 + motStore[xLeft+1]; fromLeftID:=fromLeftID shl 8 + motStore[xLeft+2]; // fromLeftID:=fromLeftID shl 8 + motStore[xLeft+3]; Inc(lastLeftID,fromLeftID+1); myBlockID:=lastLeftID-1; if myBlockID>=maxBlockID then Exit; // data error! myBlockY:=myBlockID div myBlockLine; myBlockX:=myBlockID mod myBlockLine; myBlockID:=1 + myBlockX*FIMGBLockX + myBlockY*FIMGBlockY*NewBmpInfo.Width; toLeftID:=motStore[yLeft]; toLeftID:=toLeftID shl 8 + motStore[yLeft+1]; toLeftID:=toLeftID shl 8 + motStore[yLeft+2]; // toLeftID:=toLeftID shl 8 + motStore[yLeft+3]; myLastLeft:=myLastLeft xor toLeftID; oldLeftID:=myBlockID+myLastLeft+1; if oldLeftID>=maxToBlockID then Exit; // data error! ImageItemCopy(-myBlockID,oldLeftID); Inc(xLeft,3); Inc(yLeft,3); end; finally ReleaseBitmapInfo(OldBmpInfo); end; end; for i:=1 to chgColor do begin fromColorID:=motStore[xColor]; fromColorID:=fromColorID shl 8 + motStore[xColor+1]; fromColorID:=fromColorID shl 8 + motStore[xColor+2]; // fromColorID:=fromColorID shl 8 + motStore[xColor+3]; Inc(lastColorID,fromColorID+1); myBlockID:=lastColorID-1; if myBlockID>=maxBlockID then Exit; // data error! myBlockY:=myBlockID div myBlockLine; myBlockX:=myBlockID mod myBlockLine; myBlockID:=1 + myBlockX*FIMGBlockX + myBlockY*FIMGBlockY*NewBmpInfo.Width; toColorID:=motStore[yColor]; toColorID:=toColorID shl 8 + motStore[yColor+1]; toColorID:=toColorID shl 8 + motStore[yColor+2]; // toColorID:=toColorID shl 8 + motStore[yColor+3]; myLastColor:=myLastColor xor toColorID; case NewBmpInfo.BuffType of btBGRA32: begin colorBGR.R:=myLastColor and $FF; colorBGR.G:=myLastColor shr 8 and $FF; colorBGR.B:=myLastColor shr 16 and $FF; colorBGR.A:=255; myFinalColor:=LongWord(colorBGR); end; else begin colorRGB.R:=myLastColor and $FF; colorRGB.G:=myLastColor shr 8 and $FF; colorRGB.B:=myLastColor shr 16 and $FF; colorRGB.A:=255; myFinalColor:=LongWord(colorRGB); end; end; SetBlockColor(-myBlockID,myFinalColor); Inc(xColor,3); Inc(yColor,3); end; end; begin Result:=False; if length(Data)<5 then Exit; // no data FLZW:=(Data[0] and img_LZW)=img_LZW; FRLE:=(Data[0] and img_RLE)=img_RLE; FJPG:=(Data[0] and img_JPG)=img_JPG; FDIF:=(Data[0] and img_DIF)=img_DIF; FMOT:=(Data[0] and img_MOT)=img_MOT; FCUR:=(Data[0] and img_CUR)=img_CUR; HeadSize:=0; JPGSize:=0; RLESize:=0; MOTSize:=0; CURSize:=0; if FJPG then begin if length(Data)<11 then Exit; // data error HeadSize:=Data[5]; HeadSize:=HeadSize shl 8 + Data[6]; if FRLE then begin if length(Data)<15 then Exit; // data error JPGSize:=Data[7]; JPGSize:=JPGSize shl 8 + Data[8]; JPGSize:=JPGSize shl 8 + Data[9]; JPGSize:=JPGSize shl 8 + Data[10]; RLESize:=Data[11]; RLESize:=RLESize shl 8 + Data[12]; RLESize:=RLESize shl 8 + Data[13]; RLESize:=RLESize shl 8 + Data[14]; DataStart:=15; if FMOT then MOTSize:=length(Data)-DataStart-JPGSize-RLESize; end else begin JPGSize:=Data[7]; JPGSize:=JPGSize shl 8 + Data[8]; JPGSize:=JPGSize shl 8 + Data[9]; JPGSize:=JPGSize shl 8 + Data[10]; DataStart:=11; if FMOT then MOTSize:=length(Data)-DataStart-JPGSize; end; haveBmp:=True; end else if FRLE then begin if length(Data)<9 then Exit; // data error RLESize:=Data[5]; RLESize:=RLESize shl 8 + Data[6]; RLESize:=RLESize shl 8 + Data[7]; RLESize:=RLESize shl 8 + Data[8]; DataStart:=9; if FMOT then MOTSize:=length(data)-DataStart-RLESize; haveBmp:=True; end else if FMOT then begin if length(Data)<9 then Exit; // data error MOTSize:=Data[5]; MOTSize:=MOTSize shl 8 + Data[6]; MOTSize:=MOTSize shl 8 + Data[7]; MOTSize:=MOTSize shl 8 + Data[8]; DataStart:=9; haveBmp:=True; end else if FCUR then begin CURSize:=Data[1]; CURSize:=CURSize shl 8 + Data[2]; CURSize:=CURSize shl 8 + Data[3]; CURSize:=CURSize shl 8 + Data[4]; DataStart:=5; haveBmp:=False; end else Exit; // no data if haveBmp then begin SizeX:=Data[1]; SizeX:=SizeX shl 8 + Data[2]; SizeY:=Data[3]; SizeY:=SizeY shl 8 + Data[4]; ResizeBitmapInfo(BmpInfo,SizeX,SizeY,not FDIF); NewBmpInfo:=MapBitmapInfo(BmpInfo); end; try SetLength(jpgStore,0); SetLength(rleStore,0); SetLength(motStore,0); SetLength(curStore,0); if FLZW then begin if JPGSize>0 then begin lzwStore:=Copy(Data,DataStart,JPGSize); jpgStore:=ZDecompress_Ex(lzwStore); Setlength(lzwStore,0); end; if RLESize>0 then begin lzwStore:=Copy(Data,DataStart+JPGSize,RLESize); rleStore:=ZDecompress_Ex(lzwStore); SetLength(lzwStore,0); end; if MOTSize>0 then begin lzwStore:=Copy(Data,DataStart+JPGSize+RLESize,MOTSize); motStore:=ZDecompress_Ex(lzwStore); SetLength(lzwStore,0); end; if CURSize>0 then begin lzwStore:=Copy(Data,DataStart+JPGSize+RLESize+MOTSize,CURSize); curStore:=ZDecompress_Ex(lzwStore); SetLength(lzwStore,0); end; end else begin if JPGSize>0 then jpgStore:=Copy(Data,DataStart,JPGSize); if RLESize>0 then rleStore:=Copy(Data,DataStart+JPGSize,RLESize); if MOTSize>0 then motStore:=Copy(Data,DataStart+JPGSize+RLESize,MOTSize); if CURSize>0 then curStore:=Copy(Data,DataStart+JPGSize+RLESize+MOTSize,CURSize); end; if length(curStore)>0 then begin if assigned(FMouseCursor) then FMouseCursor.Update(curStore); SetLength(curStore,0); end; if length(motStore)>0 then begin MotionDecompensation; SetLength(motStore,0); end; if length(jpgStore)>0 then begin if HeadSize>0 then begin SetLength(JPGHeadStore,0); if FDIF or FRLE then Result:=JPEGDiffToBitmap(JPGHeadStore,jpgStore,NewBmpInfo) else Result:=JPEGToBitmap(jpgStore,NewBmpInfo); if Result then JPGHeadStore:=Copy(jpgStore,0,HeadSize); end else begin if FDIF or FRLE then Result:=JPEGDiffToBitmap(JPGHeadStore,jpgStore,NewBmpInfo) else Result:=JPEGToBitmap(jpgStore,NewBmpInfo); end; SetLength(jpgStore,0); end else Result:=True; if length(rleStore)>0 then begin if Result then begin bsize:=NewBmpInfo.BytesPerLine*NewBmpInfo.Height; case NewBmpInfo.BuffType of btRGBA32: RGBA32_Decompress(Addr(rleStore[0]), NewBmpInfo.TopData, length(rleStore), bsize, NewBmpInfo.Width, NewBmpInfo.Height, NewBmpInfo.Reverse); btBGRA32: BGRA32_Decompress(Addr(rleStore[0]), NewBmpInfo.TopData, length(rleStore), bsize, NewBmpInfo.Width, NewBmpInfo.Height, NewBmpInfo.Reverse); end; end; SetLength(rleStore,0); end; finally if haveBmp then UnMapBitmapInfo(NewBmpInfo); end; end; procedure TRtcImageDecoder.ImageItemCopy(left, right: integer); var leftP, rightP: PLongWord; leftStride, rightStride, movedPixels, x,y:integer; begin if (left<>0) and (right<>0) then begin if left>0 then begin leftP:=PLongWord(OldBmpInfo.TopData); leftStride:=OldBmpInfo.PixelsToNextLine-FIMGBlockX; if OldBmpInfo.Reverse then begin movedPixels:=(left-1) mod OldBmpInfo.Width; Inc(leftP,movedPixels); Dec(leftP,(left-1)-movedPixels); end else Inc(leftP,left-1); end else begin leftP:=PLongWord(NewBmpInfo.TopData); leftStride:=NewBmpInfo.PixelsToNextLine-FIMGBlockX; if NewBmpInfo.Reverse then begin movedPixels:=(-left-1) mod NewBmpInfo.Width; Inc(leftP,movedPixels); Dec(leftP,(-left-1)-movedPixels); end else Dec(leftP,left+1); end; if right>0 then begin rightP:=PLongWord(OldBmpInfo.TopData); rightStride:=OldBmpInfo.PixelsToNextLine-FIMGBlockX; if OldBmpInfo.Reverse then begin movedPixels:=(right-1) mod OldBmpInfo.Width; Inc(rightP,movedPixels); Dec(rightP,(right-1)-movedPixels); end else Inc(rightP,right-1); end else begin rightP:=PLongWord(NewBmpInfo.TopData); rightStride:=NewBmpInfo.PixelsToNextLine-FIMGBlockX; if NewBmpInfo.Reverse then begin movedPixels:=(-right-1) mod NewBmpInfo.Width; Inc(rightP,movedPixels); Dec(rightP,(-right-1)-movedPixels); end else Dec(rightP,right+1); end; if MotionDebug then begin for y:=1 to FIMGBlockY do begin for x:=1 to FIMGBlockX do begin leftP^:=(rightP^ and $FFE0E0E0) or $FF00FF00; Inc(leftP); Inc(rightP); end; Inc(leftP,leftStride); Inc(rightP,rightStride); end; end else begin for y:=1 to FIMGBlockY do begin for x:=1 to FIMGBlockX do begin leftP^:=rightP^; Inc(leftP); Inc(rightP); end; Inc(leftP,leftStride); Inc(rightP,rightStride); end; end; end; end; procedure TRtcImageDecoder.SetBlockColor(left:integer; right:LongWord); var leftP: PLongWord; leftStride, movedPixels, x,y:integer; begin if left>0 then begin leftP:=PLongWord(OldBmpInfo.TopData); leftStride:=OldBmpInfo.PixelsToNextLine-FIMGBlockX; if OldBmpInfo.Reverse then begin movedPixels:=(left-1) mod OldBmpInfo.Width; Inc(leftP,movedPixels); Dec(leftP,(left-1)-movedPixels); end else Inc(leftP,left-1); end else if left<0 then begin leftP:=PLongWord(NewBmpInfo.TopData); leftStride:=NewBmpInfo.PixelsToNextLine-FIMGBlockX; if NewBmpInfo.Reverse then begin movedPixels:=(-left-1) mod NewBmpInfo.Width; Inc(leftP,movedPixels); Dec(leftP,(-left-1)-movedPixels); end else Dec(leftP,left+1); end else Exit; if MotionDebug then right:=(right and $FFE0E0E0) or $FF0000FF; for y:=1 to FIMGBlockY do begin for x:=1 to FIMGBlockX do begin leftP^:=right; Inc(leftP); end; Inc(leftP,leftStride); end; end; procedure TRtcImageDecoder.SetMotionDebug(const Value: boolean); begin FMotionDebug := Value; end; end.
unit ArchAccsFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, Db, DBTables, DBGrids, ExtCtrls, DBCtrls, BtrDS, Menus, AccountsFrm, SearchFrm, StdCtrls, ComCtrls, Common, Bases, Utilits, CommCons; type TArchAccsForm = class(TDataBaseForm) DataSource: TDataSource; DBGrid: TDBGrid; EditMenu: TMainMenu; FuncItem: TMenuItem; FindItem: TMenuItem; ArchPopupMenu: TPopupMenu; ChildStatusBar: TStatusBar; BtnPanel: TPanel; NameLabel: TLabel; SearchIndexComboBox: TComboBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FindItemClick(Sender: TObject); procedure SearchIndexComboBoxClick(Sender: TObject); private SearchForm: TSearchForm; public end; const ArchAccsForm: TArchAccsForm = nil; implementation {$R *.DFM} procedure TArchAccsForm.FormCreate(Sender: TObject); begin ObjList.Add(Self); DataSource.DataSet := GlobalBase(biAccArc); TakeMenuItems(FuncItem, ArchPopupMenu.Items); ArchPopupMenu.Images := EditMenu.Images; SearchForm := TSearchForm.Create(Self); DefineGridCaptions(DBGrid, PatternDir+'ArchAccs.tab'); SearchForm.SourceDBGrid := DBGrid; SearchIndexComboBox.ItemIndex := 0; SearchIndexComboBoxClick(Sender); end; procedure TArchAccsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TArchAccsForm.FormDestroy(Sender: TObject); begin ObjList.Remove(Self); ArchAccsForm := nil; end; procedure TArchAccsForm.FindItemClick(Sender: TObject); begin SearchForm.ShowModal; end; procedure TArchAccsForm.SearchIndexComboBoxClick(Sender: TObject); begin (DataSource.DataSet as TBtrDataSet).IndexNum := SearchIndexComboBox.ItemIndex end; end.
unit ParameterTypesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 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, DragHelper, System.Generics.Collections, OrderQuery, DSWrap; type TParameterTypeW = class(TOrderW) private FParameterType: TFieldWrap; FID: TFieldWrap; FTableName: TParamWrap; public constructor Create(AOwner: TComponent); override; procedure AddNewValue(const AValue: string); function GetParameterTypeID(const AParameterType: string): Integer; procedure LocateOrAppend(AValue: string); property ParameterType: TFieldWrap read FParameterType; property ID: TFieldWrap read FID; property TableName: TParamWrap read FTableName; end; TQueryParameterTypes = class(TQueryOrder) FDQueryID: TFDAutoIncField; FDQueryParameterType: TWideStringField; FDQueryOrd: TIntegerField; fdqDeleteNotUsedPT: TFDQuery; private FW: TParameterTypeW; procedure DoBeforeOpen(Sender: TObject); { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; function ApplyFilter(ATableName: string): Integer; function SearchByTableName(const ATableName: string): Integer; property W: TParameterTypeW read FW; { Public declarations } end; implementation {$R *.dfm} uses RepositoryDataModule, NotifyEvents, StrHelper, BaseQuery; constructor TQueryParameterTypes.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TParameterTypeW; AutoTransaction := False; TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList); end; function TQueryParameterTypes.ApplyFilter(ATableName: string): Integer; var ASQL: string; begin // Получаем первоначальный запрос ASQL := SQL; ASQL := SQL; ASQL := ASQL.Replace('/* ShowDuplicate', '', [rfReplaceAll]); ASQL := ASQL.Replace('ShowDuplicate */', '', [rfReplaceAll]); if ATableName.IsEmpty then begin FDQuery.Close; FDQuery.SQL.Text := ASQL; FDQuery.Open; Result := FDQuery.RecordCount; end else Result := SearchEx([TParamRec.Create(W.TableName.FullName, ATableName, ftWideString)], -1, ASQL) end; function TQueryParameterTypes.CreateDSWrap: TDSWrap; begin Result := TParameterTypeW.Create(FDQuery); end; procedure TQueryParameterTypes.DoBeforeOpen(Sender: TObject); begin // Удаляем неиспользуемые типы параметров fdqDeleteNotUsedPT.ExecSQL; end; function TQueryParameterTypes.SearchByTableName(const ATableName : string): Integer; begin Assert(not ATableName.IsEmpty); Result := SearchEx([TParamRec.Create(W.TableName.FullName, ATableName, ftWideString)]); end; constructor TParameterTypeW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FOrd := TFieldWrap.Create(Self, 'Ord'); FParameterType := TFieldWrap.Create(Self, 'ParameterType'); // Параметр SQL запроса FTableName := TParamWrap.Create(Self, 'TableName'); end; procedure TParameterTypeW.AddNewValue(const AValue: string); begin Assert(not AValue.IsEmpty); TryAppend; ParameterType.F.AsString := AValue; tryPost; end; function TParameterTypeW.GetParameterTypeID(const AParameterType : string): Integer; var V: Variant; begin Result := 0; V := FDDataSet.LookupEx(ParameterType.FieldName, AParameterType, PKFieldName, [lxoCaseInsensitive]); if not VarIsNull(V) then Result := V end; procedure TParameterTypeW.LocateOrAppend(AValue: string); begin if not FDDataSet.LocateEx(ParameterType.FieldName, AValue, [lxoCaseInsensitive]) then AddNewValue(AValue); end; end.
program daemon; uses Cthreads, Classes, Unix, Sysutils, inifiles, Process, BaseUnix ; type TsendThread = class(TThread) private protected procedure Execute; override; Function mount(var nomefilesfs,pID:String):String; Function flush(var pid:String):integer; public end; type DaemonStatus = (Run,Ready,Busy); Tprocedures = class Procedure checkloop ; Function is_sudo: boolean; Procedure suicide; Procedure sendError(Const text:String); end; var XProcess: Tprocess; shutdown:boolean; currentPid:String; proc:Tprocedures; send:TsendThread; semaphores:DaemonStatus; // (not used for now) It represents the daemon's status Procedure Tprocedures.sendError(Const text:String); begin XProcess := Tprocess.Create(nil); XProcess.CommandLine := '/usr/sbin/sfs/SFSerror "'+text+'"'; XProcess.Options := [poNewProcessGroup, poUsePipes]; if sysutils.FileExists('/usr/sbin/sfs/SFSerror') then begin XProcess.Execute; end; end; Procedure Tprocedures.suicide; //close the daemon cleaning any pending instance begin semaphores:=busy; sysutils.DeleteFile('/tmp/sfs/suicide'); writeln('The Daemon is now halted!'); shutdown:=true; unix.Shell('rm /tmp/sfs/*'); exit; writeln('The Daemon is now halt!'); end; Function TProcedures.is_sudo: boolean; //to determinate if it is runnig in Super user mode or not! begin if fpgeteuid = 0 then result := true else result := false; End; procedure TsendThread.execute; //this procedure read the file SFSsend.sfs and determinate the command to execute var inifile:Tinifile; mount_command:boolean; umount_command:boolean; sfsfile:string; pid:string; begin semaphores:=Busy; writeln('Command received... reading file /tmp/sfs/SFSsend.cfg'); inifile := Tinifile.Create('/tmp/sfs/SFSsend.cfg'); mount_command := inifile.ReadBool('DAEMON','mount',false); umount_command := inifile.ReadBool('DAEMON','umount',false); sfsfile := inifile.ReadString('DAEMON','sfsfile',''); pid := inifile.ReadString('DAEMON','processID',''); sysutils.DeleteFile('/tmp/sfs/SFSsend.cfg'); if mount_command = true then if umount_command=false then send.mount(sfsfile,pid); if umount_command = true then if mount_command=false then send.flush(pid); end; Function TsendThread.mount(var nomefilesfs,pID:String):String; //this function mount the sfs file described into the SFSsend.cfg file //the univoke key is the sfslauncher's process ID Var process: cint; k: smallint; stop: boolean; f: textfile; carattere: Ppchar; stringa,parametrogenDefault,path: string; Begin semaphores:=Run; //extract the sfs filename without the absolute path writeln('I have to mount the file '+nomefilesfs); writeln('SFS instance number: '+pID); parametrogenDefault:= sysutils.ExtractFileName(nomefilesfs); If Not sysutils.DirectoryExists('/.mounted/')Then unix.shell('mkdir /.mounted'); If Not sysutils.DirectoryExists('/.mounted/'+pID)Then Begin path := '/.mounted/'+pID; unix.shell('mkdir '''+path+''''); writeln('mounting... '+parametrogenDefault+' '+path); process := unix.Shell('mount -t squashfs -o loop '''+nomefilesfs+''' '+'"'+path+'"'); unix.WaitProcess(process); Try system.Assign(f,'/tmp/sfs/'+pID); rewrite(f); writeln(f,path); closefile(f); Except proc.sendError('Unable to comunicate with sfslauncher. Please check the /tmp/sfs permissions!'); END; End; mount:=path; semaphores:=ready; End; Function TsendThread.flush(var pid:String):integer; //procedure for dismantling and cleaning var path:String; Begin semaphores:=Run; writeln('Flushing SFS instance number: '+pid); path := '/.mounted/'+pid; writeln('Unmounting, please wait ...'); unix.Shell('umount -l -d '+'"'+path+'"'); //PROCEDURE OF UMOUNT IN USERMODE writeln('Flushing ...'); unix.Shell('rmdir --ignore-fail-on-non-empty "'+path+'"'); semaphores:=ready; if not sysutils.DirectoryExists(path)then result:=0 else result:=-1; End; Procedure Tprocedures.checkloop ; //this procedure create 255 loop back devices were mount 255 sfs software simultaniously! Begin If Not sysutils.FileExists('/dev/loop255') Then Begin if fileexists('/usr/sbin/sfs/MAKEloop')then unix.Shell('rm /dev/loop*'); unix.Shell('cp /usr/sbin/sfs/MAKEloop /dev'); unix.Shell('chmod 777 /dev/MAKEloop'); unix.Shell('cd /dev && exec ./MAKEloop loop'); // migliorare questo punto End; End; /////////////////MAIN//////////////// begin if proc.is_sudo = true then begin if not sysutils.DirectoryExists('/tmp/sfs')then sysutils.CreateDir('/tmp/sfs'); if not sysutils.DirectoryExists('/etc/sfs')then sysutils.CreateDir('/etc/sfs'); if sysutils.DirectoryExists('/.mounted')then unix.Shell('rm -R /.mounted/*'); writeln('Checking loop-back devices...'); unix.Shell('modprobe loop'); proc.checkloop; unix.Shell('modprobe squashfs'); shutdown:=false; writeln('The SFS daemon is now listening....'); while shutdown=false do begin if sysutils.FileExists('/tmp/sfs/suicide') then proc.suicide; unix.Shell('chmod 777 -R /tmp/sfs && chmod 777 -R /etc/sfs'); if sysutils.FileExists('/tmp/sfs/SFSsend.cfg')then begin send := TsendThread.Create(false); send.Execute; end; sleep(500); // for the 99% of the time the daemon sleep, decreasing its overhead end; sysutils.DeleteFile('/tmp/sfs/SFSsend.cfg'); end else writeln('Hey!! You must be root to launch this daemon!'); end.
unit DemoBase; interface {$IFDEF WIN32} {$DEFINE MSWINDOWS} {$ENDIF} {$IFDEF WIN64} {$DEFINE MSWINDOWS} {$ENDIF} uses Classes, SysUtils, DemoFrame, Windows, ComCtrls, Controls, Graphics, Forms, ShellAPI; type TDemoType = (dtDemo, dtCategory); TDemo = class protected FName: string; FHint: string; FDescription: string; FDemoType: TDemoType; FFrameClass: TDemoFrameClass; FFrame: TDemoFrame; public constructor Create(Name, Hint, Description: string; DemoType: TDemoType; FrameClass: TDemoFrameClass); destructor Destroy; override; procedure LoadDemoCode(Strings: TStrings); procedure OpenDemoFolder; procedure FreeFrame; property Name: string read FName; property Hint: string read FHint; property Description: string read FDescription; property DemoType: TDemoType read FDemoType; property FrameClass: TDemoFrameClass read FFrameClass; property Frame: TDemoFrame read FFrame; end; TDemos = class protected FSelectedDemo: TDemo; public destructor Destroy; override; procedure RegisterDemo(DemoName, DemoHint, DemoDescription, DemoCategory: string; FrameClass: TDemoFrameClass; ImgIndex: integer); function SelectDemo(DemoIndex: integer): TDemo; //Create demo frame by DemoIndex property SelectedDemo: TDemo read FSelectedDemo; end; implementation destructor TDemos.Destroy; begin FSelectedDemo.Free; inherited; end; procedure TDemos.RegisterDemo(DemoName, DemoHint, DemoDescription, DemoCategory: string; FrameClass: TDemoFrameClass; ImgIndex: integer); begin FSelectedDemo := TDemo.Create(DemoName, DemoHint, DemoDescription, dtDemo, FrameClass); end; function TDemos.SelectDemo(DemoIndex: integer): TDemo; //Init and show demo by DemoIndex begin Result := FSelectedDemo; with FSelectedDemo do if FFrame = nil then begin FFrame := FFrameClass.Create(nil); end else FFrame.Show; end; {TDemo} constructor TDemo.Create(Name, Hint, Description: string; DemoType: TDemoType; FrameClass: TDemoFrameClass); begin inherited Create; FName := Name; FHint := Hint; FDescription := Description; FFrameClass := FrameClass; FDemoType := DemoType; end; destructor TDemo.Destroy; begin FreeFrame; inherited; end; procedure TDemo.LoadDemoCode(Strings: TStrings); var FileName: string; begin if DemoType = dtCategory then Strings.Clear else begin {$IFDEF MSWINDOWS} FileName := Format('%s\%s\%s.pas', [ExtractFilePath(Application.ExeName), Description, Name]); {$ELSE} FileName := Format('%s/%s/%s.pas', [ExtractFilePath(Application.ExeName), Description, Name]); {$ENDIF} if FileExists(FileName) then Strings.LoadFromFile(FileName) else Strings.Clear; end; end; procedure TDemo.OpenDemoFolder; var FolderName: string; begin if DemoType = dtDemo then begin FolderName := ExtractFilePath(Application.ExeName) + Description; ShellExecute(0, 'open', PChar(FolderName), '', '.', SW_SHOW); end; end; procedure TDemo.FreeFrame; begin FFrame.Finalize; FFrame.Free; FFrame := nil; end; end.
unit AAniversariantes; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Buttons, ComCtrls, Grids, DBGrids, Tabela, DBKeyViolation, Db, DBTables, Menus, DBClient; type TFAniversariantes = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BFechar: TBitBtn; BEnviarEmail: TBitBtn; EDatInicio: TCalendario; Label2: TLabel; EDatFim: TCalendario; CPeriodo: TCheckBox; PanelColor3: TPanelColor; PanelColor4: TPanelColor; Splitter1: TSplitter; PanelColor5: TPanelColor; PanelColor6: TPanelColor; PanelColor7: TPanelColor; PanelColor8: TPanelColor; PanelColor9: TPanelColor; Label1: TLabel; Splitter2: TSplitter; PanelColor10: TPanelColor; Label3: TLabel; PanelColor11: TPanelColor; Label4: TLabel; PanelColor12: TPanelColor; Label5: TLabel; GClientesFornecedores: TGridIndice; GContatosCliente: TGridIndice; GProspects: TGridIndice; GContatosProspect: TGridIndice; CADCLIENTES: TSQL; CADCLIENTESD_DAT_NAS: TSQLTimeStampField; CADCLIENTESIDADE: TFMTBCDField; CADCLIENTESC_NOM_CLI: TWideStringField; CADCLIENTESC_FO1_CLI: TWideStringField; CADCLIENTESC_END_ELE: TWideStringField; CADCLIENTESC_CID_CLI: TWideStringField; DataCADCLIENTES: TDataSource; CONTATOCLIENTE: TSQL; DataCONTATOCLIENTE: TDataSource; CONTATOCLIENTEDATNASCIMENTO: TSQLTimeStampField; CONTATOCLIENTENOMCONTATO: TWideStringField; CONTATOCLIENTEC_NOM_CLI: TWideStringField; CONTATOCLIENTEC_NOM_FAN: TWideStringField; CONTATOCLIENTEC_FO1_CLI: TWideStringField; CONTATOCLIENTEC_END_ELE: TWideStringField; CONTATOCLIENTEC_CID_CLI: TWideStringField; CONTATOCLIENTEIDADE: TFMTBCDField; Splitter3: TSplitter; PROSPECT: TSQL; DataPROSPECT: TDataSource; PROSPECTDATNASCIMENTO: TSQLTimeStampField; PROSPECTIDADE: TFMTBCDField; PROSPECTNOMPROSPECT: TWideStringField; PROSPECTDESFONE1: TWideStringField; PROSPECTDESEMAILCONTATO: TWideStringField; PROSPECTDESCIDADE: TWideStringField; CONTATOPROSPECT: TSQL; DataCONTATOPROSPECT: TDataSource; CONTATOPROSPECTDATNASCIMENTO: TSQLTimeStampField; CONTATOPROSPECTIDADE: TFMTBCDField; CONTATOPROSPECTNOMCONTATO: TWideStringField; CONTATOPROSPECTNOMPROSPECT: TWideStringField; CONTATOPROSPECTNOMFANTASIA: TWideStringField; CONTATOPROSPECTDESFONE1: TWideStringField; CONTATOPROSPECTDESEMAILCONTATO: TWideStringField; CONTATOPROSPECTDESCIDADE: TWideStringField; PClientes: TPopupMenu; EnviarEMail1: TMenuItem; Telemarketing1: TMenuItem; CADCLIENTESI_COD_CLI: TFMTBCDField; PContatosCliente: TPopupMenu; EnviarEMail2: TMenuItem; Telemarketing2: TMenuItem; CONTATOCLIENTECODCLIENTE: TFMTBCDField; PROSPECTCODPROSPECT: TFMTBCDField; CONTATOPROSPECTCODPROSPECT: TFMTBCDField; PProspects: TPopupMenu; EMail1: TMenuItem; Telemarketing3: TMenuItem; PContatosProspect: TPopupMenu; EMail2: TMenuItem; Telemarketing4: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure GClientesFornecedoresOrdem(Ordem: String); procedure CPeriodoClick(Sender: TObject); procedure GContatosClienteOrdem(Ordem: String); procedure GProspectsOrdem(Ordem: String); procedure GContatosProspectOrdem(Ordem: String); procedure EnviarEMail1Click(Sender: TObject); procedure Telemarketing1Click(Sender: TObject); procedure EnviarEMail2Click(Sender: TObject); procedure Telemarketing2Click(Sender: TObject); procedure EMail1Click(Sender: TObject); procedure Telemarketing3Click(Sender: TObject); procedure EMail2Click(Sender: TObject); procedure Telemarketing4Click(Sender: TObject); private VprOrdemCliente, VprOrdemContatoCliente, VprOrdemProspect, VprOrdemContatoProspect: String; procedure InicializaTela; procedure AtualizaConsultas; procedure AtualizaConsultaCliente; procedure AdicionaFiltrosCliente(VpaSelect: TStrings); procedure AtualizaConsultaContatoCliente; procedure AdicionaFiltrosContatoCliente(VpaSelect: TStrings); procedure AtualizaConsultaProspect; procedure AdicionaFiltrosProspect(VpaSelect: TStrings); procedure AtualizaConsultaContatoProspect; procedure AdicionaFiltrosContatoProspect(VpaSelect: TStrings); procedure EmailCliente; //rafael procedure TelemarketingCliente(VpaCodCliente: Integer); procedure EMailContatoCliente; //rafael procedure EMailProspect; //rafael procedure TelemarketingProspect(VpaCodProspect: Integer); procedure EmailContatoProspect; //rafael public end; var FAniversariantes: TFAniversariantes; implementation uses APrincipal, FunData, FunSQL, UnDados, ANovoTeleMarketing, ConstMsg, ANovoTelemarketingProspect; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFAniversariantes.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } InicializaTela; VprOrdemCliente:= ''; VprOrdemContatoCliente:= ''; VprOrdemProspect:= ''; VprOrdemContatoProspect:= ''; AtualizaConsultas; end; { ******************* Quando o formulario e fechado ************************** } procedure TFAniversariantes.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } CADCLIENTES.Close; PROSPECT.Close; CONTATOCLIENTE.Close; CONTATOPROSPECT.Close; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFAniversariantes.BFecharClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFAniversariantes.CPeriodoClick(Sender: TObject); begin AtualizaConsultas; end; {******************************************************************************} procedure TFAniversariantes.InicializaTela; begin EDatInicio.DateTime:= PrimeiroDiaMes(Date); EDatFim.DateTime:= UltimoDiaMes(Date); ActiveControl:= EDatInicio; end; {******************************************************************************} procedure TFAniversariantes.AtualizaConsultas; begin AtualizaConsultaCliente; AtualizaConsultaContatoCliente; AtualizaConsultaProspect; AtualizaConsultaContatoProspect; end; {******************************************************************************} procedure TFAniversariantes.AtualizaConsultaCliente; begin CADCLIENTES.Close; CADCLIENTES.SQL.Clear; CADCLIENTES.SQL.Add('SELECT CLI.I_COD_CLI, CLI.D_DAT_NAS, ('+ FormatDateTime('YYYY',Now) +'- '+SqlTextoAno('CLI.D_DAT_NAS')+') IDADE,'+ ' CLI.C_NOM_CLI, CLI.C_FO1_CLI, CLI.C_END_ELE, CLI.C_CID_CLI'+ ' FROM CADCLIENTES CLI'+ ' WHERE CLI.I_COD_CLI = CLI.I_COD_CLI'); AdicionaFiltrosCliente(CADCLIENTES.SQL); CADCLIENTES.SQL.Add(VprOrdemCliente); CADCLIENTES.Open; GClientesFornecedores.ALinhaSQLOrderBy:= CADCLIENTES.SQL.Count-1; end; {******************************************************************************} procedure TFAniversariantes.AdicionaFiltrosCliente(VpaSelect: TStrings); begin //verificar - não encontrei outra forma mais fácil de fazer if CPeriodo.Checked then begin VpaSelect.Add(' AND '+SQLTextoDia('CLI.D_DAT_NAS')+' BETWEEN '+IntToStr(Dia(EDatInicio.Datetime))+' AND '+IntToStr(Dia(EDatFim.Datetime))); VpaSelect.Add(' AND '+SQLTextoMes('CLI.D_DAT_NAS')+' BETWEEN '+IntToStr(Mes(EDatInicio.Datetime))+' AND '+IntToStr(Mes(EDatFim.Datetime))); // VpaSelect.Add(SQLTextoDataEntreAAAAMMDD('CLI.D_DAT_NAS',EDatInicio.Datetime,EDatFim.Datetime,True)); end; end; {******************************************************************************} procedure TFAniversariantes.GClientesFornecedoresOrdem(Ordem: String); begin VprOrdemCliente:= Ordem; end; {******************************************************************************} procedure TFAniversariantes.AtualizaConsultaContatoCliente; begin CONTATOCLIENTE.Close; CONTATOCLIENTE.SQL.Clear; CONTATOCLIENTE.SQL.Add('SELECT CCL.CODCLIENTE, CCL.DATNASCIMENTO, ('+ FormatDateTime('YYYY',Now) +'- '+SqlTExtoAno('CCL.DATNASCIMENTO')+') IDADE,'+ ' CCL.NOMCONTATO, CLI.C_NOM_CLI, CLI.C_NOM_FAN, CLI.C_FO1_CLI, CLI.C_END_ELE, CLI.C_CID_CLI'+ ' FROM CONTATOCLIENTE CCL, CADCLIENTES CLI'+ ' WHERE CLI.I_COD_CLI = CCL.CODCLIENTE'); AdicionaFiltrosContatoCliente(CONTATOCLIENTE.SQL); CONTATOCLIENTE.SQL.Add(VprOrdemContatoCliente); CONTATOCLIENTE.Open; GContatosCliente.ALinhaSQLOrderBy:= CONTATOCLIENTE.SQL.Count-1; end; {******************************************************************************} procedure TFAniversariantes.AdicionaFiltrosContatoCliente(VpaSelect: TStrings); begin //verificar - não encontrei outra forma mais fácil de fazer if CPeriodo.Checked then begin VpaSelect.Add(' AND '+SQLTextoDia('CCL.DATNASCIMENTO')+' BETWEEN '+IntToStr(Dia(EDatInicio.Datetime))+' AND '+IntToStr(Dia(EDatFim.Datetime))); VpaSelect.Add(' AND '+SQLTextoMes('CCL.DATNASCIMENTO')+' BETWEEN '+IntToStr(Mes(EDatInicio.Datetime))+' AND '+IntToStr(Mes(EDatFim.Datetime))); // VpaSelect.Add(SQLTextoDataEntreAAAAMMDD('CCL.DATNASCIMENTO',EDatInicio.Datetime,Incdia(EDatFim.Datetime,1),True)); end; end; {******************************************************************************} procedure TFAniversariantes.GContatosClienteOrdem(Ordem: String); begin VprOrdemContatoCliente:= Ordem; end; {******************************************************************************} procedure TFAniversariantes.AtualizaConsultaProspect; begin PROSPECT.Close; PROSPECT.SQL.Clear; PROSPECT.SQL.Add('SELECT PPT.CODPROSPECT, PPT.DATNASCIMENTO, ('+ FormatDateTime('YYYY',Now) +'- '+SqlTextoAno('PPT.DATNASCIMENTO')+') IDADE,'+ ' PPT.NOMPROSPECT, PPT.DESFONE1, PPT.DESEMAILCONTATO, PPT.DESCIDADE'+ ' FROM PROSPECT PPT'+ ' WHERE PPT.CODPROSPECT = PPT.CODPROSPECT'); AdicionaFiltrosProspect(PROSPECT.SQL); PROSPECT.SQL.Add(VprOrdemProspect); PROSPECT.Open; GProspects.ALinhaSQLOrderBy:= PROSPECT.SQL.Count-1; end; {******************************************************************************} procedure TFAniversariantes.AdicionaFiltrosProspect(VpaSelect: TStrings); begin //verificar - não encontrei outra forma mais fácil de fazer if CPeriodo.Checked then begin VpaSelect.Add(' AND '+SQLTextoDia('PPT.DATNASCIMENTO')+ ' BETWEEN '+IntToStr(Dia(EDatInicio.Datetime))+' AND '+IntToStr(Dia(EDatFim.Datetime))); VpaSelect.Add(' AND '+SQLTextoMes('PPT.DATNASCIMENTO')+ ' BETWEEN '+IntToStr(Mes(EDatInicio.Datetime))+' AND '+IntToStr(Mes(EDatFim.Datetime))); end; end; {******************************************************************************} procedure TFAniversariantes.GProspectsOrdem(Ordem: String); begin VprOrdemProspect:= Ordem; end; {******************************************************************************} procedure TFAniversariantes.AtualizaConsultaContatoProspect; begin CONTATOPROSPECT.Close; CONTATOPROSPECT.SQL.Clear; CONTATOPROSPECT.SQL.Add('SELECT CPP.CODPROSPECT, CPP.DATNASCIMENTO, ('+ FormatDateTime('YYYY',Now) +'- '+SqlTextoAno('CPP.DATNASCIMENTO')+') IDADE, CPP.NOMCONTATO,'+ ' PPT.NOMPROSPECT, PPT.NOMFANTASIA, PPT.DESFONE1, PPT.DESEMAILCONTATO, PPT.DESCIDADE'+ ' FROM CONTATOPROSPECT CPP, PROSPECT PPT'+ ' WHERE PPT.CODPROSPECT = CPP.CODPROSPECT'); AdicionaFiltrosContatoProspect(CONTATOPROSPECT.SQL); CONTATOPROSPECT.SQL.Add(VprOrdemContatoProspect); CONTATOPROSPECT.Open; GContatosProspect.ALinhaSQLOrderBy:= CONTATOPROSPECT.SQL.Count-1; end; {******************************************************************************} procedure TFAniversariantes.AdicionaFiltrosContatoProspect(VpaSelect: TStrings); begin if CPeriodo.Checked then begin VpaSelect.Add(' AND '+SQLTextoDia('CPP.DATNASCIMENTO')+' BETWEEN '+IntToStr(Dia(EDatInicio.Datetime))+' AND '+IntToStr(Dia(EDatFim.Datetime))); VpaSelect.Add(' AND '+SQLTextoMes('CPP.DATNASCIMENTO')+' BETWEEN '+IntToStr(Mes(EDatInicio.Datetime))+' AND '+IntToStr(Mes(EDatFim.Datetime))); end; end; {******************************************************************************} procedure TFAniversariantes.GContatosProspectOrdem(Ordem: String); begin VprOrdemContatoProspect:= Ordem; end; {******************************************************************************} procedure TFAniversariantes.EnviarEMail1Click(Sender: TObject); begin EmailCliente; end; {******************************************************************************} procedure TFAniversariantes.EmailCliente; begin end; {******************************************************************************} procedure TFAniversariantes.Telemarketing1Click(Sender: TObject); begin if CADCLIENTESI_COD_CLI.AsInteger <> 0 then TelemarketingCliente(CADCLIENTESI_COD_CLI.AsInteger) else aviso('CLIENTE INVÁLIDO!!!'#13'É necessário selecionar um cliente antes de fazer o telemarketing.'); end; {******************************************************************************} procedure TFAniversariantes.TelemarketingCliente(VpaCodCliente: Integer); begin FNovoTeleMarketing:= TFNovoTeleMarketing.CriarSDI(Application,'',True); FNovoTeleMarketing.TeleMarketingCliente(VpaCodCliente); FNovoTeleMarketing.Free; end; {******************************************************************************} procedure TFAniversariantes.EnviarEMail2Click(Sender: TObject); begin EMailContatoCliente; end; {******************************************************************************} procedure TFAniversariantes.EMailContatoCliente; begin end; {******************************************************************************} procedure TFAniversariantes.Telemarketing2Click(Sender: TObject); begin if CONTATOCLIENTECODCLIENTE.AsInteger <> 0 then TelemarketingCliente(CONTATOCLIENTECODCLIENTE.AsInteger) else aviso('CONTATO DO CLIENTE INVÁLIDO!!!'#13'É necessário selecionar o contato de um cliente antes de fazer o telemarketing.'); end; {******************************************************************************} procedure TFAniversariantes.EMail1Click(Sender: TObject); begin EMailProspect; end; {******************************************************************************} procedure TFAniversariantes.EMailProspect; begin end; {******************************************************************************} procedure TFAniversariantes.Telemarketing3Click(Sender: TObject); begin if PROSPECTCODPROSPECT.AsInteger <> 0 then TelemarketingProspect(PROSPECTCODPROSPECT.AsInteger) else aviso('PROSPECT INVÁLIDO!!!'#13'É necessário selecionar um prospect antes de fazer o telemarketing.'); end; {******************************************************************************} procedure TFAniversariantes.TelemarketingProspect(VpaCodProspect: Integer); begin FNovoTeleMarketingProspect:= TFNovoTeleMarketingProspect.CriarSDI(Application,'',True); FNovoTeleMarketingProspect.TeleMarketingProspect(VpaCodProspect); FNovoTeleMarketingProspect.Free; end; {******************************************************************************} procedure TFAniversariantes.EMail2Click(Sender: TObject); begin EmailContatoProspect; end; {******************************************************************************} procedure TFAniversariantes.EmailContatoProspect; begin end; {******************************************************************************} procedure TFAniversariantes.Telemarketing4Click(Sender: TObject); begin if CONTATOPROSPECTCODPROSPECT.AsInteger <> 0 then TelemarketingProspect(CONTATOPROSPECTCODPROSPECT.AsInteger) else aviso('CONTATO DO PROSPECT INVÁLIDO!!!'#13'É necessário selecionar o contato de um prospect antes de fazer o telemarketing.'); end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFAniversariantes]); end.
unit PerformanceTest; {$mode objfpc}{$H+} interface uses SysUtils, fpcunit, testregistry, LCLIntf, uEnums, TestHelper, uIntXLibTypes, uIntX; type { TTestPerformance } TTestPerformance = class(TTestCase) published procedure Multiply128BitNumbers(); private Fint1, Fint2: TIntX; procedure Inner(); end; implementation procedure TTestPerformance.Multiply128BitNumbers(); var temp1, temp2: TIntXLibUInt32Array; A, B: UInt32; begin SetLength(temp1, 4); temp1[0] := 47668; temp1[1] := 58687; temp1[2] := 223234234; temp1[3] := 42424242; SetLength(temp2, 4); temp2[0] := 5674356; temp2[1] := 34656476; temp2[2] := 45667; temp2[3] := 678645646; Fint1 := TIntX.Create(temp1, False); Fint2 := TIntX.Create(temp2, False); A := GetTickCount; TTestHelper.Repeater(100000, @Inner); B := GetTickCount; WriteLn(Format('classic multiply operation took %u ms', [B - A])); end; procedure TTestPerformance.Inner(); begin TIntX.Multiply(Fint1, Fint2, TMultiplyMode.mmClassic); end; initialization RegisterTest(TTestPerformance); end.
unit frmNewPassword_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TfrmNewPasswordGenerator = class(TForm) btnGenerate: TButton; pnlPasswordOut: TPanel; bmbClose: TBitBtn; rgpGenStyle: TRadioGroup; procedure btnGenerateClick(Sender: TObject); private { Private declarations } // variables used iNum1, iNum2, iNum3: integer; cChar1, cChar2: char; sLetter1, sLetter2, sLetter3, sLetter4,sLetter5,sTextPassword: string; tDesktop: TextFile; procedure GenerationAndSequencing; public { Public declarations } sPassword:string; //constants for password generation const arrSpecial: array [1 .. 8] of char = ('@', '!', '#', '$', '%', '^', '&', '*'); arrLetters: array [1 .. 26] of char = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); end; var frmNewPasswordGenerator: TfrmNewPasswordGenerator; implementation {$R *.dfm} procedure TfrmNewPasswordGenerator.btnGenerateClick(Sender: TObject); begin Randomize; GenerationAndSequencing; end; procedure TfrmNewPasswordGenerator.GenerationAndSequencing; begin // if nothing is selected if rgpGenStyle.ItemIndex = -1 then begin ShowMessage('Please select a style'); end; //simple style if rgpGenStyle.ItemIndex = 0 then begin Randomize; iNum1 := Random(35) + 1; iNum2 := Random(35) + 1; sLetter1 := arrLetters[Random(26) + 1]; sLetter3 := arrLetters[Random(26) + 1]; sLetter5 := arrLetters[Random(26) + 1]; sPassword:= sLetter1+IntToStr(iNum1)+sLetter5+IntToStr(iNum2)+sLetter1; pnlPasswordOut.Caption:= sPassword; AssignFile(tDesktop, 'NEWLY GENERATED PASSWORD.txt'); Rewrite(tDesktop); sTextPassword := 'Password:' + ' ' + sPassword; Writeln(tDesktop,sTextPassword); CloseFile(tDesktop); end; //Intermediate style if rgpGenStyle.ItemIndex = 1 then begin Randomize; iNum1 := Random(50) + 1; iNum2 := Random(50) + 1; sLetter2 := Uppercase(arrLetters[Random(26) + 1]); sLetter4 := Uppercase(arrLetters[Random(26) + 1]); sLetter1 := arrLetters[Random(26) + 1]; sLetter3 := arrLetters[Random(26) + 1]; sPassword:=sLetter4+IntToStr(iNum1)+sLetter1+IntToStr(iNum2)+sLetter2+sLetter3; pnlPasswordOut.Caption:= sPassword; AssignFile(tDesktop, 'NEWLY GENERATED PASSWORD.txt'); Rewrite(tDesktop); sTextPassword := 'Password:' + ' ' + sPassword; Writeln(tDesktop,sTextPassword); CloseFile(tDesktop); end; //Complex style if rgpGenStyle.ItemIndex = 2 then begin Randomize; cChar1 := arrSpecial[Random(8) + 1]; cChar2 := arrSpecial[Random(8) + 1]; iNum1 := Random(65) + 1; iNum2 := Random(65) + 1; sLetter2 := Uppercase(arrLetters[Random(26) + 1]); sLetter4 := Uppercase(arrLetters[Random(26) + 1]); sLetter1 := arrLetters[Random(26) + 1]; sLetter3 := arrLetters[Random(26) + 1]; sPassword:=sLetter2+cChar1+IntToStr(iNum1)+sLetter4+cChar2+sLetter1+IntToStr(iNum2)+sLetter3; pnlPasswordOut.Caption:= sPassword; AssignFile(tDesktop, 'NEWLY GENERATED PASSWORD.txt'); Rewrite(tDesktop); sTextPassword := 'Password:' + ' ' + sPassword; Writeln(tDesktop,sTextPassword); CloseFile(tDesktop); end; //successful generation if pnlPasswordOut.Caption = sPassword then begin ShowMessage('Password successfully generated, text file saved!'); end; end; end.
unit KOLHilightEdit; { Мне нужен достаточно простой текстовой редактор, без особых универсальностей. Но с возможностью синтаксической расцветки. Быстрый. Маленький. Без глюков. За 3 дня управлюсь? Владимир Кладов, (C) 2005. Время изготовления рабочей версии - 3 дня от начала проекта (с 27.08.2005 по 29.08.2005, управился), с добавлением некоторых фич (индент, FastReplaceSelection, AutoOverwrite, Indent, Autocompletion) и правкой некоторых ошибок - итого 4 дня. Хорошо, 5 дней, и не буду больше сюда возвращаться. Лучше напишу мемуар "как я писал мемо-компонент за 3... нет, 5 дней". Кстати, пригодится Autocompletion :) } interface {$I KOLDEF.INC} uses Windows, Messages, MMSystem, KOL; // Выключая (комментируя) одну из строк ниже, можно отказаться от части // возможностей (в любом сочетании), соответственно облегчив код на немного. {$DEFINE CtrlArrowMoveByWords} {$DEFINE DblClkSelectWord} {$DEFINE MouseWheelScrolls} {.$DEFINE ProcessHotkeys} //{$DEFINE Only_ReadOnly} {$DEFINE ProvideUndoRedo} {$DEFINE ProvideSmartTabs} {$DEFINE ProvideCustomTabs} {$DEFINE ProvideHighlight} {$DEFINE ProvideBookmarks} {$DEFINE UseBufferBitmap} // less flic! {$DEFINE DrawRightMargin} //{$DEFINE RightZigzagIndicateLongLine} {$DEFINE FastReplaceSelection} {$DEFINE AutoOverwrite} {$DEFINE ProvideAutoCompletion} //{$DEFINE AutocompletionCaseSensitive} //{$DEFINE AutoCompletionNumbers} {$DEFINE AutocompletionFastFillDictionary} {$DEFINE UseStrListEx} // by sugg. of Thaddy de Koning, 6-Feb-2006 //{$DEFINE BeepOnError} {$DEFINE AllowLeftFromColumn0} {$DEFINE AlwaysHorzScrollBar_ofsize_MaxLineWidth} const MaxLineWidth = 1024; type TOptionEdit = ( oeReadOnly, oeOverwrite, oeKeepTrailingSpaces, oeSmartTabs, oeHighlight, oeAutoCompletion ); TOptionsEdit = set of TOptionEdit; TTokenAttrs = packed record fontstyle: TFontStyle; fontcolor: TColor; backcolor: TColor; end; TOnScanToken = function( Sender: PControl; const FromPos: TPoint; var Attrs: TTokenAttrs ): Integer of object; { Методика подцветки синтаксиса такова: устанавливается обработчик события OnScanToken, который по необходимости получает координату FromPos, берет строку Lines[ FromPos.Y ], и с позиции FromPos.X (считается с нуля) определяет атрибуты токена (записывает их в Attrs), и возвращает длину токена. Не надо делать никакого компонента, если без него можно обойтись. } TFindReplaceOption = ( froBack, froCase, froSpaces, froReplace, froAll ); TFindReplaceOptions = set of TFindReplaceOption; TOnText = function( Sender: PControl; LineNo: Integer; var S: KOLString ): Boolean of object; TOnInsertLine = procedure( Sender: PControl; LineNo: Integer; var S: KOLString ) of object; TOnDeleteLine = procedure( Sender: PControl; LineNo: Integer ) of object; TOnNewLine = function( Sender: PControl; LineNo: Integer; var S: KOLString ): Integer of object; { Здесь предварительно объявлем объект PHilight } PHilight = ^THilight; { Здесь объявлен контрол, наследуемый от PControl. Большинство методов, специфичных для HilightEdit, выносятся в CustomObj, доступный через свойство Edit. Сам объект HilightEdit имеет только методы, унаследованные от TControl и позволяющие управлять общими для всех контролов характеристиками. } PHilightMemo = ^THilightMemo; THilightMemo = object( TControl ) protected //fCollectUpdRgn: HRGN; procedure Init; virtual; function GetEdit: PHilight; public property Edit: PHilight read GetEdit; destructor Destroy; virtual; end; { А здесь объявляем сопутствующий объект, который и содержит все специфичные для Hilighting'а свойства и методы. } THilight = object( TObj ) private FCaret: TPoint; FTopLine: Integer; FLeftCol: Integer; function GetCount: Integer; function GetLines(Idx: Integer): KOLString; procedure SetLines(Idx: Integer; const Value: KOLString); function GetSelection: KOLString; procedure SetSelection(const Value: KOLString); procedure SetSelBegin(const Value: TPoint); procedure SetSelEnd(const Value: TPoint); procedure SetCaret(const Value: TPoint); procedure SetTopLine(const Value: Integer); procedure SetLeftCol(const Value: Integer); function GetText: KOLString; procedure SetText(Value: KOLString); procedure SetOnScanToken(const Value: TOnScanToken); function GetLineData(Idx: Integer): DWORD; procedure SetLineData(Idx: Integer; const Value: DWORD); protected FMemo: PHilightMemo; // ссылка на хозяина - контрол procedure Init; virtual; public destructor Destroy; virtual; procedure Clear; //-------------------------------------------------------------------------- // Доступ к количеству строк и чтение-запись строк из программы property Count: Integer read GetCount; property Lines[ Idx: Integer ]: KOLString read GetLines write SetLines; property LineData[ Idx: Integer ]: DWORD read GetLineData write SetLineData; property Text: KOLString read GetText write SetText; { ! Не следует использовать свойства Text, Caption самого контрола THilightMemo - они не имеют отношения к отображаемому тексту. Следует использовать методы и свойства объекта Edit, в частности, это свойство Text ! } procedure InvalidateLine( y: Integer ); public RightMarginChars: Integer; // по умолчанию 80, при вкл. DrawRightMargin RightMarginColor: TColor; // по умолчанию clBlue protected FLines: {$IFDEF UNICODE_CTRLS} {$IFDEF UseStrListEx} PWStrListEx {$ELSE} PWStrList {$ENDIF}; // текст {$ELSE} {$IFDEF UseStrListEx} PStrListEx {$ELSE} PStrList {$ENDIF}; // текст {$ENDIF} FBufferBitmap: PBitmap; procedure DoPaint( DC: HDC ); protected FChangeLevel: Integer; procedure Changing; // начало блока изменений procedure Changed; // конец блока изменений protected FOnScanToken: TOnScanToken; public //-------------------------------------------------------------------------- // Раскраска синтаксиса property OnScanToken: TOnScanToken read FOnScanToken write SetOnScanToken; public //-------------------------------------------------------------------------- // Утилиты редактирования Options: TOptionsEdit; procedure DeleteLine( y: Integer; UseScroll: Boolean ); procedure InsertLine( y: Integer; const S: KOLString; UseScroll: Boolean ); protected procedure DeleteLine1( y: Integer ); protected fOnInsertLine: TOnInsertLine; fOnDeleteLine: TOnDeleteLine; public //-------------------------------------------------------------------------- // События изменения состава строк property OnDeleteLine: TOnDeleteLine read fOnDeleteLine write fOnDeleteLine; property OnInsertLine: TOnInsertLine read fOnInsertLine write fOnInsertLine; public //-------------------------------------------------------------------------- // Управление отступом procedure Indent( delta: Integer ); public //-------------------------------------------------------------------------- // Текущая позиция (каретка) property Caret: TPoint read FCaret write SetCaret; function Client2Coord( const P: TPoint ): TPoint; procedure CaretToView; { CaretToView обеспечивает скроллирование текста таким образом, чтобы каретка ввода вмсте со следующим символом оказались в видимой части окна. } public //-------------------------------------------------------------------------- // Выделенная область protected FSelBegin, FSelEnd, FSelFrom: TPoint; // начало, конец выделенной области // и позиция, от которой выделение стартовало (для продолжения) public procedure SetSel( const Pos1, Pos2, PosFrom: TPoint ); { SetSel устанавливает новое выделение и позицию начального маркера выделения за один вызов. } property Selection: KOLString read GetSelection write SetSelection; property SelBegin: TPoint read FSelBegin write SetSelBegin; property SelEnd: TPoint read FSelEnd write SetSelEnd; property SelFrom: TPoint read FSelFrom write FSelFrom; function SelectionAvailable: Boolean; procedure DeleteSelection; procedure InvalidateSelection; // пометить видимую часть области выделения // как испорченную public //-------------------------------------------------------------------------- // Позиционирование и выделение мышью protected FMouseDown: Boolean; // TRUE, когда нажата левая клавиша мыши FOnScroll: TOnEvent; fOnNewLine: TOnNewLine; procedure DoMouseDown( X, Y, Shift: Integer ); procedure DoMouseMove( X, Y: Integer ); //-------------------------------------------------------------------------- // Скроллирование и состояние скроллеров: procedure AdjustHScroll; procedure AdjustVScroll; procedure DoScroll( Cmd, wParam: DWord ); public property OnScroll: TOnEvent read FOnScroll write FOnScroll; property OnNewLine: TOnNewLine read fOnNewLine write fOnNewLine; //-------------------------------------------------------------------------- // Работа со словами (слово под курсором, под кареткой, движение // каретки по словам) function WordAtPosStart( const AtPos: TPoint ): TPoint; function WordAtPos( const AtPos: TPoint ): KOLString; function FindNextWord( const FromPos: TPoint; LookForLettersDigits: Boolean ): TPoint; function FindPrevWord( const FromPos: TPoint; LookForLettersDigits: Boolean ): TPoint; procedure SelectWordUnderCursor; function FindNextTabPos( const FromPos: TPoint ): Integer; function FindPrevTabPos( const FromPos: TPoint ): Integer; public //-------------------------------------------------------------------------- // Регулируемый размер табуляции protected fTabSize: Integer; procedure SetTabSize( Value: Integer ); function GetTabSize: Integer; public property TabSize: Integer read GetTabSize write SetTabSize; function GiveNextTabPos( FromPos: Integer ): Integer; public //-------------------------------------------------------------------------- // Обслуживание клавиатуры procedure DoKeyDown( Key, Shift: Integer ); procedure DoKeyChar( Key: KOLChar ); public //-------------------------------------------------------------------------- // Текущая верхняя строка и левая колонка property TopLine: Integer read FTopLine write SetTopLine; property LeftCol: Integer read FLeftCol write SetLeftCol; //-------------------------------------------------------------------------- // Число полных и неполных строк на странице function LinesPerPage: Integer; function LinesVisiblePartial: Integer; //-------------------------------------------------------------------------- // Ширина символа и число видимых колонок в странице function CharWidth: Integer; function ColumnsVisiblePartial: Integer; function MaxLineWidthOnPage: Integer; //-------------------------------------------------------------------------- // Высота строки function LineHeight: Integer; protected FBitmap: PBitmap; // используется для подсчета ширины и высоты символов FCharWidth: Integer; // запоминает однажды рассчитанную ширину 1-го символа FLineHeight: Integer;// запоминает однажды рассчитанную высоту строки { Шрифт предполагается моноширинный. } public //-------------------------------------------------------------------------- // Работа с откатом function CanUndo: Boolean; function CanRedo: Boolean; procedure Undo; procedure Redo; protected FUndoList, FRedoList: PStrList; FUndoingRedoing: Boolean; // Пока TRUE, не наполнять стек отката procedure DoUndoRedo( List1, List2: PStrList ); //-------------------------------------------------------------------------- // Закладки protected FBookmarks: array[ 0..9 ] of TPoint; FOnBookmark: TOnEvent; procedure SetBookmark( Idx: Integer; const Value: TPoint ); function GetBookMark( IDx: Integer ): TPoint; {$IFDEF ProvideBookmarks} procedure FixBookmarks( const FromPos: TPoint; deltaX, deltaY: Integer ); {$ENDIF} public property Bookmarks[ Idx: Integer ]: TPoint read GetBookMark write SetBookmark; property OnBookmark: TOnEvent read FOnBookmark write FOnBookmark; public //-------------------------------------------------------------------------- // Поиск / замена function FindReplace( S: KOLString; const ReplaceTo: KOLString; const FromPos: TPoint; FindReplaceOptions: TFindReplaceOptions; SelectFound: Boolean ): TPoint; public //-------------------------------------------------------------------------- // Авто-завершение { Внимание! Во избежание проблем Applet должен использоваться как отдельный объект KOL.TApplet ! } // особой необходимости использовать методы ниже нет. Только если хочется // вызвать список принудительно или наполнить словарь своим кодом. AutoCompleteMinWordLength: Integer; // По умолчанию 2 символа, для более FShowAutoCompletion: Boolean; procedure AutoAdd2Dictionary( S: PKOLChar ); // добавить все слова из строки procedure AutoCompletionShow; // Показать список, если есть procedure AutoCompletionHide; // Скрыть список слов procedure AutoCompletionClear; // Очистить словарь protected // коротких не вызывать авто-список FAutoCompletionForm: PControl; // форма для показа авто-списка FAutoCompletionList: PControl; // list view FDictionary: {$IFDEF UNICODE_CTRLS} PWStrListEx {$ELSE} PStrListEx {$ENDIF}; // весь список слов, хранит номер последней вставки FAutoFirst, FAutoCount: Integer; // слова текущего показа в автосписке FAutoBestFirst: Integer; // первое лучшее слово - вначале выделено FLastInsertIdx: Integer; // счетчик вставок FAutoWord: KOLString; // для какого начала слова вызван авто-список FAutoPos: TPoint; // в каком месте была каретка при вызове FnotAdd2Dictionary1time: Boolean; // устанавливается на 1 раз procedure AutoListData( Sender: PControl; Idx, SubItem: Integer; var Txt: KOL_String; var ImgIdx: Integer; var State: DWORD; var Store: Boolean ); // Обеспечить отображение списка слов function AutoListMessage( var Msg: TMsg; var Rslt: Integer ): Boolean; procedure AutoCompleteWord( n: Integer ); // выполнить автокомплекцию! procedure AutoformCloseEvent( Sender: PObj; var Accept: Boolean ); procedure AutoFormShowEvent( Sender: PObj ); procedure FastFillDictionary; // только для Text := новое значение protected //-------------------------------------------------------------------------- // Виртуальный текст FOnGetLine: TOnText; FOnSetLine: TOnText; public property OnGetLine: TOnText read FOnGetLine write FOnGetLine; // Есть возможность в качестве "подставного" текста указать текст с нужным // количеством (хотя бы пустых) строк, но сами строки предоставлять в этом // обработчике - по требованию. property OnSetLine: TOnText read FOnSetLine write FOnSetLine; end; function NewHilightEdit( AParent: PControl ): PHilightMemo; procedure Beep; // Стандартный звук var Upper: array[ Char ] of Char; procedure InitUpper; implementation // Вспомогательные функции function IsLetterDigit( C: KOLChar ): Boolean; begin {$IFDEF UNICODE_CTRLS} if Ord(C)>255 then Result := TRUE // считаем все символы >255 буквами else {$ENDIF UNICODE_CTRLS} Result := Char(Ord( C )) in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ]; end; function IsLetter( C: KOLChar ): Boolean; begin {$IFDEF UNICODE_CTRLS} if Ord(C)>255 then Result := TRUE // считаем все символы >255 буквами else {$ENDIF UNICODE_CTRLS} Result := Char(Ord( C )) in [ {$INCLUDE HilightLetters.inc} ]; end; procedure Beep; begin PlaySound( 'Default', 0, SND_ALIAS ); end; procedure InitUpper; var c: Char; begin for c := #0 to #255 do Upper[ c ] := AnsiUpperCase( c )[ 1 ]; end; function AnsiStrLComp( S1, S2: PChar; L: Integer ): Integer; begin Result := 0; while L > 0 do begin Result := Ord( Upper[ S1^ ] ) - Ord( Upper[ S2^ ] ); if Result <> 0 then Exit; Dec( L ); Inc( S1 ); Inc( S2 ); end; end; function WAnsiStrLComp( S1, S2: PWideChar; L: Integer ): Integer; begin Result := 0; while L > 0 do begin if (Ord(S1^) <= 255) and (Ord(S2^) <= 255) then Result := Ord( Upper[ Char(Ord( S1^ )) ] ) - Ord( Upper[ Char(Ord( S2^ )) ] ) else Result := Ord( S1^ ) - Ord( S2^ ); if Result <> 0 then Exit; Dec( L ); Inc( S1 ); Inc( S2 ); end; end; const msgCaret = 1; msgDblClk = 2; msgShow = 3; msgComplete = 4; { Обработчик сообщений контрола. Цель - обработать WM_PAINT и WM_PRINT. Так же - обработать установку и снятие фокуса для отображения каретки. Так же - обработать клавиши - WM_KEYDOWN, WM_CHAR. Так же - обработать сообщения мыши. И прочее. } function HilightWndFunc( Sender: PControl; var Msg: TMsg; var Rslt: Integer ) : Boolean; var PaintStruct: TPaintStruct; OldPaintDC: HDC; HilightEdit: PHilightMemo; Edit: PHilight; Cplxity: Integer; CR: TRect; i: Integer; // для WM_KEYDOWN: Shift: Integer; // для WM_CHAR: C: KOLChar; // для WM_PASTE: S: KOLString; begin Result := FALSE; // по умолчанию - продолжать обработку по цепочке HilightEdit := Pointer( Sender ); if HilightEdit = nil then Exit; Edit := HilightEdit.Edit; CASE Msg.message OF WM_PAINT, WM_PRINT: begin HilightEdit.fUpdRgn := CreateRectRgn( 0, 0, 0, 0 ); Cplxity := Integer( GetUpdateRgn( HilightEdit.fHandle, HilightEdit.fUpdRgn, FALSE ) ); if (Cplxity = NULLREGION) or (Cplxity = ERROR) then begin DeleteObject( HilightEdit.fUpdRgn ); HilightEdit.fUpdRgn := 0; end; if (HilightEdit.fCollectUpdRgn <> 0) and (HilightEdit.fUpdRgn <> 0) then begin if CombineRgn( HilightEdit.fCollectUpdRgn, HilightEdit.fCollectUpdRgn, HilightEdit.fUpdRgn, RGN_OR ) = COMPLEXREGION then begin windows.GetClientRect( HilightEdit.fHandle, CR ); DeleteObject( HilightEdit.fCollectUpdRgn ); HilightEdit.fCollectUpdRgn := CreateRectRgnIndirect( CR ); end; InvalidateRgn( HilightEdit.fHandle, HilightEdit.fCollectUpdRgn, FALSE{fEraseUpdRgn} ); end; OldPaintDC := HilightEdit.fPaintDC; HilightEdit.fPaintDC := Msg.wParam; if HilightEdit.fPaintDC = 0 then HilightEdit.fPaintDC := BeginPaint( HilightEdit.fHandle, PaintStruct ); if HilightEdit.fCollectUpdRgn <> 0 then SelectClipRgn( HilightEdit.fPaintDC, HilightEdit.fCollectUpdRgn ); Edit.DoPaint( HilightEdit.fPaintDC ); if assigned( HilightEdit.fCanvas ) then HilightEdit.fCanvas.Handle := 0; if Msg.wParam = 0 then EndPaint( HilightEdit.fHandle, PaintStruct ); HilightEdit.fPaintDC := OldPaintDC; if HilightEdit.fUpdRgn <> 0 then DeleteObject( HilightEdit.fUpdRgn ); HilightEdit.fUpdRgn := 0; Rslt := 0; Result := True; end; WM_SETFOCUS, WM_KILLFOCUS: begin HilightEdit.Postmsg( WM_USER+msgCaret, 0, 0 ); end; WM_USER+msgCaret: begin Edit.Caret := Edit.Caret; end; WM_KEYDOWN: begin Shift := GetShiftState; if Assigned( HilightEdit.OnKeyDown ) then HilightEdit.OnKeyDown( HilightEdit, Msg.wParam, Shift ); if Msg.wParam <> 0 then Edit.DoKeyDown( Msg.wParam, Shift ); end; WM_LBUTTONDOWN: begin HilightEdit.Focused := TRUE; Edit.DoMouseDown( SmallInt( Loword( Msg.lParam ) ), SmallInt( hiWord( Msg.lParam ) ), GetShiftState ); end; WM_RBUTTONDOWN, WM_MBUTTONDOWN: begin HilightEdit.Focused := TRUE; end; WM_LBUTTONUP: begin Edit.DoMouseMove( SmallInt( Loword( Msg.lParam ) ), SmallInt( hiWord( Msg.lParam ) ) ); Edit.FMouseDown := FALSE; ReleaseCapture; end; WM_MOUSEMOVE: begin if Edit.FMouseDown then Edit.DoMouseMove( SmallInt( Loword( Msg.lParam ) ), SmallInt( hiWord( Msg.lParam ) ) ); end; {$IFDEF MouseWheelScrolls} WM_MOUSEWHEEL: begin i := SmallInt( HiWord( Msg.wParam ) ); if i div 40 <> 0 then Edit.TopLine := Edit.TopLine - i div 40; end; {$ENDIF} {$IFDEF DblClkSelectWord} WM_LBUTTONDBLCLK: begin Shift := GetShiftState; Edit.DoMouseDown( SmallInt( Loword( Msg.lParam ) ), SmallInt( hiWord( Msg.lParam ) ), Shift ); Edit.FMouseDown := FALSE; ReleaseCapture; HilightEdit.Postmsg( WM_USER+msgDblClk, Shift, 0 ); end; WM_USER+msgDblClk: begin Shift := Msg.wParam; if Shift and MK_SHIFT = 0 then Edit.SelectWordUnderCursor; end; {$ENDIF} {$IFNDEF Only_ReadOnly} WM_CHAR: begin C := KOLChar( Msg.wParam ); if Assigned( HilightEdit.OnChar ) then HilightEdit.OnChar( HilightEdit, C, GetShiftState ); if (C = #9) and (GetShiftState and MK_CONTROL <> 0) then C := #0; //Supress Ctrl-I to Tab conversion if C <> #0 then Edit.DoKeyChar( C ) else Result := TRUE; end; {$ENDIF} WM_SIZE: begin Edit.AdjustHScroll; Edit.AdjustVScroll; end; WM_HScroll: Edit.DoScroll( SC_HSCROLL, Msg.wParam ); WM_VScroll: Edit.DoScroll( SC_VSCROLL, Msg.wParam ); WM_SETFONT: begin Edit.FCharWidth := 0; Edit.FLineHeight := 0; Edit.Caret := Edit.Caret; end; WM_COPY: if Edit.SelectionAvailable then Text2Clipboard( Edit.Selection ); {$IFNDEF Only_ReadOnly} WM_CUT: if Edit.SelectionAvailable then begin Text2Clipboard( Edit.Selection ); Edit.DeleteSelection; end; WM_PASTE: begin S := Clipboard2Text; if S = '' then {$IFDEF BeepOnError} Beep {$ENDIF} else Edit.Selection := S; end; {$ENDIF} END; end; { Создание контрола-носителя, без затей. } function NewHilightEdit( AParent: PControl ): PHilightMemo; var HilightObj: PHilight; begin Result := PHilightMemo( _NewControl( AParent, 'HILIGHTEDIT', WS_CHILD or WS_VISIBLE or WS_TABSTOP // WS_TABSTOP нужен для ловли фокуса ввода or WS_HSCROLL or WS_VSCROLL or WS_BORDER, TRUE, nil ) ); Result.ExStyle := Result.ExStyle or WS_EX_CLIENTEDGE; Result.ClsStyle := (Result.ClsStyle or CS_DBLCLKS) and not (CS_HREDRAW or CS_VREDRAW); Result.Cursor := LoadCursor( 0, IDC_IBEAM ); { При создании HilightMemo создается и сопутствующий объект Edit } new( HilightObj, Create ); HilightObj.FMemo := Result; Result.FCustomObj := Pointer( HilightObj ); { Присоединим обработчик сообщений } Result.AttachProc( HilightWndFunc ); { Начальные установки } Result.Color := clWindow; Result.Font.FontName := 'Courier New'; Result.Font.FontHeight := 16; //Result.Tabstop := TRUE; //Result.Enabled := TRUE; Result.fLookTabKeys := [ ] end; { THilightMemo } destructor THilightMemo.Destroy; begin inherited; end; function THilightMemo.GetEdit: PHilight; begin Result := PHilight( FCustomObj ); end; procedure THilightMemo.Init; begin inherited; end; { THilight } procedure THilight.AdjustHScroll; var SBInfo: TScrollInfo; begin SBInfo.cbSize := Sizeof( SBInfo ); SBInfo.fMask := SIF_PAGE or SIF_POS or SIF_RANGE; SBInfo.nMin := 0; SBInfo.nMax := Max( MaxLineWidthOnPage, Caret.X+1 ); SBInfo.nPage := ColumnsVisiblePartial; SBInfo.nPos := FLeftCol; SBInfo.nTrackPos := FLeftCol; SetScrollInfo( FMemo.Handle, SB_HORZ, SBInfo, TRUE ); if Assigned(fOnScroll) then fOnScroll(FMemo); end; procedure THilight.AdjustVScroll; var SBInfo: TScrollInfo; begin SBInfo.cbSize := Sizeof( SBInfo ); SBInfo.fMask := SIF_PAGE or SIF_POS or SIF_RANGE; SBInfo.nMin := 0; SBInfo.nMax := Count-1; SBInfo.nPage := LinesPerPage; SBInfo.nPos := TopLine; SBInfo.nTrackPos := TopLine; SetScrollInfo( FMemo.Handle, SB_VERT, SBInfo, TRUE ); if Assigned(fOnScroll) then fOnScroll(FMemo); end; procedure THilight.AutoAdd2Dictionary(S: PKOLChar); var From: PKOLChar; i, c, L, LItem: Integer; W: KOLString; handled: Boolean; begin while S^ <> #0 do begin if {$IFDEF UNICODE_CTRLS} (Ord(S^) <= 255) and (Char(Ord(S^)) in [ {$INCLUDE HilightLetters.inc} {$IFDEF AutocompletionNunbers}, '0'..'9' {$ENDIF} ]) or (Ord(S^)>255) {$ELSE} S^ in [ {$INCLUDE HilightLetters.inc} {$IFDEF AutocompletionNunbers}, '0'..'9' {$ENDIF} ] {$ENDIF} then begin From := S; inc( S ); while {$IFDEF UNICODE_CTRLS} (Ord(S^) <= 255) and (Char(Ord(S^)) in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ]) or (Ord(S^)>255) {$ELSE} S^ in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ] {$ENDIF} do inc( S ); L := (DWORD( S ) - DWORD( From )) div Sizeof( KOLChar ); if L > AutoCompleteMinWordLength then begin handled := FALSE; for i := 0 to FDictionary.Count-1 do begin {$IFDEF AutoCompletionCaseSensitive} c := StrLComp( From, FDictionary.ItemPtrs[ i ], L ); {$ELSE} {$IFDEF UNICODE_CTRLS} c := WAnsiStrLComp( From, FDictionary.ItemPtrs[ i ], L ); {$ELSE} c := AnsiStrLComp( From, FDictionary.ItemPtrs[ i ], L ); {$ENDIF} {$ENDIF} if c = 0 then begin if L < Length( FDictionary.Items[ i ] ) then begin SetString( W, From, L ); FDictionary.Insert( i, W ); end; // иначе эта строка уже есть в словаре handled := TRUE; break; end else if c > 0 then // такого слова еще нет? begin LItem := Length( FDictionary.Items[ i ] ); if (LItem < L) and {$IFDEF UNICODE_CTRLS} {$IFDEF AutoCompletionCaseSensitive} (WStrLComp( From, FDictionary.ItemPtrs[ i ], LItem ) = 0) {$ELSE} (WAnsiStrLComp( From, FDictionary.ItemPtrs[ i ], LItem ) = 0) {$ENDIF} {$ELSE} {$IFDEF AutoCompletionCaseSensitive} (StrLComp( From, FDictionary.ItemPtrs[ i ], LItem ) = 0) {$ELSE} (AnsiStrLComp( From, FDictionary.ItemPtrs[ i ], LItem ) = 0) {$ENDIF} {$ENDIF UNICODE_CTRLS} then continue; // еще не нашлось, двигаем дальше SetString( W, From, L ); FDictionary.Insert( i, W ); handled := TRUE; break; end; // если c < 0, продолжаем искать место для вставки // в итоге словарь автоматически отсортирован по алфавиту end; if not handled then // добавить слово в конец begin SetString( W, From, L ); FDictionary.Add( W ); end; end; end else inc( S ); end; end; procedure THilight.AutoCompleteWord(n: Integer); var W: KOLString; M: TMsg; begin // подавить WM_CHAR, который может прийти по ENTER: PeekMessage( M, FAutoCompletionList.Handle, WM_CHAR, WM_CHAR, pm_Remove ); AutoCompletionHide; if n < 0 then Exit; // кликнули мимо - не заменять W := FDictionary.Items[ FAutoFirst + n ]; inc( FAutoCount ); FDictionary.Objects[ FAutoFirst + n ] := FAutoCount; SelectWordUnderCursor; Selection := W; //Caret := MakePoint( Caret.X + Length( W ), Caret.Y ); CaretToView; end; procedure THilight.AutoCompletionClear; begin FDictionary.Clear; end; procedure THilight.AutoCompletionHide; begin if Assigned( FAutoCompletionForm ) and FAutoCompletionForm.Visible then begin FAutoCompletionForm.Hide; FMemo.Focused := TRUE; end; end; procedure THilight.AutoCompletionShow; var W, W1: KOLString; FromPos, Pt: TPoint; DR: TRect; i, j, BestIdx: Integer; BestCounter: DWORD; DicW: PKOLChar; begin W := WordAtPos( Caret ); W1 := W; if (W = '') or not( oeAutoCompletion in Options ) then begin AutoCompletionHide; Exit; end; if Assigned( FAutoCompletionForm ) and FAutoCompletionForm.Visible and (FAutoWord = W) and (FAutoPos.X = FCaret.X) and (FAutoPos.Y = FCaret.Y) then Exit; // для этого слова уже показана FAutoPos := Caret; FAutoWord := W; AutoCompletionHide; FromPos := WordAtPosStart( Caret ); W := Copy( W, 1, Caret.X - FromPos.X ); if Length( W ) < AutoCompleteMinWordLength then Exit; for i := 0 to FDictionary.Count-1 do begin DicW := FDictionary.ItemPtrs[ i ]; {$IFDEF UNICODE_CTRLS} {$IFDEF AutocompletionCaseSensitive} if WStrLComp( PKOLChar( W ), DicW, Length( W ) ) = 0 then {$ELSE} if WAnsiStrLComp( PKOLChar( W ), DicW, Length( W ) ) = 0 then {$ENDIF} {$ELSE} {$IFDEF AutocompletionCaseSensitive} if StrLComp( PChar( W ), DicW, Length( W ) ) = 0 then {$ELSE} if AnsiStrLComp( PChar( W ), DicW, Length( W ) ) = 0 then {$ENDIF} {$ENDIF UNICODE_CTRLS} begin FAutoFirst := i; FAutoCount := 0; BestIdx := i; BestCounter := 0; for j := i+1 to FDictionary.Count do begin DicW := FDictionary.ItemPtrs[ j ]; if (j >= FDictionary.Count) or {$IFDEF UNICODE_CTRLS} {$IFDEF AutocompletionCaseSensitive} (WStrLComp( PKOLChar( W ), DicW, Length( W ) ) <> 0) {$ELSE} (WAnsiStrLComp( PKOLChar( W ), DicW, Length( W ) ) <> 0) {$ENDIF} {$ELSE} {$IFDEF AutocompletionCaseSensitive} (StrLComp( PChar( W ), DicW, Length( W ) ) <> 0) {$ELSE} (AnsiStrLComp( PChar( W ), DicW, Length( W ) ) <> 0) {$ENDIF} {$ENDIF UNICODE_CTRLS} then begin FAutoCount := j-i; break; end else if FDictionary.Objects[ j ] > BestCounter then begin BestCounter := FDictionary.Objects[ j ]; BestIdx := j; end; end; if FAutoCount > 0 then begin if (FAutoCount = 1) and (AnsiCompareStrNoCase(FDictionary.Items[ FAutoFirst ], W1) = 0) then Exit; // есть только 1 слово и оно совпадает с тем что под кареткой if FAutoCompletionForm = nil then begin FAutoCompletionForm := NewForm( Applet, '' ).SetSize( 300, 200 ); { Внимание! Во избежание проблем Applet должен использоваться как отдельный объект KOL.TApplet ! } FAutoCompletionForm.Visible := FALSE; FAutoCompletionForm.Style := WS_POPUP or WS_TABSTOP or WS_CLIPCHILDREN or WS_THICKFRAME or WS_CLIPSIBLINGS; //FAutoCompletionForm.OnClose := AutoFormCloseEvent; FAutoCompletionForm.MinHeight := 100; FAutoCompletionForm.OnShow := AutoFormShowEvent; FAutoCompletionList := NewListView( FAutoCompletionForm, lvsDetailNoHeader, [ lvoRowSelect, lvoOwnerData ], nil, nil, nil ).SetAlign( caClient ); FAutoCompletionList.LVColAdd( '', taLeft, FAutoCompletionList.ClientWidth-2 ); FAutoCompletionList.OnMessage := AutoListMessage; FAutoCompletionList.OnLVData := AutoListData; end; FAutoCompletionForm.Font.Assign( FMemo.Font ); FAutoCompletionList.LVCount := 0; // сброс - на всякий случай Pt := MakePoint( (Caret.X - LeftCol)*CharWidth, (Caret.Y+1 - TopLine)*LineHeight ); Pt := FMemo.Client2Screen( Pt ); DR := GetDesktopRect; if Pt.x + FAutoCompletionForm.Width > DR.Right then Pt.x := Pt.x - FAutoCompletionForm.Width; if Pt.x < DR.Left then Pt.x := DR.Left; if Pt.y + FAutoCompletionForm.Height > DR.Bottom then Pt.y := Pt.y - LineHeight - FAutoCompletionForm.Height; FAutoCompletionForm.Position := Pt; FShowAutoCompletion := TRUE; FAutoCompletionForm.Show; FAutoCompletionForm.BringToFront; FAutoCompletionList.LVCount := FAutoCount; FAutoCompletionList.LVStyle := lvsList; FAutoCompletionList.LVStyle := lvsDetailNoHeader; FAutoCompletionList.Focused := TRUE; FShowAutoCompletion := FALSE; //FAutoCompletionList.LVCurItem := BestIdx; //FAutoCompletionList.LVMakeVisible( BestIdx - FAutoFirst, FALSE ); FAutoBestFirst := BestIdx - FAutoFirst; end; Exit; end; end; end; { Обработчик сообщений для list view формы, в котором показан список слов для автоматического завершения по ENTER или клику мыши. } procedure THilight.AutoformCloseEvent(Sender: PObj; var Accept: Boolean); begin Accept := FALSE; FAutoCompletionForm.Hide; end; procedure THilight.AutoFormShowEvent(Sender: PObj); begin FAutoCompletionList.Postmsg( WM_USER + msgShow, 0, 0 ); end; procedure THilight.AutoListData(Sender: PControl; Idx, SubItem: Integer; var Txt: KOL_String; var ImgIdx: Integer; var State: DWORD; var Store: Boolean); begin Txt := FDictionary.Items[ FAutoFirst + Idx ]; //Store := FALSE; ибо по умолчанию end; function THilight.AutoListMessage(var Msg: TMsg; var Rslt: Integer): Boolean; begin Result := FALSE; CASE Msg.message OF WM_KILLFOCUS: { Так, мы не нужны - скроемся с глаз } begin //if Assigned( FAutoCompletionList) and // (DWORD( Msg.wParam ) <> FAutoCompletionList.Handle) then if not FShowAutoCompletion then begin FnotAdd2Dictionary1time := TRUE; AutoCompletionHide; FnotAdd2Dictionary1time := FALSE; end; end; WM_KEYUP, WM_SYSKEYUP, WM_SYSKEYDOWN, WM_SYSCHAR, WM_CHAR: { Это не к нам, отдать в HilightMemo } FMemo.Perform( Msg.message, Msg.wParam, Msg.lParam ); WM_KEYDOWN: { К нам относится только UP, DOWN, ENTER - все остальное отдать хозяину на обработку } CASE Msg.wParam OF VK_UP, VK_DOWN: ; // Пусть list view позаботится VK_RETURN: AutoCompleteWord( FAutoCompletionList.LVCurItem ); VK_ESCAPE: AutoCompletionHide; else FMemo.Perform( Msg.message, Msg.wParam, Msg.lParam ); END; WM_LBUTTONDOWN: // Авто-завершить по клику на слове, закрыть по клику вне списка FAutoCompletionList.Postmsg( WM_USER+msgComplete, 0, 0 ); WM_USER+msgComplete: AutoCompleteWord( FAutoCompletionList.LVCurItem ); WM_SIZE: // выровнять ширину колонки: FAutoCompletionList.LVColWidth[ 0 ] := FAutoCompletionList.ClientWidth - 2; WM_USER+msgShow: begin FAutoCompletionList.LVCurItem := FAutoBestFirst; FAutoCompletionList.LVMakeVisible( FAutoBestFirst, FALSE ); end; END; end; function THilight.CanRedo: Boolean; begin {$IFDEF ProvideUndoRedo} Result := FRedoList.Count > 0; {$ELSE} Result := FALSE; {$ENDIF} end; function THilight.CanUndo: Boolean; begin {$IFDEF ProvideUndoRedo} Result := FUndoList.Count > 0; {$ELSE} Result := FALSE; {$ENDIF} end; procedure THilight.CaretToView; begin if Caret.X < LeftCol then LeftCol := Caret.X else if LeftCol + FMemo.ClientWidth div CharWidth < Caret.X + 1 then LeftCol := Caret.X + 1 - FMemo.ClientWidth div CharWidth; if Caret.Y < TopLine then TopLine := Caret.Y else if TopLine + LinesPerPage <= Caret.Y then TopLine := Caret.Y - LinesPerPage + 1; Caret := Caret; end; procedure THilight.Changed; var y, k: Integer; L: KOLString; begin if FChangeLevel <= 0 then Exit; Dec( FChangeLevel ); if FChangeLevel = 0 then begin {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then begin if FUndoList.Last[ 1 ] = 'B' then // не было изменений begin FUndoList.Delete( FUndoList.Count-1 ); Exit; end else // завершается цепочка изменений begin FRedoList.Clear; FUndoList.Add( 'E' + Int2Str( Caret.X ) + ':' + Int2Str( Caret.Y ) ); // Сделаем оптимизацию для случая последовательных изменений // в пределах одной строки: k := FUndoList.Count; if (k >= 6) and (FUndoList.Items[ k-2 ][ 1 ] = 'R') and (FUndoList.Items[ k-3 ][ 1 ] = 'B') and (FUndoList.Items[ k-4 ][ 1 ] = 'E') and (FUndoList.Items[ k-5 ][ 1 ] = 'R') and (FUndoList.Items[ k-6 ][ 1 ] = 'B') then begin L := FUndoList.Items[ k-5 ]; Delete( L, 1, 1 ); y := Str2Int( L ); if y = Caret.Y then begin // Да, изменения в той же строке: FUndoList.Delete( k-2 ); FUndoList.Delete( k-3 ); FUndoList.Delete( k-4 ); { Из новой порции сохраняется только последняя строка, в которой запоминаются новые координаты курсора } end; end; end; end; {$ENDIF} if Assigned( FMemo.OnChange ) then FMemo.OnChange( FMemo ); end; end; procedure THilight.Changing; begin Inc( FChangeLevel ); {$IFDEF ProvideUndoRedo} if FUndoingRedoing then Exit; if FChangeLevel = 1 then FUndoList.Add( 'B' + Int2Str( Caret.X ) + ':' + Int2Str( Caret.Y ) ); {$ENDIF} end; function THilight.CharWidth: Integer; begin if FCharWidth = 0 then begin FBitmap.Canvas.Font.Assign( FMemo.Font ); FCharWidth := FMemo.Canvas.TextWidth( 'W' ); end; Result := FCharWidth; end; procedure THilight.Clear; var i: Integer; begin Text := ''; {$IFDEF ProvideUndoRedo} FUndoList.Clear; FRedoList.Clear; {$ENDIF} {$IFDEF ProvideBookmarks} for i := 0 to 9 do Bookmarks[ i ] := MakePoint( 0, 0 ); {$ENDIF} end; function THilight.Client2Coord(const P: TPoint): TPoint; begin Result := MakePoint( P.X div CharWidth + LeftCol, P.Y div LineHeight + TopLine ); end; function THilight.ColumnsVisiblePartial: Integer; begin Result := FMemo.ClientWidth div CharWidth; if Result * CharWidth < FMemo.ClientWidth then Inc( Result ); end; procedure THilight.DeleteLine(y: Integer; UseScroll: Boolean); var R: TRect; begin if y >= Count then Exit; Changing; DeleteLine1( y ); if (y >= TopLine) and (y < TopLine + LinesVisiblePartial) then begin if UseScroll and (y < TopLine + LinesPerPage) then begin R := MakeRect( 0, (y+1 - TopLine)*LineHeight, FMemo.ClientWidth, FMemo.ClientHeight ); ScrollWindowEx( FMemo.Handle, 0, -LineHeight, @ R, nil, 0, nil, SW_INVALIDATE ); end else begin R := MakeRect( 0, (y - TopLine)*LineHeight, FMemo.ClientWidth, FMemo.ClientHeight ); InvalidateRect( FMemo.Handle, @ R, TRUE ); end; end; Changed; {$IFDEF ProvideBookmarks} FixBookmarks( MakePoint( 0, y ), 0, -1 ); {$ENDIF} TopLine := TopLine; end; procedure THilight.DeleteLine1(y: Integer); begin if y >= Count then Exit; if Assigned( fOnDeleteLine ) then fOnDeleteLine( FMemo, y ); {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then FUndoList.Add( 'D' + Int2Str( y ) + '=' + FLines.Items[ y ] ); {$ENDIF} FLines.Delete( y ); end; procedure THilight.DeleteSelection; var i, n: Integer; L: KOLString; begin Changing; Caret := SelBegin; i := SelBegin.Y + 1; n := 0; while i < SelEnd.Y do begin // удаляется строка целиком DeleteLine1( i ); dec( FSelEnd.Y ); inc( n ); end; L := Copy( Lines[ SelBegin.Y ], 1, SelBegin.x ); if Length( L ) < SelBegin.x then L := L + StrRepeat( ' ', SelBegin.x - Length( L ) ); L := L + CopyEnd( Lines[ SelEnd.y ], SelEnd.x + 1 ); if SelBegin.y < SelEnd.y then begin // склеиваются две строки DeleteLine( SelEnd.y, n = 0 ); end; Lines[ SelBegin.y ] := L; if n > 0 then begin {$IFDEF ProvideBookmarks} FixBookmarks( SelBegin, 0, -n ); {$ENDIF} TopLine := TopLine; FMemo.Invalidate; end; SetSel( SelBegin, SelBegin, SelBegin ); Changed; CaretToView; end; destructor THilight.Destroy; begin FLines.Free; // разрушен текст FBitmap.Free; {$IFDEF UseBufferBitmap} Free_And_Nil( FBufferBitmap ); {$ENDIF} {$IFDEF ProvideUndoRedo} FUndoList.Free; FRedoList.Free; {$ENDIF} {$IFDEF ProvideAutoCompletion} if Assigned( FAutoCompletionForm ) then begin FAutoCompletionForm.Close; FAutoCompletionForm := nil; end; Free_And_Nil( FDictionary ); {$ENDIF} inherited; end; procedure THilight.DoKeyChar(Key: KOLChar); var S, S1: KOLString; t: Integer; procedure InsertChar( C: KOLChar ); begin //if Caret.Y < 0 then Caret := MakePoint( 0, Caret.X ); S := Lines[ Caret.Y ]; while Length( S ) < Caret.X do S := S + ' '; S := Copy( S, 1, Caret.X ) + C + CopyEnd( S, Caret.X+1 ); Lines[ Caret.Y ] := S; end; procedure ReplaceChar( C: KOLChar ); begin S := Lines[ Caret.Y ]; while Length( S ) < Caret.X do S := S + ' '; S := Copy( S, 1, Caret.X ) + C + CopyEnd( S, Caret.X+2 ); Lines[ Caret.Y ] := S; end; {$IFDEF ProvideAutoCompletion} var NeedAdd2Dictionary: Integer; CanShowAutoCompletion: Boolean; {$ENDIF} begin if oeReadOnly in Options then Exit; Changing; {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := -1; CanShowAutoCompletion := FALSE; {$ENDIF} TRY S := Lines[ Caret.Y ]; S1 := S; CASE Key OF #27: ; // escape - игнорируем (или закрываем окно Autocompletion) #13: // enter begin if SelectionAvailable then begin Caret := SelBegin; DeleteSelection; if oeOverwrite in Options then begin CaretToView; Changed; Exit; end; end; if oeOverwrite in Options then begin // просто переход в начало следующей строки при Overwrite if Caret.Y = Count-1 then Lines[ Caret.Y+1 ] := ''; {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := Caret.Y; {$ENDIF} Caret := MakePoint( 0, Caret.Y+1 ); end else begin // разбиение строки на 2 и переход в начало следующей строки S := Lines[ Caret.Y ]; Lines[ Caret.Y ] := Copy( S, 1, Caret.X ); S := CopyEnd( S, Caret.X+1 ); {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := Caret.Y; {$ENDIF} Caret := MakePoint( 0, Caret.Y+1 ); {$IFDEF ProvideSmartTabs} // предварить необходимым количеством пробелов для SmartTab t := 0; if Assigned(fOnNewLine) then t := fOnNewLine(FMemo, Caret.Y, S) else if oeSmartTabs in Options then begin t := FindNextTabPos( Caret ); if t > 0 then S := StrRepeat( ' ', t ) + S; end; Caret := MakePoint( t, Caret.Y ); {$ENDIF} InsertLine( Caret.Y, S, TRUE ); end; CaretToView; end; #9: // tab begin {$IFDEF ProvideSmartTabs} if not SelectionAvailable and (oeOverwrite in Options) then SetSel( Caret, MakePoint( Caret.X+1, Caret.Y ), Caret ); if SelectionAvailable then begin Caret := SelBegin; DeleteSelection; CaretToView; end; S := Lines[ Caret.Y ]; t := Caret.X; if oeSmartTabs in Options then t := FindNextTabPos( Caret ); {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := Caret.Y; {$ENDIF} if t > Caret.X then begin S := Copy( S, 1, Caret.X ) + StrRepeat( ' ', t - Caret.X ) + CopyEnd( S, Caret.X + 1 ); Lines[ Caret.Y ] := S; Caret := MakePoint( t, Caret.Y ); SetSel( Caret, Caret, Caret ); end else {$ENDIF ProvideSmartTabs} begin {$IFDEF ProvideCustomTabs} t := GiveNextTabPos( Caret.X ); S := Copy( S, 1, Caret.X ) + StrRepeat( ' ', t - Caret.X ) + CopyEnd( S, Caret.X + 1 ); Lines[ Caret.Y ] := S; Caret := MakePoint( t, Caret.Y ); SetSel( Caret, Caret, Caret ); {$ELSE} InsertChar( #9 ); Caret := MakePoint( ((Caret.X + 8) div 8) * 8, Caret.Y ); {$ENDIF} end; end; #8: // backspace begin if SelectionAvailable then begin Caret := SelBegin; DeleteSelection; CaretToView; Exit; end; if Caret.X > 0 then // удаление символа begin {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := Caret.Y; {$ENDIF} {$IFDEF ProvideSmartTabs} t := Caret.X; if (oeSmartTabs in Options) and (t > 0) and (Trim( Copy( S, 1, t ) ) = '') then t := FindPrevTabPos( Caret ); if t < Caret.X then begin Delete( S, t+1, Caret.X-t ); Lines[ Caret.Y ] := S; Caret := MakePoint( t, Caret.Y ); end else {$ENDIF} begin Delete( S, Caret.X, 1 ); Lines[ Caret.Y ] := S; Caret := MakePoint( Caret.X-1, Caret.Y ); end; end else // слияние строки с предыдущей begin if Caret.Y = 0 then Exit; // не с чем сливать S1 := Lines[ Caret.Y-1 ]; Caret := MakePoint( Length( S1 ), Caret.Y-1 ); {$IFDEF ProvideAutoCompletion} NeedAdd2Dictionary := Caret.Y; {$ENDIF} S1 := S1 + S; Lines[ Caret.Y ] := S1; DeleteLine( Caret.Y+1, TRUE ); end; end; else // any char (edit) if Key < ' ' then Exit; // прочие управляющие коды игнорируем if not SelectionAvailable and (oeOverwrite in Options) then SetSel( Caret, MakePoint( Caret.X+1, Caret.Y ), Caret ); if SelectionAvailable and (oeOverwrite in Options) then begin Caret := SelBegin; ReplaceChar( Key ); end else begin if SelectionAvailable then begin Caret := SelBegin; DeleteSelection; CaretToView; end; InsertChar( Key ); end; Caret := MakePoint( Caret.X+1, Caret.Y ); {$IFDEF ProvideAutoCompletion} if {$IFDEF UNICODE_CTRLS} (Ord(Key) <= 255) and (Char(Ord(Key)) in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ] ) or (Ord(Key) > 255) {$ELSE} Key in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ] {$ENDIF} then CanShowAutocompletion := TRUE else NeedAdd2Dictionary := Caret.Y; {$ENDIF} END; SetSel( Caret, Caret, Caret ); FINALLY Changed; CaretToView; END; {$IFDEF ProvideAutoCompletion} if (NeedAdd2Dictionary >= 0) and (NeedAdd2Dictionary < Count) then AutoAdd2Dictionary( FLines.ItemPtrs[ NeedAdd2Dictionary ] ); if CanShowAutocompletion then AutoCompletionShow else AutoCompletionHide; {$ENDIF} end; procedure THilight.DoKeyDown(Key, Shift: Integer); procedure MoveLeftUp( NewCaretX, NewCaretY: Integer ); begin {$IFDEF AllowLeftFromColumn0} if (NewCaretX < 0) and (NewCaretY > 0) then begin Dec( NewCaretY ); NewCaretX := Length( Lines[ NewCaretY ] ); end; {$ENDIF} Caret := MakePoint( Max( 0, NewCaretX ), //Min( Count-1, Max( 0, NewCaretY ) ) ); Max( 0, Min( Count-1, NewCaretY ) ) ); CaretToView; if Shift and MK_SHIFT <> 0 then SetSel( Caret, SelFrom, SelFrom ) else SetSel( Caret, Caret, Caret ); end; procedure MoveRightDown( NewCaretX, NewCaretY: Integer ); begin Caret := MakePoint( Max( 0, NewCaretX ), //Min( Count-1, Max( 0, NewCaretY ) ) ); Max( 0, Min( Count-1, NewCaretY ) ) ); CaretToView; if Shift and MK_SHIFT <> 0 then SetSel( SelFrom, Caret, SelFrom ) else SetSel( Caret, Caret, Caret ); end; var NewCaret: TPoint; S: KOLString; begin Changing; TRY CASE Key OF VK_LEFT: {$IFDEF CtrlArrowMoveByWords} if Shift and MK_CONTROL <> 0 then begin {NewCaret := WordAtPosStart( Caret ); if (NewCaret.y = Caret.y) and (NewCaret.x = Caret.y) then NewCaret := FindPrevWord( NewCaret, TRUE );} NewCaret := FindPrevWord( Caret, TRUE ); MoveLeftUp ( NewCaret.X, NewCaret.Y ); end else {$ENDIF} MoveLeftUp ( Caret.X-1, Caret.Y ); VK_RIGHT: {$IFDEF CtrlArrowMoveByWords} if Shift and MK_CONTROL <> 0 then begin {NewCaret := WordAtPosStart( Caret ); Inc( NewCaret.X, Length( WordAtPos( Caret ) ) ); if (NewCaret.y = Caret.y) and (NewCaret.x = Caret.y) then NewCaret := FindNextWord( NewCaret, TRUE );} NewCaret := Caret; Inc( NewCaret.X, Length( WordAtPos( NewCaret ) ) ); NewCaret := FindNextWord( NewCaret, TRUE ); //Inc( NewCaret.X, Length( WordAtPos( NewCaret ) ) ); MoveRightDown( NewCaret.X, NewCaret.Y ); end else {$ENDIF} MoveRightDown( Caret.X+1, Caret.Y ); VK_HOME: if Shift and MK_CONTROL <> 0 then MoveLeftUp ( 0, 0 ) else MoveLeftUp ( 0, Caret.Y ); VK_END: if Shift and MK_CONTROL <> 0 then MoveRightDown( 0, Count-1 ) else MoveRightDown( Length( TrimRight( Lines[ Caret.Y ] ) ), Caret.Y ); VK_UP: MoveLeftUp ( Caret.X, Caret.Y-1 ); VK_DOWN: MoveRightDown( Caret.X, Caret.Y+1 ); VK_PAGE_UP: MoveLeftUp ( Caret.X, Caret.Y - LinesPerPage ); VK_PAGE_DOWN:MoveRightDown( Caret.X, Caret.Y + LinesPerPage ); {$IFNDEF Only_ReadOnly} VK_DELETE: if oeReadOnly in Options then begin Changed; Exit; end else if SelectionAvailable then begin if Shift and MK_SHIFT <> 0 then FMemo.Perform( WM_CUT, 0, 0 ) else begin Caret := SelBegin; DeleteSelection; end; end else if Caret.X >= Length( Lines[ Caret.Y ] ) then begin // слияние строк if Caret.Y = Count-1 then Exit; S := Lines[ Caret.Y ]; while Length( S ) < Caret.X do S := S + ' '; Lines[ Caret.Y ] := S + Lines[ Caret.Y+1 ]; DeleteLine( Caret.Y+1, TRUE ); SetSel( Caret, Caret, Caret ); end else begin // удаление одного символа S := Lines[ Caret.Y ]; Delete( S, Caret.X+1, 1 ); Lines[ Caret.Y ] := S; end; VK_INSERT: if oeReadOnly in Options then Exit else if Shift and MK_SHIFT <> 0 then FMemo.Perform( WM_PASTE, 0, 0 ) else if Shift and MK_CONTROL <> 0 then FMemo.Perform( WM_COPY, 0, 0 ) else {$IFDEF AutoOverwrite} if Shift = 0 then begin if oeOverwrite in Options then Options := Options - [ oeOverwrite ] else Options := Options + [ oeOverwrite ]; Caret := Caret; end {$ENDIF} ; {$IFDEF ProcessHotkeys} Word( 'V' ): if oeReadOnly in Options then Exit else if Shift and MK_CONTROL <> 0 then FMemo.Perform( WM_PASTE, 0, 0 ); Word( 'Y' ): if oeReadOnly in Options then Exit else if Shift and MK_CONTROL <> 0 then begin DeleteLine( Caret.Y, TRUE ); Caret := Caret; end; Word( 'X' ): if oeReadOnly in Options then Exit else if Shift and MK_CONTROL <> 0 then FMemo.Perform( WM_CUT, 0, 0 ); {$ENDIF} {$ENDIF} {$IFDEF ProcessHotkeys} Word( 'C' ): if Shift and MK_CONTROL <> 0 then FMemo.Perform( WM_COPY, 0, 0 ); {$IFDEF ProvideUndoRedo} Word( 'Z' ): begin while FChangeLevel > 0 do Changed; { устраняем строку B<x>:<y>, добавленную вызовом Changing } if Shift and MK_CONTROL <> 0 then begin if Shift and MK_SHIFT <> 0 then // ctrl+shift+Z - redo Redo else Undo; end; Exit; { предотвращаем вызов Changed } end; {$ENDIF} {$ENDIF} END; FINALLY Changed; END; end; procedure THilight.DoMouseDown(X, Y: Integer; Shift: Integer); var Pt: TPoint; begin Pt := MakePoint( X div CharWidth + LeftCol, Y div LineHeight + TopLine ); if Shift and MK_SHIFT <> 0 then SetSel( SelFrom, Pt, SelFrom ) else SetSel( Pt, Pt, Pt ); Caret := Pt; FMouseDown := TRUE; SetCapture( FMemo.Handle ); end; procedure THilight.DoMouseMove(X, Y: Integer); var Pt: TPoint; begin if not FMouseDown then Exit; // todo: возможна активная реакция на движение мыши? if x < 0 then x := 0; if y < 0 then y := 0; Pt := MakePoint( X div CharWidth + LeftCol, Y div LineHeight + TopLine ); SetSel( SelFrom, Pt, SelFrom ); Caret := Pt; CaretToView; end; procedure THilight.DoPaint(DC: HDC); var x, y, i, L: Integer; R, R0, Rsel, CR: TRect; OldClip, NewClip: HRgn; P: TPoint; Attrs: TTokenAttrs; Canvas: PCanvas; begin CR := FMemo.ClientRect; NewClip := CreateRectRgnIndirect( FMemo.ClientRect ); CombineRgn( NewClip, NewClip, FMemo.UpdateRgn, RGN_AND ); SelectClipRgn( DC, NewClip ); DeleteObject( NewClip ); y := 0; {$IFDEF UseBufferBitmap} if (FBufferBitmap <> nil) and ( (FBufferBitmap.Width < FMemo.ClientWidth) or (FBufferBitmap.Height < LineHeight) ) then Free_And_Nil( FBufferBitmap ); if FBufferBitmap = nil then FBufferBitmap := NewBitmap( FMemo.ClientWidth, LineHeight ); Canvas := FBufferBitmap.Canvas; {$ENDIF} Canvas.Font.Assign( FMemo.Font ); for i := TopLine to TopLine + LinesPerPage + 1 do begin if y >= CR.Bottom then break; if i >= Count then break; R := MakeRect( 0, y, CR.Right, y + LineHeight ); R0 := R; {$IFDEF UseBufferBitmap} OffsetRect( R0, -R0.Left, -R0.Top ); {$ENDIF} if SelectionAvailable and (FSelBegin.Y <= i) and (FSelEnd.Y >= i) then begin // по крайней мере часть строки попадает в выделение: FMemo.Canvas.Brush.Color := clHighlight; FMemo.Canvas.Font.Color := clHighlightText; FMemo.Canvas.Font.FontStyle := [ ]; Rsel := R; if i = SelBegin.Y then Rsel.Left := Max( 0, (FSelBegin.X - FLeftCol)*CharWidth ); if i = SelEnd.Y then Rsel.Right := Max( 0, (FSelEnd.X - FLeftCol)*CharWidth ); if Rsel.Right > Rsel.Left then begin OldClip := CreateRectRgn( 0,0,0,0 ); GetClipRgn( DC, OldClip ); NewClip := CreateRectRgnIndirect( Rsel ); SelectClipRgn( DC, NewClip ); FMemo.Canvas.TextRect( R, 0, R.Top, CopyEnd( Lines[ i ], FLeftCol+1 ) ); SelectClipRgn( DC, OldClip ); ExtSelectClipRgn( DC, NewClip, RGN_DIFF ); DeleteObject( NewClip ); DeleteObject( OldClip ); end; end; if RectInRegion( FMemo.UpdateRgn, R ) then begin Canvas.Brush.Color := FMemo.Color; Canvas.Font.Color := clWindowText; Canvas.Font.FontStyle := [ ]; {$IFDEF ProvideHighlight} if Assigned( FOnScanToken ) and (oeHighlight in Options) then begin Canvas.FillRect( R0 ); //Canvas.Brush.BrushStyle := bsClear; P := MakePoint( 0, i ); Attrs.fontcolor := clWindowText; Attrs.backcolor := clWindow; Attrs.fontstyle := [ ]; while P.X < LeftCol+ColumnsVisiblePartial do begin L := OnScanToken( FMemo, P, Attrs ); if L <= 0 then L := Length( Lines[ i ] ) - P.X; if L <= 0 then break; if P.X + L >= LeftCol then begin Canvas.Font.Color := Attrs.fontcolor; Canvas.Font.FontStyle := Attrs.fontstyle; Canvas.Brush.Color := Attrs.backcolor; while L > 0 do begin Canvas.TextOut( R0.Left + (P.X - LeftCol)*CharWidth, R0.Top, Copy( Lines[ i ], P.X+1, 1 ) ); Inc( P.X ); Dec( L ); end; end else P.X:= P.X + L; end; Canvas.Brush.BrushStyle := bsSolid; {$IFDEF DrawRightMargin} x := (RightMarginChars - LeftCol)*CharWidth; {$IFDEF RightZigzagIndicateLongLine} if Length( TrimRight( Lines[ i ] ) ) > RightMarginChars then begin Canvas.Pen.Color := RightMarginColor; Canvas.MoveTo( x, R0.Top ); Canvas.LineTo( x-2, R0.Top + LineHeight div 3 ); Canvas.LineTo( x+2, R0.Top + LineHeight * 2 div 3 ); Canvas.LineTo( x, R0.Bottom ); end else {$ENDIF} begin Canvas.Brush.Color := RightMarginColor; Canvas.FillRect( MakeRect( x, R0.Top, x+1, R0.Bottom ) ); Canvas.Brush.Color := FMemo.Color; end; {$ENDIF DrawRightMargin} {$IFDEF UseBufferBitmap} BitBlt( DC, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top, Canvas.Handle, 0, 0, SRCCOPY ); {$ENDIF} end else {$ENDIF} begin FMemo.Canvas.Brush.Color := FMemo.Color; FMemo.Canvas.Font.Color := clWindowText; FMemo.Canvas.Font.FontStyle := [ ]; FMemo.Canvas.TextRect( R, 0, R.Top, CopyEnd( Lines[ i ], LeftCol + 1 ) ); {$IFDEF DrawRightMargin} x := (RightMarginChars - LeftCol)*CharWidth; {$IFDEF RightZigzagIndicateLongLine} if Length( TrimRight( Lines[ i ] ) ) > RightMarginChars then begin FMemo.Canvas.Pen.Color := RightMarginColor; FMemo.Canvas.MoveTo( x, R.Top ); FMemo.Canvas.LineTo( x-2, R.Top + LineHeight div 3 ); FMemo.Canvas.LineTo( x+2, R.Top + LineHeight * 2 div 3 ); FMemo.Canvas.LineTo( x, R.Bottom ); end else {$ENDIF} FMemo.Canvas.Brush.Color := RightMarginColor; FMemo.Canvas.FillRect( MakeRect( x, R.Top, x+1, R.Bottom ) ); FMemo.Canvas.Brush.Color := FMemo.Color; {$ENDIF} end; //GdiFlush; end; y := y + LineHeight; end; if y < CR.Bottom then begin // стереть остаток не занятый строками {$IFDEF DrawRightMargin} x := (RightMarginChars - LeftCol)*CharWidth; R := MakeRect( 0, y, x, CR.Bottom ); FMemo.Canvas.Brush.Color := FMemo.Color; FMemo.Canvas.FillRect( R ); if x < CR.Right then begin FMemo.Canvas.Brush.Color := RightMarginColor; R.Left := x; R.Right := x+1; FMemo.Canvas.FillRect( R ); FMemo.Canvas.Brush.Color := FMemo.Color; R.Left := x+1; R.Right := CR.Right; FMemo.Canvas.FillRect( R ); end; {$ELSE} R := MakeRect( 0, y, CR.Right, CR.Bottom ); FMemo.Canvas.FillRect( R ); {$ENDIF} end; end; procedure THilight.DoScroll(Cmd, wParam: DWord); begin CASE Cmd OF SC_HSCROLL: CASE loWord( wParam ) OF SB_LEFT, SB_LINELEFT: LeftCol := LeftCol-1; SB_RIGHT,SB_LINERIGHT: LeftCol := LeftCol+1; SB_PAGELEFT: LeftCol := LeftCol - FMemo.ClientWidth div CharWidth; SB_PAGERIGHT: LeftCol := LeftCol + FMemo.ClientWidth div CharWidth; SB_THUMBTRACK: LeftCol := HiWord( wParam ); END; SC_VSCROLL: CASE loWord( wParam ) OF SB_LEFT, SB_LINELEFT: TopLine := TopLine-1; SB_RIGHT,SB_LINERIGHT: TopLine := TopLine+1; SB_PAGELEFT: TopLine := TopLine - LinesPerPage; SB_PAGERIGHT: TopLine := TopLine + LinesPerPage; SB_THUMBTRACK: TopLine := HiWord( wParam ); END; END; end; procedure THilight.DoUndoRedo(List1, List2: PStrList); var L1, L2: KOLString; x, y: Integer; begin // Задача: инвертировать изменения из списка List1, // сохранить обратные изменения в списке List2 FUndoingRedoing := TRUE; Assert( List1.Last[ 1 ] = 'E' ); List2.Add( 'B' + CopyEnd( List1.Last, 2 ) ); List1.Delete( List1.Count-1 ); while TRUE do begin L1 := List1.Last; List1.Delete( List1.Count-1 ); CASE L1[ 1 ] OF 'A': // было: добавление строки в конец, обратная: удаление последней строки begin L2 := 'D' + Int2Str( Count-1 ) + '=' + FLines.Last; FLines.Delete( Count-1 ); end; 'D': // было: удаление строки, обратная: вставка строки begin Delete( L1, 1, 1 ); y := Str2Int( L1 ); Parse( L1, '=' ); L2 := 'I' + Int2Str( y ); InsertLine( y, L1, FALSE ); end; 'I': // было: вставка строки, обратная: удаление строки begin Delete( L1, 1, 1 ); y := Str2Int( L1 ); L2 := 'D' + Int2Str( y ) + '=' + Lines[ y ]; DeleteLine( y, FALSE ); end; 'R': // было: изменение строки begin Delete( L1, 1, 1 ); y := Str2Int( L1 ); Parse( L1, '=' ); L2 := 'R' + Int2Str( y ) + '=' + Lines[ y ]; Lines[ y ] := L1; end; 'B': // дошли до начала группы изменений begin L2 := 'E' + CopyEnd( L1, 2 ); Delete( L1, 1, 1 ); x := Str2Int( L1 ); Parse( L1, ':' ); y := Str2Int( L1 ); // вернём каретку в позицию до начала блока изменений Caret := MakePoint( x, y ); SetSel( Caret, Caret, Caret ); CaretToView; end; END; List2.Add( L2 ); if L2[ 1 ] = 'E' then break; end; FUndoingRedoing := FALSE; AdjustHScroll; AdjustVScroll; // По окончании, вызвать OnChange: if Assigned( FMemo.OnChange ) then FMemo.OnChange( FMemo ); end; procedure THilight.FastFillDictionary; type TByteArray = array[ 0..100000 ] of Byte; PByteArray = ^TByteArray; var i: Integer; HashTable: PByteArray; S, From: PKOLChar; TempMemStream: PStream; ChkSum: DWORD; EOL: KOLChar; DicAsTxt: KOLString; begin FDictionary.Clear; HashTable := AllocMem( 65536 ); // место для 512К 1-битных флажков "присутствия" TempMemStream := NewMemoryStream; // сюда пишем добавляемые слова EOL := #13; TRY for i := 0 to FLines.Count-1 do begin S := FLines.ItemPtrs[ i ]; while S^ <> #0 do begin if {$IFDEF UNICODE_CTRLS} (Ord(S^) <= 255) and (Char(Ord(S^)) in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ]) or (Ord(S^) > 255) {$ELSE} S^ in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ] {$ENDIF} then begin From := S; ChkSum := Byte( From^ ); inc( S ); while {$IFDEF UNICODE_CTRLS} (Ord(S^) <= 255) and (Char(Ord(S^)) in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ]) or (Ord(S^) > 255) {$ELSE} S^ in [ {$INCLUDE HilightLetters.inc}, '0'..'9' ] {$ENDIF} do begin {$IFDEF UNICODE_CTRLS} if Ord(S^) > 255 then ChkSum := (( ChkSum shl 1) or (ChkSum shr 18) and 1 ) xor Ord(S^) else {$ENDIF UNICODE_CTRLS} ChkSum := (( ChkSum shl 1) or (ChkSum shr 18) and 1 ) xor {$IFDEF AutocompletionCaseSensitive} Ord( S^ ) {$ELSE} Ord( Upper[ Char(Ord( S^ )) ] ) {$ENDIF} ; inc( S ); end; if DWORD(S) - DWORD(From) > DWORD(AutoCompleteMinWordLength) then begin ChkSum := ChkSum and $7FFFF; if HashTable[ ChkSum shr 3 ] and (1 shl (ChkSum and 7)) = 0 then begin HashTable[ ChkSum shr 3 ] := HashTable[ ChkSum shr 3 ] or (1 shl (ChkSum and 7)); TempMemStream.Write( From^, DWORD( S ) - DWORD( From ) ); TempMemStream.Write( EOL, Sizeof( KOLChar ) ); end; end; end else Inc( S ); end; end; if TempMemStream.Position > 0 then begin SetString( DicAsTxt, PKOLChar( TempMemStream.Memory ), TempMemStream.Position div Sizeof( KOLChar ) ); FDictionary.Text := DicAsTxt; FDictionary.Sort( {$IFDEF AutocompletionCaseSensitive} TRUE {$ELSE} FALSE {$ENDIF} ); end; FINALLY TempMemStream.Free; FreeMem( HashTable ); END; end; function THilight.FindNextTabPos(const FromPos: TPoint): Integer; var P, P1, P2: TPoint; begin P := FromPos; P1 := P; Result := P.X; while (P.Y > 0) or (P.X > 0) do begin P2 := P; P := FindPrevWord( P2, FALSE ); if (P.X = P2.X) and (P.Y = P2.Y) then begin Result := P.X; break; end else if (P.X >= FromPos.X) and ((Result = FromPos.X) or (P.Y = P1.Y)) then begin Result := P.X; P1 := P; end else if (P.Y < P1.Y) or (P.X <= FromPos.X) then break; end; end; function THilight.FindNextWord(const FromPos: TPoint; LookForLettersDigits: Boolean): TPoint; var S: KOLString; i, y: Integer; begin y := FromPos.Y; i := FromPos.X; while TRUE do begin S := Lines[ y ]; while i < Length( S )-1 do begin inc( i ); if LookForLettersDigits and IsLetterDigit( S[ i+1 ] ) or not LookForLettersDigits and (S[ i+1 ] > ' ') then begin // найдено следующее слово Result := MakePoint( i, y ); Exit; end; end; // дошли до конца строки, слово еще не найдено if y = Count-1 then // это последняя строка break; i := -1; inc( y ); end; Result := MakePoint( i, y ); end; function THilight.FindPrevTabPos(const FromPos: TPoint): Integer; var P, P2: TPoint; begin P := FromPos; Result := P.X; while (P.Y > 0) or (P.X > 0) do begin P2 := P; P := FindPrevWord( P, FALSE ); if (P.X = P2.X) and (P.Y = P2.Y) or (P.X < FromPos.X) then begin Result := P.X; break; end; end; end; function THilight.FindPrevWord(const FromPos: TPoint; LookForLettersDigits: Boolean): TPoint; var S: KOLString; i, y: Integer; begin Result := FromPos; y := FromPos.Y; i := FromPos.X; while TRUE do begin S := Lines[ y ]; if i = -1 then i := Length( S )+1 else dec( i ); while i > 0 do begin dec( i ); if (LookForLettersDigits and not IsLetterDigit( (Copy( S, i+1, 1 ) + ' ')[ 1 ] ) or not LookForLettersDigits and (Copy( S, i+1, 1 ) <= ' ')) and (i+2 <= Length( S ) ) and (LookForLettersDigits and IsLetterDigit( (Copy( S, i+2, 1 ) + ' ')[ 1 ] ) or not LookForLettersDigits and (Copy( S, i+2, 1 ) > ' ')) then begin // найдено предыдующее слово Result := MakePoint( i+1, y ); Exit; end else if (i = 0) and (Length( S ) > 0) and IsLetterDigit( S[ 1 ] ) then begin Result := MakePoint( 0, y ); Exit; end; end; // дошли до начала строки, слово еще не найдено if y = 0 then // это первая строка Exit; i := -1; dec( y ); end; Result := MakePoint( i, y ); end; function THilight.FindReplace( S: KOLString; const replaceTo: KOLString; const FromPos: TPoint; FindReplaceOptions: TFindReplaceOptions; SelectFound: Boolean): TPoint; var P: TPoint; L: KOLString; i: Integer; function CompareSubstr( var i: Integer ): Boolean; var j: Integer; begin Result := FALSE; i := 1; j := 1; while j <= Length( S ) do begin if P.X + i > Length( L ) then Exit; if not(froSpaces in FindReplaceOptions) and (S[ j ] = ' ') then begin inc( j ); if not((L[ P.X + i ] = #9) or (L[ P.X+1 ] =' ')) then Exit; while (P.X + i <= Length( L )) and ((L[ P.X + i ] = #9) or (L[ P.X+1 ] =' ')) do inc( i ); end else if froCase in FindReplaceOptions then begin if L[ P.X + i ] <> S[ j ] then Exit; inc( i ); inc( j ); end else begin {$IFDEF UNICODE_CTRLS} if ( Ord(L[ P.X+i ]) > 255 ) or ( Ord( S[ j ] ) > 255 ) then begin if L[ P.X + i ] <> S[ j ] then Exit; end else {$ENDIF UNICODE_CTRLS} begin if Upper[ Char( Ord( L[ P.X + i ] ) ) ] <> Upper[ Char( Ord( S[ j ] ) ) ] then Exit; end; inc( i ); inc( j ); end; end; Result := TRUE; end; begin Result := FromPos; if not( froSpaces in FindReplaceOptions ) then begin {$IFDEF UNICODE_CTRLS} while WStrReplace( S, #9, ' ' ) do; while WStrReplace( S, ' ', ' ' ) do; {$ELSE} while StrReplace( S, #9, ' ' ) do; while StrReplace( S, ' ', ' ' ) do; {$ENDIF} end; P := FromPos; L := Lines[ P.Y ]; while TRUE do begin if froBack in FindReplaceOptions then begin Dec( P.X ); if P.X < 0 then begin Dec( P.Y ); L := Lines[ P.Y ]; if P.Y < 0 then Exit; P.X := Length( L ); continue; end; end else begin Inc( P.X ); if P.X >= Length( L ) then begin P.X := 0; Inc( P.Y ); if P.Y >= Count then Exit; L := Lines[ P.Y ]; end; end; if CompareSubstr( i ) then begin if froReplace in FindReplaceOptions then begin SelBegin := P; SelEnd := MakePoint( P.X+i-1, P.Y ); Selection := ReplaceTo; SelEnd := Caret; end else if SelectFound then begin SelBegin := P; SelEnd := MakePoint( P.X+i-1, P.Y ); Caret := SelEnd; end; if not( froReplace in FindReplaceOptions ) or not( froAll in FindReplaceOptions ) then break; end; end; CaretToView; Result := P; end; {$IFDEF ProvideBookmarks} procedure THilight.FixBookmarks(const FromPos: TPoint; deltaX, deltaY: Integer); var i: Integer; begin for i := 0 to 9 do if (FBookmarks[ i ].X >= 0) and (FBookmarks[ i ].Y >= 0) then begin if (FBookmarks[ i ].Y = FromPos.Y) and (FBookmarks[ i ].X >= FromPos.X) then Inc( FBookmarks[ i ].X, deltaX ); if (FBookmarks[ I ].Y >= FromPos.Y) then Inc( FBookmarks[ i ].Y, deltaY ); end; if Assigned(FOnBookmark) then FOnBookmark(@Self); end; {$ENDIF} function THilight.GetBookMark(IDx: Integer): TPoint; begin if (Idx < 0) or (Idx > 9) then Exit; Result := FBookmarks[ Idx ]; end; function THilight.GetCount: Integer; begin Result := FLines.Count; end; function THilight.GetLineData(Idx: Integer): DWORD; begin Result := FLines.Objects[ Idx ]; end; function THilight.GetLines(Idx: Integer): KOLString; var i, j: Integer; begin Result := FLines.Items[ Idx ]; if Assigned( FOnGetLine ) then FOnGetLine( FMemo, Idx, Result ); // все символы табуляции превращаются в необходимое количество пробелов: i := 0; while i < Length( Result ) do begin if Result[ i+1 ] = #9 then begin j := GiveNextTabPos(i); Result := Copy( Result, 1, i ) + StrRepeat( ' ', j-i ) + CopyEnd( Result, i+2 ); end; inc( i ); end; if not( oeKeepTrailingSpaces in Options) then Result := TrimRight( Result ); end; function THilight.GetSelection: KOLString; var i: Integer; S: KOLString; begin Result := ''; // Собрать все строки и фрагменты строк выделенной области for i := SelBegin.Y to SelEnd.Y do begin S := Lines[ i ]; if i = SelEnd.Y then S := Copy( S, 1, SelEnd.X ); if i = SelBegin.Y then S := CopyEnd( S, SelBegin.X+1 ); if i > SelBegin.Y then Result := Result + #13#10; Result := Result + S; end; end; function THilight.GetTabSize: Integer; begin Result := fTabSize; if Result <= 0 then Result := 8; end; function THilight.GetText: KOLString; begin Result := FLines.Text; end; function THilight.GiveNextTabPos(FromPos: Integer): Integer; var t: Integer; begin t := TabSize; Result := ( (FromPos + t) div t ) * t; end; procedure THilight.Indent(delta: Integer); var y, i, k: Integer; S: KOLString; begin Changing; for y := FSelBegin.y to FSelEnd.y do begin if (FSelEnd.y > FSelBegin.y) and (FSelEnd.y = y) and (FSelEnd.x = 0) then break; S := Lines[ y ]; if delta > 0 then begin S := StrRepeat( ' ', delta ) + S; {$IFDEF ProvideBookmarks} FixBookmarks( MakePoint( 0, y ), delta, 0 ); {$ENDIF} end else if delta < 0 then begin k := 0; for i := 1 to Length( S ) do if S[ i ] > ' ' then break else inc( k ); if -delta < k then k := -delta; if k > 0 then begin Delete( S, 1, k ); {$IFDEF ProvideBookmarks} FixBookmarks( MakePoint( 0, y ), -k, 0 ); {$ENDIF} end; end else break; Lines[ y ] := S; end; if (FSelEnd.x = 0) and (FSelEnd.y > FSelBegin.y) then SetSel( MakePoint( FSelBegin.x + delta, FSelBegin.y ), FSelEnd, MakePoint( FSelBegin.x + delta, FSelBegin.y ) ) else SetSel( MakePoint( FSelBegin.x + delta, FSelBegin.y ), MakePoint( FSelEnd.x + delta, FSelEnd.y ), MakePoint( FSelFrom.x + delta, FSelBegin.y ) ); Changed; CaretToView; end; procedure THilight.Init; {$IFDEF ProvideBookmarks} var i: Integer;{$ENDIF} begin {$IFDEF UNICODE_CTRLS} {$IFDEF UseStrListEx} FLines := NewWStrListEx; {$ELSE} FLines := NewWStrList; {$ENDIF} {$ELSE} {$IFDEF UseStrListEx} FLines := NewStrListEx; {$ELSE} FLines := NewStrList; {$ENDIF} {$ENDIF UNICODE_CTRLS} FBitmap := NewDibBitmap( 1, 1, pf32bit ); {$IFDEF ProvideUndoRedo} FUndoList := NewStrList; FRedoList := NewStrList; {$ENDIF} {$IFDEF DrawRightMargin} RightMarginChars := 80; RightMarginColor := clBlue; {$ENDIF} {$IFDEF ProvideAutoCompletion} {$IFDEF UNICODE_CTRLS} FDictionary := NewWStrListEx; {$ELSE} FDictionary := NewStrListEx; {$ENDIF UNICODE_CTRLS} {$ENDIF} AutoCompleteMinWordLength := 2; {$IFDEF ProvideBookmarks} for i := 0 to 9 do FBookmarks[i].Y := -1; {$ENDIF} end; procedure THilight.InsertLine(y: Integer; const S: KOLString; UseScroll: Boolean); var R: TRect; str: KOLString; begin Changing; str := S; if Assigned( fOnInsertLine ) then fOnInsertLine( FMemo, y, str ); while Count < y do begin FLines.Add( '' ); {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then FUndoList.Add( 'A' ); {$ENDIF} UseScroll := FALSE; end; FLines.Insert( y, str ); {$IFDEF ProvideBookmarks} FixBookmarks( MakePoint( 0, y ), 0, 1 ); {$ENDIF} {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then FUndoList.Add( 'I' + Int2Str( y ) ); {$ENDIF} if UseScroll and (y >= TopLine) and (y < TopLine + LinesPerPage) then begin R := MakeRect( 0, (y - TopLine)*LineHeight, FMemo.ClientWidth, FMemo.ClientHeight ); ScrollWindowEx( FMemo.Handle, 0, LineHeight, @ R, nil, 0, nil, SW_INVALIDATE ); //InvalidateLine( y ); end else begin R := MakeRect( 0, (y - TopLine)*LineHeight, FMemo.ClientWidth, FMemo.ClientHeight ); InvalidateRect( FMemo.Handle, @ R, TRUE ); end; Changed; end; procedure THilight.InvalidateLine(y: Integer); var R: TRect; begin if y < TopLine then Exit; if y > TopLine + LinesVisiblePartial then Exit; R := MakeRect( 0, (y - TopLine)*LineHeight, FMemo.ClientWidth, (y+1 - TopLine)*LineHeight ); InvalidateRect( FMemo.Handle, @ R, TRUE ); end; procedure THilight.InvalidateSelection; var y: Integer; R: TRect; begin // просмотреть все видимые строки, и те, из них, которые содержат // части выделения, пометить как испорченные - для перерисовки. for y := Max( TopLine, SelBegin.Y ) to Min( TopLine + LinesVisiblePartial - 1, SelEnd.Y ) do begin R := MakeRect( 0, (y - TopLine)*LineHeight, FMemo.ClientWidth, FMemo.ClientHeight ); InvalidateRect( FMemo.Handle, @ R, TRUE ); end; end; function THilight.LineHeight: Integer; begin if FLineHeight = 0 then begin FBitmap.Canvas.Font.Assign( FMemo.Font ); FLineHeight := FBitmap.Canvas.TextHeight( 'A/_' ); end; Result := FLineHeight; if Result = 0 then Result := 16; end; function THilight.LinesPerPage: Integer; begin Result := FMemo.ClientHeight div LineHeight; end; function THilight.LinesVisiblePartial: Integer; begin Result := FMemo.ClientHeight div LineHeight; if Result * LineHeight < FMemo.ClientHeight then Inc( Result ); end; function THilight.MaxLineWidthOnPage: Integer; {$IFNDEF AlwaysHorzScrollBar_ofsize_MaxLineWidth} var i: Integer; {$ENDIF} begin {$IFDEF AlwaysHorzScrollBar_ofsize_MaxLineWidth} Result := MaxLineWidth; {$ELSE} Result := 0; for i := TopLine to TopLine + (FMemo.Height+LineHeight-1) div LineHeight - 1 do begin if i >= Count then break; Result := Max( Result, Length( Lines[ i ] ) ); end; {$ENDIF} end; procedure THilight.Redo; begin {$IFDEF ProvideUndoRedo} if not CanRedo then Exit; DoUndoRedo( FRedoList, FUndoList ); {$ENDIF} end; function THilight.SelectionAvailable: Boolean; begin Result := ((SelBegin.X <> SelEnd.X) or (SelBegin.Y <> SelEnd.Y)) and ((SelBegin.Y < Count-1) or (SelBegin.Y = Count-1) and (SelBegin.X < Length( FLines.Last ))); end; procedure THilight.SelectWordUnderCursor; var WordStart, WordEnd: TPoint; W: KOLString; begin W := WordAtPos( Caret ); if W = '' then Exit; WordStart := WordAtPosStart( Caret ); WordEnd := WordStart; inc( WordEnd.X, Length( W ) ); SetSel( WordStart, WordEnd, WordStart ); Caret := WordEnd; CaretToView; end; procedure THilight.SetBookmark( Idx: Integer; const Value: TPoint ); begin if (Idx < 0) or (Idx > 9) then Exit; FBookmarks[ Idx ] := Value; if Assigned(FOnBookmark) then FOnBookmark(@Self); end; procedure THilight.SetCaret(const Value: TPoint); begin {$IFDEF ProvideAutoCompletion} if (FCaret.Y < Count) and (FCaret.Y >= 0) and (FCaret.Y <> Value.Y) and not FnotAdd2Dictionary1time then AutoAdd2Dictionary( FLines.ItemPtrs[ FCaret.Y ] ); if (FCaret.x <> Value.x) or (FCaret.y <> Value.y) then AutoCompletionHide; {$ENDIF} FCaret := Value; if (FCaret.Y >= TopLine) and (FCaret.Y < TopLine + LinesVisiblePartial) and (FCaret.X >= LeftCol) and (FCaret.X <= LeftCol + ColumnsVisiblePartial) and {(FMemo.Focused) and} (GetFocus = FMemo.Handle) then begin {$IFDEF AutoOverwrite} if oeOverwrite in Options then CreateCaret( FMemo.Handle, 0, CharWidth, LineHeight ) else {$ENDIF} CreateCaret( FMemo.Handle, 0, 1, LineHeight ); SetCaretPos( (FCaret.X - LeftCol) * CharWidth, (FCaret.Y - TopLine) * LineHeight ); ShowCaret( FMemo.Handle ); end else HideCaret( FMemo.Handle ); AdjustHScroll; end; procedure THilight.SetLeftCol(const Value: Integer); var WasLeftCol: Integer; begin WasLeftCol := FLeftCol; if WasLeftCol <> Value then begin FLeftCol := Value; if FLeftCol < 0 then FLeftCol := 0; if FLeftCol >= MaxLineWidth then FLeftCol := MaxLineWidth; if FLeftCol < 0 then FLeftCol := 0; ScrollWindowEx( FMemo.Handle, (-FLeftCol + WasLeftCol)*CharWidth, 0, nil, nil, 0, nil, SW_INVALIDATE ); Caret := Caret; end; // установить горизонтальный скроллер в правильное положение: AdjustHScroll; if Assigned(FOnScroll) then FOnScroll(FMemo); end; procedure THilight.SetLineData(Idx: Integer; const Value: DWORD); begin FLines.Objects[ Idx ] := Value; end; procedure THilight.SetLines(Idx: Integer; const Value: KOLString); var U: KOLString; begin Changing; if Assigned( FOnSetLine ) then begin U := Value; if not FOnSetLine( FMemo, Idx, U ) then Exit; end; while FLines.Count <= Idx do begin FLines.Add( '' ); {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then FUndoList.Add( 'A' ); {$ENDIF} end; if FLines.Items[ Idx ] <> Value then begin {$IFDEF ProvideUndoRedo} if not FUndoingRedoing then begin U := 'R' + Int2Str( Idx ) + '='; if Copy( FUndoList.Last, 1, Length( U ) ) <> U then FUndoList.Add( U + FLines.Items[ Idx ] ); end; {$ENDIF} FLines.Items[ Idx ] := Value; end; InvalidateLine( Idx ); Changed; end; procedure THilight.SetOnScanToken(const Value: TOnScanToken); begin FOnScanToken := Value; FMemo.Invalidate; end; procedure THilight.SetSel(const Pos1, Pos2, PosFrom: TPoint); begin if (Pos1.Y > Pos2.Y) or (Pos1.Y = Pos2.Y) and (Pos1.X > Pos2.X) then begin SelBegin := Pos2; SelEnd := Pos1; end else begin SelBegin := Pos1; SelEnd := Pos2; end; SelFrom := PosFrom; end; procedure THilight.SetSelBegin(const Value: TPoint); begin if (FSelBegin.X = Value.X) and (FSelBegin.Y = Value.Y) then Exit; InvalidateSelection; // выделение могло измениться, все выделение обновится FSelBegin := Value; if (FSelEnd.Y < FSelBegin.Y) or (FSelEnd.Y = FSelBegin.Y) and (FSelEnd.X < FSelBegin.X) then FSelEnd := FSelBegin; InvalidateSelection; // обновить новое выделение if Assigned( FMemo.OnSelChange ) then FMemo.OnSelChange( FMemo ); end; procedure THilight.SetSelection(const Value: KOLString); var S1, L: KOLString; {$IFDEF FastReplaceSelection} SL: PStrList; y: Integer; {$ELSE} S: KOLString; MoreLinesLeft: Boolean; {$IFDEF ProvideBookmarks} deltaX: Integer; {$ENDIF} {$ENDIF} begin // удалить выделение, вставить новое значение взамен, все записать в откат Changing; DeleteSelection; {$IFDEF FastReplaceSelection} if Value <> '' then begin SL := NewStrList; TRY SL.Text := Value; if (Value <> '') and ((Value[ Length( Value ) ] = #13) or (Value[ Length( Value ) ] = #10) ) then SL.Add( '' ); L := Lines[ Caret.Y ]; if Length( L ) < Caret.X then L := L + StrRepeat( ' ', Caret.X - Length( L ) ); S1 := ''; // будем вставлять в последнюю строку if SL.Count = 1 then begin L := Copy( L, 1, Caret.X ) + SL.Items[ 0 ] + CopyEnd( L, Caret.X+1 ); FCaret.x := FCaret.x+Length( SL.Items[ 0 ] ); Lines[ Caret.Y ] := L; end else begin S1 := CopyEnd( L, Caret.X+1 ); L := Copy( L, 1, Caret.X ) + SL.Items[ 0 ]; //S1 := SL.Items[ Count-1 ]; Lines[ Caret.Y ] := L; {$IFDEF ProvideBookmarks} FixBookmarks( Caret, Length( SL.Items[ 0 ] ) - Length( S1 ), SL.Count-1 ); {$ENDIF} for y := 1 to SL.Count-2 do begin L := SL.Items[ y ]; InsertLine( Caret.Y+y, L, FALSE ); end; y := SL.Count-1; L := S1; // + Lines[ Caret.y+y ]; InsertLine( Caret.Y+y, SL.Last + L, FALSE ); //Lines[ Caret.y+y ] := L; Caret := MakePoint( Length( SL.Last ), Caret.y+y ); end; FINALLY SL.Free; END; end; {$ELSE} // медленный вариант {$IFDEF ProvideBookmarks} deltaX := -1; {$ENDIF} S := Value; MoreLinesLeft := FALSE; while (S <> '') or MoreLinesLeft do begin MoreLinesLeft := (pos( #13, S ) > 0) or (pos( #10, S ) > 0); S1 := Parse( S, #13#10 ); {$IFDEF ProvideBookmarks} if deltaX < 0 then begin deltaX := Length( S1 ); FixBookmarks( Caret, deltaX, 0 ); end; {$ENDIF} if (S <> '') and (S[ 1 ] = #10) then Delete( S, 1, 1 ); L := Lines[ Caret.Y ]; while Length( L ) < Caret.X do L := L + ' '; if MoreLinesLeft then begin Lines[ FCaret.Y ] := Copy( L, 1, Caret.X ) + S1; L := CopyEnd( L, Caret.X+1 ); InsertLine( Caret.Y+1, L, FALSE ); Caret := MakePoint( 0, Caret.Y+1 ); end else begin Lines[ Caret.Y ] := Copy( L, 1, Caret.X ) + S1 + CopyEnd( L, Caret.X+1 ); Caret := MakePoint( Caret.X + Length( S1 ), Caret.Y ); end; end; {$ENDIF} AdjustHScroll; AdjustVScroll; SetSel( Caret, Caret, Caret ); CaretToView; Changed; end; procedure THilight.SetSelEnd(const Value: TPoint); begin if (FSelEnd.X = Value.X) and (FSelEnd.Y = Value.Y) then Exit; InvalidateSelection; // выделение могло измениться, все выделение обновится FSelEnd := Value; if (FSelBegin.Y > FSelEnd.Y) or (FSelBegin.Y = FSelEnd.Y) and (FSelBegin.X > FSelEnd.X) then FSelBegin := FSelEnd; InvalidateSelection; // обновить новое выделение if Assigned( FMemo.OnSelChange ) then FMemo.OnSelChange( FMemo ); end; procedure THilight.SetTabSize(Value: Integer); begin if Value <= 0 then Value := 8; fTabSize := Value; end; procedure THilight.SetText(Value: KOLString); var i: Integer; begin if (Pos(#13#10, Value) = 0) and (Pos(#10, Value) + Pos(#13, Value) > 0) then begin i := 1; while i <= Length(Value) do begin if (Value[i] = #13) and ((i = Length(Value)) or (Value[i + 1] <> #10)) then Insert(#10, Value, i + 1) else if (Value[i] = #10) and ((i = 1) or (Value[i - 1] <> #13)) then Insert(#13, Value, i); Inc(i); end; end; FLines.Text := Value; TopLine := TopLine; FMemo.Invalidate; {$IFDEF ProvideAutoCompletion} AutoCompletionHide; {$IFDEF AutocompletionFastFillDictionary} FastFillDictionary; {$ELSE} FDictionary.Clear; for i := 0 to FLines.Count-1 do AutoAdd2Dictionary( FLines.ItemPtrs[ i ] ); {$ENDIF} {$ENDIF} end; procedure THilight.SetTopLine(const Value: Integer); var WasTopLine: Integer; begin WasTopLine := FTopLine; FTopLine := Value; if FTopLine < 0 then FTopLine := 0; if FTopLine >= Count then FTopLine := Count; if Count = 0 then begin Exit; end; if FTopLine + LinesPerPage >= Count then FTopLine := Count - LinesPerPage; if FTopLine < 0 then FTopLine := 0; if WasTopLine <> FTopLine then begin ScrollWindowEx( FMemo.Handle, 0, (WasTopLine - FTopLine)*LineHeight, nil, nil, 0, nil, SW_INVALIDATE ); Caret := Caret; end; // установить вертикальный скроллер в правильное положение: AdjustVScroll; if Assigned(FOnScroll) then FOnScroll(FMemo); end; procedure THilight.Undo; begin {$IFDEF ProvideUndoRedo} if not CanUndo then Exit; DoUndoRedo( FUndoList, FRedoList ); {$ENDIF} end; function THilight.WordAtPos(const AtPos: TPoint): KOLString; var FromPos: TPoint; S: KOLString; i: Integer; begin Result := ''; if AtPos.Y >= Count then Exit; FromPos := WordAtPosStart( AtPos ); S := Lines[ FromPos.Y ]; i := FromPos.X; while TRUE do begin inc( i ); if i >= Length( S ) then break; if not IsLetterDigit( S[ i+1 ] ) then break; end; Result := Trim( Copy( S, FromPos.X+1, i-FromPos.X ) ); end; function THilight.WordAtPosStart(const AtPos: TPoint): TPoint; var S: KOLString; i: Integer; begin Result := AtPos; if AtPos.Y >= Count then Exit; S := Lines[ AtPos.Y ]; if (AtPos.X < Length( S )) and IsLetterDigit( S[ AtPos.X+1 ] ) then i := AtPos.X else if (AtPos.X-1 > 0) and (AtPos.X-1 < Length( S )) and IsLetterDigit( S[ AtPos.X ] ) then i := AtPos.X-1 else Exit; while i > -1 do begin Dec( i ); if (i < 0) or not IsLetterDigit( S[ i+1 ] ) then begin Result.X := i+1; break; end; end; end; initialization InitUpper; end.
unit caUndoRedo; {$INCLUDE ca.inc} interface uses // Standard Delphi units  Classes, SysUtils, Contnrs, Math, // ca units  caClasses, caLog; type //--------------------------------------------------------------------------- // IcaCommandItem   //--------------------------------------------------------------------------- IcaCommandItem = interface ['{ADD5ADA5-7145-4735-AA05-15029DB0E6C5}'] // Property methods  function GetDescription: string; procedure SetDescription(const Value: string); // Interface methods  procedure Execute; procedure Reverse; // Properties  property Description: string read GetDescription write SetDescription; end; //--------------------------------------------------------------------------- // TcaCommandItem   //--------------------------------------------------------------------------- TcaCommandItem = class(TInterfacedObject, IcaCommandItem) private // Private fields  FDescription: string; // Property methods  function GetDescription: string; procedure SetDescription(const Value: string); // Interface methods  procedure Execute; procedure Reverse; protected // Protected methods  procedure DoExecute; virtual; abstract; procedure DoReverse; virtual; abstract; end; //---------------------------------------------------------------------------- // IcaCommandList   //---------------------------------------------------------------------------- IcaCommandList = interface ['{B20E722E-3736-46B9-A863-54697CC9BFAB}'] // Property methods  function GetCount: Integer; function GetItem(Index: Integer): IcaCommandItem; function GetItemIndex: Integer; function GetName: string; procedure SetName(const Value: string); // Interface methods  function Add(const ADescription: string): IcaCommandItem; function IndexOf(AItem: IcaCommandItem): Integer; procedure Clear; procedure Redo; procedure Undo; // Properties  property Count: Integer read GetCount; property ItemIndex: Integer read GetItemIndex; property Items[Index: Integer]: IcaCommandItem read GetItem; default; property Name: string read GetName write SetName; end; //---------------------------------------------------------------------------- // TcaCommandList   //---------------------------------------------------------------------------- TcaCommandList = class(TInterfacedObject, IcaCommandList) private // Private fields  FItemIndex: Integer; FList: IInterfaceList; FName: string; // Property methods  function GetCount: Integer; function GetItem(Index: Integer): IcaCommandItem; function GetItemIndex: Integer; function GetName: string; procedure SetName(const Value: string); // Interface methods  function Add(const ADescription: string): IcaCommandItem; function IndexOf(AItem: IcaCommandItem): Integer; procedure Clear; procedure Redo; procedure Undo; protected // Protected methods  function CreateItem: IcaCommandItem; virtual; abstract; public // Create/Destroy  procedure AfterConstruction; override; procedure BeforeDestruction; override; end; //--------------------------------------------------------------------------- // IcaUndoRedo   //--------------------------------------------------------------------------- IcaUndoRedo = interface ['{59D77B49-C863-4E3C-AB17-8D01C847F98C}'] // Property methods  function GetRedoItems: TStrings; function GetUndoItems: TStrings; // Interface methods  function Add(const ADescription: string): IcaCommandItem; function AddCommandList(const AName: string): IcaCommandList; function CanUndo: Boolean; function CanRedo: Boolean; procedure SelectCommandList(const AName: string; ACreateIfNotFound: Boolean); procedure Redo; procedure RedoGroup(ARedoCount: Integer); procedure Undo; procedure UndoGroup(AUndoCount: Integer); // Properties  property RedoItems: TStrings read GetRedoItems; property UndoItems: TStrings read GetUndoItems; end; //--------------------------------------------------------------------------- // TcaUndoRedo   //--------------------------------------------------------------------------- TcaUndoRedo = class(TInterfacedObject, IcaUndoRedo, IcaLoggable) private // Private fields  FCommandList: IcaCommandList; FList: IInterfaceList; FRedoItems: TStrings; FUndoItems: TStrings; // Property methods  function GetRedoItems: TStrings; function GetUndoItems: TStrings; // Interface methods - IcaUndoRedo  function Add(const ADescription: string): IcaCommandItem; function AddCommandList(const AName: string): IcaCommandList; function CanUndo: Boolean; function CanRedo: Boolean; procedure SelectCommandList(const AName: string; ACreateIfNotFound: Boolean); procedure Redo; procedure RedoGroup(ARedoCount: Integer); procedure Undo; procedure UndoGroup(AUndoCount: Integer); // Interface methods - IcaLoggable  procedure SendToLog(const AMsg: String; AClearLog: Boolean = False); protected // Protected methods  function CreateCommandList: IcaCommandList; virtual; abstract; public // Create/Destroy  procedure AfterConstruction; override; procedure BeforeDestruction; override; end; implementation //--------------------------------------------------------------------------- // TcaCommandItem   //--------------------------------------------------------------------------- // Interface methods  procedure TcaCommandItem.Execute; begin DoExecute; end; procedure TcaCommandItem.Reverse; begin DoReverse; end; // Property methods  function TcaCommandItem.GetDescription: string; begin Result := FDescription; end; procedure TcaCommandItem.SetDescription(const Value: string); begin FDescription := Value; end; //--------------------------------------------------------------------------- // TcaCommandItem   //--------------------------------------------------------------------------- // No implementation  //---------------------------------------------------------------------------- // TcaCommandList   //---------------------------------------------------------------------------- // Create/Destroy  procedure TcaCommandList.AfterConstruction; begin inherited; FList := TInterfaceList.Create; FItemIndex := -1; end; procedure TcaCommandList.BeforeDestruction; begin inherited; end; // Interface methods  function TcaCommandList.Add(const ADescription: string): IcaCommandItem; begin while FItemIndex >= 0 do begin FList.Delete(0); Dec(FItemIndex); end; Result := CreateItem; Result.Description := ADescription; FList.Insert(0, Result); end; function TcaCommandList.IndexOf(AItem: IcaCommandItem): Integer; begin Result := FList.IndexOf(AItem); end; procedure TcaCommandList.Clear; begin FList.Clear; end; procedure TcaCommandList.Redo; var CommandItem: IcaCommandItem; begin CommandItem := FList[FItemIndex] as IcaCommandItem; CommandItem.Execute; if FItemIndex >= 0 then Dec(FItemIndex); end; procedure TcaCommandList.Undo; var CommandItem: IcaCommandItem; begin if FItemIndex < FList.Count then Inc(FItemIndex); CommandItem := FList[FItemIndex] as IcaCommandItem; CommandItem.Reverse; end; // Property methods  function TcaCommandList.GetCount: Integer; begin Result := FList.Count; end; function TcaCommandList.GetItem(Index: Integer): IcaCommandItem; begin Result := FList[Index] as IcaCommandItem; end; function TcaCommandList.GetItemIndex: Integer; begin Result := FItemIndex; end; function TcaCommandList.GetName: string; begin Result := FName; end; procedure TcaCommandList.SetName(const Value: string); begin FName := Value; end; //--------------------------------------------------------------------------- // TcaUndoRedo   //--------------------------------------------------------------------------- procedure TcaUndoRedo.AfterConstruction; begin inherited; FList := TInterfaceList.Create; FRedoItems := TStringList.Create; FUndoItems := TStringList.Create; end; procedure TcaUndoRedo.BeforeDestruction; begin inherited; FRedoItems.Free; FUndoItems.Free; end; // Interface methods - IcaUndoRedo  function TcaUndoRedo.Add(const ADescription: string): IcaCommandItem; begin Result := nil; if Assigned(FCommandList) then Result := FCommandList.Add(ADescription); end; function TcaUndoRedo.AddCommandList(const AName: string): IcaCommandList; begin Result := CreateCommandList; Result.Name := AName; FList.Add(Result); end; function TcaUndoRedo.CanRedo: Boolean; begin Result := False; if Assigned(FCommandList) then Result := (FCommandList.Count <> 0) and (FCommandList.ItemIndex >= 0); end; function TcaUndoRedo.CanUndo: Boolean; begin Result := False; if Assigned(FCommandList) then Result := (FCommandList.Count <> 0) and (FCommandList.ItemIndex < Pred(FCommandList.Count)); end; procedure TcaUndoRedo.SelectCommandList(const AName: string; ACreateIfNotFound: Boolean); var Index: Integer; begin FCommandList := nil; for Index := 0 to Pred(Flist.Count) do if (FList[Index] as IcaCommandList).Name = AName then begin FCommandList := FList[Index] as IcaCommandList; Break; end; if ACreateIfNotFound and (not Assigned(FCommandList)) then FCommandList := AddCommandList(AName); end; procedure TcaUndoRedo.Redo; begin if Assigned(FCommandList) then FCommandList.Redo; end; procedure TcaUndoRedo.RedoGroup(ARedoCount: Integer); var Index: Integer; begin for Index := 1 to ARedoCount do Redo; end; procedure TcaUndoRedo.Undo; begin if Assigned(FCommandList) then FCommandList.Undo; end; procedure TcaUndoRedo.UndoGroup(AUndoCount: Integer); var Index: Integer; begin for Index := 1 to AUndoCount do Undo; end; // Interface methods - IcaLoggable  procedure TcaUndoRedo.SendToLog(const AMsg: String; AClearLog: Boolean = False); var Index: Integer; begin if AClearLog then Log.Clear; if AMsg <> '' then Log.Send(AMsg); Log.Send('ItemIndex', FCommandList.ItemIndex); Log.Indent; for Index := 0 to Pred(FCommandList.Count) do begin Log.BeginLine; Log.Send('Index', Index); Log.Send('', FCommandList[Index].Description); Log.SendLine; end; Log.Outdent; end; // Property methods  function TcaUndoRedo.GetRedoItems: TStrings; var Index: Integer; begin FRedoItems.Clear; if Assigned(FCommandList) then for Index := FCommandList.ItemIndex downto 0 do FRedoItems.AddObject(FCommandList[Index].Description, Pointer(Index)); Result := FRedoItems; end; function TcaUndoRedo.GetUndoItems: TStrings; var Index: Integer; begin FUndoItems.Clear; if Assigned(FCommandList) then for Index := Succ(FCommandList.ItemIndex) to Pred(FCommandList.Count) do FUndoItems.AddObject(FCommandList[Index].Description, Pointer(Index)); Result := FUndoItems; end; end.
unit Billiards.Period; interface type TBilliardPeriod = class private fID: integer; fPeriodUntil: string; fPeriodFrom: string; public constructor Create; overload; constructor Create(ADate: TDate); overload; function ToString: string; override; property ID: integer read fID write fID; property PeriodFrom: string read fPeriodFrom write fPeriodFrom; property PeriodUntil: string read fPeriodUntil write fPeriodUntil; end; implementation uses SysUtils, Classes, DB, IBDatabase, IBQuery, IBCustomDataSet, Billiards.DataModule; { TBilliardPeriod } constructor TBilliardPeriod.Create; begin Create(Now); end; constructor TBilliardPeriod.Create(ADate: TDate); var SL: TStringList; begin inherited Create; if not BilliardDataModule.BilliardDB.Connected then BilliardDataModule.BilliardDB.Open; SL := TStringList.Create; try SL.Add('select ID,'); SL.Add(' PERIODFROM,'); SL.Add(' PERIODUNTIL'); SL.Add(' from PERIODS'); SL.Add(' where CURRENT_DATE between PERIODFROM and PERIODUNTIL'); BilliardDataModule.sqlQuery.SQL.Assign(SL); finally SL.Free; end; BilliardDataModule.sqlQuery.Open; if BilliardDataModule.sqlQuery.RecordCount = 1 then begin BilliardDataModule.sqlQuery.First; fID := BilliardDataModule.sqlQuery.FieldByName('id').AsInteger; fPeriodFrom := BilliardDataModule.sqlQuery.FieldByName('periodfrom').AsString; fPeriodUntil := BilliardDataModule.sqlQuery.FieldByName('perioduntil').AsString; end; BilliardDataModule.sqlQuery.Close; end; function TBilliardPeriod.ToString: string; begin Result := '"Period": { '; Result := Result + Format(#13#10'"ID": "%d", ', [fID]); Result := Result + Format(#13#10'"From": "%s", ', [fPeriodFrom]); Result := Result + Format(#13#10'"Until": "%s" }', [fPeriodUntil]); Result := Result + #13#10'}'; end; end.
unit uoversion; interface uses Windows, SysUtils, Classes, global; // This unit provides version information of client executables. function GetExePath(PHnd : Cardinal) : AnsiString; function ScanVer(WHnd : Cardinal) : AnsiString; implementation var PSHnd : Cardinal; PSProc : function(PHnd, MHnd : Cardinal; FN : PAnsiChar; Size : Cardinal) : Cardinal; stdcall; //////////////////////////////////////////////////////////////////////////////// function GetExePath(PHnd : Cardinal) : AnsiString; // if you know the process handle, this function will give you the file path var Buf : array[0..4095] of Byte; begin Result:=''; if PHnd=0 then Exit; if not Assigned(PSProc) then Exit; PSProc(PHnd,0,@Buf,SizeOf(Buf)); Result:=PAnsiChar(@Buf); end; //////////////////////////////////////////////////////////////////////////////// function GetFileVer(FN : AnsiString) : AnsiString; // reads version string from file info structure var c : Cardinal; s : AnsiString; Info : PVSFixedFileInfo; begin Result:=''; // get size c:=GetFileVersionInfoSize(PAnsiChar(FN),c); if c=0 then Exit; // get info SetLength(s,c); GetFileVersionInfo(PAnsiChar(FN),0,c,@s[1]); VerQueryValue(@s[1],'\',Pointer(Info),c); if c<SizeOf(Info^) then Exit; // return version string Result:=IntToStr(HiWord(Info^.dwFileVersionMS))+'.'+ IntToStr(LoWord(Info^.dwFileVersionMS))+'.'+ IntToStr(HiWord(Info^.dwFileVersionLS))+'.'+ IntToStr(LoWord(Info^.dwFileVersionLS)); end; //////////////////////////////////////////////////////////////////////////////// function ReadScan1(PHnd : Cardinal) : AnsiString; // detects version of clients 1.26.x - 2.0.x const Scan1 = #199#134#152#0#0#0#255#255#255#255#161#1#1#1#1#80#141#76#36#36#104; var c : Cardinal; begin Result:=''; c:=SearchMem(PHnd,Scan1,#1); if c=0 then Exit; ReadMem(PHnd, c+11, @c, 4); Result:=#0#0#0#0#0#0#0#0#0#0#0; ReadMem(PHnd, c+4, @Result[1], 10); Result:=PAnsiChar(Result); end; //////////////////////////////////////////////////////////////////////////////// function ReadScan2(PHnd : Cardinal) : AnsiString; // detects version of clients 3.0.x - 5.0.6e const Scan2 = #104#2#2#2#2#232#2#2#2#2#131#196#24#198#5#2#2#2#2#1#184; var a : array[0..9] of Byte; c : Cardinal; begin Result:=''; c:=SearchMem(PHnd,Scan2,#2); if c=0 then Exit; ReadMem(PHnd, c-15, @a, 10); Result:=IntToStr(Byte(a[9]))+'.'+ IntToStr(Byte(a[7]))+'.'+ IntToStr(Byte(a[5])); ReadMem(PHnd, PCardinal(@a)^, @a, 10); Result:=Result+PAnsiChar(@a); end; //////////////////////////////////////////////////////////////////////////////// function ScanVer(WHnd : Cardinal) : AnsiString; // returns the client version string var PHnd : Cardinal; begin Result:=''; // get process handle GetWindowThreadProcessID(WHnd,PHnd); PHnd:=OpenProcess(PROCESS_ALL_ACCESS,False,PHnd); if PHnd=0 then Exit; repeat // use file version if client >= 6.0.0 (very fast) Result:=GetFileVer(GetExePath(PHnd)); if Result<>'' then if Result[1]>='6' then Break; // Beware: Clients 5.0.4f - 5.0.6e also have file versions, but they // differ from the official 3 numbers + 1 letter scheme. So they actually // have two versions, one in code (correct) and one in file info (wrong). // detect clients 3.0.x - 5.0.6e Result:=ReadScan2(PHnd); if Result<>'' then Break; // detect clients 1.26.x - 2.0.x Result:=ReadScan1(PHnd); if Result<>'' then Break; // still nothing? must be clients 5.0.7.0 - 5.0.9.x Result:=GetFileVer(GetExePath(PHnd)); until True; CloseHandle(PHnd); end; //////////////////////////////////////////////////////////////////////////////// initialization PSHnd:=LoadLibrary('psapi.dll'); Pointer(PSProc):=GetProcAddress(PSHnd,'GetModuleFileNameExA'); finalization FreeLibrary(PSHnd); end.
unit mCoverSheetDisplayPanel_CPRS_Vitals; { ================================================================================ * * Application: CPRS - CoverSheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-21 * * Description: Vitals display panel for CPRS Coversheet. * * Notes: * ================================================================================ } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.ImgList, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, mCoverSheetDisplayPanel_CPRS, iCoverSheetIntf, oDelimitedString; type TfraCoverSheetDisplayPanel_CPRS_Vitals = class(TfraCoverSheetDisplayPanel_CPRS) private fSeparator: TMenuItem; fUpdateVitals: TMenuItem; protected { Inherited events - TfraGridPanel } procedure OnPopupMenu(Sender: TObject); override; procedure OnPopupMenuInit(Sender: TObject); override; procedure OnPopupMenuFree(Sender: TObject); override; { Inherited events - TfraCoverSheetDisplayPanel_CPRS } procedure OnAddItems(aList: TStrings); override; procedure OnGetDetail(aRec: TDelimitedString; aDetail: TStrings); override; procedure OnShowDetail(aText: TStrings; aTitle: string = ''; aPrintable: boolean = false); override; { Introduced Events } procedure OnUpdateVitals(Sender: TObject); virtual; public constructor Create(aOwner: TComponent); override; end; var fraCoverSheetDisplayPanel_CPRS_Vitals: TfraCoverSheetDisplayPanel_CPRS_Vitals; implementation {$R *.dfm} uses ORFn, ORNet, rMisc, uCore, uVitals; { TfraCoverSheetDisplayPanel_CPRS_Vitals } constructor TfraCoverSheetDisplayPanel_CPRS_Vitals.Create(aOwner: TComponent); begin inherited; AddColumn(0, 'Vital'); AddColumn(1, 'Value'); AddColumn(2, 'Date Taken'); AddColumn(3, 'Conv. Value'); AddColumn(4, 'Quals'); CollapseColumns; end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnPopupMenu(Sender: TObject); begin inherited; fUpdateVitals.Enabled := True; end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnPopupMenuFree(Sender: TObject); begin FreeAndNil(fSeparator); FreeAndNil(fUpdateVitals); inherited; end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnPopupMenuInit(Sender: TObject); begin inherited; fSeparator := NewLine; fUpdateVitals := NewItem('Update Vitals ...', 0, False, True, OnUpdateVitals, 0, 'pmnVitals_UpdateVitals'); pmn.Items.Add(fSeparator); pmn.Items.Add(fUpdateVitals); end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnShowDetail(aText: TStrings; aTitle: string; aPrintable: boolean); begin // Tricking the UI to go to Vitals Lite when single clicked OnUpdateVitals(lvData); end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnUpdateVitals(Sender: TObject); var aFunctionAddr: TGMV_VitalsViewForm; aFunctionName: AnsiString; aRtnRec: TDllRtnRec; aStartDate: string; aVitalsAbbv: string; begin { Availble Forms: GMV_FName :='GMV_VitalsEnterDLG'; GMV_FName :='GMV_VitalsEnterForm'; GMV_FName :='GMV_VitalsViewForm'; GMV_FName :='GMV_VitalsViewDLG'; } lvData.Enabled := false; try try aFunctionName := 'GMV_VitalsViewDLG'; aRtnRec := LoadVitalsDLL; case aRtnRec.Return_Type of DLL_Success: try @aFunctionAddr := GetProcAddress(VitalsDLLHandle, PAnsiChar(aFunctionName)); if Assigned(aFunctionAddr) then begin if Patient.Inpatient then aStartDate := FormatDateTime('mm/dd/yy', Now - 7) else aStartDate := FormatDateTime('mm/dd/yy', IncMonth(Now, -6)); if lvData.Selected <> nil then aVitalsAbbv := lvData.Selected.Caption else aVitalsAbbv := ''; aFunctionAddr(RPCBrokerV, Patient.DFN, IntToStr(Encounter.Location), aStartDate, FormatDateTime('mm/dd/yy', Now), GMV_APP_SIGNATURE, GMV_CONTEXT, GMV_CONTEXT, Patient.Name, Format('%s %d', [Patient.SSN, Patient.Age]), Encounter.LocationName + U + aVitalsAbbv); end else MessageDLG('Can''t find function "GMV_VitalsViewDLG".', mtError, [mbok], 0); except on E: Exception do MessageDLG('Error running Vitals Lite: ' + E.Message, mtError, [mbok], 0); end; DLL_Missing: begin TaskMessageDlg('File Missing or Invalid', aRtnRec.Return_Message, mtError, [mbok], 0); end; DLL_VersionErr: begin TaskMessageDlg('Incorrect Version Found', aRtnRec.Return_Message, mtError, [mbok], 0); end; end; finally @aFunctionAddr := nil; UnloadVitalsDLL; end; CoverSheet.OnRefreshPanel(Self, CV_CPRS_VITL); CoverSheet.OnRefreshPanel(Self, CV_CPRS_RMND); finally lvData.Enabled := True; end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnAddItems(aList: TStrings); var aRec: TDelimitedString; aStr: string; begin if aList.Count = 0 then aList.Add('^No Vitals Found.'); try lvData.Items.BeginUpdate; for aStr in aList do begin aRec := TDelimitedString.Create(aStr); if lvData.Items.Count = 0 then if aRec.GetPieceIsNull(1) and (aList.Count = 1) then CollapseColumns else ExpandColumns; with lvData.Items.Add do begin Caption := aRec.GetPiece(2); SubItems.Add(aRec.GetPiece(5)); SubItems.Add(FormatDateTime(DT_FORMAT, aRec.GetPieceAsTDateTime(4))); SubItems.Add(aRec.GetPiece(6)); SubItems.Add(aRec.GetPiece(7)); Data := aRec; end; end; finally lvData.Items.EndUpdate; end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Vitals.OnGetDetail(aRec: TDelimitedString; aDetail: TStrings); var aDateTime: TDateTime; begin aDateTime := FMDateTimeToDateTime(aRec.GetPieceAsDouble(4)); aDetail.Clear; aDetail.Add(Format('%s %s', ['Vital ..........', aRec.GetPieceAsString(2)])); aDetail.Add(Format('%s %s', ['Date/Time ......', FormatDateTime('MMM DD, YYYY@hh:mm', aDateTime)])); aDetail.Add(Format('%s %s', ['Value ..........', aRec.GetPieceAsString(5)])); aDetail.Add(Format('%s %s', ['Conv. Value ....', aRec.GetPieceAsString(6)])); aDetail.Add(Format('%s %s', ['Qualifiers .....', aRec.GetPieceAsString(7)])); end; end.
unit uOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Registry, ExtCtrls, UITypes, XmlIniFile, uConstant; type TOptions = class(TForm) btnCancel0: TButton; btnCancel1: TButton; btnCancel2: TButton; btnFile1: TButton; btnFile2: TButton; btnGetPosition: TButton; btnOk0: TButton; btnOk1: TButton; btnOk2: TButton; cbxGoParking: TCheckBox; cmbApp: TComboBox; cmbBaudRate: TComboBox; cmbDataBits: TComboBox; cmbFlowControl: TComboBox; cmbParity: TComboBox; cmbComPort: TComboBox; cmbRotateSpeed: TComboBox; cmbStopBits: TComboBox; edtAzOffset: TEdit; edtElements: TEdit; edtInifile: TEdit; edtIntervalTime: TEdit; edtParkingAz: TEdit; edtParkingEl: TEdit; edtRegKey: TEdit; grpAzimuth: TGroupBox; grpParking: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label16: TLabel; OpenDialog1: TOpenDialog; PageControl1: TPageControl; rgpAzimuth: TRadioGroup; rgpElevation: TRadioGroup; tabApp: TTabSheet; tabCom: TTabSheet; tabGs232: TTabSheet; procedure btnCancel0Click(Sender: TObject); procedure btnFile2Click(Sender: TObject); procedure btnGetPositionClick(Sender: TObject); procedure btnOk0Click(Sender: TObject); procedure cmbAppChange(Sender: TObject); procedure cmbComPortChange(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure btnFile1Click(Sender: TObject); private { Private 宣言 } XMLIni: TXMLIniFile; XMLIniName: string; function CheckData: boolean; procedure ReadXMLIniFile1; procedure ReadXMLIniFile2; procedure WriteXMLIniFile1; procedure WriteXMLIniFile2; procedure GetComList(); public { Public 宣言 } end; var Options: TOptions; implementation {$R *.dfm} uses uMain; procedure TOptions.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := CheckData; end; procedure TOptions.FormCreate(Sender: TObject); begin XMLIniName := ChangeFileExt(Application.ExeName,'.xml'); GetComList(); // ReadInifileの前に処理が必要 ReadXMLInifile1; ReadXMLInifile2; end; procedure TOptions.btnGetPositionClick(Sender: TObject); var Az, El: integer; begin Main.GS232.GetPos(Az, El); if (Az <> StrToInt(edtParkingAz.Text)) or (El <> StrToInt(edtParkingEl.Text)) then begin edtParkingAz.Text := IntToStr((Az + 3600) mod 360); edtParkingEl.Text := IntToStr((El + 1800) mod 180); end; end; procedure TOptions.btnOk0Click(Sender: TObject); begin WriteXmlIniFile1(); WriteXmlIniFile2(); end; procedure TOptions.btnCancel0Click(Sender: TObject); begin WriteXmlIniFile1(); end; procedure TOptions.btnFile1Click(Sender: TObject); var s: string; begin s := edtInifile.Text; // 一時退避 with OpenDialog1 do begin InitialDir := ExtractFileDir(edtInifile.Text); FileName := ExtractFileName(edtInifile.Text); DefaultExt := '.ini'; Filter := 'Ini file (*.*)|*.ini'; if Execute then begin edtInifile.Text := FileName end else edtInifile.Text := s; end; end; procedure TOptions.btnFile2Click(Sender: TObject); var s: string; begin s := edtElements.Text; // 一時退避 with OpenDialog1 do begin InitialDir := ExtractFileDir(edtElements.Text); FileName := ExtractFileName(edtElements.Text); DefaultExt := '.TXT'; Filter := 'Text file (*.*)|*.TXT'; if Execute then edtElements.Text := FileName else edtElements.Text := s; end; end; procedure TOptions.cmbAppChange(Sender: TObject); begin XMLIni := TXMLIniFile.Create(XMLIniName); try XMLIni.OpenNode(cnRegistry, false); edtRegKey.Text := XMLIni.ReadString(cmbApp.Text, ''); finally FreeAndNil(XMLIni); end; end; procedure TOptions.cmbComPortChange(Sender: TObject); var i: integer; begin i := cmbComPort.Items.IndexOf(cmbComPort.Text); if i = -1 then // Items無いにない時-1が帰ってくる begin; MessageDlg('ComPortのPort No.が誤っています', mtError, [mbOK], 0); cmbComPort.SetFocus; exit; end; end; function TOptions.CheckData(): boolean; var Reg: TRegistry; i: integer; RootKey: integer; function CheckFile(a, b: string): boolean; begin result := true; if a = '' then begin MessageDlg(format('%sの指定が空白です', [a]), mtError, [mbOK], 0); result := false; exit; end else begin if not FileExists(b) then begin MessageDlg(format('%sの%s ファイルが見つかりません', [a, b]), mtError, [mbOK], 0); result := false; exit; end end; end; begin result := false; if not CheckFile(cnInifile, XMLIniName) then exit; if not CheckFile(cnElements, edtElements.Text) then exit; if edtRegKey.Text = '' then begin MessageDlg(format('%sのレジストリ指定が空白です', [edtIniFile.Text]), mtError, [mbOK], 0); exit; end; Reg := TRegistry.Create; try RootKey := HKEY_CURRENT_USER; if not Reg.OpenKey(edtRegKey.Text, False) then begin; MessageDlg(format('%sのレジストリが読めません', [edtIniFile.Text]), mtError, [mbOK], 0); Exit; end; finally FreeAndNil(Reg); end; i := cmbComPort.Items.IndexOf(cmbComPort.Text); if i = -1 then // Items無いにない時-1が帰ってくる begin; MessageDlg('Com PortのPort No.が誤っています', mtError, [mbOK], 0); Exit; end; result := true; end; procedure TOptions.ReadXmlIniFile1(); begin XMLIni := TXMLIniFile.Create(XMLIniName); try XMLIni.OpenNode(cnNodeOptions, true); Self.Left := XmlIni.ReadInteger(cnLeft, 0); Self.Top := XmlIni.ReadInteger(cnTop, 0); PageControl1.TabIndex := XMLIni.ReadInteger(cnTabIndex, 0); if (Self.Left = 0) and (Self.Top = 0) then begin Self.Left := (Screen.Width - Self.Width) Div 2; Self.Top := (Screen.Height - Self.Height) Div 2; end; finally FreeAndNil(XMLIni); end; end; procedure TOptions.ReadXmlIniFile2(); begin XMLIni := TXMLIniFile.Create(XMLIniName); try XMLIni.OpenNode(cnNodeOptions, true); XMLIni.OpenNode(cnNodeApp, true); cmbApp.Text := XMLIni.ReadString(cnApp, 'CALSAT32'); edtInifile.Text := XMLIni.ReadString(cnInifile, 'C:\Calsat32\CALSAT32.INI'); edtRegKey.Text := XMLIni.ReadString(cnRegKey, '\Software\VB and VBA Program Settings\JR1HUO\CALSAT32'); edtElements.Text := XMLIni.ReadString(cnElements, 'C:\Calsat32\ELEM.TXT'); XMLIni.OpenNode(cnNodeCom, true); cmbComPort.Text := XMLIni.ReadString(cnComPort, cmbComPort.items.Strings[0]); cmbBaudRate.Text := IntToStr(XMLIni.ReadInteger(cnBaudRate, 9600)); cmbDataBits.Text := XMLIni.ReadString(cnDataBits, '8'); cmbParity.Text := XMLIni.ReadString(cnParity, 'None'); cmbStopBits.Text := XMLIni.ReadString(cnStopBits, '1'); cmbFlowControl.Text := XMLIni.ReadString(cnFlowControl, 'Hardware'); XMLIni.OpenNode(cnNodeGS232, true); rgpAzimuth.ItemIndex := XmlIni.ReadInteger(cnAzRotator, 0); rgpElevation.ItemIndex := XmlIni.ReadInteger(cnElRotator, 0); edtIntervalTime.Text := IntToStr(XmlIni.ReadInteger(cnInterval, 1000)); edtAzOffset.Text := IntToStr(XMLIni.ReadInteger(cnAzOffset, 0)); cmbRotateSpeed.ItemIndex := XMLIni.ReadInteger(cnRotateSpeed, 1); edtParkingAz.Text := IntToStr(XMLIni.ReadInteger(cnParkingAz, 0)); edtParkingEl.text := IntToStr(XMLIni.ReadInteger(cnGoParking, 0)); cbxGoParking.Checked := XMLIni.ReadBool(cnGoParking, true); finally FreeAndNil(XMLIni); end; end; procedure TOptions.WriteXmlIniFile1(); begin XMLIni := TXMLIniFile.Create(XMLIniName); try XMLIni.OpenNode(cnNodeOptions, true); XmlIni.WriteInteger(cnLeft, Self.Left); XmlIni.WriteInteger(cnTop, Self.Top); XMLIni.WriteInteger(cnTabIndex, PageControl1.TabIndex); XmlIni.CloseNode; XmlIni.UpdateFile; finally FreeAndNil(XMLIni); end; end; procedure TOptions.WriteXmlIniFile2(); begin XMLIni := TXMLIniFile.Create(XMLIniName); try XMLIni.OpenNode(cnNodeApp, true); XMLIni.WriteString(cnApp, cmbApp.Text); XMLIni.WriteString(cnInifile, edtInifile.Text); XMLIni.WriteString(cnRegKey, edtRegKey.text); XMLIni.WriteString(cnElements, edtElements.Text); XmlIni.CloseNode; XmlIni.UpdateFile; XMLIni.OpenNode(cnNodeCom, true); XMLIni.WriteString(cnComPort, cmbComPort.text); XMLIni.WriteInteger(cnBaudRate, StrToInt(cmbBaudRate.text)); XMLIni.WriteString(cnDataBits, cmbDataBits.Text); XMLIni.WriteString(cnParity, cmbParity.text); XMLIni.WriteString(cnStopBits, cmbStopBits.text); XMLIni.WriteString(cnFlowControl, cmbFlowControl.text); XmlIni.CloseNode; XmlIni.UpdateFile; XMLIni.OpenNode(cnNodeGS232, true); XmlIni.WriteInteger(cnInterval, StrToInt(edtIntervalTime.Text)); XmlIni.WriteInteger(cnAzRotator, rgpAzimuth.ItemIndex); XmlIni.WriteInteger(cnElRotator, rgpElevation.ItemIndex); XMLIni.WriteInteger(cnAzOffset, StrToInt(EdtAzOffset.Text)); XMLIni.WriteInteger(cnRotateSpeed, cmbRotateSpeed.ItemIndex); XMLIni.WriteInteger(cnParkingAz, StrToInt(edtParkingAz.Text)); XMLIni.WriteInteger(cnParkingEl, StrToInt(edtParkingEl.Text)); XMLIni.WriteBool(cnGoParking, cbxGoParking.Checked); XmlIni.CloseNode; XmlIni.UpdateFile; finally FreeAndNil(XMLIni); end; end; procedure TOptions.GetComList(); var i: integer; sl: TStringList; reg: TRegistry; begin sl := TStringList.Create; reg := TRegistry.Create(KEY_READ); try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey('HARDWARE\DEVICEMAP\SERIALCOMM', False) then begin reg.GetValueNames(sl); for i := 0 to Pred(sl.Count) do if reg.GetDataType(sl.Strings[i]) = rdString then cmbComPort.Items.Append(reg.ReadString(sl.Strings[i])); end; finally reg.Free; sl.Free; end; end; end.
unit GongZuoLiangTongJi; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, ComCtrls, StdCtrls, Buttons, shellapi, ComObj; type TGongZuoLiangTongJiForm = class(TForm) GroupBox4: TGroupBox; btnCreateReport: TBitBtn; STDir: TStaticText; btnBrowse: TBitBtn; ERP1: TEdit; btnOpenReport: TBitBtn; pbCreateReport: TProgressBar; SEFDlg: TSaveDialog; ADO02: TADOQuery; ADO02_All: TADOQuery; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnBrowseClick(Sender: TObject); procedure btnOpenReportClick(Sender: TObject); procedure btnCreateReportClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } m_FullFileName_TongJi:string;//EXCEL文件XLS文件的全路径 txtFile:textFile; strOutTxt:string; strPath:string; m_intBeginRowOfExcelFile:Integer; m_intGeShu_Col:Integer; //在Excel表中个数或组数所在的列 m_intGongZuoLiang_Col:Integer; //在Excel表中工作量所在的列 m_isWritenTitle:Boolean; //记录是否写过表头了 m_strSQL_WhereClause_Drills_IsNot_JieKong:string;//sql 语句的where 子句中的一个条件 ,从Drills表中选出当前工程中不是借孔的钻孔 m_JueSuan_FieldName:string; //决定当前参与决算的字段名 如 can_juesuan can_juesuan1 can_juesuan9 function getOneBoreInfo(strProjectCode: string;strBoreCode: string):integer; function getAllBoreInfo(strProjectCode: string;intTag:integer):integer; function getAllBoreInfo_Jie(strProjectCode:string;intTag:integer):Integer; function getStandardThroughInfo(strProjectCode: string):integer; //计算标准贯入试验 function getProveMeasureInfo(strProjectCode: string):integer; //勘探点测量 function getRomDustTestInfo(strProjectCode: string):integer; function getEarthWaterInfo(strProjectCode: string):integer; function getZhongLiChuTanInfo(strProjectCode: string):Integer; public { Public declarations } procedure setJueSuanFieldName(iIndex:integer);//在参与决算的钻孔批次设定后,设定这个变量。这样参与决算的字段名就是can_juesuan + 这个变量,就变成了can_juesuan1 can_juesuan2这种真实的字段名 end; var GongZuoLiangTongJiForm: TGongZuoLiangTongJiForm; implementation uses public_unit; {$R *.dfm} procedure TGongZuoLiangTongJiForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:= caFree; end; procedure TGongZuoLiangTongJiForm.btnBrowseClick(Sender: TObject); var SaveFName:string; begin SEFDlg.DefaultExt :='xls'; SEFDlg.Title :=FILE_SAVE_TITLE_GZL; SEFDlg.FileName :=trim(erp1.text); SEFDlg.Filter :='Excel文件(*.xls)|*.xls'; if not SEFDlg.Execute then exit; SaveFName:=SEFDlg.FileName ; erp1.text:=SaveFName; end; procedure TGongZuoLiangTongJiForm.btnOpenReportClick(Sender: TObject); var sfName:string; begin sfName:=trim(ERP1.Text); if fileexists(sfName) then shellexecute(application.Handle,PAnsiChar(''),PAnsiChar(sfName),PAnsiChar(''),PAnsiChar(''),SW_SHOWNORMAL) else Application.Messagebox(FILE_NOTEXIST,HINT_TEXT, MB_ICONEXCLAMATION + mb_Ok); end; procedure TGongZuoLiangTongJiForm.btnCreateReportClick(Sender: TObject); var strPath:string; intResult:integer; i:integer; strProjectNo:string; begin ERP1.Text := Trim(ERP1.Text); if pos('.xls',ERP1.Text)=0 then ERP1.Text:=ERP1.TEXT+'.xls'; i:=Length(ERP1.text); repeat if copy(ERP1.text,i,1)='\' then begin strPath:=copy(ERP1.text,1,i); i:=0; end; i:=i-1; until i<=0; if not DirectoryExists(strPath) then ForceDirectories(strPath); copyfile(pChar(ExtractFileDir(Application.Exename)+'\XLS\工作量统计表.xls'),PChar(ERP1.text),false); m_FullFileName_TongJi := ERP1.Text; strProjectNo := g_ProjectInfo.prj_no_ForSQL; pbCreateReport.min:=0; pbCreateReport.Max:=110; pbCreateReport.Step:=10; pbCreateReport.Position:=10; //钻探(陆上) intResult:=getAllBoreInfo(strProjectNo,0); pbCreateReport.Position:=20; //钻探(水上) intResult:=getAllBoreInfo(strProjectNo,1); //钻探 借孔 intResult:=getAllBoreInfo_Jie(strProjectNo,2); pbCreateReport.Position:=30; //单桥静力触探 intResult:=getAllBoreInfo(strProjectNo,3); pbCreateReport.Position:=40; //双桥静力触探 intResult:=getAllBoreInfo(strProjectNo,4); //静力触探 借孔 intResult:=getAllBoreInfo_Jie(strProjectNo,5); pbCreateReport.Position:=50; //麻花钻 intResult:=getAllBoreInfo(strProjectNo,6); //麻花钻 借孔 intResult:=getAllBoreInfo_Jie(strProjectNo,7); pbCreateReport.Position:=60; //室内土试验费 intResult:=getRomDustTestInfo(strProjectNo); //取土,水样 intResult:=getEarthWaterInfo(strProjectNo); pbCreateReport.Position:=70; //标准贯入试验 intResult:=getStandardThroughInfo(strProjectNo); pbCreateReport.Position:=80; //动力触探试验 intResult:= getZhongLiChuTanInfo(strProjectNo); //勘探点测量 //intResult:=getProveMeasureInfo(strProjectNo); pbCreateReport.Position:=100; pbCreateReport.Position:=110; MessageBox(application.Handle,'决算报表已经生成。','系统提示',MB_OK+MB_ICONINFORMATION); end; function TGongZuoLiangTongJiForm.getAllBoreInfo(strProjectCode: string; intTag: integer): integer; var ExcelApplication1:Variant; ExcelWorkbook1:Variant; range,sheet:Variant; xlsFileName:string; intDrillCount:Integer; //钻孔个数 dSumDrillDepth:Double; //钻孔总深度 intResult:integer; intRow,intCol:integer; strd_t_no:string; //钻孔型号编号 dblTmp:double; begin if intTag=0 then strd_t_no:='1,4,5'; //陆上孔 if intTag=1 then strd_t_no:='2'; // 水上孔 if intTag=3 then strd_t_no:='6'; // 单桥 if intTag=4 then strd_t_no:='7'; // 双桥 if intTag=6 then strd_t_no:='3'; // 麻花钻(小螺纹钻) //正常孔统计 ADO02_All.Close; ADO02_All.SQL.Text:='select * from drills where '+m_JueSuan_FieldName+'=0 and prj_no=''' +strProjectCode+''' and d_t_no in ('+strd_t_no+')' + m_strSQL_WhereClause_Drills_IsNot_JieKong; ADO02_All.Open; intDrillCount := 0; dSumDrillDepth:= 0; while not ADO02_All.Recordset.eof do begin intDrillCount := intDrillCount +1; dSumDrillDepth := dSumDrillDepth + ADO02_All.fieldByName('comp_depth').AsFloat; ADO02_All.Next; end; ADO02_All.Close; //准备将数据写入统计EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=m_FullFileName_TongJi; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); Sheet:= ExcelApplication1.Activesheet; ExcelApplication1.Cells(m_intBeginRowOfExcelFile+intTag, m_intGeShu_Col):= IntToStr(intDrillCount); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+intTag, m_intGongZuoLiang_Col):= FormatFloat('0.00',dSumDrillDepth); ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; Result:=0; end; function TGongZuoLiangTongJiForm.getEarthWaterInfo( strProjectCode: string): integer; var ExcelApplication1:Variant; ExcelWorkbook1:Variant; xlsFileName:string; dblCount:Array[1..10] of double; i:integer; begin //取土,水样 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ ' and prj_no='''+ strProjectCode + ''' and (not wet_density is null);'; ADO02.Open; dblCount[1]:=ADO02.fieldByName('Num').Value; // //取土,水样(捶击法>30米) // ADO02.Close; // ADO02.SQL.Text:='select count(*) as Num from earthsample '+ // 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 and prj_no='''+strProjectCode+''') '+ // 'and s_depth_begin>30 and prj_no='''+ strProjectCode + ''' and (not wet_density is null);'; // // ADO02.Open; // dblCount[2]:=ADO02.fieldByName('Num').Value; //扰动样 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+ strProjectCode + ''' and wet_density is null;'; ADO02.Open; dblCount[2]:=ADO02.fieldByName('Num').Value; //写入EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=ERP1.Text;; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+8,m_intGeShu_Col):=dblCount[1]; //原状土样 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+9,m_intGeShu_Col):=dblCount[2]; //扰动土样 ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; result:=0; end; function TGongZuoLiangTongJiForm.getOneBoreInfo(strProjectCode, strBoreCode: string): integer; begin end; function TGongZuoLiangTongJiForm.getProveMeasureInfo( strProjectCode: string): integer; begin end; function TGongZuoLiangTongJiForm.getRomDustTestInfo( strProjectCode: string): integer; var ExcelApplication1:Variant; ExcelWorkbook1:Variant; xlsFileName:string; dblearthsample:Array[1..50] of double; dblEarthSampleTeShu:array[1..50] of Double;//特殊样 i:integer; begin for i:=1 to 50 do begin dblearthsample[i]:=0; dblEarthSampleTeShu[i]:=0; end; //含水量 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong+' AND prj_no='''+strProjectCode+''' ) '+ 'and prj_no='''+strProjectCode+''' and aquiferous_rate is not null'; ADO02.Open; dblearthSample[1]:=ADO02.fieldByName('Num').Value; //含水量 //容重 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and wet_density is not null'; ADO02.Open; dblearthSample[2]:=ADO02.fieldByName('Num').Value; //容重 //液限 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and liquid_limit is not null'; ADO02.Open; dblearthSample[3]:=ADO02.fieldByName('Num').Value; //液限 //塑限 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and shape_limit is not null'; ADO02.Open; dblearthSample[4]:=ADO02.fieldByName('Num').Value; //塑限 //比重 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and soil_proportion is not null'; ADO02.Open; dblearthSample[5]:=ADO02.fieldByName('Num').Value; //比重 //直剪(快剪) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and cohesion is not null'; ADO02.Open; dblearthSample[6]:=ADO02.fieldByName('Num').Value; //直剪(快剪) //直剪(固快) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and cohesion_gk is not null'; ADO02.Open; dblearthSample[7]:=ADO02.fieldByName('Num').Value; //直剪(固快) //压缩(常速) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (zip_coef is not null or zip_modulus is not null);'; ADO02.Open; dblearthSample[11]:=ADO02.fieldByName('Num').Value; //压缩(常速) //颗分(比重计) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from earthsample '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (sand_big is not null or sand_middle is not null or sand_small is not null or powder_big is not null or powder_small is not null or clay_grain is not null or li is not null)'; ADO02.Open; dblearthSample[12]:=ADO02.fieldByName('Num').Value; //颗分(比重计) //以下为特殊样计算 //先期固结压力 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (gygj_pc is not null)'; ADO02.Open; dblEarthSampleTeShu[1]:=ADO02.fieldByName('Num').Value; //固结系数 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (gjxs50_1 is not null or gjxs100_1 is not null or gjxs200_1 is not null or gjxs400_1 is not null or gjxs50_2 is not null or gjxs100_2 is not null or gjxs200_2 is not null or gjxs400_2 is not null)'; ADO02.Open; dblEarthSampleTeShu[3]:=ADO02.fieldByName('Num').Value; //无侧限抗压强度 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (wcxkyqd_yz is not null or wcxkyqd_cs is not null or wcxkyqd_lmd is not null)'; ADO02.Open; dblEarthSampleTeShu[4]:=ADO02.fieldByName('Num').Value; //天然坡角(水上、水下) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (trpj_g is not null or trpj_sx is not null)'; ADO02.Open; dblEarthSampleTeShu[6]:=ADO02.fieldByName('Num').Value; // 三轴压缩 不固结不排水(UU) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (szsy_zyl_njl_uu is not null or szsy_zyl_nmcj_uu is not null)'; ADO02.Open; dblEarthSampleTeShu[7]:=ADO02.fieldByName('Num').Value; // 三轴压缩 固结不排水(CU) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (szsy_zyl_njl_cu is not null or szsy_zyl_nmcj_cu is not null)'; ADO02.Open; dblEarthSampleTeShu[8]:=ADO02.fieldByName('Num').Value; //渗透试验 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (stxs_kv is not null or stxs_kh is not null)'; ADO02.Open; dblEarthSampleTeShu[9]:=ADO02.fieldByName('Num').Value; //静止侧压力系数 K0 ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (jzcylxs is not null)'; ADO02.Open; dblEarthSampleTeShu[11]:=ADO02.fieldByName('Num').Value; //基床系数(垂直) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (jcxs_v_005_01 is not null or jcxs_v_01_02 is not null or jcxs_v_02_04 is not null)'; ADO02.Open; dblEarthSampleTeShu[12]:=ADO02.fieldByName('Num').Value; //基床系数(水平) ADO02.Close; ADO02.SQL.Text:='select count(*) as Num from TeShuYang '+ 'where drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and prj_no='''+strProjectCode+''' and (jcxs_h_005_01 is not null or jcxs_h_01_02 is not null or jcxs_h_02_04 is not null)'; ADO02.Open; dblEarthSampleTeShu[13]:=ADO02.fieldByName('Num').Value; ADO02.Close; //写入EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=ERP1.Text; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); //常规样 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+12,m_intGeShu_Col):=dblearthSample[1]; //含水量 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+13,m_intGeShu_Col):=dblearthSample[2]; //容 重 或 密度 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+14,m_intGeShu_Col):=dblearthSample[3]; //液 限 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+15,m_intGeShu_Col):=dblearthSample[4]; //塑 限 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+16,m_intGeShu_Col):=dblearthSample[5]; //比 重 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+17,m_intGeShu_Col):=dblearthSample[6]; //直剪快剪 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+18,m_intGeShu_Col):=dblearthSample[7]; //直剪固快 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+19,m_intGeShu_Col):=dblearthSample[11]; //压缩常速 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+20,m_intGeShu_Col):=dblearthSample[12]; //颗分 比重计 //特殊样 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+21,m_intGeShu_Col):= dblEarthSampleTeShu[1]; //先期固结压力 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+22,m_intGeShu_Col):= dblEarthSampleTeShu[3]; //固结系数 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+23,m_intGeShu_Col):= dblEarthSampleTeShu[12]; //基床系数(垂直) ExcelApplication1.Cells(m_intBeginRowOfExcelFile+24,m_intGeShu_Col):= dblEarthSampleTeShu[13]; //基床系数(水平) ExcelApplication1.Cells(m_intBeginRowOfExcelFile+25,m_intGeShu_Col):= dblEarthSampleTeShu[4]; //无侧限抗压强度 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+26,m_intGeShu_Col):= FloatToStr(dblEarthSampleTeShu[7]+dblEarthSampleTeShu[8]); //三轴压缩 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+27,m_intGeShu_Col):=dblEarthSampleTeShu[9]; //渗透试验 ExcelApplication1.Cells(m_intBeginRowOfExcelFile+28,m_intGeShu_Col):= dblEarthSampleTeShu[6]; //天然坡角(水上、水下) //ExcelApplication1.Cells(28,35):=dblEarthSampleTeShu[1]+dblEarthSampleTeShu[3]; //先期固结压力(含固结系数)和92决算不一样 //ExcelApplication1.Cells(30,35):=dblEarthSampleTeShu[3]; //固结系数 //ExcelApplication1.Cells(32,35):=dblEarthSampleTeShu[4]; //无侧限抗压强度 //ExcelApplication1.Cells(33,35):=dblEarthSampleTeShu[6]; //天然坡角(水上、水下) //ExcelApplication1.Cells(34,35):=dblEarthSampleTeShu[7]; //三轴压缩 不固结不排水(UU) //ExcelApplication1.Cells(35,35):=dblEarthSampleTeShu[8]; //三轴压缩 固结不排水(CU) //ExcelApplication1.Cells(42,26):=dblEarthSampleTeShu[9]; //渗透试验 //ExcelApplication1.Cells(44,26):=dblEarthSampleTeShu[11]; //静止侧压力系数 K0 ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; result:=0; end; function TGongZuoLiangTongJiForm.getStandardThroughInfo( strProjectCode: string): integer; var intMore50:integer; intLess50:integer; intCount:integer; ExcelApplication1:Variant; ExcelWorkbook1:Variant; xlsFileName:string; strSQL: string; begin ADO02.Close; ADO02.SQL.Text:='select spt.*,stratum.stra_category from spt join stratum '+ 'on spt.prj_no=stratum.prj_no and spt.drl_no=stratum.drl_no '+ 'and spt.stra_no=stratum.stra_no and spt.sub_no=stratum.sub_no '+ 'where spt.drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and spt.prj_no='''+strProjectCode+''''; ADO02.Open; intCount := 0; while not ADO02.eof do begin intCount := intCount + 1; ADO02.Next; end; //写入EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=ERP1.Text; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+10,m_intGeShu_Col):=IntToStr(intCount); ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; result:=0; end; function TGongZuoLiangTongJiForm.getZhongLiChuTanInfo( strProjectCode: string): Integer; var intCount:integer; dGongZuoLiang:double; dEnd_Begin:Double; //每个试验的结束深度减去开始深度的值 iStra_category:Integer;//土层类型 iPt_type:Integer;//重力触探类型 0 轻型 1 重型 2 超重型 ExcelApplication1:Variant; ExcelWorkbook1:Variant; xlsFileName:string; strSQL: string; begin ADO02.Close; ADO02.SQL.Text:='select dpt.*,stratum.stra_category92 FROM dpt JOIN stratum '+ 'on dpt.prj_no=stratum.prj_no and dpt.drl_no=stratum.drl_no '+ 'and dpt.stra_no=stratum.stra_no and dpt.sub_no=stratum.sub_no '+ 'where dpt.drl_no in (select drl_no from drills where '+m_JueSuan_FieldName+'=0 ' + m_strSQL_WhereClause_Drills_IsNot_JieKong +' AND prj_no='''+strProjectCode+''') '+ 'and dpt.prj_no='''+strProjectCode+''''; ADO02.Open; intCount := 0; dGongZuoLiang := 0; while not ADO02.eof do begin intCount := intCount + 1; dEnd_Begin:= ADO02.FieldByName('end_depth').AsFloat - ADO02.FieldByName('begin_depth').AsFloat; dGongZuoLiang := dGongZuoLiang + dEnd_Begin ; ADO02.Next; end; //写入EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=ERP1.Text; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+11,m_intGeShu_Col):=IntToStr(intCount); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+11,m_intGongZuoLiang_Col):=IntToStr(intCount); ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; result:=0; end; procedure TGongZuoLiangTongJiForm.setJueSuanFieldName(iIndex: integer); begin if iIndex<=0 then m_JueSuan_FieldName := 'can_juesuan' else m_JueSuan_FieldName := 'can_juesuan' + IntToStr(iIndex); end; procedure TGongZuoLiangTongJiForm.FormCreate(Sender: TObject); begin setJueSuanFieldName(0); m_intBeginRowOfExcelFile :=3; m_intGeShu_Col := 6; m_intGongZuoLiang_Col := 7; m_strSQL_WhereClause_Drills_IsNot_JieKong := ' AND ((isJieKong is null) or (isJieKong<>'+BOOLEAN_True+'))'; end; function TGongZuoLiangTongJiForm.getAllBoreInfo_Jie(strProjectCode: string; intTag: integer): Integer; var ExcelApplication1:Variant; ExcelWorkbook1:Variant; range,sheet:Variant; xlsFileName:string; intDrillCount:Integer; //钻孔个数 dSumDrillDepth:Double; //钻孔总深度 intResult:integer; intRow,intCol:integer; strd_t_no:string; //钻孔型号编号 dblTmp:double; begin if intTag=2 then strd_t_no:='1,2,4,5'; //陆上孔 水上孔 if intTag=5 then strd_t_no:='6,7'; // 单桥 双桥 if intTag=7 then strd_t_no:='3'; // 麻花钻(小螺纹钻) //借孔统计 ADO02_All.Close; ADO02_All.SQL.Text:='select * from drills where '+m_JueSuan_FieldName+'=0 and prj_no=''' +strProjectCode+''' and d_t_no in ('+strd_t_no+')' + ' AND isJieKong='+BOOLEAN_True; ADO02_All.Open; intDrillCount := 0; dSumDrillDepth:= 0; while not ADO02_All.Recordset.eof do begin intDrillCount := intDrillCount +1; dSumDrillDepth := dSumDrillDepth + ADO02_All.fieldByName('comp_depth').AsFloat; ADO02_All.Next; end; ADO02_All.Close; //准备将数据写入统计EXCEL文件 ExcelApplication1:=CreateOleObject('Excel.Application'); ExcelWorkbook1:=CreateOleobject('Excel.Sheet'); xlsFileName:=m_FullFileName_TongJi; ExcelWorkbook1:=ExcelApplication1.workBooks.Open(xlsFileName); Sheet:= ExcelApplication1.Activesheet; ExcelApplication1.Cells(m_intBeginRowOfExcelFile+intTag, m_intGeShu_Col):= IntToStr(intDrillCount); ExcelApplication1.Cells(m_intBeginRowOfExcelFile+intTag, m_intGongZuoLiang_Col):= FormatFloat('0.00',dSumDrillDepth); ExcelWorkbook1.Save; ExcelWorkbook1.Close; ExcelApplication1.Quit; ExcelApplication1:=Unassigned; Result:=0; end; end.
unit ReportCashBookItem; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, ComCtrls, ToolWin; type TReportCashBookItemForm = class(TForm) Panel1: TPanel; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; ToolButton3: TToolButton; PayButton: TToolButton; PrintButton: TToolButton; DBGridEh1: TDBGridEh; CancelButton: TButton; OKButton: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OKButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ReportCashBookItemForm: TReportCashBookItemForm; implementation uses Main, StoreDM, ReportDM; {$R *.dfm} procedure TReportCashBookItemForm.FormCreate(Sender: TObject); begin { with ReportDataModule.CashBookDataSet do begin SelectSQL.Clear; SelectSQL.Add('SELECT *'); SelectSQL.Add('FROM "CashBook"'); SelectSQL.Add('WHERE "FirmID" = ' + IntToStr(MainFirm)); SelectSQL.Add('ORDER BY "Date"'); // ShowMessage(SQL.Text); Open; end;{} ReportDataModule.CashBookItemQuery.Open; Caption := 'Вкладной лист Кассовой книги'; end; procedure TReportCashBookItemForm.FormClose(Sender: TObject; var Action: TCloseAction); begin ReportDataModule.CashBookItemQuery.Close; Release; end; procedure TReportCashBookItemForm.OKButtonClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TReportCashBookItemForm.CancelButtonClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TReportCashBookItemForm.PrintButtonClick(Sender: TObject); begin // ReportDebtorPrintForm := TReportDebtorPrintForm.Create(Self); // ReportDebtorPrintForm.ShowModal; end; procedure TReportCashBookItemForm.Edit1Change(Sender: TObject); {var Find : String;{} begin { Find := AnsiUpperCase(Edit1.Text); with ReportDataModule.DebtorQuery do begin Close; SQL.Strings[2] := 'WHERE (UPPER("CustomerName" COLLATE PXW_CYRL) CONTAINING ''' + Find + ''')'; Open; end;{} end; procedure TReportCashBookItemForm.InsertButtonClick(Sender: TObject); begin // end; end.
PROGRAM proscore(input,output) VAR score:real; BEGIN writeln('Please enter a score'); read(score); writeln('score=',score); IF score>=90 THEN writeln('outstanding'); ELSE IF score>=60 THEN writeln('satisfactory') ELSE writeln('unsatisfactory') END.
unit uUsuario; interface uses uEmpresa; type TUsuario = class private codigo: Integer; ativo: char; nomeUsuario: String; login: String; senha: String; public // construtor da classe constructor TUsuarioCreate; // destrutor da classe destructor TUsuarioDestroy; // metodos "procedimento" set do Objeto procedure setCodigo(param: Integer); procedure setAtivo(param: char); procedure setNomeUsuario(param: String); procedure setLogin(param: String); procedure setSenha(param: String); // metodos "funcoes" get do Objeto function getCodigo: Integer; function getAtivo: char; function getNomeUsuario: String; function getLogin: String; function getSenha: String; end; var usuario :TUsuario; implementation { TUsuario implementacao dos metodos get e set } function TUsuario.getAtivo: char; begin Result := ativo; end; function TUsuario.getCodigo: Integer; begin Result := codigo; end; function TUsuario.getLogin: String; begin Result := login; end; function TUsuario.getNomeUsuario: String; begin Result := nomeUsuario; end; function TUsuario.getSenha: String; begin Result := senha; end; procedure TUsuario.setAtivo(param: char); begin ativo := param; end; procedure TUsuario.setCodigo(param: Integer); begin codigo := param; end; procedure TUsuario.setLogin(param: String); begin login := param; end; procedure TUsuario.setNomeUsuario(param: String); begin nomeUsuario := param; end; procedure TUsuario.setSenha(param: String); begin senha := param; end; constructor TUsuario.TUsuarioCreate; begin codigo := 0; nomeUsuario := ''; login := ''; senha := ''; end; destructor TUsuario.TUsuarioDestroy; begin FreeInstance; end; end.
unit DMMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComServ, ComObj, VCLCom, StdVcl, BdeProv, BdeMts, DataBkr, DBClient, MtsRdm, Mtx, MtsCustomerTreeProject_TLB, Db, DBTables, Provider, DMCustomerTreeU; type TMtsCustomerTree = class(TMtsDataModule, IMtsCustomerTree) procedure CustomerTreeDeactivate(Sender: TObject); procedure CustomerTreeActivate(Sender: TObject); private { Private declarations } Group: ISharedPropertyGroup; FDMCustomerTree: TDMCustomerTree; procedure CreateSharedProperties; function GetEditCustomerRole: WideString; function GetEmpNo: Integer; function GetDMCustomerTree: TDMCustomerTree; public { Public declarations } property DMCustomerTree: TDMCustomerTree read GetDMCustomerTree; protected function GetCustomersList: OleVariant; safecall; function GetCustomerTree(CustNo: Integer; MetaData: WordBool): OleVariant; safecall; procedure SetEmpNo(EmpNo: Integer); safecall; procedure SetMTSOptions(const RoleCanEdit: WideString); safecall; function ApplyCustomerTree(Delta: OleVariant; out ErrorCount: Integer): OleVariant; safecall; function GetPartsList: OleVariant; safecall; end; implementation {$R *.DFM} uses ActiveX; const { Shared property names } SEditCustomerRole = 'EditCustomerRole'; SEmpNo = 'EmpNo'; function TMtsCustomerTree.GetCustomersList: OleVariant; begin Result := DMCustomerTree.GetCustomersList; SetComplete; end; function TMtsCustomerTree.GetCustomerTree(CustNo: Integer; MetaData: WordBool): OleVariant; begin // DMCustomerTree.CanEditCustomer := IsCallerInRole(GetEditCustomerRole); Result := DMCustomerTree.GetCustomerOrdersTree(CustNo, MetaData); SetComplete; end; procedure TMtsCustomerTree.SetMTSOptions(const RoleCanEdit: WideString); begin if Assigned(Group) then Group.PropertyByName[sEditCustomerRole].Value := RoleCanEdit; SetComplete; end; procedure TMtsCustomerTree.CreateSharedProperties; const SQualifier = 'CustomerTree'; var W: PWideChar; Activity: IObjectContextActivity; Guid: TGuid; Exists: WordBool; begin if Assigned(ObjectContext) then begin ObjectContext.QueryInterface(IObjectContextActivity, Activity); if Assigned(Activity) then begin Guid := Activity.GetActivityId; StringFromCLSID(Guid, W); end else W := ''; Group := CreateSharedPropertyGroup(SQualifier + '.' + W); CoTaskMemFree(W); Group.CreateProperty(sEditCustomerRole, Exists); if not Exists then Group.PropertyByName[sEditCustomerRole].Value := ''; Group.CreateProperty(sEmpNo, Exists); if not Exists then Group.PropertyByName[sEmpNo].Value := 0; end; end; function TMtsCustomerTree.GetEditCustomerRole: WideString; begin if Assigned(Group) then Result := Group.PropertyByName[sEditCustomerRole].Value else Result := ''; end; function TMtsCustomerTree.GetEmpNo: Integer; begin if Assigned(Group) then Result := Group.PropertyByName[SEmpNo].Value else Result := 1; end; procedure TMtsCustomerTree.SetEmpNo(EmpNo: Integer); begin try DMCustomerTree.ValidateEmpNo(EmpNo); if Assigned(Group) then Group.PropertyByName[SEmpNo].Value := EmpNo; finally SetComplete; end; end; function TMtsCustomerTree.ApplyCustomerTree(Delta: OleVariant; out ErrorCount: Integer): OleVariant; begin Result := DMCustomerTree.ApplyCustomerTree(Delta, ErrorCount); end; procedure TMtsCustomerTree.CustomerTreeDeactivate(Sender: TObject); begin Group := nil; if Assigned(FDMCustomerTree) then FDMCustomerTree.Database1.Connected := False; end; function TMtsCustomerTree.GetPartsList: OleVariant; begin Result := DMCustomerTree.GetPartsList; end; function TMtsCustomerTree.GetDMCustomerTree: TDMCustomerTree; begin if not Assigned(FDMCustomerTree) then begin FDMCustomerTree := TDMCustomerTree.Create(nil); FDMCustomerTree.Database1.Connected := True; end; Result := FDMCustomerTree; end; procedure TMtsCustomerTree.CustomerTreeActivate(Sender: TObject); begin CreateSharedProperties; end; initialization TComponentFactory.Create(ComServer, TMtsCustomerTree, Class_MtsCustomerTree, ciMultiInstance, tmApartment); end.
// // Created by the DataSnap proxy generator. // 20/11/2016 06:38:13 // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminRestClient) private { FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; } FNovoUsuarioCommand: TDSRestCommand; FRemoveUsuarioCommand: TDSRestCommand; FAtualizaUsuarioCommand: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; { function EchoString(Value: string; const ARequestFilter: string = ''): string; function ReverseString(Value: string; const ARequestFilter: string = ''): string; } function NovoUsuario(Value: string; const ARequestFilter: string = ''): string; function RemoveUsuario(Value: string; const ARequestFilter: string = ''): string; function AtualizaUsuario(Value: string; const ARequestFilter: string = ''): string; end; const { TServerMethods1_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); } TServerMethods1_NovoUsuario: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_RemoveUsuario: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_AtualizaUsuario: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); implementation { function TServerMethods1Client.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare(TServerMethods1_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare(TServerMethods1_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; } function TServerMethods1Client.NovoUsuario(Value: string; const ARequestFilter: string): string; begin if FNovoUsuarioCommand = nil then begin FNovoUsuarioCommand := FConnection.CreateCommand; FNovoUsuarioCommand.RequestType := 'GET'; FNovoUsuarioCommand.Text := 'TServerMethods1.NovoUsuario'; FNovoUsuarioCommand.Prepare(TServerMethods1_NovoUsuario); end; FNovoUsuarioCommand.Parameters[0].Value.SetWideString(Value); FNovoUsuarioCommand.Execute(ARequestFilter); Result := FNovoUsuarioCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.RemoveUsuario(Value: string; const ARequestFilter: string): string; begin if FRemoveUsuarioCommand = nil then begin FRemoveUsuarioCommand := FConnection.CreateCommand; FRemoveUsuarioCommand.RequestType := 'GET'; FRemoveUsuarioCommand.Text := 'TServerMethods1.RemoveUsuario'; FRemoveUsuarioCommand.Prepare(TServerMethods1_RemoveUsuario); end; FRemoveUsuarioCommand.Parameters[0].Value.SetWideString(Value); FRemoveUsuarioCommand.Execute(ARequestFilter); Result := FRemoveUsuarioCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.AtualizaUsuario(Value: string; const ARequestFilter: string): string; begin if FAtualizaUsuarioCommand = nil then begin FAtualizaUsuarioCommand := FConnection.CreateCommand; FAtualizaUsuarioCommand.RequestType := 'GET'; FAtualizaUsuarioCommand.Text := 'TServerMethods1.AtualizaUsuario'; FAtualizaUsuarioCommand.Prepare(TServerMethods1_AtualizaUsuario); end; FAtualizaUsuarioCommand.Parameters[0].Value.SetWideString(Value); FAtualizaUsuarioCommand.Execute(ARequestFilter); Result := FAtualizaUsuarioCommand.Parameters[1].Value.GetWideString; end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin { FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; } FNovoUsuarioCommand.DisposeOf; FRemoveUsuarioCommand.DisposeOf; FAtualizaUsuarioCommand.DisposeOf; inherited; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLTexLensFlare<p> Texture-based Lens flare object.<p> <b>History : </b><font size=-1><ul> <li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>30/03/07 - DaStr - Added $I GLScene.inc <li>23/03/07 - DaStr - Added missing parameters in procedure's implementation (thanks Burkhard Carstens) (Bugtracker ID = 1681409) <li>25/09/03 - EG - Creation from GLLensFlare split </ul></font><p> } unit GLTexLensFlare; interface {$I GLScene.inc} uses System.Classes, GLScene, GLVectorGeometry, GLObjects, GLTexture, OpenGLTokens, GLContext, GLRenderContextInfo, GLBaseClasses, GLState, GLVectorTypes; type // TGLTextureLensFlare // TGLTextureLensFlare = class(TGLBaseSceneObject) private { Private Declarations } FSize: integer; FCurrSize: Single; FNumSecs: integer; FAutoZTest: boolean; //used for internal calculation FDeltaTime: Double; FImgSecondaries: TGLTexture; FImgRays: TGLTexture; FImgRing: TGLTexture; FImgGlow: TGLTexture; FSeed: Integer; procedure SetImgGlow(const Value: TGLTexture); procedure SetImgRays(const Value: TGLTexture); procedure SetImgRing(const Value: TGLTexture); procedure SetImgSecondaries(const Value: TGLTexture); procedure SetSeed(const Value: Integer); protected { Protected Declarations } procedure SetSize(aValue: integer); procedure SetNumSecs(aValue: integer); procedure SetAutoZTest(aValue: boolean); public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BuildList(var rci: TRenderContextInfo); override; procedure DoProgress(const progressTime: TProgressTimes); override; published { Public Declarations } //: MaxRadius of the flare. property Size: integer read FSize write SetSize default 50; //: Random seed property Seed: Integer read FSeed write SetSeed; //: Number of secondary flares. property NumSecs: integer read FNumSecs write SetNumSecs default 8; //: Number of segments used when rendering circles. //property Resolution: integer read FResolution write SetResolution default 64; property AutoZTest: boolean read FAutoZTest write SetAutoZTest default True; // The Textures property ImgGlow: TGLTexture read FImgGlow write SetImgGlow; property ImgRays: TGLTexture read FImgRays write SetImgRays; property ImgRing: TGLTexture read FImgRing write SetImgRing; property ImgSecondaries: TGLTexture read FImgSecondaries write SetImgSecondaries; property ObjectsSorting; property Position; property Visible; property OnProgress; property Behaviours; property Effects; end; implementation // ------------------ // ------------------ TGLTextureLensFlare ------------------ // ------------------ constructor TGLTextureLensFlare.Create(AOwner: TComponent); begin inherited; Randomize; FSeed := Random(2000) + 465; // Set default parameters: ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling]; FSize := 50; FCurrSize := FSize; FNumSecs := 8; FAutoZTest := True; FImgRays := TGLTexture.Create(Self); FImgSecondaries := TGLTexture.Create(Self); FImgRing := TGLTexture.Create(Self); FImgGlow := TGLTexture.Create(Self); end; procedure TGLTextureLensFlare.SetSize(aValue: integer); begin if FSize <> aValue then begin FSize := aValue; FCurrSize := FSize; StructureChanged; end; end; procedure TGLTextureLensFlare.SetNumSecs(aValue: integer); begin if FNumSecs <> aValue then begin FNumSecs := aValue; StructureChanged; end; end; // SetAutoZTest // procedure TGLTextureLensFlare.SetAutoZTest(aValue: boolean); begin if FAutoZTest <> aValue then begin FAutoZTest := aValue; StructureChanged; end; end; // BuildList // procedure TGLTextureLensFlare.BuildList(var rci: TRenderContextInfo); var v, rv, screenPos, posVector: TAffineVector; depth, rnd: Single; flag: Boolean; i: Integer; CurrentBuffer: TGLSceneBuffer; begin CurrentBuffer := TGLSceneBuffer(rci.buffer); SetVector(v, AbsolutePosition); // are we looking towards the flare? rv := VectorSubtract(v, PAffineVector(@rci.cameraPosition)^); if VectorDotProduct(rci.cameraDirection, rv) > 0 then begin // find out where it is on the screen. screenPos := CurrentBuffer.WorldToScreen(v); if (screenPos.V[0] < rci.viewPortSize.cx) and (screenPos.V[0] >= 0) and (screenPos.V[1] < rci.viewPortSize.cy) and (screenPos.V[1] >= 0) then begin if FAutoZTest then begin depth := CurrentBuffer.GetPixelDepth(Round(ScreenPos.V[0]), Round(rci.viewPortSize.cy - ScreenPos.V[1])); // but is it behind something? if screenPos.V[2] >= 1 then flag := (depth >= 1) else flag := (depth >= screenPos.V[2]); end else flag := True; end else flag := False; end else flag := False; MakeVector(posVector, screenPos.V[0] - rci.viewPortSize.cx / 2, screenPos.V[1] - rci.viewPortSize.cy / 2, 0); // make the glow appear/disappear progressively if Flag then if FCurrSize < FSize then FCurrSize := FCurrSize + FDeltaTime * 200 {FSize * 4}; if not Flag then if FCurrSize > 0 then FCurrSize := FCurrSize - FDeltaTime * 200 {FSize * 4}; if FCurrSize <= 0 then Exit; // Prepare matrices GL.MatrixMode(GL_MODELVIEW); GL.PushMatrix; GL.LoadMatrixf(@CurrentBuffer.BaseProjectionMatrix); GL.MatrixMode(GL_PROJECTION); GL.PushMatrix; GL.LoadIdentity; GL.Scalef(2 / rci.viewPortSize.cx, 2 / rci.viewPortSize.cy, 1); rci.GLStates.Disable(stLighting); rci.GLStates.Disable(stDepthTest); rci.GLStates.Enable(stBlend); rci.GLStates.SetBlendFunc(bfOne, bfOne); //Rays and Glow on Same Position GL.PushMatrix; GL.Translatef(posVector.V[0], posVector.V[1], posVector.V[2]); if not ImgGlow.Disabled and Assigned(ImgGlow.Image) then begin ImgGlow.Apply(rci); GL.begin_(GL_QUADS); GL.TexCoord2f(0, 0); GL.Vertex3f(-FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 0); GL.Vertex3f(FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 1); GL.Vertex3f(FCurrSize, FCurrSize, 0); GL.TexCoord2f(0, 1); GL.Vertex3f(-FCurrSize, FCurrSize, 0); GL.end_; ImgGlow.UnApply(rci); end; if not ImgRays.Disabled and Assigned(ImgRays.Image) then begin ImgRays.Apply(rci); GL.begin_(GL_QUADS); GL.TexCoord2f(0, 0); GL.Vertex3f(-FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 0); GL.Vertex3f(FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 1); GL.Vertex3f(FCurrSize, FCurrSize, 0); GL.TexCoord2f(0, 1); GL.Vertex3f(-FCurrSize, FCurrSize, 0); GL.end_; ImgRays.UnApply(rci); end; GL.PopMatrix; if not ImgRing.Disabled and Assigned(ImgRing.Image) then begin GL.PushMatrix; GL.Translatef(posVector.V[0] * 1.1, posVector.V[1] * 1.1, posVector.V[2]); ImgRing.Apply(rci); GL.begin_(GL_QUADS); GL.TexCoord2f(0, 0); GL.Vertex3f(-FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 0); GL.Vertex3f(FCurrSize, -FCurrSize, 0); GL.TexCoord2f(1, 1); GL.Vertex3f(FCurrSize, FCurrSize, 0); GL.TexCoord2f(0, 1); GL.Vertex3f(-FCurrSize, FCurrSize, 0); GL.end_; ImgRing.UnApply(rci); GL.PopMatrix; end; if not ImgSecondaries.Disabled and Assigned(ImgSecondaries.Image) then begin RandSeed := FSeed; GL.PushMatrix; ImgSecondaries.Apply(rci); for i := 1 to FNumSecs do begin rnd := 2 * Random - 1; v := PosVector; if rnd < 0 then ScaleVector(V, rnd) else ScaleVector(V, 0.8 * rnd); GL.PushMatrix; GL.Translatef(v.V[0], v.V[1], v.V[2]); rnd := random * 0.5 + 0.1; GL.begin_(GL_QUADS); GL.TexCoord2f(0, 0); GL.Vertex3f(-FCurrSize * rnd, -FCurrSize * rnd, 0); GL.TexCoord2f(1, 0); GL.Vertex3f(FCurrSize * rnd, -FCurrSize * rnd, 0); GL.TexCoord2f(1, 1); GL.Vertex3f(FCurrSize * rnd, FCurrSize * rnd, 0); GL.TexCoord2f(0, 1); GL.Vertex3f(-FCurrSize * rnd, FCurrSize * rnd, 0); GL.end_; GL.PopMatrix end; ImgSecondaries.UnApply(rci); GL.PopMatrix; end; // restore state GL.PopMatrix; GL.MatrixMode(GL_MODELVIEW); GL.PopMatrix; if Count > 0 then Self.RenderChildren(0, Count - 1, rci); end; // DoProgress // procedure TGLTextureLensFlare.DoProgress(const progressTime: TProgressTimes); begin FDeltaTime := progressTime.deltaTime; inherited; end; procedure TGLTextureLensFlare.SetImgGlow(const Value: TGLTexture); begin FImgGlow.Assign(Value); StructureChanged; end; procedure TGLTextureLensFlare.SetImgRays(const Value: TGLTexture); begin FImgRays.Assign(Value); StructureChanged; end; procedure TGLTextureLensFlare.SetImgRing(const Value: TGLTexture); begin FImgRing.Assign(Value); StructureChanged; end; procedure TGLTextureLensFlare.SetImgSecondaries(const Value: TGLTexture); begin FImgSecondaries.Assign(Value); StructureChanged; end; destructor TGLTextureLensFlare.Destroy; begin FImgRays.Free; FImgSecondaries.Free; FImgRing.Free; FImgGlow.Free; inherited; end; procedure TGLTextureLensFlare.SetSeed(const Value: Integer); begin FSeed := Value; StructureChanged; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClasses([TGLTextureLensFlare]); end.
unit ADAPT.Demo.PrecisionThreads.TestThread; {$I ADAPT.inc} interface uses System.Classes, System.SysUtils, ADAPT.Intf, ADAPT, ADAPT.Threads, ADAPT.Collections.Intf; type TTestPerformanceData = record DesiredTickRate: ADFloat; ExtraTime: ADFloat; TickRateLimit: ADFloat; TickRate: ADFloat; TickRateAverage: ADFloat; TickRateAverageOver: Cardinal; end; ITestPerformanceSummary = interface(IADInterface) ['{E3C3E313-9B0D-4442-880D-E4561587957B}'] // Getters function GetDesiredTickRateMax: ADFloat; function GetDesiredTickRateMin: ADFloat; function GetExtraTimeMax: ADFloat; function GetExtraTimeMin: ADFLoat; function GetTickRateLimitMax: ADFloat; function GetTickRateLimitMin: ADFloat; function GetTickRateMax: ADFloat; function GetTickRateMin: ADFloat; function GetTickRateAverageMax: ADFloat; function GetTickRateAverageMin: ADFloat; function GetTickRateAverageOverMax: Cardinal; function GetTickRateAverageOverMin: Cardinal; // Setters procedure SetDesiredTickRateMax(const ADesiredTickRateMax: ADFloat); procedure SetDesiredTickRateMin(const ADesiredTickRateMin: ADFloat); procedure SetExtraTimeMax(const AExtraTimeMax: ADFloat); procedure SetExtraTimeMin(const AExtraTimeMin: ADFloat); procedure SetTickRateLimitMax(const ATickRateLimitMax: ADFloat); procedure SetTickRateLimitMin(const ATickRateLimitMin: ADFloat); procedure SetTickRateMax(const ATickRateMax: ADFloat); procedure SetTickRateMin(const ATickRateMin: ADFloat); procedure SetTickRateAverageMax(const ATickRateAverageMax: ADFloat); procedure SetTickRateAverageMin(const ATickRateAverageMin: ADFloat); procedure SetTickRateAverageOverMax(const ATickRateAverageOverMax: Cardinal); procedure SetTickRateAverageOverMin(const ATickRateAverageOverMin: Cardinal); // Properties property DesiredTickRateMax: ADFloat read GetDesiredTickRateMax write SetDesiredTickRateMax; property DesiredTickRateMin: ADFloat read GetDesiredTickRateMin write SetDesiredTickRateMin; property ExtraTimeMax: ADFloat read GetExtraTimeMax write SetExtraTimeMax; property ExtraTimeMin: ADFloat read GetExtraTimeMin write SetExtraTimeMin; property TickRateLimitMax: ADFloat read GetTickRateLimitMax write SetTickRateLimitMax; property TickRateLimitMin: ADFloat read GetTickRateLimitMin write SetTickRateLimitMin; property TickRateMax: ADFloat read GetTickRateMax write SetTickRateMax; property TickRateMin: ADFloat read GetTickRateMin write SetTickRateMin; property TickRateAverageMax: ADFloat read GetTickRateAverageMax write SetTickRateAverageMax; property TickRateAverageMin: ADFloat read GetTickRateAverageMin write SetTickRateAverageMin; property TickRateAverageOverMax: Cardinal read GetTickRateAverageOverMax write SetTickRateAverageOverMax; property TickRateAverageOverMin: Cardinal read GetTickRateAverageOverMin write SetTickRateAverageOverMin; end; TTestPerformanceSummary = class(TADObject, ITestPerformanceSummary) private FDesiredTickRateMax, FDesiredTickRateMin: ADFloat; FExtraTimeMax, FExtraTimeMin: ADFloat; FTickRateLimitMax, FTickRateLimitMin: ADFloat; FTickRateMax, FTickRateMin: ADFloat; FTickRateAverageMax, FTickRateAverageMin: ADFloat; FTickRateAverageOverMax, FTickRateAverageOVerMin: Cardinal; // Getters { ITestPerformanceSummary } function GetDesiredTickRateMax: ADFloat; function GetDesiredTickRateMin: ADFloat; function GetExtraTimeMax: ADFloat; function GetExtraTimeMin: ADFLoat; function GetTickRateLimitMax: ADFloat; function GetTickRateLimitMin: ADFloat; function GetTickRateMax: ADFloat; function GetTickRateMin: ADFloat; function GetTickRateAverageMax: ADFloat; function GetTickRateAverageMin: ADFloat; function GetTickRateAverageOverMax: Cardinal; function GetTickRateAverageOverMin: Cardinal; // Setters { ITestPerformanceSummary } procedure SetDesiredTickRateMax(const ADesiredTickRateMax: ADFloat); procedure SetDesiredTickRateMin(const ADesiredTickRateMin: ADFloat); procedure SetExtraTimeMax(const AExtraTimeMax: ADFloat); procedure SetExtraTimeMin(const AExtraTimeMin: ADFloat); procedure SetTickRateLimitMax(const ATickRateLimitMax: ADFloat); procedure SetTickRateLimitMin(const ATickRateLimitMin: ADFloat); procedure SetTickRateMax(const ATickRateMax: ADFloat); procedure SetTickRateMin(const ATickRateMin: ADFloat); procedure SetTickRateAverageMax(const ATickRateAverageMax: ADFloat); procedure SetTickRateAverageMin(const ATickRateAverageMin: ADFloat); procedure SetTickRateAverageOverMax(const ATickRateAverageOverMax: Cardinal); procedure SetTickRateAverageOverMin(const ATickRateAverageOverMin: Cardinal); public constructor Create(const AFirstValues: TTestPerformanceData); reintroduce; // Properties { ITestPerformanceSummary } property DesiredTickRateMax: ADFloat read GetDesiredTickRateMax write SetDesiredTickRateMax; property DesiredTickRateMin: ADFloat read GetDesiredTickRateMin write SetDesiredTickRateMin; property ExtraTimeMax: ADFloat read GetExtraTimeMax write SetExtraTimeMax; property ExtraTimeMin: ADFloat read GetExtraTimeMin write SetExtraTimeMin; property TickRateLimitMax: ADFloat read GetTickRateLimitMax write SetTickRateLimitMax; property TickRateLimitMin: ADFloat read GetTickRateLimitMin write SetTickRateLimitMin; property TickRateMax: ADFloat read GetTickRateMax write SetTickRateMax; property TickRateMin: ADFloat read GetTickRateMin write SetTickRateMin; property TickRateAverageMax: ADFloat read GetTickRateAverageMax write SetTickRateAverageMax; property TickRateAverageMin: ADFloat read GetTickRateAverageMin write SetTickRateAverageMin; property TickRateAverageOverMax: Cardinal read GetTickRateAverageOverMax write SetTickRateAverageOverMax; property TickRateAverageOverMin: Cardinal read GetTickRateAverageOverMin write SetTickRateAverageOverMin; end; ITestPerformanceDataCircularList = IADCircularList<TTestPerformanceData>; TTestTickCallback = procedure(const APerformanceLog: ITestPerformanceDataCircularList; const APerformanceSummary: ITestPerformanceSummary) of object; // Our Callback Type. { This Test Thread simply builds a historical dataset of Thread Performance Data. A Notify Event is called (if Assigned, of course) to output/consume this historical Performance Data. This Test Thread is designed to supplement a "Unit Test", since Unit Tests don't work in the context of a multi-threaded system. } TTestThread = class(TADPrecisionThread) private FPerformanceData: ITestPerformanceDataCircularList; FTickCallback: TTestTickCallback; FWorkSimMax: Integer; // Getters function GetHistoryLimit: Integer; function GetTickCallback: TTestTickCallback; // Setters procedure SetHistoryLimit(const AHistoryLimit: Integer); procedure SetTickCallback(const ACallback: TTestTickCallback); procedure SetWorkSimMax(const AWorkSimMax: Integer); // Internal Methods procedure LogPerformanceData; procedure InvokeCallbackIfAssigned; protected { TADPrecisionThread } function GetDefaultTickRateAverageOver: Cardinal; override; function GetDefaultTickRateLimit: ADFloat; override; function GetDefaultTickRateDesired: ADFloat; override; procedure Tick(const ADelta, AStartTime: ADFloat); override; public constructor Create(const ACreateSuspended: Boolean); override; // Properties property HistoryLimit: Integer read GetHistoryLimit write SetHistoryLimit; property TickCallback: TTestTickCallback read GetTickCallback write SetTickCallback; property WorkSimMax: Integer write FWorkSimMax; end; implementation uses ADAPT.Collections; type TTestPerformanceDataCircularList = class(TADCircularList<TTestPerformanceData>); { TTestPerformanceSummary } constructor TTestPerformanceSummary.Create(const AFirstValues: TTestPerformanceData); begin inherited Create; FDesiredTickRateMax := AFirstValues.DesiredTickRate; FDesiredTickRateMin := AFirstValues.DesiredTickRate; FExtraTimeMax := AFirstValues.ExtraTime; FExtraTimeMin := AFirstValues.ExtraTime; FTickRateLimitMax := AFirstValues.TickRateLimit; FTickRateLimitMin := AFirstValues.TickRateLimit; FTickRateMax := AFirstValues.TickRate; FTickRateMin := AFirstValues.TickRate; FTickRateAverageMax := AFirstValues.TickRateAverage; FTickRateAverageMin := AFirstValues.TickRateAverage; FTickRateAverageOverMax := AFirstValues.TickRateAverageOver; FTickRateAverageOVerMin := AFirstValues.TickRateAverageOver; end; function TTestPerformanceSummary.GetDesiredTickRateMax: ADFloat; begin Result := FDesiredTickRateMax; end; function TTestPerformanceSummary.GetDesiredTickRateMin: ADFloat; begin Result := FDesiredTickRateMin; end; function TTestPerformanceSummary.GetExtraTimeMax: ADFloat; begin Result := FExtraTimeMax; end; function TTestPerformanceSummary.GetExtraTimeMin: ADFLoat; begin Result := FExtraTimeMin; end; function TTestPerformanceSummary.GetTickRateAverageMax: ADFloat; begin Result := FTickRateAverageMax; end; function TTestPerformanceSummary.GetTickRateAverageMin: ADFloat; begin Result := FTickRateAverageMin; end; function TTestPerformanceSummary.GetTickRateAverageOverMax: Cardinal; begin Result := FTickRateAverageOverMax; end; function TTestPerformanceSummary.GetTickRateAverageOverMin: Cardinal; begin Result := FTickRateAverageOverMin; end; function TTestPerformanceSummary.GetTickRateLimitMax: ADFloat; begin Result := FTickRateLimitMax; end; function TTestPerformanceSummary.GetTickRateLimitMin: ADFloat; begin Result := FTickRateLimitMin; end; function TTestPerformanceSummary.GetTickRateMax: ADFloat; begin Result := FTickRateMax; end; function TTestPerformanceSummary.GetTickRateMin: ADFloat; begin Result := FTickRateMin; end; procedure TTestPerformanceSummary.SetDesiredTickRateMax(const ADesiredTickRateMax: ADFloat); begin FDesiredTickRateMax := ADesiredTickRateMax; end; procedure TTestPerformanceSummary.SetDesiredTickRateMin(const ADesiredTickRateMin: ADFloat); begin FDesiredTickRateMin := ADesiredTickRateMin; end; procedure TTestPerformanceSummary.SetExtraTimeMax(const AExtraTimeMax: ADFloat); begin FExtraTimeMax := AExtraTimeMax; end; procedure TTestPerformanceSummary.SetExtraTimeMin(const AExtraTimeMin: ADFloat); begin FExtraTimeMin := AExtraTimeMin; end; procedure TTestPerformanceSummary.SetTickRateAverageMax(const ATickRateAverageMax: ADFloat); begin FTickRateAverageMax := ATickRateAverageMax; end; procedure TTestPerformanceSummary.SetTickRateAverageMin(const ATickRateAverageMin: ADFloat); begin FTickRateAverageMin := ATickRateAverageMin; end; procedure TTestPerformanceSummary.SetTickRateAverageOverMax(const ATickRateAverageOverMax: Cardinal); begin FTickRateAverageOverMax := ATickRateAverageOverMax; end; procedure TTestPerformanceSummary.SetTickRateAverageOverMin(const ATickRateAverageOverMin: Cardinal); begin FTickRateAverageOverMin := ATickRateAverageOverMin; end; procedure TTestPerformanceSummary.SetTickRateLimitMax(const ATickRateLimitMax: ADFloat); begin FTickRateLimitMax := ATickRateLimitMax; end; procedure TTestPerformanceSummary.SetTickRateLimitMin(const ATickRateLimitMin: ADFloat); begin FTickRateLimitMin := ATickRateLimitMin; end; procedure TTestPerformanceSummary.SetTickRateMax(const ATickRateMax: ADFloat); begin FTickRateMax := ATickRateMax; end; procedure TTestPerformanceSummary.SetTickRateMin(const ATickRateMin: ADFloat); begin FTickRateMin := ATickRateMin; end; { TTestThread } constructor TTestThread.Create(const ACreateSuspended: Boolean); begin inherited; FPerformanceData := TTestPerformanceDataCircularList.Create(50); FWorkSimMax := 50; end; function TTestThread.GetDefaultTickRateAverageOver: Cardinal; begin Result := 50; end; function TTestThread.GetDefaultTickRateDesired: ADFloat; begin Result := 30; { Remember that a "Desired" Tick Rate is NOT the same as a "Tick Rate Limit". We might want to have NO Rate Limit, but still desire a MINIMUM rate. This information can then be used to calculate any "extra time" available on a Tick, which can be used to perform optional "additional processing". } end; function TTestThread.GetDefaultTickRateLimit: ADFloat; begin Result := 60; // We default the demo to 60 ticks per second. end; function TTestThread.GetHistoryLimit: Integer; begin FLock.AcquireRead; try Result := FPerformanceData.Capacity; finally FLock.ReleaseRead; end; end; function TTestThread.GetTickCallback: TTestTickCallback; begin FLock.AcquireRead; // This needs to be "Threadsafe" try Result := FTickCallback; finally FLock.ReleaseRead; end; end; procedure TTestThread.InvokeCallbackIfAssigned; var LPerformanceData: ITestPerformanceDataCircularList; LPerformanceSummary: ITestPerformanceSummary; I: Integer; begin if FPerformanceData.Count > 0 then begin FLock.AcquireRead; // We acquire the Lock so that the Callback cannot be changed while we're using it... try LPerformanceData := TTestPerformanceDataCircularList.Create(FPerformanceData.Capacity); LPerformanceSummary := TTestPerformanceSummary.Create(FPerformanceData[0]); for I := 0 to FPerformanceData.Count - 1 do begin LPerformanceData.Add(FPerformanceData[I]); if I > 0 then begin // Desired Tick Rate if FPerformanceData[I].DesiredTickRate > LPerformanceSummary.DesiredTickRateMax then LPerformanceSummary.DesiredTickRateMax := FPerformanceData[I].DesiredTickRate; if FPerformanceData[I].DesiredTickRate < LPerformanceSummary.DesiredTickRateMin then LPerformanceSummary.DesiredTickRateMin := FPerformanceData[I].DesiredTickRate; // Extra Time if FPerformanceData[I].ExtraTime > LPerformanceSummary.ExtraTimeMax then LPerformanceSummary.ExtraTimeMax := FPerformanceData[I].ExtraTime; if FPerformanceData[I].ExtraTime < LPerformanceSummary.ExtraTimeMin then LPerformanceSummary.ExtraTimeMin := FPerformanceData[I].ExtraTime; // Tick Rate Limit if FPerformanceData[I].TickRateLimit > LPerformanceSummary.TickRateLimitMax then LPerformanceSummary.TickRateLimitMax := FPerformanceData[I].TickRateLimit; if FPerformanceData[I].TickRateLimit < LPerformanceSummary.TickRateLimitMin then LPerformanceSummary.TickRateLimitMin := FPerformanceData[I].TickRateLimit; // Tick Rate if FPerformanceData[I].TickRate > LPerformanceSummary.TickRateMax then LPerformanceSummary.TickRateMax := FPerformanceData[I].TickRate; if FPerformanceData[I].TickRate < LPerformanceSummary.TickRateMin then LPerformanceSummary.TickRateMin := FPerformanceData[I].TickRate; // Tick Rate Average if FPerformanceData[I].TickRateAverage > LPerformanceSummary.TickRateAverageMax then LPerformanceSummary.TickRateMax := FPerformanceData[I].TickRateAverage; if FPerformanceData[I].TickRateAverage < LPerformanceSummary.TickRateAverageMin then LPerformanceSummary.TickRateAverageMin := FPerformanceData[I].TickRateAverage; // Tick Rate Average Over if FPerformanceData[I].TickRateAverageOver > LPerformanceSummary.TickRateAverageOverMax then LPerformanceSummary.TickRateAverageOverMax := FPerformanceData[I].TickRateAverageOver; if FPerformanceData[I].TickRateAverageOver < LPerformanceSummary.TickRateAverageOverMin then LPerformanceSummary.TickRateAverageOverMin := FPerformanceData[I].TickRateAverageOver; end; end; finally FLock.ReleaseRead; // ...Now we can release the Lock as we're done with the Callback. end; if Assigned(FTickCallback) then // We need to check that the Callback has been Assigned Synchronize(procedure // We Synchronize the Callback because our Demo consumes it on the UI Thread. begin FTickCallback(LPerformanceData, LPerformanceSummary); // Invoke the Callback... end); end; end; procedure TTestThread.LogPerformanceData; var LPerformanceData: TTestPerformanceData; begin FLock.AcquireRead; // We acquire the Lock so that the Callback cannot be changed while we're using it... try LPerformanceData.DesiredTickRate := TickRateDesired; LPerformanceData.ExtraTime := CalculateExtraTime; LPerformanceData.TickRateLimit := TickRateLimit; LPerformanceData.TickRate := TickRate; LPerformanceData.TickRateAverage := TickRateAverage; LPerformanceData.TickRateAverageOver := TickRateAverageOver; finally FLock.ReleaseRead; // ...Now we can release the Lock as we're done with the Callback. end; FPerformanceData.Add(LPerformanceData); end; procedure TTestThread.SetHistoryLimit(const AHistoryLimit: Integer); begin FLock.AcquireWrite; try FPerformanceData.Capacity := AHistoryLimit; finally FLock.ReleaseWrite; end; end; procedure TTestThread.SetTickCallback(const ACallback: TTestTickCallback); begin FLock.AcquireWrite; // This needs to be "Threadsafe" try FTickCallback := ACallback; finally FLock.ReleaseWrite; end; end; procedure TTestThread.SetWorkSimMax(const AWorkSimMax: Integer); begin FWorkSimMax := AWorkSimMax; end; procedure TTestThread.Tick(const ADelta, AStartTime: ADFloat); begin // Update Historical Performance Dataset LogPerformanceData; // Notify the Callback to consume the updated Performance Dataset InvokeCallbackIfAssigned; // Simulate some work Sleep(Random(FWorkSimMax)); end; end.
unit BrickCamp.IRedisRepository; interface type IRedisRepository = interface ['{12C2DA6A-ADD0-4097-9FC5-115CCAA7797D}'] function Connnect : Boolean; function SetValue(Keyname : String; Value : String) : Boolean; function GetValue(Keyname : String; var Value : String) : Boolean; end; implementation end.
{*******************************************************} { } { Midas RemoteDataModule Pooler Demo } { } {*******************************************************} unit Pooler; interface uses ComObj, ActiveX, Server_TLB, Classes, SyncObjs, Windows; type { This is the pooler class. It is resonsible for managing the pooled RDMs. It implements the same interface as the RDM does, and each call will get an unused RDM and use it for the call. } TPooler = class(TAutoObject, IPooledRDM) protected { IDataBroker } function GetProviderNames: OleVariant; safecall; { IPooledRDM } procedure Select(const SQLStr: WideString; out Data: OleVariant); safecall; function LockRDM: IPooledRDM; procedure UnlockRDM(Value: IPooledRDM); end; { The pool manager is responsible for keeping a list of RDMs that are being pooled and for giving out unused RDMs. } TPoolManager = class(TObject) private FRDMList: TList; FMaxCount: Integer; FTimeout: Integer; FCriticalSection: TCriticalSection; FSemaphore: THandle; function GetLock(Index: Integer): Boolean; procedure ReleaseLock(Index: Integer; var Value: IPooledRDM); function CreateNewInstance: IPooledRDM; public constructor Create; destructor Destroy; override; function LockRDM: IPooledRDM; procedure UnlockRDM(var Value: IPooledRDM); property Timeout: Integer read FTimeout; property MaxCount: Integer read FMaxCount; end; PRDM = ^TRDM; TRDM = record Intf: IPooledRDM; InUse: Boolean; end; var PoolManager: TPoolManager; implementation uses ComServ, SrvrDM, SysUtils, ThrddCF; constructor TPoolManager.Create; begin FRDMList := TList.Create; FCriticalSection := TCriticalSection.Create; FTimeout := 5000; FMaxCount := 15; FSemaphore := CreateSemaphore(nil, FMaxCount, FMaxCount, nil); end; destructor TPoolManager.Destroy; var i: Integer; begin FCriticalSection.Free; for i := 0 to FRDMList.Count - 1 do begin PRDM(FRDMList[i]).Intf := nil; FreeMem(PRDM(FRDMList[i])); end; FRDMList.Free; CloseHandle(FSemaphore); inherited Destroy; end; function TPoolManager.GetLock(Index: Integer): Boolean; begin FCriticalSection.Enter; try Result := not PRDM(FRDMList[Index]).InUse; if Result then PRDM(FRDMList[Index]).InUse := True; finally FCriticalSection.Leave; end; end; procedure TPoolManager.ReleaseLock(Index: Integer; var Value: IPooledRDM); begin FCriticalSection.Enter; try PRDM(FRDMList[Index]).InUse := False; Value := nil; ReleaseSemaphore(FSemaphore, 1, nil); finally FCriticalSection.Leave; end; end; function TPoolManager.CreateNewInstance: IPooledRDM; var p: PRDM; begin FCriticalSection.Enter; try New(p); p.Intf := RDMFactory.CreateComObject(nil) as IPooledRDM; p.InUse := True; FRDMList.Add(p); Result := p.Intf; finally FCriticalSection.Leave; end; end; function TPoolManager.LockRDM: IPooledRDM; var i: Integer; begin Result := nil; if WaitForSingleObject(FSemaphore, Timeout) = WAIT_FAILED then raise Exception.Create('Server too busy'); for i := 0 to FRDMList.Count - 1 do begin if GetLock(i) then begin Result := PRDM(FRDMList[i]).Intf; Exit; end; end; if FRDMList.Count < MaxCount then Result := CreateNewInstance; if Result = nil then { This shouldn't happen because of the sempahore locks } raise Exception.Create('Unable to lock RDM'); end; procedure TPoolManager.UnlockRDM(var Value: IPooledRDM); var i: Integer; begin for i := 0 to FRDMList.Count - 1 do begin if Value = PRDM(FRDMList[i]).Intf then begin ReleaseLock(i, Value); break; end; end; end; { Each call for the server is wrapped in a call to retrieve the RDM, and then when it is finished it releases the RDM. } function TPooler.GetProviderNames: OleVariant; var RDM: IPooledRDM; begin RDM := LockRDM; try Result := RDM.GetProviderNames; finally UnlockRDM(RDM); end; end; procedure TPooler.Select(const SQLStr: WideString; out Data: OleVariant); var RDM: IPooledRDM; begin RDM := LockRDM; try RDM.Select(SQLStr, Data); finally UnlockRDM(RDM); end; end; function TPooler.LockRDM: IPooledRDM; begin Result := PoolManager.LockRDM; end; procedure TPooler.UnlockRDM(Value: IPooledRDM); begin PoolManager.UnlockRDM(Value); end; initialization PoolManager := TPoolManager.Create; TThreadedAutoObjectFactory.Create(ComServer, TPooler, Class_Pooler, ciMultiInstance); finalization PoolManager.Free; end.
unit Style.Login; interface uses System.classes, System.SysUtils, FMX.Forms; type TStyleLogin = class(TForm) public const // Style Header and Footer... LyTopAndButtom = $FF802280; // Style Body... LyBody = $FFFFFFFF; // Style Label Title... LbTitleTextLogin = 'Login'; LbTitleTextMenu = 'Idea Developer'; LbColor = $FFF4EAF4; LbFontSize = 24 ; LbHeightSize = 40 ; LbWidthSize = 200; // Text Align... LbTextAlign = 'Certer'; // Style RCEdits... RcBorderRadius = 25; RcBackground = $FFFFFFFF; // Style Line... RcLineLeftAndRight = 25; // Style Edits... EdtAling = 'Client'; EdtMargem = 3; EdtTextPromptLogin = 'Login'; EdtTextPromptSenha = 'Senha'; EdiTextColor = $AA802280; end; implementation uses FMX.StdCtrls; { TStyleLogin } end.
{ Include file for the downstream interface of the CAN library. This * interface is for optional use by subsystems that provide device dependent * CAN I/O. * * The CAN library presents device independent CAN I/O to applications. The * unique handlers for each of the supported device dependent CAN I/O * subsystems are built into the CAN library. This is necessary since some * of these subsystems may have been developed without any knowledge of the * CAN library. * * This interface provides general resources from the CAN library that may be * useful for subsystems implementing CAN I/O. Using these resources is not a * requirement for support from the CAN library, but may make such support more * efficient and easier to implement both for the CAN library driver and the * device dependent subsystem. } procedure can_devlist_add ( {add entry to CAN devices list} in out devs: can_devs_t; {list to add entry to} out dev_p: can_dev_p_t); {returned pointing to new entry} val_param; extern; procedure can_devlist_create ( {create new CAN devices list} in out mem: util_mem_context_t; {parent context for dynamic memory} out devs: can_devs_t); {returned initialized and empty list} val_param; extern;
unit TestTestingHelperUtils; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, StdCtrls, Controls, Buttons, ComCtrls, Classes, Dialogs, Windows, Variants, Forms, SysUtils, ITHelper.TestingHelperUtils, Graphics, Messages; Type TestApplicationFunctions = Class(TTestCase) Published Procedure TestResolvePath; End; implementation { TestApplicationFunctions } procedure TestApplicationFunctions.TestResolvePath; Var strFName, strPath, strResult : String; begin strFName := '.\Athingy.exe'; strPath := 'C:\Borland Studio Projects\Application\Athingy\'; strResult := 'C:\Borland Studio Projects\Application\Athingy\Athingy.exe'; CheckEquals(ResolvePath(strFName, strPath), strResult, 'Test 1'); strFName := '.\New Folder\Athingy.exe'; strPath := 'C:\Borland Studio Projects\Application\Athingy\'; strResult := 'C:\Borland Studio Projects\Application\Athingy\New Folder\Athingy.exe'; CheckEquals(ResolvePath(strFName, strPath), strResult, 'Test 2'); strFName := '..\Athingy.exe'; strPath := 'C:\Borland Studio Projects\Application\Athingy\'; strResult := 'C:\Borland Studio Projects\Application\Athingy.exe'; CheckEquals(ResolvePath(strFName, strPath), strResult, 'Test 3'); strFName := '..\..\Athingy.exe'; strPath := 'C:\Borland Studio Projects\Application\Athingy\'; strResult := 'C:\Borland Studio Projects\Athingy.exe'; CheckEquals(ResolvePath(strFName, strPath), strResult, 'Test 4'); strFName := 'C:\Borland Studio Projects\Application\Athingy\Athingy.exe'; strPath := 'C:\Borland Studio Projects\Application\Athingy\'; strResult := 'C:\Borland Studio Projects\Application\Athingy\Athingy.exe'; CheckEquals(ResolvePath(strFName, strPath), strResult, 'Test 5'); end; initialization RegisterTest('Functions', TestApplicationFunctions.Suite); end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit SimpleDispatcherImpl; interface {$MODE OBJFPC} uses DispatcherIntf, DependencyIntf, EnvironmentIntf, ResponseIntf, ResponseFactoryIntf, RequestIntf, RequestFactoryIntf, RequestHandlerIntf, RouteHandlerIntf, RouteMatcherIntf; type (*!------------------------------------------------ * simple dispatcher implementation without * middleware support. It is faster than * TDispatcher because it does not process middlewares * stack during dispatching request * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TSimpleDispatcher = class(TInterfacedObject, IDispatcher, IDependency) private routeCollection : IRouteMatcher; responseFactory : IResponseFactory; requestFactory : IRequestFactory; public constructor create( const routes : IRouteMatcher; const respFactory : IResponseFactory; const reqFactory : IRequestFactory ); destructor destroy(); override; function dispatchRequest(const env: ICGIEnvironment) : IResponse; end; implementation uses sysutils; constructor TSimpleDispatcher.create( const routes : IRouteMatcher; const respFactory : IResponseFactory; const reqFactory : IRequestFactory ); begin routeCollection := routes; responseFactory := respFactory; requestFactory := reqFactory; end; destructor TSimpleDispatcher.destroy(); begin inherited destroy(); routeCollection := nil; responseFactory := nil; requestFactory := nil; end; function TSimpleDispatcher.dispatchRequest(const env: ICGIEnvironment) : IResponse; var routeHandler : IRouteHandler; method : string; uriParts : TStringArray; begin try method := env.requestMethod(); //remove any query string parts uriParts := env.requestUri().split('?'); routeHandler := routeCollection.match(method, uriParts[0]); result := routeHandler.handleRequest( requestFactory.build(env), responseFactory.build(env) ); finally routeHandler := nil; uriParts := nil; end; end; end.
unit JSONSerialize; interface type JSONPath = class(TCustomAttribute) private FName: string; public constructor Create(const AName: string); property Name: string read FName; end; function JSONString(obj: TObject): string; overload; function JSONString(intf: IInterface): string; overload; function JSONString(ARecordPtr, TypeInfoPtr: Pointer): string; overload; implementation uses {$IF CompilerVersion > 26} //Delphi XE6 or later. System.JSON, {$ELSE} Data.DBXJSON, System.TypInfo, {$ENDIF} System.Classes, System.Generics.Collections, System.Rtti, System.SysUtils; type ToJSON = class public class function FromValue(InValue: TValue): TJSONValue; end; { JSONName } constructor JSONPath.Create(const AName: string); begin FName := AName; end; function JSONSerializeObj(ptr, typinf: Pointer): TJSONObject; forward; function JSONSerializeInterface(intf: IInterface): TJSONObject; forward; function TryGetJSONValue(const Root: TJSONObject; const Path: string; var Value: TJSONValue): Boolean; {$IF CompilerVersion < 27} //Delphi XE5 or earlier var Pair: TJSONPair; {$ENDIF} begin {$IF CompilerVersion > 26} //Delphi XE6 or later. Result := Root.TryGetValue(Path, Value); {$ELSE} Pair := Root.Get(Path); Result := Assigned(Pair); if Result then Value := Pair.JsonValue else Value := nil; {$ENDIF} end; function GetJSONString(const Value: TJSONValue): string; begin {$IF CompilerVersion > 26} //Delphi XE6 or later. Result := Value.ToJSON; {$ELSE} Result := Value.ToString; {$ENDIF} end; class function ToJSON.FromValue(InValue: TValue): TJSONValue; var I: Integer; AValue: TValue; AJSONValue: TJSONValue; begin Result := nil; case InValue.Kind of tkChar, tkString, tkWChar, tkLString, tkWString, tkUString: if InValue.AsString <> '' then Result := TJSONString.Create(InValue.AsString); tkInteger: if InValue.AsInteger <> 0 then Result := TJSONNumber.Create(InValue.AsInteger); tkInt64: if InValue.AsInt64 <> 0 then Result := TJSONNumber.Create(InValue.AsInt64); tkFloat: if not ((InValue.AsExtended = 0) or (InValue.AsExtended = 25569)) then Result := TJSONNumber.Create(InValue.AsExtended); tkEnumeration: if InValue.AsBoolean then Result := TJSONTrue.Create; tkClass: begin if (InValue.AsObject is TJSONValue) then Result := ((InValue.AsObject as TJSONValue).Clone as TJSONValue) else Result := JSONSerializeObj(InValue.AsObject, InValue.TypeInfo); if GetJSONString(Result) = '{}' then begin FreeAndNil(Result); end; end; tkRecord: begin Result := JSONSerializeObj(InValue.GetReferenceToRawData, InValue.TypeInfo); if GetJSONString(Result) = '{}' then FreeAndNil(Result); end; tkInterface: begin Result := JSONSerializeInterface(InValue.AsInterface); if GetJSONString(Result) = '{}' then FreeAndNil(Result); end; tkArray, tkDynArray: begin Result := TJSONArray.Create; for I := 0 to InValue.GetArrayLength - 1 do begin AValue := InValue.GetArrayElement(I); AJSONValue := ToJSON.FromValue(AValue); if Assigned(AJSONValue) then (Result as TJSONArray).AddElement(AJSONValue); end; if GetJSONString(Result) = '[]' then FreeAndNil(Result); end; else Result := nil; end; end; procedure JSONSerializeValue(Result: TJSONObject; TypeKind: TTypeKind; InValue: TValue; JSONName: string); var OutValue, Temp: TJSONValue; Root: TJSONObject; Names: TStringList; I: Integer; begin OutValue := ToJSON.FromValue(InValue); if Assigned(OutValue) then begin Root := Result; names := TStringList.Create; try ExtractStrings(['\','/'], [], PWideChar(JSONName), names); for I := 0 to Names.Count - 2 do begin if not TryGetJSONValue(Root, Names[I], Temp) then begin Temp := TJSONObject.Create; Root.AddPair(Names[I], Temp); end; Root := Temp as TJSONObject; end; Root.AddPair(Names[Names.Count - 1], OutValue); finally FreeAndNil(Names); end; end; end; function JSONSerializeObj(ptr, typinf: Pointer): TJSONObject; var ctx: TRttiContext; t : TRttiType; p : TRttiProperty; f : TRttiField; a : TCustomAttribute; begin Result := TJSONObject.Create; t := ctx.GetType(typinf); for f in t.GetFields do for a in f.GetAttributes do if a is JSONPath then JSONSerializeValue(Result, f.FieldType.TypeKind, f.GetValue(ptr), JSONPath(a).Name); for p in t.GetProperties do for a in p.GetAttributes do if a is JSONPath then JSONSerializeValue(Result, p.PropertyType.TypeKind, p.GetValue(ptr), JSONPath(a).Name); end; function JSONSerializeInterface(intf: IInterface): TJSONObject; var obj: TObject; begin obj := TObject(intf); Result := JSONSerializeObj(obj, obj.ClassInfo); end; function JSONString(obj: TObject): string; var json: TJSONObject; begin json := JSONSerializeObj(obj, obj.ClassInfo); try Result := GetJSONString(json); finally FreeAndNil(json); end; end; function JSONString(intf: IInterface): string; var json: TJSONObject; begin json := JSONSerializeInterface(intf); try Result := GetJSONString(json); finally FreeAndNil(json); end; end; function JSONString(ARecordPtr, TypeInfoPtr: Pointer): string; var json: TJSONObject; begin json := JSONSerializeObj(ARecordPtr, TypeInfoPtr); try Result := GetJSONString(json); finally FreeAndNil(json); end; end; end.
unit UMyClass; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ToolWin, ActnMan, ActnCtrls, ActnMenus, Menus, Data.DB, Data.Win.ADODB, Contnrs, Generics.Collections, UConnection; type TMyClass = class private /// <link>aggregation</link> Connection: TConnection; ADOQuery: TADOQuery; DataSource: TDataSource; public function GetADOQuery: TADOQuery; function GetDataSource: TDataSource; constructor create; end; implementation { TMyClass } constructor TMyClass.create; begin Connection := TConnection.create; if not Assigned(ADOQuery) then ADOQuery := TADOQuery.create(nil); ADOQuery.Connection := Connection.GetADOConnection; ADOQuery.Close; ADOQuery.SQL.Clear; ADOQuery.SQL.add('SELECT * FROM store.element;'); ADOQuery.Open; ADOQuery.Active := true; if not Assigned(DataSource) then DataSource := TDataSource.create(nil); DataSource.DataSet := ADOQuery; end; function TMyClass.GetADOQuery: TADOQuery; begin result := ADOQuery; end; function TMyClass.GetDataSource: TDataSource; begin result := DataSource; end; end.
unit Konstanty; interface type TTicket = record Min : integer; Norm, Zlav : integer; end; TTickets = array of TTicket; TClientInfo = record Name, Company, Serial : string; LastUpdate : string; end; TServerInfo = record Host : string; Port : word; end; var ROOT_DIR : string; ROZVRHY_DIR : string; // Obrazky : MAP_FILE : string; HODINY_FILE : string; // Datove subory : ZASTAVKY_FILE : string; // Listky : TICKETS : TTickets; // Konštanty : HEKTOMETER : word; SPEED : integer; // Settings nastavenia casu DEF_SETTINGS : record Time : integer; Den : integer; Zlavneny : boolean; Rezerva : integer; AutoShow : boolean; end; // Synchronization CLIENTINFO : TClientInfo; SERVERINFO : TServerInfo; function GetTickets( Key : string ) : TTickets; implementation uses Windows, Registry, Classes, SysUtils; function GetTickets( Key : string ) : TTickets; var Reg : TRegistry; Strings : TStringList; I,J : integer; S, S1 : string; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey( Key , False ); Strings := TStringList.Create; try Reg.GetValueNames( Strings ); SetLength( Result , Strings.Count ); for I := 0 to Strings.Count-1 do begin S := Reg.ReadString( Strings[I] ); Result[I].Min := StrToInt( Strings[I] ); J := 1; S1 := ''; repeat S1 := S1 + S[J]; Inc( J ); until S[J] = ';'; Result[I].Norm := StrToInt( S1 ); S1 := ''; for J := J+1 to Length( S ) do S1 := S1 + S[J]; Result[I].Zlav := StrToInt( S1 ); end; finally Strings.Free; end; finally Reg.Free; end; end; procedure ReadRegs; var Reg : TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey( '\Software\MHDClient\Dirs' , False ); ROOT_DIR := Reg.ReadString( 'App_dir' ); ROZVRHY_DIR := Reg.ReadString( 'Rozvrhy_dir' ); Reg.OpenKey( '\Software\MHDClient\Files' , False ); ZASTAVKY_FILE := Reg.ReadString( 'Zastavky' ); MAP_FILE := Reg.ReadString( 'Mapa' ); HODINY_FILE := Reg.ReadString( 'Hodiny' ); Reg.OpenKey( '\Software\MHDClient\Consts' , False ); HEKTOMETER := Reg.ReadInteger( '100m' ); SPEED := Reg.ReadInteger( 'Speed' ); Reg.OpenKey( '\Software\MHDClient\Settings' , False ); with DEF_SETTINGS do begin Time := Reg.ReadInteger( 'Time' ); Den := Reg.ReadInteger( 'Den' ); if (Reg.ReadString( 'Zlavneny' ) = 'True') then Zlavneny := True else Zlavneny := False; Rezerva := StrToInt( Reg.ReadString( 'Rezerva' ) ); if (Reg.ReadString( 'AutoShow' ) = 'True') then AutoShow := True else AutoShow := False; end; Reg.OpenKey( '\Software\MHDClient\Synchronization' , False ); CLIENTINFO.LastUpdate := Reg.ReadString( 'Last' ); Reg.OpenKey( '\Software\MHDClient\Synchronization\Settings' , False ); SERVERINFO.Host := Reg.ReadString( 'Host' ); SERVERINFO.Port := Reg.ReadInteger( 'Port' ); Reg.OpenKey( '\Software\MHDClient\User' , False ); CLIENTINFO.Name := Reg.ReadString( 'Name' ); CLIENTINFO.Company := Reg.ReadString( 'Company' ); CLIENTINFO.Serial := Reg.ReadString( 'Serial' ); finally Reg.Free; end; end; procedure WriteRegs; var Reg : TRegistry; Strings : TStringList; I : integer; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey( '\Software\MHDClient\Settings' , False ); with DEF_SETTINGS do begin Reg.WriteInteger( 'Time' , Time ); Reg.WriteInteger( 'Den' , Den ); if Zlavneny then Reg.WriteString( 'Zlavneny' , 'True' ) else Reg.WriteString( 'Zlavneny' , 'False' ); Reg.WriteString( 'Rezerva' , IntToStr( Rezerva ) ); if AutoShow then Reg.WriteString( 'AutoShow' , 'True' ) else Reg.WriteString( 'AutoShow' , 'False' ); end; Reg.OpenKey( '\Software\MHDClient\Tickets' , False ); Strings := TStringList.Create; try Reg.GetValueNames( Strings ); for I := 0 to Strings.Count-1 do Reg.DeleteValue( Strings[I] ); finally Strings.Free; end; for I := 0 to Length( TICKETS )-1 do Reg.WriteString( IntToStr( TICKETS[I].Min ) , IntToStr( TICKETS[I].Norm ) + ';' + IntToStr( TICKETS[I].Zlav ) ); Reg.OpenKey( '\Software\MHDClient\Synchronization' , False ); Reg.WriteString( 'Last' , CLIENTINFO.LastUpdate ); finally Reg.Free; end; end; initialization ReadRegs; TICKETS := GetTickets( '\Software\MHDClient\Tickets' ); finalization WriteRegs; end.
unit unConstantes; interface const mProblemasNaConexaoComBanco :string = 'Problemas na conexão com o banco!'; mProblemasNaExecucaoDaConsulta :string = 'Problemas na execução da consulta!'; mRegistroNaoLocalizado :string = 'Registro não localizado!'; mSelecioneParaEdicao :string = 'Selecione um registro para edição!'; mSelecioneParaExclusao :string = 'Selecione um registro para exclusão!'; mCanceleOuGrave :string = 'Cancele ou grave a operação atual!'; mNenhumRegistroEncontrado :string = 'Nenhum registro encontrado com esses parâmetros'; mProblemasAoProcessarEstoque :string = 'Problemas ao processar o estoque! '; mFuncaoNaoHabilitada :string = 'Função não habilitada para esta rotina! '; mPerguntaGravacao :string = 'Deseja gravar a edição corrente?'; mPerguntaCancela :string = 'Deseja cancelar a edição corrente?'; mPerguntaExclusao :string = 'Deseja excluir o registro atual?'; implementation end.
program nonogram; uses math, sysutils; type Cell = (Fill, Empty, Unknown); Board = Array of Array of Cell; Clues = Array of Integer; TClueArray = Array of Clues; function convertClue(strarr : Array of AnsiString) : TClueArray; var res : TClueArray; temp : Array of AnsiString; i, j : Longint; begin setLength(res, Length(strarr)); for i := 0 to Length(strarr)-1 do begin temp := strarr[i].Split(' '); setLength(res[i], Length(temp)); for j := 0 to Length(temp)-1 do res[i][j] := StrToInt(temp[j]); end; Exit(res); end; function initBoard(height, width : Integer) : Board; var i, j : Longint; b : Board; begin setLength(b, height); for i := 0 to height-1 do begin setLength(b[i], width); for j := 0 to width-1 do b[i][j] := Unknown; end; Exit(b); end; procedure showBoard(b : Board); var i, j : Longint; begin for i := 0 to Length(b)-1 do begin for j := 0 to Length(b[i])-1 do Case b[i][j] of Fill : write('O'); Empty : write(' '); Unknown : write('.'); end; writeln(); end; end; function countFilled(arr : Array of Cell) : Clues; var counting : Boolean = False; i, count : Integer; res : Clues; begin setLength(res, 0); count := 0; for i := 0 to Length(arr)-1 do begin if arr[i] = Unknown then break; if counting then if arr[i] = Fill then count += 1 else begin setLength(res, Length(res)+1); res[Length(res)-1] := count; counting := False; count := 0; end else if arr[i] = Fill then begin counting := True; count := 1; end; end; if counting then begin setLength(res, Length(res)+1); res[Length(res)-1] := count; end; if Length(res) = 0 then res := [0]; Exit(res); end; function countFilledHard(arr : Array of Cell) : Clues; var counting : Boolean = False; i, count : Integer; res : Clues; begin setLength(res, 0); count := 0; for i := 0 to Length(arr)-1 do begin if arr[i] = Unknown then break; if counting then if arr[i] = Fill then count += 1 else begin setLength(res, Length(res)+1); res[Length(res)-1] := count; counting := False; count := 0; end else if arr[i] = Fill then begin counting := True; count := 1; end; end; if counting and (arr[i] <> Unknown) then begin setLength(res, Length(res)+1); res[Length(res)-1] := count; end; Exit(res); end; function isFull(arr : Array of Cell) : Boolean; begin Exit(arr[Length(arr)-1] <> Unknown) end; function isValidClue(arr, clue : Clues; isfull, hard : Boolean) : Boolean; var i : Integer; begin if isfull or hard then begin if isfull then if Length(arr) <> Length(clue) then Exit(false); for i := 0 to min( Length(clue), Length(arr) )-1 do if arr[i] <> clue[i] then Exit(false); end else begin if Length(arr) > Length(clue) then Exit(false); for i := 0 to min( Length(clue), Length(arr) )-1 do if arr[i] > clue[i] then Exit(false); end; Exit(True); end; function isValid(b : Board; tc, lc : TClueArray; row,col : Integer) : Boolean; var i : Integer; tempcol : Array of Cell; begin { Check Rows } if not isValidClue(countFilled(b[row]), lc[row], isFull(b[row]), false) then Exit(False); if b[row][col] = Empty then if not isValidClue(countFilledHard(b[row]), lc[row], false, true) then Exit(False); { Check Columns } setLength(tempcol, Length(b)); for i := 0 to Length(b)-1 do tempcol[i] := b[i][col]; if not isValidClue(countFilled(tempcol), tc[col], isFull(tempcol), false) then Exit(False); if b[row][col] = Empty then if not isValidClue(countFilledHard(tempcol), tc[col], false, true) then Exit(False); Exit(True); end; var done : Boolean = False; textfile : Text; tc_str, lc_str : AnsiString; tc_strarr, lc_strarr : Array of AnsiString; top_clue, left_clue : TClueArray; i, width, height : Integer; gameboard : Board; printid : Integer = 0; procedure solve(b : Board; tc, lc : TClueArray; y, x : Integer); var height, width, ny, nx : Integer; Tcell : Cell; newb : Board; filled : Boolean; begin if done then Exit; height := Length(b); width := Length(b[0]); if b[height-1][width-1] <> Unknown then begin done := true; showBoard(b); end; filled := b[y][width-1] <> Unknown; if filled then begin if printid mod 100 = 0 then begin showBoard(b); writeln; end; printid += 1; end; nx := x + 1; ny := y; if nx >= width then begin ny += 1; if ny >= height then Exit; nx := nx mod width; end; if Random() < 0.5 then begin for Tcell := Fill to Empty do begin b[ny][nx] := Tcell; if isValid(b, tc, lc, ny, nx) then begin setLength(newb, height); for i := 0 to height-1 do newb[i] := Copy(b[i]); solve(newb, tc, lc, ny, nx); end; end; end else begin for Tcell := Empty downto Fill do begin b[ny][nx] := Tcell; if isValid(b, tc, lc, ny, nx) then begin setLength(newb, height); for i := 0 to height-1 do newb[i] := Copy(b[i]); solve(newb, tc, lc, ny, nx); end; end; end; end; begin assign(textfile, 'nonogram.txt'); reset(textfile); readln(textfile, tc_str); readln(textfile, lc_str); close(textfile); randomize(); tc_strarr := tc_str.Split(','); lc_strarr := lc_str.Split(','); width := Length(tc_strarr); height := Length(lc_strarr); gameboard := initBoard(height, width); top_clue := convertClue(tc_strarr); left_clue := convertClue(lc_strarr); solve(gameboard, top_clue, left_clue, 0, -1); end.
unit FamilyExQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FamilyQuery, 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, ApplyQueryFrame, NotifyEvents, System.Generics.Collections, DBRecordHolder, DSWrap; type TFamilyExW = class(TFamilyW) private FAnalog: TFieldWrap; public constructor Create(AOwner: TComponent); override; procedure RefreshQuery; override; property Analog: TFieldWrap read FAnalog; end; TQueryFamilyEx = class(TQueryFamily) private FOn_ApplyUpdate: TNotifyEventsEx; function GetFamilyExW: TFamilyExW; { Private declarations } protected procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property FamilyExW: TFamilyExW read GetFamilyExW; property On_ApplyUpdate: TNotifyEventsEx read FOn_ApplyUpdate; { Public declarations } end; implementation {$R *.dfm} constructor TQueryFamilyEx.Create(AOwner: TComponent); begin inherited; FOn_ApplyUpdate := TNotifyEventsEx.Create(Self); FRecordHolder := TRecordHolder.Create(); end; destructor TQueryFamilyEx.Destroy; begin FreeAndNil(FOn_ApplyUpdate); FreeAndNil(FRecordHolder); inherited; end; procedure TQueryFamilyEx.ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin // ничего не делаем при удаении end; procedure TQueryFamilyEx.ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin // Ничего не делаем при добавлении end; procedure TQueryFamilyEx.ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin // Оповещаем что надо обработать обновление On_ApplyUpdate.CallEventHandlers(Self); end; function TQueryFamilyEx.CreateDSWrap: TDSWrap; begin Result := TFamilyExW.Create(FDQuery); end; function TQueryFamilyEx.GetFamilyExW: TFamilyExW; begin Result := W as TFamilyExW; end; constructor TFamilyExW.Create(AOwner: TComponent); begin inherited; FAnalog := TFieldWrap.Create(Self, 'Analog'); end; procedure TFamilyExW.RefreshQuery; begin // При каждом обновлении в запрос добавляются разные дополнительные поля. // Поэтому обычный Refresh не подходит DataSet.DisableControls; try if DataSet.Active then DataSet.Close; DataSet.Open; NeedRefresh := False; finally DataSet.EnableControls; end; end; end.
{ "Screen Capture Link" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) } unit rtcXScreenCapture; interface {$include rtcDefs.inc} uses Classes, rtcTypes, rtcInfo, rtcXGateCIDs, rtcXImgEncode, rtcXScreenUtils, {$IFDEF WINDOWS} rtcVScreenUtilsWin, rtcVWinStation, {$ENDIF} {$IFDEF MACOSX} rtcFScreenUtilsOSX, {$ENDIF} rtcXImgCapture; type { @Abstract(RTC Screen Capture Link) Link this component to a TRtcHttpGateClient to handle Screen Capture events. } {$IFDEF IDE_XE2up} [ComponentPlatformsAttribute(pidAll)] {$ENDIF} TRtcScreenCaptureLink = class(TRtcImageCaptureLink) private ParamsChanged1, ParamsChanged2, ParamsChanged3:boolean; //ParamsChanged1 FMirrorDriver:boolean; // False //ParamsChanged2 FWindowsAero:boolean; // True //ParamsChanged3 FLayeredWindows:boolean; // True FAllMonitors:boolean; // False procedure SetMirrorDriver(const Value: boolean); procedure SetWindowsAero(const Value: boolean); procedure SetAllMonitors(const Value: boolean); procedure SetLayeredWindows(const Value: boolean); protected function CreateImageEncoder:TRtcImageEncoder; override; procedure ResetParamsChanged; override; procedure UpdateChangedParams; override; function CaptureMouseInitial:RtcByteArray; override; function CaptureMouseDelta:RtcByteArray; override; function CaptureImage:boolean; override; procedure CaptureImageFailCheck; override; procedure MouseControlExecute(Data:TRtcValue); override; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; published property CaptureMirrorDriver:boolean read FMirrorDriver write SetMirrorDriver default False; property CaptureWindowsAero:boolean read FWindowsAero write SetWindowsAero default True; property CaptureLayeredWindows:boolean read FLayeredWindows write SetLayeredWindows default True; property CaptureAllMonitors:boolean read FAllMonitors write SetAllMonitors default False; end; implementation { TRtcScreenCaptureLink } constructor TRtcScreenCaptureLink.Create(AOwner: TComponent); begin inherited; FMirrorDriver:=False; FWindowsAero:=True; FLayeredWindows:=True; FAllMonitors:=False; end; destructor TRtcScreenCaptureLink.Destroy; begin inherited; {$IFDEF WINDOWS} if CurrentMirrorDriver then DisableMirrorDriver; if not CurrentAero then EnableAero; {$ENDIF} end; procedure TRtcScreenCaptureLink.SetMirrorDriver(const Value: boolean); begin FMirrorDriver := Value; ParamsChanged1 := True; end; procedure TRtcScreenCaptureLink.SetWindowsAero(const Value: boolean); begin FWindowsAero := Value; ParamsChanged2 := True; end; procedure TRtcScreenCaptureLink.SetAllMonitors(const Value: boolean); begin FAllMonitors := Value; ParamsChanged3:=True; end; procedure TRtcScreenCaptureLink.SetLayeredWindows(const Value: boolean); begin FLayeredWindows := Value; ParamsChanged3:=True; end; function TRtcScreenCaptureLink.CreateImageEncoder: TRtcImageEncoder; begin {$IFDEF WINDOWS} Result:=TRtcImageEncoder.Create(GetScreenBitmapInfo); {$ELSE} {$IFDEF MACOSX} Result:=TRtcImageEncoder.Create(GetScreenBitmapInfo); {$ELSE} {$Message Warn 'CreateImageEncoder: Unknown Bitmap Format'} {$ENDIF} {$ENDIF} end; procedure TRtcScreenCaptureLink.ResetParamsChanged; begin inherited; ParamsChanged1:=True; ParamsChanged2:=True; ParamsChanged3:=True; end; procedure TRtcScreenCaptureLink.UpdateChangedParams; begin inherited; {$IFDEF WINDOWS} if ParamsChanged1 then begin ParamsChanged1:=False; if CurrentMirrorDriver<>FMirrorDriver then begin if FMirrorDriver then EnableMirrorDriver else DisableMirrorDriver; end; end; if ParamsChanged2 then begin ParamsChanged2:=False; if CurrentAero<>FWindowsAero then begin if FWindowsAero then EnableAero else DisableAero; end; end; {$ENDIF} if ParamsChanged3 then begin ParamsChanged3:=False; RtcCaptureSettings.CompleteBitmap:=True; RtcCaptureSettings.LayeredWindows:=FLayeredWindows; RtcCaptureSettings.AllMonitors:=FAllMonitors; end; end; function TRtcScreenCaptureLink.CaptureMouseInitial: RtcByteArray; begin {$IFDEF WINDOWS} MouseSetup; GrabMouse; Result:=CaptureMouseCursor; {$ELSE} Result:=nil; {$ENDIF} end; function TRtcScreenCaptureLink.CaptureMouseDelta: RtcByteArray; begin {$IFDEF WINDOWS} GrabMouse; Result:=CaptureMouseCursorDelta; {$ELSE} Result:=nil; {$ENDIF} end; function TRtcScreenCaptureLink.CaptureImage: boolean; begin {$IFDEF WINDOWS} Result:=ScreenCapture(ImgEncoder.OldBmpInfo,ImgEncoder.NeedRefresh); {$ELSE} {$IFDEF MACOSX} Result:=ScreenCapture(ImgEncoder.OldBmpInfo,ImgEncoder.NeedRefresh); {$ELSE} Result:=False; {$ENDIF} {$ENDIF} end; procedure TRtcScreenCaptureLink.CaptureImageFailCheck; begin inherited; {$IFDEF WINDOWS} SwitchToActiveDesktop(true); {$ENDIF} end; procedure TRtcScreenCaptureLink.MouseControlExecute(Data: TRtcValue); begin inherited; {$IFDEF WINDOWS} case Data.asRecord.asInteger['C'] of cid_ControlMouseDown: Control_MouseDown(Data.asRecord.asCardinal['A'], Data.asRecord.asInteger['X'], Data.asRecord.asInteger['Y'], TMouse_Button(Data.asRecord.asInteger['B'])); cid_ControlMouseMove: Control_MouseMove(Data.asRecord.asCardinal['A'], Data.asRecord.asInteger['X'], Data.asRecord.asInteger['Y']); cid_ControlMouseUp: Control_MouseUp(Data.asRecord.asCardinal['A'], Data.asRecord.asInteger['X'], Data.asRecord.asInteger['Y'], TMouse_Button(Data.asRecord.asInteger['B'])); cid_ControlMouseWheel: Control_MouseWheel(Data.asRecord.asInteger['W']); cid_ControlKeyDown: Control_KeyDown(Data.asRecord.asInteger['K']); cid_ControlKeyUp: Control_KeyUp(Data.asRecord.asInteger['K']); end; {$ENDIF} end; end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 Algorithms.pas. } { } { The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by } { Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) } { All rights reserved. } { } { Contributors: } { Florent Ouchet (outchy) } { } {**************************************************************************************************} { } { The Delphi Container Library } { } {**************************************************************************************************} { } { Last modified: $Date:: 2008-01-15 23:30:26 +0100 (mar., 15 janv. 2008) $ } { Revision: $Rev:: 2309 $ } { Author: $Author:: outchy $ } { } {**************************************************************************************************} unit JclAlgorithms; {$I jcl.inc} {$I containers\JclAlgorithms.int} {$I containers\JclAlgorithms.imp} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JclBase, JclContainerIntf; // Compare functions {$JPPEXPANDMACRO SIMPLECOMPAREINT(IntfSimpleCompare,const ,IInterface)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(AnsiStrSimpleCompare,const ,AnsiString)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(WideStrSimpleCompare,const ,WideString)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(StrSimpleCompare,const ,string)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(SingleSimpleCompare,const ,Single)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(DoubleSimpleCompare,const ,Double)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(ExtendedSimpleCompare,const ,Extended)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(FloatSimpleCompare,const ,Float)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(IntegerSimpleCompare,,Integer)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(CardinalSimpleCompare,,Cardinal)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(Int64SimpleCompare,const ,Int64)} {$IFNDEF CLR} {$JPPEXPANDMACRO SIMPLECOMPAREINT(PtrSimpleCompare,,Pointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO SIMPLECOMPAREINT(SimpleCompare,,TObject)} {$JPPEXPANDMACRO SIMPLECOMPAREINT(IntegerCompare,,TObject)} // Compare functions for equality {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(IntfSimpleEqualityCompare,const ,IInterface)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(AnsiStrSimpleEqualityCompare,const ,AnsiString)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(WideStrSimpleEqualityCompare,const ,WideString)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(StrSimpleEqualityCompare,const ,string)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(SingleSimpleEqualityCompare,const ,Single)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(DoubleSimpleEqualityCompare,const ,Double)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(ExtendedSimpleEqualityCompare,const ,Extended)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(FloatSimpleEqualityCompare,const ,Float)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(IntegerSimpleEqualityCompare,,Integer)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(CardinalSimpleEqualityCompare,,Cardinal)} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(Int64SimpleEqualityCompare,const ,Int64)} {$IFNDEF CLR} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(PtrSimpleEqualityCompare,,Pointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO SIMPLEEQUALITYCOMPAREINT(SimpleEqualityCompare,,TObject)} // Apply algorithms {$JPPEXPANDMACRO APPLYINT(Apply,IJclIntfIterator,TIntfApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclAnsiStrIterator,TAnsiStrApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclWideStrIterator,TWideStrApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclSingleIterator,TSingleApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclDoubleIterator,TDoubleApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclExtendedIterator,TExtendedApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclIntegerIterator,TIntegerApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclCardinalIterator,TCardinalApplyFunction)} overload; {$JPPEXPANDMACRO APPLYINT(Apply,IJclInt64Iterator,TInt64ApplyFunction)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO APPLYINT(Apply,IJclPtrIterator,TPtrApplyFunction)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO APPLYINT(Apply,IJclIterator,TApplyFunction)} overload; // Find algorithms {$JPPEXPANDMACRO FINDINT(Find,IJclIntfIterator,const ,AInterface,IInterface,TIntfCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclIntfIterator,const ,AInterface,IInterface,TIntfEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclWideStrIterator,const ,AString,WideString,TWideStrCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclWideStrIterator,const ,AString,WideString,TWideStrEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclSingleIterator,const ,AValue,Single,TSingleCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclSingleIterator,const ,AValue,Single,TSingleEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclDoubleIterator,const ,AValue,Double,TDoubleCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclDoubleIterator,const ,AValue,Double,TDoubleEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclExtendedIterator,const ,AValue,Extended,TExtendedCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclExtendedIterator,const ,AValue,Extended,TExtendedEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclIntegerIterator,,AValue,Integer,TIntegerCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclIntegerIterator,,AValue,Integer,TIntegerEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclCardinalIterator,,AValue,Cardinal,TCardinalCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclCardinalIterator,,AValue,Cardinal,TCardinalEqualityCompare)} overload; {$JPPEXPANDMACRO FINDINT(Find,IJclInt64Iterator,const ,AValue,Int64,TInt64Compare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclInt64Iterator,const ,AValue,Int64,TInt64EqualityCompare)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO FINDINT(Find,IJclPtrIterator,,APtr,Pointer,TPtrCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclPtrIterator,,APtr,Pointer,TPtrEqualityCompare)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO FINDINT(Find,IJclIterator,,AObject,TObject,TCompare)} overload; {$JPPEXPANDMACRO FINDEQINT(Find,IJclIterator,,AObject,TObject,TEqualityCompare)} overload; // CountObject algorithms {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclIntfIterator,const ,AInterface,IInterface,TIntfCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclIntfIterator,const ,AInterface,IInterface,TIntfEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclWideStrIterator,const ,AString,WideString,TWideStrCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclWideStrIterator,const ,AString,WideString,TWideStrEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclSingleIterator,const ,AValue,Single,TSingleCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclSingleIterator,const ,AValue,Single,TSingleEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclDoubleIterator,const ,AValue,Double,TDoubleCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclDoubleIterator,const ,AValue,Double,TDoubleEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclExtendedIterator,const ,AValue,Extended,TExtendedCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclExtendedIterator,const ,AValue,Extended,TExtendedEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclIntegerIterator,,AValue,Integer,TIntegerCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclIntegerIterator,,AValue,Integer,TIntegerEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclCardinalIterator,,AValue,Cardinal,TCardinalCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclCardinalIterator,,AValue,Cardinal,TCardinalEqualityCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclInt64Iterator,const ,AValue,Int64,TInt64Compare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclInt64Iterator,const ,AValue,Int64,TInt64EqualityCompare)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclPtrIterator,,APtr,Pointer,TPtrCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclPtrIterator,,APtr,Pointer,TPtrEqualityCompare)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclIterator,,AObject,TObject,TCompare)} overload; {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclIterator,,AObject,TObject,TEqualityCompare)} overload; // Copy algorithms {$JPPEXPANDMACRO COPYINT(Copy,IJclIntfIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclAnsiStrIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclWideStrIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclSingleIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclDoubleIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclExtendedIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclIntegerIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclCardinalIterator)} overload; {$JPPEXPANDMACRO COPYINT(Copy,IJclInt64Iterator)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO COPYINT(Copy,IJclPtrIterator)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO COPYINT(Copy,IJclIterator)} overload; // Generate algorithms {$JPPEXPANDMACRO GENERATEINT(Generate,IJclIntfList,const ,AInterface,IInterface)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclAnsiStrList,const ,AString,AnsiString)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclWideStrList,const ,AString,WideString)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclSingleList,const ,AValue,Single)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclDoubleList,const ,AValue,Double)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclExtendedList,const ,AValue,Extended)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclIntegerList,,AValue,Integer)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclCardinalList,,AValue,Cardinal)} overload; {$JPPEXPANDMACRO GENERATEINT(Generate,IJclInt64List,const ,AValue,Int64)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO GENERATEINT(Generate,IJclPtrList,,APtr,Pointer)} overload; {$ENDIF CLR} {$JPPEXPANDMACRO GENERATEINT(Generate,IJclList,,AObject,TObject)} overload; // Fill algorithms {$JPPEXPANDMACRO FILLINT(Fill,IJclIntfIterator,const ,AInterface,IInterface)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclAnsiStrIterator,const ,AString,AnsiString)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclWideStrIterator,const ,AString,WideString)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclSingleIterator,const ,AValue,Single)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclDoubleIterator,const ,AValue,Double)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclExtendedIterator,const ,AValue,Extended)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclIntegerIterator,,AValue,Integer)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclCardinalIterator,,AValue,Cardinal)} overload; {$JPPEXPANDMACRO FILLINT(Fill,IJclInt64Iterator,const ,AValue,Int64)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO FILLINT(Fill,IJclPtrIterator,,APtr,Pointer)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO FILLINT(Fill,IJclIterator,,AObject,TObject)} overload; // Reverse algorithms {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclIntfIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclAnsiStrIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclWideStrIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclSingleIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclDoubleIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclExtendedIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclIntegerIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclCardinalIterator)} overload; {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclInt64Iterator)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclPtrIterator)} overload; {$ENDIF CLR} {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclIterator)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclIntfList,L,R,TIntfCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclAnsiStrList,L,R,TAnsiStrCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclWideStrList,L,R,TWideStrCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclSingleList,L,R,TSingleCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclDoubleList,L,R,TDoubleCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclExtendedList,L,R,TExtendedCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclIntegerList,L,R,TIntegerCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclCardinalList,L,R,TCardinalCompare)} overload; {$JPPEXPANDMACRO SORTINT(QuickSort,IJclInt64List,L,R,TInt64Compare)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO SORTINT(QuickSort,IJclPtrList,L,R,TPtrCompare)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO SORTINT(QuickSort,IJclList,L,R,TCompare)} overload; var IntfSortProc: TIntfSortProc = QuickSort; AnsiStrSortProc: TAnsiStrSortProc = QuickSort; WideStrSortProc: TWideStrSortProc = QuickSort; SingleSortProc: TSingleSortProc = QuickSort; DoubleSortProc: TDoubleSortProc = QuickSort; ExtendedSortProc: TExtendedSortProc = QuickSort; IntegerSortProc: TIntegerSortProc = QuickSort; CardinalSortProc: TCardinalSortProc = QuickSort; Int64SortProc: TInt64SortProc = QuickSort; {$IFNDEF CLR} PtrSortProc: TPtrSortProc = QuickSort; {$ENDIF ~CLR} SortProc: TSortProc = QuickSort; // Sort algorithms {$JPPEXPANDMACRO SORTINT(Sort,IJclIntfList,First,Last,TIntfCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclAnsiStrList,First,Last,TAnsiStrCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclWideStrList,First,Last,TWideStrCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclSingleList,First,Last,TSingleCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclDoubleList,First,Last,TDoubleCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclExtendedList,First,Last,TExtendedCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclIntegerList,First,Last,TIntegerCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclCardinalList,First,Last,TCardinalCompare)} overload; {$JPPEXPANDMACRO SORTINT(Sort,IJclInt64List,First,Last,TInt64Compare)} overload; {$IFNDEF CLR} {$JPPEXPANDMACRO SORTINT(Sort,IJclPtrList,First,Last,TPtrCompare)} overload; {$ENDIF ~CLR} {$JPPEXPANDMACRO SORTINT(Sort,IJclList,First,Last,TCompare)} overload; {$IFDEF SUPPORTS_GENERICS} type // cannot implement generic global functions TJclAlgorithms<T> = class private //FSortProc: TSortProc; public class {$JPPEXPANDMACRO APPLYINT(Apply,IJclIterator<T>,TApplyFunction<T>)} class {$JPPEXPANDMACRO FINDINT(Find,IJclIterator<T>,const ,AItem,T,TCompare<T>)} overload; class {$JPPEXPANDMACRO FINDEQINT(Find,IJclIterator<T>,const ,AItem,T,TEqualityCompare<T>)} overload; class {$JPPEXPANDMACRO COUNTOBJECTINT(CountObject,IJclIterator<T>,const ,AItem,T,TCompare<T>)} overload; class {$JPPEXPANDMACRO COUNTOBJECTEQINT(CountObject,IJclIterator<T>,const ,AItem,T,TEqualityCompare<T>)} overload; class {$JPPEXPANDMACRO COPYINT(Copy,IJclIterator<T>)} class {$JPPEXPANDMACRO GENERATEINT(Generate,IJclList<T>,const ,AItem,T)} class {$JPPEXPANDMACRO FILLINT(Fill,IJclIterator<T>,const ,AItem,T)} class {$JPPEXPANDMACRO REVERSEINT(Reverse,IJclIterator<T>)} class {$JPPEXPANDMACRO SORTINT(QuickSort,IJclList<T>,L,R,TCompare<T>)} class {$JPPEXPANDMACRO SORTINT(Sort,IJclList<T>,First,Last,TCompare<T>)} //class property SortProc: TSortProc<T> read FSortProc write FSortProc; end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclAlgorithms.pas $'; Revision: '$Revision: 2309 $'; Date: '$Date: 2008-01-15 23:30:26 +0100 (mar., 15 janv. 2008) $'; LogPath: 'JCL\source\common' ); {$ENDIF UNITVERSIONING} implementation uses {$IFNDEF RTL140_UP} JclWideStrings, {$ENDIF ~RTL140_UP} SysUtils; function IntfSimpleCompare(const Obj1, Obj2: IInterface): Integer; begin if Integer(Obj1) < Integer(Obj2) then Result := -1 else if Integer(Obj1) > Integer(Obj2) then Result := 1 else Result := 0; end; function AnsiStrSimpleCompare(const Obj1, Obj2: AnsiString): Integer; begin // (rom) changed to case sensitive compare Result := CompareStr(Obj1, Obj2); end; function WideStrSimpleCompare(const Obj1, Obj2: WideString): Integer; begin // (rom) changed to case sensitive compare Result := WideCompareStr(Obj1, Obj2); end; function StrSimpleCompare(const Obj1, Obj2: string): Integer; begin case SizeOf(Obj1[1]) of SizeOf(AnsiChar): Result := CompareStr(Obj1, Obj2); SizeOf(WideChar): Result := WideCompareStr(Obj1, Obj2); else raise EJclOperationNotSupportedError.Create; end; end; function SingleSimpleCompare(const Obj1, Obj2: Single): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function DoubleSimpleCompare(const Obj1, Obj2: Double): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function ExtendedSimpleCompare(const Obj1, Obj2: Extended): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function FloatSimpleCompare(const Obj1, Obj2: Float): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function IntegerSimpleCompare(Obj1, Obj2: Integer): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function CardinalSimpleCompare(Obj1, Obj2: Cardinal): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; function Int64SimpleCompare(const Obj1, Obj2: Int64): Integer; begin if Obj1 < Obj2 then Result := -1 else if Obj1 > Obj2 then Result := 1 else Result := 0; end; {$IFNDEF CLR} function PtrSimpleCompare(Obj1, Obj2: Pointer): Integer; begin if Integer(Obj1) < Integer(Obj2) then Result := -1 else if Integer(Obj1) > Integer(Obj2) then Result := 1 else Result := 0; end; {$ENDIF ~CLR} function SimpleCompare(Obj1, Obj2: TObject): Integer; begin if Integer(Obj1) < Integer(Obj2) then Result := -1 else if Integer(Obj1) > Integer(Obj2) then Result := 1 else Result := 0; end; function IntegerCompare(Obj1, Obj2: TObject): Integer; begin if Integer(Obj1) < Integer(Obj2) then Result := -1 else if Integer(Obj1) > Integer(Obj2) then Result := 1 else Result := 0; end; function IntfSimpleEqualityCompare(const Obj1, Obj2: IInterface): Boolean; begin Result := Integer(Obj1) = Integer(Obj2); end; function AnsiStrSimpleEqualityCompare(const Obj1, Obj2: AnsiString): Boolean; begin // (rom) changed to case sensitive compare Result := CompareStr(Obj1, Obj2) = 0; end; function WideStrSimpleEqualityCompare(const Obj1, Obj2: WideString): Boolean; begin // (rom) changed to case sensitive compare Result := WideCompareStr(Obj1, Obj2) = 0; end; function StrSimpleEqualityCompare(const Obj1, Obj2: string): Boolean; begin case SizeOf(Obj1[1]) of SizeOf(AnsiChar): Result := CompareStr(Obj1, Obj2) = 0; SizeOf(WideChar): Result := WideCompareStr(Obj1, Obj2) = 0; else raise EJclOperationNotSupportedError.Create; end; end; function SingleSimpleEqualityCompare(const Obj1, Obj2: Single): Boolean; begin Result := Obj1 = Obj2; end; function DoubleSimpleEqualityCompare(const Obj1, Obj2: Double): Boolean; begin Result := Obj1 = Obj2; end; function ExtendedSimpleEqualityCompare(const Obj1, Obj2: Extended): Boolean; begin Result := Obj1 = Obj2; end; function FloatSimpleEqualityCompare(const Obj1, Obj2: Float): Boolean; begin Result := Obj1 = Obj2; end; function IntegerSimpleEqualityCompare(Obj1, Obj2: Integer): Boolean; begin Result := Obj1 = Obj2; end; function CardinalSimpleEqualityCompare(Obj1, Obj2: Cardinal): Boolean; begin Result := Obj1 = Obj2; end; function Int64SimpleEqualityCompare(const Obj1, Obj2: Int64): Boolean; begin Result := Obj1 = Obj2; end; {$IFNDEF CLR} function PtrSimpleEqualityCompare(Obj1, Obj2: Pointer): Boolean; begin Result := Integer(Obj1) = Integer(Obj2); end; {$ENDIF ~CLR} function SimpleEqualityCompare(Obj1, Obj2: TObject): Boolean; begin Result := Integer(Obj1) = Integer(Obj2); end; {$JPPEXPANDMACRO APPLYIMP(Apply,IJclIntfIterator,TIntfApplyFunction,SetObject)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclAnsiStrIterator,TAnsiStrApplyFunction,SetString)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclWideStrIterator,TWideStrApplyFunction,SetString)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclSingleIterator,TSingleApplyFunction,SetValue)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclDoubleIterator,TDoubleApplyFunction,SetValue)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclExtendedIterator,TExtendedApplyFunction,SetValue)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclIntegerIterator,TIntegerApplyFunction,SetValue)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclCardinalIterator,TCardinalApplyFunction,SetValue)} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclInt64Iterator,TInt64ApplyFunction,SetValue)} {$IFNDEF CLR} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclPtrIterator,TPtrApplyFunction,SetPointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO APPLYIMP(Apply,IJclIterator,TApplyFunction,SetObject)} {$JPPEXPANDMACRO FINDIMP(Find,IJclIntfIterator,const ,AInterface,IInterface,TIntfCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclIntfIterator,const ,AInterface,IInterface,TIntfEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclWideStrIterator,const ,AString,WideString,TWideStrCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclWideStrIterator,const ,AString,WideString,TWideStrEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclSingleIterator,const ,AValue,Single,TSingleCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclSingleIterator,const ,AValue,Single,TSingleEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclDoubleIterator,const ,AValue,Double,TDoubleCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclDoubleIterator,const ,AValue,Double,TDoubleEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclExtendedIterator,const ,AValue,Extended,TExtendedCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclExtendedIterator,const ,AValue,Extended,TExtendedEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclIntegerIterator,,AValue,Integer,TIntegerCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclIntegerIterator,,AValue,Integer,TIntegerEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclCardinalIterator,,AValue,Cardinal,TCardinalCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclCardinalIterator,,AValue,Cardinal,TCardinalEqualityCompare)} {$JPPEXPANDMACRO FINDIMP(Find,IJclInt64Iterator,const ,AValue,Int64,TInt64Compare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclInt64Iterator,const ,AValue,Int64,TInt64EqualityCompare)} {$IFNDEF CLR} {$JPPEXPANDMACRO FINDIMP(Find,IJclPtrIterator,,APtr,Pointer,TPtrCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclPtrIterator,,APtr,Pointer,TPtrEqualityCompare)} {$ENDIF ~CLR} {$JPPEXPANDMACRO FINDIMP(Find,IJclIterator,,AObject,TObject,TCompare)} {$JPPEXPANDMACRO FINDEQIMP(Find,IJclIterator,,AObject,TObject,TEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclIntfIterator,const ,AInterface,IInterface,TIntfCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclIntfIterator,const ,AInterface,IInterface,TIntfEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclAnsiStrIterator,const ,AString,AnsiString,TAnsiStrEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclWideStrIterator,const ,AString,WideString,TWideStrCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclWideStrIterator,const ,AString,WideString,TWideStrEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclSingleIterator,const ,AValue,Single,TSingleCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclSingleIterator,const ,AValue,Single,TSingleEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclDoubleIterator,const ,AValue,Double,TDoubleCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclDoubleIterator,const ,AValue,Double,TDoubleEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclExtendedIterator,const ,AValue,Extended,TExtendedCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclExtendedIterator,const ,AValue,Extended,TExtendedEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclIntegerIterator,,AValue,Integer,TIntegerCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclIntegerIterator,,AValue,Integer,TIntegerEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclCardinalIterator,,AValue,Cardinal,TCardinalCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclCardinalIterator,,AValue,Cardinal,TCardinalEqualityCompare)} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclInt64Iterator,const ,AValue,Int64,TInt64Compare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclInt64Iterator,const ,AValue,Int64,TInt64EqualityCompare)} {$IFNDEF CLR} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclPtrIterator,,APtr,Pointer,TPtrCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclPtrIterator,,APtr,Pointer,TPtrEqualityCompare)} {$ENDIF ~CLR} {$JPPEXPANDMACRO COUNTOBJECTIMP(CountObject,IJclIterator,,AObject,TObject,TCompare)} {$JPPEXPANDMACRO COUNTOBJECTEQIMP(CountObject,IJclIterator,,AObject,TObject,TEqualityCompare)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclIntfIterator,SetObject)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclAnsiStrIterator,SetString)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclWideStrIterator,SetString)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclSingleIterator,SetValue)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclDoubleIterator,SetValue)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclExtendedIterator,SetValue)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclIntegerIterator,SetValue)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclCardinalIterator,SetValue)} {$JPPEXPANDMACRO COPYIMP(Copy,IJclInt64Iterator,SetValue)} {$IFNDEF CLR} {$JPPEXPANDMACRO COPYIMP(Copy,IJclPtrIterator,SetPointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO COPYIMP(Copy,IJclIterator,SetObject)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclIntfList,const ,AInterface,IInterface)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclAnsiStrList,const ,AString,AnsiString)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclWideStrList,const ,AString,WideString)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclSingleList,const ,AValue,Single)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclDoubleList,const ,AValue,Double)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclExtendedList,const ,AValue,Extended)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclIntegerList,,AValue,Integer)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclCardinalList,,AValue,Cardinal)} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclInt64List,const ,AValue,Int64)} {$IFNDEF CLR} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclPtrList,,APtr,Pointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO GENERATEIMP(Generate,IJclList,,AObject,TObject)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclIntfIterator,const ,AInterface,IInterface,SetObject)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclAnsiStrIterator,const ,AString,AnsiString,SetString)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclWideStrIterator,const ,AString,WideString,SetString)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclSingleIterator,const ,AValue,Single,SetValue)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclDoubleIterator,const ,AValue,Double,SetValue)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclExtendedIterator,const ,AValue,Extended,SetValue)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclIntegerIterator,,AValue,Integer,SetValue)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclCardinalIterator,,AValue,Cardinal,SetValue)} {$JPPEXPANDMACRO FILLIMP(Fill,IJclInt64Iterator,const ,AValue,Int64,SetValue)} {$IFNDEF CLR} {$JPPEXPANDMACRO FILLIMP(Fill,IJclPtrIterator,,APtr,Pointer,SetPointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO FILLIMP(Fill,IJclIterator,,AObject,TObject,SetObject)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclIntfIterator,IInterface,GetObject,SetObject)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclAnsiStrIterator,AnsiString,GetString,SetString)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclWideStrIterator,WideString,GetString,SetString)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclSingleIterator,Single,GetValue,SetValue)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclDoubleIterator,Double,GetValue,SetValue)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclExtendedIterator,Extended,GetValue,SetValue)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclIntegerIterator,Integer,GetValue,SetValue)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclCardinalIterator,Cardinal,GetValue,SetValue)} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclInt64Iterator,Int64,GetValue,SetValue)} {$IFNDEF CLR} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclPtrIterator,Pointer,GetPointer,SetPointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO REVERSEIMP(Reverse,IJclIterator,TObject,GetObject,SetObject)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclIntfList,L,R,TIntfCompare,IInterface,GetObject,SetObject)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclAnsiStrList,L,R,TAnsiStrCompare,AnsiString,GetString,SetString)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclWideStrList,L,R,TWideStrCompare,WideString,GetString,SetString)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclSingleList,L,R,TSingleCompare,Single,GetValue,SetValue)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclDoubleList,L,R,TDoubleCompare,Double,GetValue,SetValue)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclExtendedList,L,R,TExtendedCompare,Extended,GetValue,SetValue)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclIntegerList,L,R,TIntegerCompare,Integer,GetValue,SetValue)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclCardinalList,L,R,TCardinalCompare,Cardinal,GetValue,SetValue)} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclInt64List,L,R,TInt64Compare,Int64,GetValue,SetValue)} {$IFNDEF CLR} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclPtrList,L,R,TPtrCompare,Pointer,GetPointer,SetPointer)} {$ENDIF ~CLR} {$JPPEXPANDMACRO QUICKSORTIMP(QuickSort,IJclList,L,R,TCompare,TObject,GetObject,SetObject)} procedure Sort(const AList: IJclIntfList; First, Last: Integer; AComparator: TIntfCompare); begin IntfSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclAnsiStrList; First, Last: Integer; AComparator: TAnsiStrCompare); begin AnsiStrSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclWideStrList; First, Last: Integer; AComparator: TWideStrCompare); begin WideStrSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclSingleList; First, Last: Integer; AComparator: TSingleCompare); begin SingleSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclDoubleList; First, Last: Integer; AComparator: TDoubleCompare); begin DoubleSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclExtendedList; First, Last: Integer; AComparator: TExtendedCompare); begin ExtendedSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclIntegerList; First, Last: Integer; AComparator: TIntegerCompare); begin IntegerSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclCardinalList; First, Last: Integer; AComparator: TCardinalCompare); begin CardinalSortProc(AList, First, Last, AComparator); end; procedure Sort(const AList: IJclInt64List; First, Last: Integer; AComparator: TInt64Compare); begin Int64SortProc(AList, First, Last, AComparator); end; {$IFNDEF CLR} procedure Sort(const AList: IJclPtrList; First, Last: Integer; AComparator: TPtrCompare); begin PtrSortProc(AList, First, Last, AComparator); end; {$ENDIF ~CLR} procedure Sort(const AList: IJclList; First, Last: Integer; AComparator: TCompare); begin SortProc(AList, First, Last, AComparator); end; {$IFDEF SUPPORTS_GENERICS} class {$JPPEXPANDMACRO APPLYIMP(TJclAlgorithms<T>.Apply,IJclIterator<T>,TApplyFunction<T>,SetItem)} class {$JPPEXPANDMACRO FINDIMP(TJclAlgorithms<T>.Find,IJclIterator<T>,const ,AItem,T,TCompare<T>)} class {$JPPEXPANDMACRO FINDEQIMP(TJclAlgorithms<T>.Find,IJclIterator<T>,const ,AItem,T,TEqualityCompare<T>)} class {$JPPEXPANDMACRO COUNTOBJECTIMP(TJclAlgorithms<T>.CountObject,IJclIterator<T>,const ,AItem,T,TCompare<T>)} class {$JPPEXPANDMACRO COUNTOBJECTEQIMP(TJclAlgorithms<T>.CountObject,IJclIterator<T>,const ,AItem,T,TEqualityCompare<T>)} class {$JPPEXPANDMACRO COPYIMP(TJclAlgorithms<T>.Copy,IJclIterator<T>,SetItem)} class {$JPPEXPANDMACRO GENERATEIMP(TJclAlgorithms<T>.Generate,IJclList<T>,const ,AItem,T)} class {$JPPEXPANDMACRO FILLIMP(TJclAlgorithms<T>.Fill,IJclIterator<T>,const ,AItem,T,SetItem)} class {$JPPEXPANDMACRO REVERSEIMP(TJclAlgorithms<T>.Reverse,IJclIterator<T>,T,GetItem,SetItem)} class {$JPPEXPANDMACRO QUICKSORTIMP(TJclAlgorithms<T>.QuickSort,IJclList<T>,L,R,TCompare<T>,T,GetItem,SetItem)} class procedure TJclAlgorithms<T>.Sort(const AList: IJclList<T>; First, Last: Integer; AComparator: TCompare<T>); begin TJclAlgorithms<T>.QuickSort(AList, First, Last, AComparator); end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
namespace RemObjects.Elements.System; uses Foundation; [SwiftName("NSLocalizedString(key:, comment:)")] method NSLocalizedString(aKey: String; aIgnoredComment: String): String; public; inline; begin result := NSBundle.mainBundle.localizedStringForKey(aKey) value("") table(nil); end; method NSLocalizedStringFromTable(aKey: String; aTable: String; aIgnoredComment: String): String; public; inline; begin result := NSBundle.mainBundle.localizedStringForKey(aKey) value("") table(aTable); end; method NSLocalizedStringFromTableInBundle(aKey: String; aTable: String; aBundle: NSBundle; aIgnoredComment: String): String; public; inline; begin result := aBundle.mainBundle.localizedStringForKey(aKey) value("") table(aTable); end; method NSLocalizedStringWithDefaultValue(aKey: String; aTable: String; aBundle: NSBundle; aDefaultValue: String; aIgnoredComment: String): String; public; inline; begin result := aBundle.mainBundle.localizedStringForKey(aKey) value(aDefaultValue) table(aTable); end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXOracleMetaDataReader; interface uses Data.DBXCommon, Data.DBXCommonTable, Data.DBXMetaDataNames, Data.DBXMetaDataReader, Data.DBXPlatform; type /// <summary> TDBXOracleCustomMetaDataReader contains custom code for Orcale. /// </summary> /// <remarks> This class handles default values. /// </remarks> TDBXOracleCustomMetaDataReader = class(TDBXBaseMetaDataReader) public type /// <summary> TDBXOracleColumnsCursor is a filter for a cursor providing table columns. /// </summary> /// <remarks> In Oracle the default value is kept in a LONG data type. Oracle does not allow SQL /// operations like TRIM() on LONG values. /// This filter will trim the default values. /// </remarks> TDBXOracleColumnsCursor = class(TDBXCustomMetaDataTable) public destructor Destroy; override; function Next: Boolean; override; protected constructor Create(const Provider: TDBXOracleCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; public FDefaultValue: TDBXWritableValue; end; /// <summary> TDBXOracleIndexColumnsCursor is a filter for a cursor providing index columns. /// </summary> /// <remarks> In Oracle indexes can be created from expressions, therefore there are no column /// names specified for each index. /// This filter tries to extract the column name from an index expression. /// </remarks> TDBXOracleIndexColumnsCursor = class(TDBXCustomMetaDataTable) public destructor Destroy; override; function Next: Boolean; override; protected constructor Create(const Provider: TDBXOracleCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override; private function ComputeColumnName: string; private FNameValue: TDBXWritableValue; private const ColumnExpressionOrdinal = TDBXIndexColumnsIndex.Last + 1; const ColumnExpressionNullOrdinal = TDBXIndexColumnsIndex.Last + 2; end; public /// <summary> Overrides the implementation in TDBXBaseMetaDataReader. /// </summary> /// <remarks> A custom filter is added to trim the default values. /// </remarks> /// <seealso cref="TDBXOracleColumnsCursor"/> function FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override; /// <summary> Overrides the implementation in TDBXBaseMetaDataProvider. /// </summary> /// <remarks> A custom filter is added to retrieve the column names. /// </remarks> /// <seealso cref="TDBXOracleColumnsCursor"/> function FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable; override; protected procedure PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray); override; function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override; end; TDBXOracleMetaDataReader = class(TDBXOracleCustomMetaDataReader) public function FetchCatalogs: TDBXTable; override; function FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable; override; protected function AreSchemasSupported: Boolean; override; function GetProductName: string; override; function IsNestedTransactionsSupported: Boolean; override; function IsSetRowSizeSupported: Boolean; override; function GetSqlForSchemas: string; override; function GetSqlForTables: string; override; function GetSqlForViews: string; override; function GetSqlForColumns: string; override; function GetSqlForIndexes: string; override; function GetSqlForIndexColumns: string; override; function GetSqlForForeignKeys: string; override; function GetSqlForForeignKeyColumns: string; override; function GetSqlForSynonyms: string; override; function GetSqlForProcedures: string; override; function GetSqlForProcedureSources: string; override; function GetSqlForProcedureParameters: string; override; function GetSqlForPackages: string; override; function GetSqlForPackageSources: string; override; function GetSqlForPackageProcedures: string; override; function GetSqlForPackageProcedureParameters: string; override; function GetSqlForUsers: string; override; function GetSqlForRoles: string; override; function GetReservedWords: TDBXStringArray; override; end; implementation uses System.SysUtils; procedure TDBXOracleCustomMetaDataReader.PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray); var Def: TDBXDataTypeDescription; begin inherited PopulateDataTypes(Hash, Types, Descr); Def := TDBXDataTypeDescription.Create('REF CURSOR', TDBXDataTypes.CursorType, 0, NullString, NullString, 0, 0, NullString, NullString, NullString, NullString, 0); Hash[Def.TypeName] := Def; Def := TDBXDataTypeDescription.Create('PL/SQL BOOLEAN', TDBXDataTypes.BooleanType, 0, NullString, NullString, 0, 0, NullString, NullString, NullString, NullString, 0); Hash[Def.TypeName] := Def; Def := TDBXDataTypeDescription.Create('BINARY_INTEGER', TDBXDataTypes.Int32Type, 0, NullString, NullString, 0, 0, NullString, NullString, NullString, NullString, 0); Hash[Def.TypeName] := Def; end; function TDBXOracleCustomMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; var Types: TDBXDataTypeDescriptionArray; begin SetLength(Types,22); Types[0] := TDBXDataTypeDescription.Create('BFILE', TDBXDataTypes.BlobType, 4294967296, 'BFILE', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[1] := TDBXDataTypeDescription.Create('BLOB', TDBXDataTypes.BlobType, 4294967296, 'BLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[2] := TDBXDataTypeDescription.Create('CHAR', TDBXDataTypes.WideStringType, 2000, 'CHAR({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.LiteralSupported); Types[3] := TDBXDataTypeDescription.Create('CLOB', TDBXDataTypes.WideStringType, 4294967296, 'CLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[4] := TDBXDataTypeDescription.Create('DATE', TDBXDataTypes.TimeStampType, 19, 'DATE', NullString, -1, -1, 'TO_DATE(''', ''',''YYYY-MM-DD HH24:MI:SS'')', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[5] := TDBXDataTypeDescription.Create('FLOAT', TDBXDataTypes.BcdType, 126, 'FLOAT({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[6] := TDBXDataTypeDescription.Create('BINARY_FLOAT', TDBXDataTypes.SingleType, 7, 'BINARY_FLOAT', NullString, -1, -1, '', '', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[7] := TDBXDataTypeDescription.Create('BINARY_DOUBLE', TDBXDataTypes.DoubleType, 53, 'BINARY_DOUBLE', NullString, -1, -1, '', '', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[8] := TDBXDataTypeDescription.Create('INTERVAL DAY TO SECOND', TDBXDataTypes.IntervalType, 0, 'INTERVAL DAY({0}) TO SECOND({1})', 'Precision,Scale', -1, -1, 'TO_DSINTERVAL(''', ''')', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[9] := TDBXDataTypeDescription.Create('INTERVAL YEAR TO MONTH', TDBXDataTypes.IntervalType, 0, 'INTERVAL YEAR({0}) TO MONTH', 'Precision', -1, -1, 'TO_YMINTERVAL(''', ''')', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[10] := TDBXDataTypeDescription.Create('LONG', TDBXDataTypes.WideStringType, 2147483647, 'LONG', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long); Types[11] := TDBXDataTypeDescription.Create('LONG RAW', TDBXDataTypes.BytesType, 2147483647, 'LONG RAW', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable); Types[12] := TDBXDataTypeDescription.Create('NCHAR', TDBXDataTypes.WideStringType, 2000, 'NCHAR({0})', 'Precision', -1, -1, 'N''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.LiteralSupported or TDBXTypeFlag.Unicode); Types[13] := TDBXDataTypeDescription.Create('NCLOB', TDBXDataTypes.WideStringType, 4294967296, 'NCLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Unicode); Types[14] := TDBXDataTypeDescription.Create('NUMBER', TDBXDataTypes.BcdType, 38, 'NUMBER({0},{1})', 'Precision,Scale', 127, -84, '', '', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[15] := TDBXDataTypeDescription.Create('NVARCHAR2', TDBXDataTypes.WideStringType, 4000, 'NVARCHAR2({0})', 'Precision', -1, -1, 'N''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported or TDBXTypeFlag.Unicode); Types[16] := TDBXDataTypeDescription.Create('RAW', TDBXDataTypes.BytesType, 2000, 'RAW({0})', 'Precision', -1, -1, 'HEXTORAW(''', ''')', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[17] := TDBXDataTypeDescription.Create('TIMESTAMP', TDBXDataTypes.TimeStampType, 27, 'TIMESTAMP({0})', 'Precision', -1, -1, 'TO_TIMESTAMP(''', ''',''YYYY-MM-DD HH24:MI:SS.FF'')', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[18] := TDBXDataTypeDescription.Create('TIMESTAMP WITH LOCAL TIME ZONE', TDBXDataTypes.TimeStampType, 27, 'TIMESTAMP({0} WITH LOCAL TIME ZONE)', 'Precision', -1, -1, 'TO_TIMESTAMP_TZ(''', ''',''YYYY-MM-DD HH24:MI:SS.FF'')', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[19] := TDBXDataTypeDescription.Create('TIMESTAMP WITH TIME ZONE', TDBXDataTypes.TimeStampType, 34, 'TIMESTAMP({0} WITH TIME ZONE)', 'Precision', -1, -1, 'TO_TIMESTAMP_TZ(''', ''',''YYYY-MM-DD HH24:MI:SS.FF TZH:TZM'')', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported); Types[20] := TDBXDataTypeDescription.Create('VARCHAR2', TDBXDataTypes.WideStringType, 4000, 'VARCHAR2({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.LiteralSupported); Types[21] := TDBXDataTypeDescription.Create('XMLTYPE', TDBXDataTypes.WideStringType, 4000, 'XMLTYPE', NullString, -1, -1, '', '', NullString, NullString, TDBXTypeFlag.LiteralSupported); Result := Types; end; function TDBXOracleCustomMetaDataReader.FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable; var ParameterNames, ParameterValues: TDBXStringArray; Cursor: TDBXTable; Columns: TDBXValueTypeArray; begin SetLength(ParameterNames,3); ParameterNames[0] := TDBXParameterName.CatalogName; ParameterNames[1] := TDBXParameterName.SchemaName; ParameterNames[2] := TDBXParameterName.TableName; SetLength(ParameterValues,3); ParameterValues[0] := Catalog; ParameterValues[1] := Schema; ParameterValues[2] := Table; Cursor := Context.ExecuteQuery(SqlForColumns, ParameterNames, ParameterValues); Columns := TDBXMetaDataCollectionColumns.CreateColumnsColumns; Result := TDBXColumnsTableCursor.Create(self, False, TDBXOracleCustomMetaDataReader.TDBXOracleColumnsCursor.Create(self, Columns, Cursor)); end; function TDBXOracleCustomMetaDataReader.FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable; var ParameterNames, ParameterValues: TDBXStringArray; Cursor: TDBXTable; Columns: TDBXValueTypeArray; begin SetLength(ParameterNames,4); ParameterNames[0] := TDBXParameterName.CatalogName; ParameterNames[1] := TDBXParameterName.SchemaName; ParameterNames[2] := TDBXParameterName.TableName; ParameterNames[3] := TDBXParameterName.IndexName; SetLength(ParameterValues,4); ParameterValues[0] := Catalog; ParameterValues[1] := Schema; ParameterValues[2] := Table; ParameterValues[3] := Index; Cursor := Context.ExecuteQuery(SqlForIndexColumns, ParameterNames, ParameterValues); Columns := TDBXMetaDataCollectionColumns.CreateIndexColumnsColumns; Result := TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.Create(self, Columns, Cursor); end; constructor TDBXOracleCustomMetaDataReader.TDBXOracleColumnsCursor.Create(const Provider: TDBXOracleCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); begin inherited Create(Provider.Context, TDBXMetaDataCollectionName.Columns, Columns, Cursor); end; destructor TDBXOracleCustomMetaDataReader.TDBXOracleColumnsCursor.Destroy; begin FreeAndNil(FDefaultValue); inherited Destroy; end; function TDBXOracleCustomMetaDataReader.TDBXOracleColumnsCursor.Next: Boolean; begin if inherited Next then begin if FDefaultValue = nil then FDefaultValue := TDBXWritableValue(TDBXValue.CreateValue(TDBXValueType(inherited GetWritableValue(TDBXColumnsIndex.DefaultValue).ValueType.Clone()))); FDefaultValue.AsString := Trim(inherited GetWritableValue(TDBXColumnsIndex.DefaultValue).AsString); Exit(True); end; if FDefaultValue <> nil then FDefaultValue.SetNull; Result := False; end; function TDBXOracleCustomMetaDataReader.TDBXOracleColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin if Ordinal = TDBXColumnsIndex.DefaultValue then Exit(FDefaultValue); Result := inherited GetWritableValue(Ordinal); end; constructor TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.Create(const Provider: TDBXOracleCustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable); begin inherited Create(Provider.Context, TDBXMetaDataCollectionName.IndexColumns, Columns, Cursor); end; destructor TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.Destroy; begin FreeAndNil(FNameValue); inherited Destroy; end; function TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.Next: Boolean; begin if inherited Next then begin if FNameValue = nil then FNameValue := TDBXWritableValue(TDBXValue.CreateValue(TDBXValueType(inherited GetWritableValue(TDBXIndexColumnsIndex.ColumnName).ValueType.Clone()))); FNameValue.AsString := ComputeColumnName; Exit(True); end; if FNameValue <> nil then FNameValue.SetNull; Result := False; end; function TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue; begin if Ordinal = TDBXIndexColumnsIndex.ColumnName then Exit(FNameValue); Result := inherited GetWritableValue(Ordinal); end; function TDBXOracleCustomMetaDataReader.TDBXOracleIndexColumnsCursor.ComputeColumnName: string; var Expression: string; begin Expression := NullString; if FCursor.Value[ColumnExpressionNullOrdinal].AsInt32 <> 0 then Exit(inherited GetWritableValue(TDBXIndexColumnsIndex.ColumnName).AsString) else begin Expression := FCursor.Value[ColumnExpressionOrdinal].AsString; if (not Expression.IsEmpty) and (Expression.Length > 0) then begin if (Expression.Length > 2) and (Expression.Chars[0] = '"') and (Expression.Chars[Expression.Length - 1] = '"') and (Expression.IndexOf(' ') < 0) then Expression := Expression.Substring(1, Expression.Length - 2); end; end; Result := Expression; end; function TDBXOracleMetaDataReader.AreSchemasSupported; begin Result := True; end; function TDBXOracleMetaDataReader.GetProductName: string; begin Result := 'Oracle'; end; function TDBXOracleMetaDataReader.IsNestedTransactionsSupported: Boolean; begin Result := True; end; function TDBXOracleMetaDataReader.IsSetRowSizeSupported: Boolean; begin Result := True; end; function TDBXOracleMetaDataReader.FetchCatalogs: TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns); end; function TDBXOracleMetaDataReader.GetSqlForSchemas: string; begin Result := 'SELECT DISTINCT NULL, OWNER ' + 'FROM ALL_OBJECTS ' + 'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) ' + 'ORDER BY 1'; end; function TDBXOracleMetaDataReader.GetSqlForTables: string; begin Result := 'SELECT /*+ NO_EXPAND */ NULL, OWNER, OBJECT_NAME, CASE WHEN OWNER IN (''SYS'',''SYSTEM'',''CTXSYS'',''DMSYS'',''EXFSYS'',''OLAPSYS'',''ORDSYS'',''MDSYS'',''WKSYS'',''WK_TEST'',''WMSYS'',''XDB'') THEN ''SYSTEM '' ELSE '''' END || OBJECT_TYPE ' + 'FROM ALL_OBJECTS ' + 'WHERE OBJECT_TYPE IN (''VIEW'',''TABLE'',''SYNONYM'') ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (OBJECT_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + ' AND ((CASE WHEN OWNER IN (''SYS'',''SYSTEM'',''CTXSYS'',''DMSYS'',''EXFSYS'',''OLAPSYS'',''ORDSYS'',''MDSYS'',''WKSYS'',''WK_TEST'',''WMSYS'',''XDB'') THEN ''SYSTEM '' ELSE '''' END) || OBJECT_TYPE IN (:TABLES,:VIEWS,:SYSTEM_TABLES,:SYSTEM_VIEWS,:SYNONYMS)) ' + 'ORDER BY 2, 3'; end; function TDBXOracleMetaDataReader.GetSqlForViews: string; begin Result := 'SELECT NULL, OWNER, VIEW_NAME, TEXT ' + 'FROM SYS.ALL_VIEWS ' + 'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (VIEW_NAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' + 'ORDER BY 2, 3'; end; function TDBXOracleMetaDataReader.GetSqlForColumns: string; begin Result := 'SELECT NULL, OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE, COALESCE(DATA_PRECISION,CHAR_COL_DECL_LENGTH,DATA_LENGTH), DATA_SCALE, COLUMN_ID, DATA_DEFAULT, DECODE(NULLABLE,''Y'',1,''YES'',1,0), 0, NULL ' + 'FROM SYS.ALL_TAB_COLUMNS ' + 'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 2, 3, COLUMN_ID'; end; function TDBXOracleMetaDataReader.FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable; var Columns: TDBXValueTypeArray; begin Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns; Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns); end; function TDBXOracleMetaDataReader.GetSqlForIndexes: string; begin Result := 'SELECT NULL, I.TABLE_OWNER, I.TABLE_NAME, I.INDEX_NAME, C.CONSTRAINT_NAME, CASE WHEN C.CONSTRAINT_TYPE = ''P'' THEN 1 ELSE 0 END, CASE WHEN I.UNIQUENESS = ''UNIQUE'' THEN 1 ELSE 0 END, 1 ' + 'FROM SYS.ALL_INDEXES I, SYS.ALL_CONSTRAINTS C ' + 'WHERE I.TABLE_OWNER=C.OWNER(+) AND I.INDEX_NAME=C.INDEX_NAME(+) AND I.TABLE_NAME=C.TABLE_NAME(+) ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(I.TABLE_OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (I.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 2, 3, 4'; end; function TDBXOracleMetaDataReader.GetSqlForIndexColumns: string; begin Result := 'SELECT NULL, C.TABLE_OWNER, C.TABLE_NAME, C.INDEX_NAME, C.COLUMN_NAME, C.COLUMN_POSITION, CASE WHEN C.DESCEND = ''DESC'' THEN 0 ELSE 1 END, E.COLUMN_EXPRESSION, CASE WHEN E.COLUMN_EXPRESSION IS NULL THEN 1 ELSE 0 END ' + 'FROM ALL_IND_COLUMNS C, ALL_IND_EXPRESSIONS E ' + 'WHERE C.INDEX_OWNER=E.INDEX_OWNER(+) AND C.INDEX_NAME=E.INDEX_NAME(+) AND C.COLUMN_POSITION=E.COLUMN_POSITION(+) ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(C.TABLE_OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (C.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (C.INDEX_NAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' + 'ORDER BY 2, 3, 4, 6'; end; function TDBXOracleMetaDataReader.GetSqlForForeignKeys: string; begin Result := 'SELECT NULL, OWNER, TABLE_NAME, CONSTRAINT_NAME ' + 'FROM ALL_CONSTRAINTS ' + 'WHERE CONSTRAINT_TYPE = ''R'' ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' + 'ORDER BY 2, 3, 4'; end; function TDBXOracleMetaDataReader.GetSqlForForeignKeyColumns: string; begin Result := 'SELECT NULL, FC.OWNER, FC.TABLE_NAME, FC.CONSTRAINT_NAME, FC.COLUMN_NAME, NULL, PC.OWNER, PC.TABLE_NAME, PC.CONSTRAINT_NAME, PC.COLUMN_NAME, FC.POSITION ' + 'FROM ALL_CONS_COLUMNS FC, ALL_CONSTRAINTS F, ALL_CONSTRAINTS P, ALL_CONS_COLUMNS PC ' + 'WHERE F.CONSTRAINT_TYPE = ''R'' ' + ' AND F.OWNER=FC.OWNER AND F.TABLE_NAME=FC.TABLE_NAME AND F.CONSTRAINT_NAME=FC.CONSTRAINT_NAME ' + ' AND F.R_OWNER=P.OWNER AND F.R_CONSTRAINT_NAME=P.CONSTRAINT_NAME ' + ' AND P.OWNER=PC.OWNER AND P.TABLE_NAME=PC.TABLE_NAME AND P.CONSTRAINT_NAME=PC.CONSTRAINT_NAME ' + ' AND FC.POSITION=PC.POSITION ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(FC.OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (FC.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FC.CONSTRAINT_NAME = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' + ' AND (1<2 OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (LOWER(PC.OWNER) = LOWER(:PRIMARY_SCHEMA_NAME) OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PC.TABLE_NAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (PC.CONSTRAINT_NAME = :PRIMARY_KEY_NAME OR (' + ':PRIMARY_KEY_NAME IS NULL)) ' + 'ORDER BY 2, 3, 4, FC.POSITION'; end; function TDBXOracleMetaDataReader.GetSqlForSynonyms: string; begin Result := 'SELECT NULL, OWNER, SYNONYM_NAME, NULL, TABLE_OWNER, TABLE_NAME ' + 'FROM ALL_SYNONYMS ' + 'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (SYNONYM_NAME = :SYNONYM_NAME OR (:SYNONYM_NAME IS NULL)) ' + 'ORDER BY 2,3'; end; function TDBXOracleMetaDataReader.GetSqlForProcedures: string; begin Result := 'SELECT NULL, OWNER, OBJECT_NAME, OBJECT_TYPE ' + 'FROM ALL_OBJECTS ' + 'WHERE OBJECT_TYPE IN (''FUNCTION'',''PROCEDURE'') ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (OBJECT_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (OBJECT_TYPE = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' + 'ORDER BY 2,3'; end; function TDBXOracleMetaDataReader.GetSqlForProcedureSources: string; begin Result := 'SELECT NULL, OWNER, NAME, TYPE, TEXT, NULL, LINE AS SOURCE_LINE_NUMBER ' + 'FROM ALL_SOURCE S ' + 'WHERE TYPE IN (''FUNCTION'',''PROCEDURE'') ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' + 'ORDER BY OWNER,NAME,LINE'; end; function TDBXOracleMetaDataReader.GetSqlForProcedureParameters: string; begin Result := 'SELECT NULL, OWNER, OBJECT_NAME, ARGUMENT_NAME, CASE WHEN POSITION=0 THEN ''RESULT'' WHEN IN_OUT=''IN/OUT'' THEN ''INOUT'' ELSE IN_OUT END, DATA_TYPE, NULL, NULL, POSITION, 1 ' + 'FROM ALL_ARGUMENTS ' + 'WHERE PACKAGE_NAME IS NULL AND DATA_LEVEL=0 AND DATA_TYPE IS NOT NULL ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (OBJECT_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (ARGUMENT_NAME = :PARAMETER_NAME OR (:PARAMETER_NAME IS NULL)) ' + 'ORDER BY OWNER,OBJECT_NAME,POSITION'; end; function TDBXOracleMetaDataReader.GetSqlForPackages: string; begin Result := 'SELECT NULL, OWNER, OBJECT_NAME ' + 'FROM ALL_OBJECTS ' + 'WHERE OBJECT_TYPE IN (''PACKAGE'') ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (OBJECT_NAME = :PACKAGE_NAME OR (:PACKAGE_NAME IS NULL)) ' + 'ORDER BY 2,3'; end; function TDBXOracleMetaDataReader.GetSqlForPackageSources: string; begin Result := 'SELECT NULL, OWNER, NAME, TEXT, LINE AS SOURCE_LINE_NUMBER ' + 'FROM ALL_SOURCE S ' + 'WHERE TYPE IN (''PACKAGE'') ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (NAME = :PACKAGE_NAME OR (:PACKAGE_NAME IS NULL)) ' + 'ORDER BY OWNER,NAME,LINE'; end; function TDBXOracleMetaDataReader.GetSqlForPackageProcedures: string; begin Result := 'SELECT NULL, OWNER, PACKAGE_NAME, OBJECT_NAME, CASE WHEN MIN(POSITION)=0 THEN ''FUNCTION'' ELSE ''PROCEDURE'' END ' + 'FROM ALL_ARGUMENTS ' + 'WHERE PACKAGE_NAME IS NOT NULL ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (PACKAGE_NAME = :PACKAGE_NAME OR (:PACKAGE_NAME IS NULL)) AND (OBJECT_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' + 'GROUP BY OWNER, PACKAGE_NAME, OBJECT_NAME ' + 'HAVING (CASE WHEN MIN(POSITION)=0 THEN ''FUNCTION'' ELSE ''PROCEDURE'' END = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL))'; end; function TDBXOracleMetaDataReader.GetSqlForPackageProcedureParameters: string; begin Result := 'SELECT NULL, OWNER, PACKAGE_NAME, OBJECT_NAME, ARGUMENT_NAME, CASE WHEN POSITION=0 THEN ''RESULT'' WHEN IN_OUT=''IN/OUT'' THEN ''INOUT'' ELSE IN_OUT END, DATA_TYPE, NULL, NULL, POSITION, 1 ' + 'FROM ALL_ARGUMENTS ' + 'WHERE PACKAGE_NAME IS NOT NULL AND DATA_LEVEL=0 AND DATA_TYPE IS NOT NULL ' + ' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(OWNER) = LOWER(:SCHEMA_NAME) OR (:SCHEMA_NAME IS NULL)) AND (PACKAGE_NAME = :PACKAGE_NAME OR (:PACKAGE_NAME IS NULL)) AND (OBJECT_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (ARGUMENT_NAME = :P' + 'ARAMETER_NAME OR (:PARAMETER_NAME IS NULL)) ' + 'ORDER BY OWNER,PACKAGE_NAME,OBJECT_NAME,POSITION'; end; function TDBXOracleMetaDataReader.GetSqlForUsers: string; begin Result := 'SELECT USERNAME FROM ALL_USERS ORDER BY 1'; end; function TDBXOracleMetaDataReader.GetSqlForRoles: string; begin Result := 'SELECT ROLE FROM SESSION_ROLES ORDER BY 1'; end; function TDBXOracleMetaDataReader.GetReservedWords: TDBXStringArray; var Words: TDBXStringArray; begin SetLength(Words,80); Words[0] := 'ALL'; Words[1] := 'ALTER'; Words[2] := 'AND'; Words[3] := 'ANY'; Words[4] := 'AS'; Words[5] := 'ASC'; Words[6] := 'BETWEEN'; Words[7] := 'BY'; Words[8] := 'CHAR'; Words[9] := 'CHECK'; Words[10] := 'CLUSTER'; Words[11] := 'COMPRESS'; Words[12] := 'CONNECT'; Words[13] := 'CREATE'; Words[14] := 'DATE'; Words[15] := 'DECIMAL'; Words[16] := 'DEFAULT'; Words[17] := 'DELETE'; Words[18] := 'DESC'; Words[19] := 'DISTINCT'; Words[20] := 'DROP'; Words[21] := 'ELSE'; Words[22] := 'EXCLUSIVE'; Words[23] := 'EXISTS'; Words[24] := 'FLOAT'; Words[25] := 'FOR'; Words[26] := 'FROM'; Words[27] := 'GRANT'; Words[28] := 'GROUP'; Words[29] := 'HAVING'; Words[30] := 'IDENTIFIED'; Words[31] := 'IN'; Words[32] := 'INDEX'; Words[33] := 'INSERT'; Words[34] := 'INTEGER'; Words[35] := 'INTERSECT'; Words[36] := 'INTO'; Words[37] := 'IS'; Words[38] := 'LIKE'; Words[39] := 'LOCK'; Words[40] := 'LONG'; Words[41] := 'MINUS'; Words[42] := 'MODE'; Words[43] := 'NOCOMPRESS'; Words[44] := 'NOT'; Words[45] := 'NOWAIT'; Words[46] := 'NULL'; Words[47] := 'NUMBER'; Words[48] := 'OF'; Words[49] := 'ON'; Words[50] := 'OPTION'; Words[51] := 'OR'; Words[52] := 'ORDER'; Words[53] := 'PCTFREE'; Words[54] := 'PRIOR'; Words[55] := 'PUBLIC'; Words[56] := 'RAW'; Words[57] := 'RENAME'; Words[58] := 'RESOURCE'; Words[59] := 'REVOKE'; Words[60] := 'SELECT'; Words[61] := 'SET'; Words[62] := 'SHARE'; Words[63] := 'SIZE'; Words[64] := 'SMALLINT'; Words[65] := 'START'; Words[66] := 'SYNONYM'; Words[67] := 'TABLE'; Words[68] := 'THEN'; Words[69] := 'TO'; Words[70] := 'TRIGGER'; Words[71] := 'UNION'; Words[72] := 'UNIQUE'; Words[73] := 'UPDATE'; Words[74] := 'VALUES'; Words[75] := 'VARCHAR'; Words[76] := 'VARCHAR2'; Words[77] := 'VIEW'; Words[78] := 'WHERE'; Words[79] := 'WITH'; Result := Words; end; end.
//----------------------------------------------------------------------------- // Original software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //----------------------------------------------------------------------------- {******************************************************************************} { ModernAppDemo by Carlo Barazzetta } { A full example of an HighDPI - VCL Themed enabled application } { See how to select the application Theme using VCLThemeSelector Form } { } { Copyright (c) 2020 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { https://github.com/EtheaDev/VCLThemeSelector } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit uSplitView; {$I ..\..\Source\VCLThemeSelector.inc} interface uses Winapi.Windows , Winapi.Messages , System.SysUtils , System.Variants , System.Classes , System.ImageList , System.Actions , Vcl.Graphics , Vcl.Controls , Vcl.Forms , Vcl.Dialogs , Vcl.ExtCtrls , Vcl.WinXCtrls , Vcl.StdCtrls , Vcl.CategoryButtons , Vcl.Buttons , Vcl.ImgList , Vcl.Imaging.PngImage , Vcl.ComCtrls , Vcl.ActnList , Vcl.Menus , Vcl.Mask , Data.DB , Datasnap.DBClient , Vcl.WinXCalendars , Vcl.CheckLst , Vcl.DBCtrls , Vcl.ColorGrd , Vcl.Samples.Spin , Vcl.Grids , Vcl.DBGrids , Vcl.ToolWin , Vcl.GraphUtil , EditForm , IconFontsImageList //uses IconFontsImageList - download free at: https://github.com/EtheaDev/IconFontsImageList , SVGIconImageList //uses SVGIconImageList - download free at: https://github.com/EtheaDev/SVGIconImageList , IconFontsUtils , FVCLThemeSelector , SVGIconImageListBase , IconFontsImageListBase , SVGIconVirtualImageList , IconFontsVirtualImageList , DImageCollections , SVGIconImage , IconFontsImage {$IFDEF VCLSTYLEUTILS} //VCLStyles support: //to compile you need to donwload VCLStyleUtils+DDetours from: //https://github.com/RRUZ/vcl-styles-utils //https://github.com/MahdiSafsafi/DDetours , Vcl.PlatformVclStylesActnCtrls , Vcl.Styles.ColorTabs , Vcl.Styles.ControlColor , Vcl.Styles.DbGrid , Vcl.Styles.DPIAware , Vcl.Styles.Fixes , Vcl.Styles.Ext , Vcl.Styles.FontAwesome , Vcl.Styles.FormStyleHooks , Vcl.Styles.NC , Vcl.Styles.OwnerDrawFix , Vcl.Styles.Utils.ScreenTips , Vcl.Styles.Utils.SysStyleHook , Vcl.Styles.WebBrowser , Vcl.Styles.Utils , Vcl.Styles.Utils.Menus , Vcl.Styles.Utils.Misc , Vcl.Styles.Utils.SystemMenu , Vcl.Styles.Utils.Graphics , Vcl.Styles.Utils.SysControls , Vcl.Styles.UxTheme , Vcl.Styles.Hooks , Vcl.Styles.Utils.Forms , Vcl.Styles.Utils.ComCtrls , Vcl.Styles.Utils.StdCtrls {$ENDIF} {$IFDEF D10_2+} , Vcl.WinXPickers {$ENDIF} ; const COMPANY_NAME = 'Ethea'; type TFormMain = class(TForm) panlTop: TPanel; SV: TSplitView; catMenuItems: TCategoryButtons; catSettings: TCategoryButtons; catMenuSettings: TCategoryButtons; catPanelSettings: TCategoryButtons; IconFontsImageList: TIconFontsVirtualImageList; ActionList: TActionList; actHome: TAction; actChangeTheme: TAction; actShowChildForm: TAction; actMenu: TAction; lblTitle: TLabel; splSplit: TSplitter; svSettings: TSplitView; IconFontsImageListColored: TIconFontsVirtualImageList; splSettings: TSplitter; actSettings: TAction; actViewOptions: TAction; pnlSettings: TPanel; pcSettings: TPageControl; tsStyle: TTabSheet; grpDisplayMode: TRadioGroup; grpCloseStyle: TRadioGroup; grpPlacement: TRadioGroup; tsAnimation: TTabSheet; tsLog: TTabSheet; lstLog: TListBox; actBack: TAction; actAnimate: TAction; actLog: TAction; PageControl: TPageControl; tsDatabase: TTabSheet; ClientDataSet: TClientDataSet; DBNavigator: TDBNavigator; DbGrid: TDBGrid; tsWindows10: TTabSheet; CalendarView: TCalendarView; CalendarPicker: TCalendarPicker; tsStandard: TTabSheet; Edit: TEdit; HomeButton: TButton; LogButton: TButton; CheckListBox: TCheckListBox; RichEdit: TRichEdit; SpinEdit: TSpinEdit; ComboBox: TComboBox; ListBox: TListBox; Memo: TMemo; ColorBox: TColorBox; MaskEdit: TMaskEdit; RadioButton: TRadioButton; RadioGroup: TRadioGroup; DBRichEdit: TDBRichEdit; Label1: TLabel; MenuButtonToolbar: TToolBar; ToolButton1: TToolButton; ToolBar: TToolBar; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; DateTimePicker: TDateTimePicker; ClientDataSetSpeciesNo: TFloatField; ClientDataSetCategory: TStringField; ClientDataSetCommon_Name: TStringField; ClientDataSetSpeciesName: TStringField; ClientDataSetLengthcm: TFloatField; ClientDataSetLength_In: TFloatField; ClientDataSetNotes: TMemoField; ClientDataSetGraphic: TGraphicField; DataSource: TDataSource; tsFont: TTabSheet; Label2: TLabel; FontTrackBar: TTrackBar; acFont: TAction; FontComboBox: TComboBox; FontSizeLabel: TLabel; acApplyFont: TAction; SaveFontButton: TButton; tsIconFonts: TTabSheet; Label3: TLabel; IconFontsSizeLabel: TLabel; IconFontsTrackBar: TTrackBar; acIconFonts: TAction; paEdit: TPanel; Label4: TLabel; DBEdit1: TDBEdit; Label5: TLabel; DBEdit2: TDBEdit; Label6: TLabel; DBEdit3: TDBEdit; Label7: TLabel; DBEdit4: TDBEdit; Label8: TLabel; DBEdit5: TDBEdit; Label9: TLabel; DBEdit6: TDBEdit; Label10: TLabel; DBMemo1: TDBMemo; Label11: TLabel; DBImage: TDBImage; FileOpenDialog: TFileOpenDialog; ButtonEdit: TSearchBox; ButtonEditDate: TSearchBox; acErrorMessage: TAction; acWarningMessage: TAction; acInfoMessage: TAction; acConfirmMessage: TAction; acAbout: TAction; SVGIconImageList: TSVGIconVirtualImageList; IconsToggleSwitch: TToggleSwitch; tswAnimation: TToggleSwitch; lblAnimationDelay: TLabel; trkAnimationDelay: TTrackBar; lblAnimationStep: TLabel; trkAnimationStep: TTrackBar; tsvDisplayMode: TToggleSwitch; ttsCloseStyle: TToggleSwitch; ttsCloseSplitView: TToggleSwitch; acExit: TAction; SVGIconImage: TSVGIconImage; IconFontImage: TIconFontImage; IconFontImageLabel: TLabel; SVGIconImageLabel: TLabel; procedure FormCreate(Sender: TObject); procedure grpDisplayModeClick(Sender: TObject); procedure grpPlacementClick(Sender: TObject); procedure grpCloseStyleClick(Sender: TObject); procedure SVClosed(Sender: TObject); procedure SVOpened(Sender: TObject); procedure SVOpening(Sender: TObject); procedure trkAnimationDelayChange(Sender: TObject); procedure trkAnimationStepChange(Sender: TObject); procedure actHomeExecute(Sender: TObject); procedure actChangeThemeExecute(Sender: TObject); procedure actShowChildFormExecute(Sender: TObject); procedure actMenuExecute(Sender: TObject); procedure CatPreventCollapase(Sender: TObject; const Category: TButtonCategory); procedure SVResize(Sender: TObject); procedure actSettingsExecute(Sender: TObject); procedure svSettingsClosed(Sender: TObject); procedure svSettingsOpened(Sender: TObject); procedure SVClosing(Sender: TObject); procedure tswAnimationClick(Sender: TObject); procedure actBackExecute(Sender: TObject); procedure actViewOptionsExecute(Sender: TObject); procedure actAnimateExecute(Sender: TObject); procedure actLogExecute(Sender: TObject); procedure svSettingsClosing(Sender: TObject); procedure FormShow(Sender: TObject); procedure tsvDisplayModeClick(Sender: TObject); procedure ttsCloseStyleClick(Sender: TObject); procedure FontTrackBarChange(Sender: TObject); procedure acFontExecute(Sender: TObject); procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); procedure FontComboBoxSelect(Sender: TObject); procedure IconFontsTrackBarChange(Sender: TObject); procedure acIconFontsExecute(Sender: TObject); procedure acApplyFontExecute(Sender: TObject); procedure acApplyFontUpdate(Sender: TObject); procedure DBImageDblClick(Sender: TObject); procedure ClientDataSetAfterPost(DataSet: TDataSet); procedure PageControlChange(Sender: TObject); procedure IconFontsImageListFontMissing(const AFontName: TFontName); procedure acMessageExecute(Sender: TObject); procedure acAboutExecute(Sender: TObject); procedure IconsToggleSwitchClick(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure acExitExecute(Sender: TObject); procedure IconImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormBeforeMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); private FActiveFont: TFont; FActiveStyleName: string; {$IFDEF D10_2+} TimePicker: TTimePicker; DatePicker: TDatePicker; {$ENDIF} {$IFNDEF D10_3+} FScaleFactor: Single; {$ENDIF} procedure UpdateButtons; procedure CreateAndFixFontComponents; procedure Log(const Msg: string); procedure AfterMenuClick; procedure ShowSettingPage(TabSheet: TTabSheet; AutoOpen: Boolean = False); procedure FontTrackBarUpdate; procedure IconFontsTrackBarUpdate; procedure SetActiveStyleName(const Value: string); procedure AdjustCatSettings; procedure UpdateDefaultAndSystemFonts; {$IFNDEF D10_4+} procedure FixSplitViewResize(ASplitView: TSplitView; const OldDPI, NewDPI: Integer); {$ENDIF} procedure UpdateIconsByType; protected procedure Loaded; override; {$IFNDEF D10_3+} procedure ChangeScale(M, D: Integer); override; {$ENDIF} public procedure ScaleForPPI(NewPPI: Integer); override; destructor Destroy; override; property ActiveStyleName: string read FActiveStyleName write SetActiveStyleName; end; var FormMain: TFormMain; implementation uses Vcl.Themes , System.UITypes; {$R *.dfm} procedure ApplyStyleElements(ARootControl: TControl; AStyleElements: TStyleElements); var I: Integer; LControl: TControl; begin ARootControl.StyleElements := AStyleElements; if ARootControl is TWinControl then For I := 0 to TWinControl(ARootControl).ControlCount -1 do begin LControl := TWinControl(ARootControl).Controls[I]; ApplyStyleElements(TWinControl(LControl), AStyleElements); end; ARootControl.Invalidate; end; { TFormMain } procedure TFormMain.IconFontsImageListFontMissing(const AFontName: TFontName); var LFontFileName: string; begin inherited; //The "material design web-font is not installed into system: load and install now from disk LFontFileName := ExtractFilePath(Application.ExeName)+'..\Fonts\Material Design Icons Desktop.ttf'; if FileExists(LFontFileName) then begin {$IFNDEF D2010+} AddFontResource(PChar(LFontFileName)); {$ELSE} AddFontResource(PWideChar(LFontFileName)); {$ENDIF} SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0); end else begin //If the font file is not available MessageDlg(Format('Warning: "%s" font is not present in your system!'+sLineBreak+ 'Please download from https://github.com/Templarian/MaterialDesign-Font and install it, because this demo is based on this font!', [AFontName]), mtError, [mbOK], 0); end; end; procedure TFormMain.FontTrackBarUpdate; begin FontSizeLabel.Caption := IntToStr(FontTrackBar.Position); end; procedure TFormMain.FormShow(Sender: TObject); begin FontTrackBarUpdate; IconFontsTrackBarUpdate; UpdateButtons; end; procedure TFormMain.CreateAndFixFontComponents; begin CalendarView.ParentFont := True; CalendarView.HeaderInfo.Font.Assign(Font); CalendarView.HeaderInfo.Font.Height := Round(CalendarView.HeaderInfo.Font.Height*1.2); CalendarView.HeaderInfo.DaysOfWeekFont.Assign(Font); CalendarPicker.ParentFont := True; {$IFDEF D10_2+} TimePicker := TTimePicker.Create(Self); TimePicker.Left := 3; TimePicker.Top := 367; TimePicker.Parent := tsWindows10; TimePicker.Font.Assign(Font); DatePicker := TDatePicker.Create(Self); DatePicker.Left := 2; DatePicker.Top := 423; DatePicker.Parent := tsWindows10; DatePicker.Font.Assign(Font); {$ENDIF} end; procedure TFormMain.FontComboBoxSelect(Sender: TObject); begin Font.Name := FontComboBox.Text; UpdateDefaultAndSystemFonts; end; procedure TFormMain.FontTrackBarChange(Sender: TObject); begin //ScaleFactor is available only from Delphi 10.3, FScaleFactor is calculated Font.Height := MulDiv(-FontTrackBar.Position, Round(100*{$IFDEF D10_3+}ScaleFactor{$ELSE}FScaleFactor{$ENDIF}), 100); FontTrackBarUpdate; UpdateDefaultAndSystemFonts; end; procedure TFormMain.IconFontsTrackBarChange(Sender: TObject); begin IconFontsImageList.Size := IconFontsTrackBar.Position; IconFontsImageListColored.Size := IconFontsTrackBar.Position; SVGIconImageList.Size := IconFontsTrackBar.Position; IconFontsTrackBarUpdate; end; procedure TFormMain.IconFontsTrackBarUpdate; var LContainerSize: Integer; procedure UpdateCategoryButtonSize(ACatButton: TCategoryButtons); begin ACatButton.ButtonHeight := LContainerSize; ACatButton.ButtonWidth := LContainerSize; end; begin IconFontsTrackBar.Position := IconFontsImageList.Size; IconFontsSizeLabel.Caption := IntToStr(IconFontsTrackBar.Position); LContainerSize := IconFontsTrackBar.Position + 10; panlTop.Height := LContainerSize + 10; SV.Top := panlTop.Top+panlTop.Height; svSettings.Top := SV.Top; ToolBar.ButtonHeight := LContainerSize; MenuButtonToolbar.ButtonHeight := LContainerSize; UpdateCategoryButtonSize(catMenuItems); UpdateCategoryButtonSize(catMenuSettings); UpdateCategoryButtonSize(catSettings); UpdateCategoryButtonSize(catPanelSettings); end; procedure TFormMain.IconImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var LIndex: Integer; begin LIndex := IconFontImage.ImageIndex; if (Button = mbRight) and (Shift = [ssRight]) then begin if IconFontImage.ImageIndex = 0 then LIndex := IconFontsImageList.Count -1 else Dec(LIndex); end else if (Button = mbLeft) and (Shift = [ssLeft]) then begin if IconFontImage.ImageIndex = IconFontsImageList.Count -1 then LIndex := 0 else Inc(LIndex); end; IconFontImage.ImageIndex := LIndex; SVGIconImage.ImageIndex := LIndex; end; procedure TFormMain.IconsToggleSwitchClick(Sender: TObject); begin if IconsToggleSwitch.State = tssOn then ImageCollectionDataModule.IconsType := itSVGIcons else ImageCollectionDataModule.IconsType := itIconFonts; UpdateIconsByType; end; {$IFNDEF D10_4+} procedure TFormMain.FixSplitViewResize(ASplitView: TSplitView; const OldDPI, NewDPI: Integer); begin ASplitView.CompactWidth := MulDiv(ASplitView.CompactWidth, NewDPI, OldDPI); ASplitView.OpenedWidth := MulDiv(ASplitView.OpenedWidth, NewDPI, OldDPI); end; {$ENDIF} procedure TFormMain.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); begin LockWindowUpdate(0); {$IFNDEF D10_3} IconFontsImageList.DPIChanged(Self, OldDPI, NewDPI); IconFontsImageListColored.DPIChanged(Self, OldDPI, NewDPI); {$ENDIF} FontTrackBarUpdate; IconFontsTrackBarUpdate; {$IFNDEF D10_4+} AdjustCatSettings; //Fix for SplitViews FixSplitViewResize(SV, OldDPI, NewDPI); FixSplitViewResize(svSettings, OldDPI, NewDPI); {$ENDIF} UpdateDefaultAndSystemFonts; end; procedure TFormMain.FormBeforeMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); begin LockWindowUpdate(Handle); end; procedure TFormMain.FormCreate(Sender: TObject); var I: Integer; begin Caption := Application.Title; //Hide Tabs for I := 0 to pcSettings.PageCount-1 do pcSettings.Pages[I].TabVisible := False; {$IFDEF D10_4+} //Assign Windows10 Style to Settings Menu svSettings.StyleName := 'Windows10'; {$ELSE} //Disable any StyleElements of Settings Menu only for Windows10 Style if FActiveStyleName = 'Windows10' then ApplyStyleElements(svSettings, [seFont]); {$ENDIF} //Assign Fonts to Combobox FontComboBox.Items.Assign(Screen.Fonts); FontComboBox.ItemIndex := FontComboBox.Items.IndexOf(Font.Name); //Title label lblTitle.Caption := Application.Title; lblTitle.Font.Color := clHighlightText; lblTitle.Font.Height := lblTitle.Font.Height - 4; lblTitle.Font.Style := lblTitle.Font.Style + [fsBold]; //Assign file for ClientDataSet {$IFDEF D10_2+} ClientDataSet.FileName := ExtractFilePath(Application.ExeName)+'..\Data\biolife_png.xml'; {$ELSE} //Delphi 10.1 cannot load png blob field automatically ClientDataSet.FileName := ExtractFilePath(Application.ExeName)+'..\Data\biolife.xml'; {$ENDIF} end; procedure TFormMain.CatPreventCollapase(Sender: TObject; const Category: TButtonCategory); begin // Prevent the catMenuButton Category group from being collapsed (Sender as TCategoryButtons).Categories[0].Collapsed := False; end; {$IFNDEF D10_3+} procedure TFormMain.ChangeScale(M, D: Integer); begin inherited; FScaleFactor := FScaleFactor * M / D; IconFontsImageList.DPIChanged(Self, M, D); IconFontsImageListColored.DPIChanged(Self, M, D); end; {$ENDIF} procedure TFormMain.ScaleForPPI(NewPPI: Integer); begin inherited; {$IFNDEF D10_3+} FScaleFactor := NewPPI / PixelsPerInch; IconFontsImageList.DPIChanged(Self, Self.PixelsPerInch, NewPPI); IconFontsImageListColored.DPIChanged(Self, Self.PixelsPerInch, NewPPI); {$ENDIF} {$IFNDEF D10_4+} FixSplitViewResize(SV, Self.PixelsPerInch, NewPPI); FixSplitViewResize(svSettings, Self.PixelsPerInch, NewPPI); {$ENDIF} end; procedure TFormMain.ClientDataSetAfterPost(DataSet: TDataSet); begin //Save content to File ClientDataSet.SaveToFile(ClientDataSet.FileName, dfXMLUTF8); end; procedure TFormMain.DBImageDblClick(Sender: TObject); begin ClientDataSet.Edit; FileOpenDialog.DefaultFolder := ExtractFilePath(ClientDataSet.FileName); if FileOpenDialog.Execute then begin ClientDataSetGraphic.LoadFromFile(FileOpenDialog.FileName); end; end; destructor TFormMain.Destroy; begin inherited; FActiveFont.Free; end; procedure TFormMain.grpDisplayModeClick(Sender: TObject); begin SV.DisplayMode := TSplitViewDisplayMode(grpDisplayMode.ItemIndex); end; procedure TFormMain.grpCloseStyleClick(Sender: TObject); begin SV.CloseStyle := TSplitViewCloseStyle(grpCloseStyle.ItemIndex); end; procedure TFormMain.grpPlacementClick(Sender: TObject); begin SV.Placement := TSplitViewPlacement(grpPlacement.ItemIndex); end; procedure TFormMain.SetActiveStyleName(const Value: string); var I: Integer; LFontColor, LColoredColor: TColor; LMaskColor: TColor; begin if Value <> '' then begin TStyleManager.SetStyle(Value); WriteAppStyleToReg(COMPANY_NAME, ExtractFileName(Application.ExeName), Value); FActiveStyleName := Value; if FActiveStyleName = 'Windows' then begin catMenuItems.Color := clHighlight; catMenuItems.Font.Color := clHighlightText; for I := 0 to catMenuItems.Categories.Count -1 do catMenuItems.Categories[I].Color := clNone; DBImage.Color := clAqua; //Default non-style "Windows": use White icons over Highlight Color LFontColor := clWhite; LColoredColor := clBlack; LMaskColor := clHighlight; end else begin if FActiveStyleName = 'Windows10' then begin //For "Windows10" style: use "Windows 10 blue" color for the icons LFontColor := RGB(0, 120, 215); LColoredColor := LFontColor; LMaskColor := clBtnFace; end else begin //Request color from Style LFontColor := TStyleManager.ActiveStyle.GetStyleFontColor(sfButtonTextNormal); LMaskColor := TStyleManager.ActiveStyle.GetStyleFontColor(sfButtonTextDisabled); LColoredColor := clBlack; end; catMenuItems.Font.Color := IconFontsImageList.FontColor; //Color for Bitmap Background DBImage.Color := TStyleManager.ActiveStyle.GetStyleColor(scGenericBackground); end; //Update IconFonts Colors IconFontsImageList.UpdateIconsAttributes(LFontColor, LMaskColor, True); IconFontsImageListColored.UpdateIconsAttributes(LColoredColor, LMaskColor, False); IconFontImage.FontColor := LColoredColor; IconFontImage.MaskColor := LMaskColor; catMenuItems.BackgroundGradientDirection := gdVertical; catMenuItems.RegularButtonColor := clNone; catMenuItems.SelectedButtonColor := clNone; end; end; procedure TFormMain.UpdateIconsByType; begin case ImageCollectionDataModule.IconsType of itIconFonts: begin MenuButtonToolbar.Images := IconFontsImageList; ToolBar.Images := IconFontsImageList; catMenuItems.Images := IconFontsImageList; catSettings.Images := IconFontsImageList; catMenuSettings.Images := IconFontsImageListColored; //Colored icons ActionList.Images := IconFontsImageList; end; itSVGIcons: begin MenuButtonToolbar.Images := SVGIconImageList; ToolBar.Images := SVGIconImageList; catMenuItems.Images := SVGIconImageList; catSettings.Images := SVGIconImageList; catMenuSettings.Images := SVGIconImageList; ActionList.Images := SVGIconImageList; end; end; UpdateButtons; end; procedure TFormMain.ShowSettingPage(TabSheet: TTabSheet; AutoOpen: Boolean = False); begin if Assigned(TabSheet) then begin pcSettings.ActivePage := TabSheet; pnlSettings.Visible := True; catMenuSettings.Visible := False; actBack.Caption := Tabsheet.Caption; if AutoOpen then svSettings.Open; end else begin pnlSettings.Visible := False; catMenuSettings.Visible := True; actBack.Caption := 'Back'; end; end; procedure TFormMain.SVClosed(Sender: TObject); begin // When TSplitView is closed, adjust ButtonOptions and Width catMenuItems.ButtonOptions := catMenuItems.ButtonOptions - [boShowCaptions]; actMenu.Hint := 'Expand'; splSplit.Visible := False; end; procedure TFormMain.SVClosing(Sender: TObject); begin SV.OpenedWidth := SV.Width; end; procedure TFormMain.SVOpened(Sender: TObject); begin // When not animating, change size of catMenuItems when TSplitView is opened catMenuItems.ButtonOptions := catMenuItems.ButtonOptions + [boShowCaptions]; actMenu.Hint := 'Collapse'; splSplit.Visible := True; splSplit.Left := SV.Left + SV.Width; end; procedure TFormMain.SVOpening(Sender: TObject); begin // When animating, change size of catMenuItems at the beginning of open catMenuItems.ButtonOptions := catMenuItems.ButtonOptions + [boShowCaptions]; end; procedure TFormMain.AdjustCatSettings; var LButtonWidth, LNumButtons, LButtonsFit: Integer; LCaptionOffset: Integer; begin catSettings.Realign; LButtonWidth := catSettings.ButtonWidth; LNumButtons := catSettings.Categories[0].Items.Count; LButtonsFit := (SV.Width) div (LButtonWidth+2); LCaptionOffset := Round(-Font.Height+14); if (LButtonsFit <> 0) and (LButtonsFit < LNumButtons) then catSettings.Height := (((LNumButtons div LButtonsFit)+1) * catSettings.ButtonHeight) + LCaptionOffset else begin catSettings.Height := catSettings.ButtonHeight + LCaptionOffset; end; end; procedure TFormMain.SVResize(Sender: TObject); begin AdjustCatSettings; end; procedure TFormMain.svSettingsClosed(Sender: TObject); begin splSettings.Visible := False; ShowSettingPage(nil); end; procedure TFormMain.svSettingsClosing(Sender: TObject); begin if svSettings.Width <> 0 then svSettings.OpenedWidth := svSettings.Width; end; procedure TFormMain.svSettingsOpened(Sender: TObject); begin splSettings.Visible := True; splSettings.Left := svSettings.Left -1; end; procedure TFormMain.trkAnimationDelayChange(Sender: TObject); begin SV.AnimationDelay := trkAnimationDelay.Position * 5; lblAnimationDelay.Caption := Format('Animation Delay (%d)', [SV.AnimationDelay]); end; procedure TFormMain.trkAnimationStepChange(Sender: TObject); begin SV.AnimationStep := trkAnimationStep.Position * 5; lblAnimationStep.Caption := Format('Animation Step (%d)', [SV.AnimationStep]); end; procedure TFormMain.ttsCloseStyleClick(Sender: TObject); begin if ttsCloseStyle.State = tssOff then SV.CloseStyle := svcCompact else SV.CloseStyle := svcCollapse; end; procedure TFormMain.tsvDisplayModeClick(Sender: TObject); begin if tsvDisplayMode.State = tssOff then SV.DisplayMode := svmDocked else SV.DisplayMode := svmOverlay; end; procedure TFormMain.tswAnimationClick(Sender: TObject); begin SV.UseAnimation := tswAnimation.State = tssOn; lblAnimationDelay.Enabled := SV.UseAnimation; trkAnimationDelay.Enabled := SV.UseAnimation; lblAnimationStep.Enabled := SV.UseAnimation; trkAnimationStep.Enabled := SV.UseAnimation; end; procedure TFormMain.acAboutExecute(Sender: TObject); begin TaskMessageDlg('About this Application', Application.Title, mtInformation, [mbOK], 2000); end; procedure TFormMain.acApplyFontExecute(Sender: TObject); begin FActiveFont.Name := FontComboBox.Text; FActiveFont.Height := -FontTrackBar.Position; WriteAppStyleAndFontToReg(COMPANY_NAME, ExtractFileName(Application.ExeName), FActiveStyleName, FActiveFont); //Update Child Forms if Assigned(FmEdit) then FmEdit.Font.Assign(Font); UpdateDefaultAndSystemFonts; AfterMenuClick; end; procedure TFormMain.acApplyFontUpdate(Sender: TObject); begin acApplyFont.Enabled := (FActiveFont.Name <> FontComboBox.Text) or (FActiveFont.Height <> FontTrackBar.Position); end; procedure TFormMain.acExitExecute(Sender: TObject); begin Close; end; procedure TFormMain.acMessageExecute(Sender: TObject); begin if Sender = acErrorMessage then MessageDlg('Error Message...', mtError, [mbOK, mbHelp], 1000) else if Sender = acWarningMessage then MessageDlg('Warning Message...', mtWarning, [mbOK, mbHelp], 1000) else if Sender = acInfoMessage then MessageDlg('Information Message...', mtInformation, [mbOK, mbHelp], 1000) else if Sender = acConfirmMessage then MessageDlg('Do you want to confirm?', mtConfirmation, [mbYes, mbNo, mbHelp], 1000); Log((Sender as TAction).Caption + ' Clicked'); end; procedure TFormMain.acFontExecute(Sender: TObject); begin ShowSettingPage(tsFont); end; procedure TFormMain.acIconFontsExecute(Sender: TObject); begin ShowSettingPage(tsIconFonts); end; procedure TFormMain.actAnimateExecute(Sender: TObject); begin ShowSettingPage(tsAnimation); end; procedure TFormMain.actBackExecute(Sender: TObject); begin ShowSettingPage(nil); end; procedure TFormMain.actHomeExecute(Sender: TObject); begin PageControl.ActivePageIndex := 0; Log(actHome.Caption + ' Clicked'); AfterMenuClick; end; procedure TFormMain.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin actHome.Enabled := not svSettings.Opened; end; procedure TFormMain.actChangeThemeExecute(Sender: TObject); begin //Show Theme selector if ShowVCLThemeSelector(FActiveStyleName, False, 3, 4) then ActiveStyleName := FActiveStyleName; end; procedure TFormMain.actLogExecute(Sender: TObject); begin if not svSettings.Opened then svSettings.Open; ShowSettingPage(tsLog); end; procedure TFormMain.actMenuExecute(Sender: TObject); begin if SV.Opened then SV.Close else SV.Open; end; procedure TFormMain.actShowChildFormExecute(Sender: TObject); begin if not Assigned(FmEdit) then FmEdit := TFmEdit.Create(Self); FmEdit.Show; Log(actShowChildForm.Caption + ' Clicked'); AfterMenuClick; end; procedure TFormMain.actSettingsExecute(Sender: TObject); begin if svSettings.Opened then svSettings.Close else svSettings.Open; end; procedure TFormMain.actViewOptionsExecute(Sender: TObject); begin ShowSettingPage(tsStyle); end; procedure TFormMain.AfterMenuClick; begin if SV.Opened and (ttsCloseSplitView.State = tssOn) then SV.Close; if svSettings.Opened and (ttsCloseSplitView.State = tssOn) then svSettings.Close; end; procedure TFormMain.UpdateButtons; begin //Buttons with Actions must be reassigned to refresh Icon HomeButton.Images := ActionList.Images; LogButton.Images := ActionList.Images; SaveFontButton.Images := ActionList.Images; //HomeButton.Action := actHome; //LogButton.Action := actLog; //SaveFontButton.Action := acApplyFont; end; procedure TFormMain.UpdateDefaultAndSystemFonts; var LHeight: Integer; begin //Update Application.DefaultFont for Childforms with ParentFont = True Application.DefaultFont.Assign(Font); //Update system fonts as user preferences LHeight := Muldiv(Font.Height, Screen.PixelsPerInch, Monitor.PixelsPerInch); Screen.IconFont.Name := Font.Name; Screen.IconFont.Height := LHeight; Screen.MenuFont.Name := Font.Name; Screen.MenuFont.Height := LHeight; Screen.MessageFont.Name := Font.Name; Screen.MessageFont.Height := LHeight; Screen.HintFont.Name := Font.Name; Screen.HintFont.Height := LHeight; Screen.CaptionFont.Name := Font.Name; Screen.CaptionFont.Height := LHeight; catMenuItems.Font.Assign(Font); end; procedure TFormMain.Loaded; var LFontHeight: Integer; begin {$IFNDEF D10_3+} FScaleFactor := 1; {$ENDIF} FActiveFont := TFont.Create; //Acquire system font and size (eg. for windows 10 Segoe UI and 14 at 96 DPI) //but without using Assign! Font.Name := Screen.IconFont.Name; //If you want to use system font Height: Font.Height := Muldiv(Screen.IconFont.Height, 96, Screen.IconFont.PixelsPerInch); //Check for Font stored into Registry (user preferences) ReadAppStyleAndFontFromReg(COMPANY_NAME, ExtractFileName(Application.ExeName), FActiveStyleName, FActiveFont); LFontHeight := FActiveFont.Height; Font.Assign(FActiveFont); //Create and Fix components for ParentFont CreateAndFixFontComponents; inherited; //Update Trackbar position with Width loaded before resize of Font FontTrackBar.Position := - LFontHeight; //For ParentFont on Child Forms UpdateDefaultAndSystemFonts; //GUI default ActiveStyleName := FActiveStyleName; svSettings.Opened := False; PageControl.ActivePageIndex := 0; end; procedure TFormMain.Log(const Msg: string); var Idx: Integer; begin Idx := lstLog.Items.Add(Msg); lstLog.TopIndex := Idx; ShowSettingPage(tsLog, True); end; procedure TFormMain.PageControlChange(Sender: TObject); begin if (PageControl.ActivePage = tsDatabase) then begin if not ClientDataSet.Active then begin Screen.Cursor := crHourGlass; try ClientDataSet.Open; ClientDataSet.LogChanges := False; finally Screen.Cursor := crDefault; end; end; end; end; end.
unit ALocalizaServico; { Autor: Rafael Budag Data Criação: 16/04/1999; Função: Gerar um orçamento Motivo alteração: } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Localizacao, StdCtrls, Buttons, Componentes1, Db, DBTables, ExtCtrls, PainelGradiente, DBGrids, Tabela, DBCtrls, Mask, UnDados, UnClassificacao, numericos, LabelCorMove, CheckLst, BotaoCadastro, DBKeyViolation, Grids, unDadosProduto, FMTBcd, SqlExpr, DBClient; type TFlocalizaServico = class(TFormularioPermissao) CadServico: TSQL; PanelColor2: TPanelColor; PanelColor5: TPanelColor; Label3: TLabel; Label2: TLabel; SpeedButton1: TSpeedButton; LDesClassificacao: TLabel; CProAti: TCheckBox; PanelColor16: TPanelColor; ENomeServico: TEditColor; GProdutos: TGridIndice; DBMemoColor1: TDBMemoColor; PainelGradiente1: TPainelGradiente; BOk: TBitBtn; BCancelar: TBitBtn; BotaoCadastrar1: TBitBtn; CadServicoI_COD_SER: TFMTBCDField; CadServicoC_NOM_SER: TWideStringField; CadServicoN_VLR_VEN: TFMTBCDField; CadServicoC_Nom_Moe: TWideStringField; CadServicoL_OBS_SER: TWideStringField; DataCadServico: TDataSource; EClassificacao: TEditColor; Aux: TSQLQuery; CadServicoN_PER_ISS: TFMTBCDField; CadServicoC_COD_CLA: TWideStringField; CadServicoN_PER_COM: TFMTBCDField; CadServicoI_COD_EMP: TFMTBCDField; CadServicoI_COD_FIS: TFMTBCDField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CProAtiClick(Sender: TObject); procedure EClassificacaoRetorno(Retorno1, Retorno2: String); procedure ENomeProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BOkClick(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure BotaoCadastrar1Click(Sender: TObject); procedure EClassificacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ENomeServicoEnter(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure EClassificacaoExit(Sender: TObject); procedure GProdutosEnter(Sender: TObject); procedure GProdutosExit(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } Cadastrou : Boolean; VprAcao : boolean; FunClassificacao: TFuncoesClassificacao; procedure AtualizaConsulta; procedure AdicionaFiltrosProduto(VpaSelect : TStrings); function LocalizaClassificacao: Boolean; function ExisteClassificacao: Boolean; public procedure ConsultaServico; function LocalizaServico( var VpaCadastrou : Boolean; var VpaCodServico : integer; Var VpaValorVenda :Double; Var VpaPerISSQN : Double ) : boolean; overload; function LocalizaServico( var VpaCadastrou : Boolean; var VpaCodServico : integer; var VpaNomServico : string; Var VpaValorVenda, VpaPerISSQN : Double ) : boolean; overload; function LocalizaServico(VpaDServicoNota : TRBDNotaFiscalServico ) : boolean; overload; function LocalizaServico(VpaDServicoNota : TRBDNotaFiscalForServico ) : boolean; overload; function LocalizaServico(VpaDServicoContrato : TRBDContratoServico ) : boolean; overload; function LocalizaServico(VpaDServicoCotacao : TRBDOrcServico) : boolean;overload; function LocalizaServico(VpaDServicoExecutado: TRBDChamadoServicoExecutado): Boolean; overload; function LocalizaServico(VpaDServicoOrcado: TRBDChamadoServicoOrcado): Boolean; overload; function LocalizaServico(VpaDServicoAmostra : TRBDServicoFixoAmostra):boolean;overload; end; var FlocalizaServico: TFlocalizaServico; implementation uses APrincipal, Constantes,ConstMsg, ALocalizaClassificacao, FunSql, ANovoServico, UnSistema; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFlocalizaServico.FormCreate(Sender: TObject); begin FunClassificacao:= TFuncoesClassificacao.criar(Self,FPrincipal.BaseDados); AtualizaConsulta; CadServicoN_VLR_VEN.EditFormat:= Varia.MascaraValor; CadServicoN_VLR_VEN.DisplayFormat:= Varia.MascaraValor; Cadastrou:= False; end; { ******************* Quando o formulario e fechado ************************** } procedure TFlocalizaServico.FormClose(Sender: TObject; var Action: TCloseAction); begin FunClassificacao.Free; Action:= CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos do filtro superior )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {**************** chama a rotina para atualizar a consulta ********************} procedure TFlocalizaServico.EClassificacaoRetorno(Retorno1, Retorno2: String); begin AtualizaConsulta; end; {*************Chama a Rotina para atualizar a select dos produtos**************} procedure TFlocalizaServico.CProAtiClick(Sender: TObject); begin AtualizaConsulta; BOk.Default := true; end; {************ se for pressionado enter atualiza a consulta ********************} procedure TFlocalizaServico.ENomeProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 13: AtualizaConsulta; VK_UP: begin ActiveControl:= EClassificacao; end; VK_DOWN: begin ActiveControl:= GProdutos; end; end; end; {******************* verifica as teclas pressionadas **************************} procedure TFlocalizaServico.EClassificacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of 13: if ExisteClassificacao then AtualizaConsulta else if LocalizaClassificacao then AtualizaConsulta; VK_DOWN: ActiveControl:= ENomeServico; VK_F3: LocalizaClassificacao; end; end; {******************* tira o botao fechar como default *************************} procedure TFlocalizaServico.ENomeServicoEnter(Sender: TObject); begin BOk.Default:= False; end; {********************* localiza as classificacoes *****************************} Function TFlocalizaServico.LocalizaClassificacao : Boolean; Var VpfCodClassificacao, VpfNomClassificacao : String; begin FLocalizaClassificacao := TFLocalizaClassificacao.CriarSDI(application,'', true); Result:= FLocalizaClassificacao.LocalizaClassificacao(VpfCodClassificacao,VpfNomClassificacao,'S'); if Result then begin EClassificacao.Text := VpfCodClassificacao; LDesClassificacao.Caption := VpfNomClassificacao; AtualizaConsulta; end; FLocalizaClassificacao.free; end; {****************** verifica se existe a classificacao ************************} function TFlocalizaServico.ExisteClassificacao : Boolean; var VpfNomClassificacao: String; begin // verificar se posso fazer desta forma VpfNomClassificacao:= FunClassificacao.RetornaNomeClassificacao(EClassificacao.Text,'S'); Result:= (VpfNomClassificacao <> ''); LDesClassificacao.Caption:= VpfNomClassificacao; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ações da consulta do Servico )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {****************** atualiza a consulta dos produtos **************************} procedure TFlocalizaServico.AtualizaConsulta; begin CadServico.Close; CadServico.sql.clear; CadServico.sql.add('Select ' + ' SER.I_COD_SER, SER.I_COD_EMP, SER.C_NOM_SER, SER.L_OBS_SER, SER.N_PER_ISS, ' + ' SER.I_COD_FIS, '+ ' (PRE.N_VLR_VEN * MOE.N_Vlr_Dia) N_VLR_VEN, ' + ' Moe.C_Nom_Moe, ' + ' CLA.C_COD_CLA, CLA.N_PER_COM '+ ' from CadServico Ser, MovTabelaPrecoServico Pre, ' + ' CadMoedas Moe, CADCLASSIFICACAO CLA'); AdicionaFiltrosProduto(CadServico.Sql); CadServico.sql.add(' and Pre.I_Cod_Emp = Ser.I_Cod_Emp '+ ' and Pre.I_Cod_Ser = Ser.I_Cod_Ser '+ ' and Moe.I_Cod_Moe = Pre.I_Cod_Moe' + ' and SER.I_COD_EMP = CLA.I_COD_EMP '+ ' and SER.C_COD_CLA = CLA.C_COD_CLA '+ ' and SER.C_TIP_CLA = CLA.C_TIP_CLA '+ ' order by c_nom_ser '); GravaEstatisticaConsulta(nil,CadServico,varia.CodigoUsuario,Self.name,NomeModulo,config.UtilizarPercentualConsulta); CadServico.Open; end; {******************* adiciona os filtros da consulta **************************} procedure TFlocalizaServico.AdicionaFiltrosProduto(VpaSelect : TStrings); begin VpaSelect.add('Where Ser.I_Cod_Emp = ' + inttostr(Varia.CodigoEmpresa)); if ENomeServico.text <> '' Then VpaSelect.Add('and Ser.C_Nom_Ser like '''+ENomeServico.text +'%'''); if EClassificacao.text <> ''Then VpaSelect.add(' and Ser.C_Cod_Cla like '''+ EClassificacao.text+ '%'''); if CProAti.Checked then VpaSelect.add(' and Ser.C_Ati_Ser = ''S'''); VpaSelect.Add(' and Pre.I_Cod_Tab = ' + IntToStr(Varia.TabelaPrecoServico)); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos dos botoes inferiores )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*********************** fecha o formulario ***********************************} procedure TFlocalizaServico.BOkClick(Sender: TObject); begin VprAcao := true; self.close; end; {*********************** Cancela a consulta ***********************************} procedure TFlocalizaServico.BCancelarClick(Sender: TObject); begin VprAcao:= false; self.close; end; {******************** cadastra um novo servico ********************************} procedure TFlocalizaServico.BotaoCadastrar1Click(Sender: TObject); var VpfCodClassificacao, VpfNomClassificacao : String; begin FNovoServico:= TFNovoServico.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoServico')); Cadastrou:= FNovoServico.InsereNovoServico('',VpfCodClassificacao,VpfNomClassificacao,true); if Cadastrou then AtualizaConsulta; FNovoServico.Free; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {********************** consulta o servico ************************************} procedure TFlocalizaServico.ConsultaServico; begin ShowModal; end; { ********************** chamada externa da localizacao de servicos ********** } function TFlocalizaServico.LocalizaServico( var VpaCadastrou: Boolean; var VpaCodServico : integer; Var VpaValorVenda : Double;var VpaPerISSQN : Double ) : boolean; begin BotaoCadastrar1.Visible:= VpaCadastrou; ShowModal; Result:= VprAcao; VpaCadastrou:= Cadastrou; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaCodServico:= CadServicoI_COD_SER.AsInteger; VpaValorVenda:= CadServicoN_VLR_VEN.AsFloat; VpaPerISSQN:= CadServicoN_PER_ISS.AsFloat; end; end; { ********************** chamada externa da localizacao de produtos ********** } function TFlocalizaServico.LocalizaServico( var VpaCadastrou : Boolean; var VpaCodServico : integer; var VpaNomServico : string; Var VpaValorVenda, VpaPerISSQN : Double ) : boolean; begin Result:= LocalizaServico(VpaCadastrou,VpaCodServico,VpaValorVenda,vpaPerISSQN); VpaCadastrou:= Cadastrou; if Result then VpaNomServico := CadServicoC_NOM_SER.AsString else VpaNomServico := ''; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoNota : TRBDNotaFiscalServico ) : boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoNota.CodServico := CadServicoI_COD_SER.AsInteger; VpaDServicoNota.ValUnitario := CadServicoN_VLR_VEN.AsFloat; if CadServicoN_PER_ISS.AsFloat > 0 then VpaDServicoNota.PerISSQN := CadServicoN_PER_ISS.AsFloat else VpaDServicoNota.PerISSQN := varia.ISSQN; VpaDServicoNota.CodClassificacao := CadServicoC_COD_CLA.AsString; VpaDServicoNota.PerComissaoClassificacao := CadServicoN_PER_COM.AsFloat; VpaDServicoNota.NomServico := CadServicoC_NOM_SER.AsString; VpaDServicoNota.CodFiscal := CadServicoI_COD_FIS.AsInteger; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoCotacao : TRBDOrcServico) : boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= false; if VprAcao then begin VpaDServicoCotacao.CodServico := CadServicoI_COD_SER.AsInteger; VpaDServicoCotacao.ValUnitario := CadServicoN_VLR_VEN.AsFloat; VpaDServicoCotacao.PerISSQN := CadServicoN_PER_ISS.AsFloat; VpaDServicoCotacao.CodClassificacao := CadServicoC_COD_CLA.AsString; VpaDServicoCotacao.PerComissaoClassificacao := CadServicoN_PER_COM.AsFloat; VpaDServicoCotacao.NomServico := CadServicoC_NOM_SER.AsString; VpaDServicoCotacao.CodFiscal := CadServicoI_COD_FIS.AsInteger; end; end; {************************** localiza a classificacao **************************} procedure TFlocalizaServico.SpeedButton1Click(Sender: TObject); begin LocalizaClassificacao; end; {***************** valida a classificacao digitada ****************************} procedure TFlocalizaServico.EClassificacaoExit(Sender: TObject); begin LDesClassificacao.Caption:= ''; if EClassificacao.Text <> '' then if not ExisteClassificacao Then if not LocalizaClassificacao then begin EClassificacao.Text:= ''; LDesClassificacao.Caption:= ''; ActiveControl:= EClassificacao; end; AtualizaConsulta; end; {********************** quando entra nos servicos *****************************} procedure TFlocalizaServico.GProdutosEnter(Sender: TObject); begin BOk.Default:= true; end; {********************* quando sai da grade ************************************} procedure TFlocalizaServico.GProdutosExit(Sender: TObject); begin BOk.Default:= false; end; {******************************************************************************} procedure TFlocalizaServico.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_DOWN: begin ActiveControl:= GProdutos; CadServico.Next; end; VK_UP: begin ActiveControl:= GProdutos; CadServico.Prior; end; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoExecutado: TRBDChamadoServicoExecutado): Boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoExecutado.CodServico:= CadServicoI_COD_SER.AsInteger; VpaDServicoExecutado.ValUnitario:= CadServicoN_VLR_VEN.AsFloat; VpaDServicoExecutado.CodEmpresaServico:= CadServicoI_COD_EMP.AsInteger; VpaDServicoExecutado.NomServico:= CadServicoC_NOM_SER.AsString; VpaDServicoExecutado.Quantidade := 1; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoOrcado: TRBDChamadoServicoOrcado): Boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoOrcado.CodServico:= CadServicoI_COD_SER.AsInteger; VpaDServicoOrcado.ValUnitario:= CadServicoN_VLR_VEN.AsFloat; VpaDServicoOrcado.CodEmpresaServico:= CadServicoI_COD_EMP.AsInteger; VpaDServicoOrcado.NomServico:= CadServicoC_NOM_SER.AsString; VpaDServicoOrcado.QtdServico := 1; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoAmostra : TRBDServicoFixoAmostra):boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoAmostra.CodServico:= CadServicoI_COD_SER.AsInteger; VpaDServicoAmostra.ValUnitario:= CadServicoN_VLR_VEN.AsFloat; VpaDServicoAmostra.CodEmpresaServico:= CadServicoI_COD_EMP.AsInteger; VpaDServicoAmostra.NomServico:= CadServicoC_NOM_SER.AsString; VpaDServicoAmostra.QtdServico := 1; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoContrato: TRBDContratoServico): boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoContrato.CodServico := CadServicoI_COD_SER.AsInteger; VpaDServicoContrato.ValUnitario := CadServicoN_VLR_VEN.AsFloat; VpaDServicoContrato.PerISSQN := CadServicoN_PER_ISS.AsFloat; VpaDServicoContrato.CodClassificacao := CadServicoC_COD_CLA.AsString; VpaDServicoContrato.NomServico := CadServicoC_NOM_SER.AsString; VpaDServicoContrato.CodFiscal := CadServicoI_COD_FIS.AsInteger; end; end; {******************************************************************************} function TFlocalizaServico.LocalizaServico(VpaDServicoNota: TRBDNotaFiscalForServico): boolean; begin ShowModal; Result:= VprAcao; if CadServico.IsEmpty then Result:= False; if VprAcao then begin VpaDServicoNota.CodServico := CadServicoI_COD_SER.AsInteger; VpaDServicoNota.ValUnitario := CadServicoN_VLR_VEN.AsFloat; VpaDServicoNota.PerISSQN := CadServicoN_PER_ISS.AsFloat; VpaDServicoNota.CodClassificacao := CadServicoC_COD_CLA.AsString; VpaDServicoNota.NomServico := CadServicoC_NOM_SER.AsString; VpaDServicoNota.CodFiscal := CadServicoI_COD_FIS.AsInteger; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFlocalizaServico]); end.
unit NoHelpForm; interface uses Classes, Forms, ExtCtrls, StdCtrls, Controls, Graphics, CrashMgr; type THelpForm = class(TForm) WarningIcon: TImage; HeaderLbl: TLabel; InfoLbl: TLabel; CloseBtn: TButton; VistaBox: TShape; procedure FormCreate(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } Language: TLanguage; end; var HelpForm: THelpForm; implementation {$R *.dfm} procedure THelpForm.FormCreate(Sender: TObject); begin DoubleBuffered := True; end; procedure THelpForm.CloseBtnClick(Sender: TObject); begin Close; end; procedure THelpForm.FormShow(Sender: TObject); begin case Language of laFrench: begin Caption := 'Obtenir de l''aide'; CloseBtn.Caption := 'Fermer'; CloseBtn.Hint := 'Fermer cette boîte de dialogue'; HeaderLbl.Caption := 'Ce logiciel ne propose aucune aide sur ce problème.'; InfoLbl.Caption := 'Vous pouvez tenter de contacter le service clientèle de votre logiciel, ou de vous rendre sur son site internet, afin d''obtenir des renseignements supplémentaires sur votre problème.'; end; laEnglish: begin Caption := 'Obtain help'; CloseBtn.Caption := 'Close'; CloseBtn.Hint := 'Close this dialog box'; HeaderLbl.Caption := 'This program does not provide any help on this issue.'; InfoLbl.Caption := 'You can visit the program''s website and contact the Customer Service Departement to get further information and obtain solutions on the issue you are currently dealing with.'; end; end; end; end.
{ "RTC Bitmap Utils (VCL)" - Copyright 2013-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcVBmpUtils; interface {$INCLUDE rtcDefs.inc} uses SysUtils, {$IFDEF IDE_XEUp} System.Types, VCL.Graphics, {$ELSE} Types, Graphics, {$ENDIF} rtcTypes, rtcInfo, rtcXJPEGConst, rtcXBmpUtils; type TRtcVCLMouseCursorData=class protected FCursorImage: TBitmap; FCursorMask: TBitmap; public constructor Create; destructor Destroy; override; end; function NewBitmapInfo(FromScreen:boolean):TRtcBitmapInfo; // Make an in-memory Bitmap from a TBitmap (copies all info and image) procedure CopyBitmapToInfo(const SrcBmp:TBitmap; var DstBmp:TRtcBitmapInfo); // Copy in-memory bitmap to a TBitmap procedure CopyInfoToBitmap(const SrcBmp:TRtcBitmapInfo; var DstBmp:TBitmap); // procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; NowMouseX, NowMouseY:integer; inControl:boolean); procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; const BmpOrig:TBitmap; NowMouseX, NowMouseY:integer; inControl:boolean); implementation function BitmapIsReverse(const Image: TBitmap): boolean; begin With Image do if Height < 2 then Result := False else Result := RtcIntPtr(ScanLine[0]) > RtcIntPtr(ScanLine[1]); end; function BitmapBytesPerLine(const Image: TBitmap): integer; begin With Image do begin if RtcIntPtr(ScanLine[0])>RtcIntPtr(ScanLine[1]) then Result := RtcIntPtr(ScanLine[0])-RtcIntPtr(ScanLine[1]) else Result := RtcIntPtr(ScanLine[1])-RtcIntPtr(ScanLine[0]); end; end; function BitmapDataPtr(const Image: TBitmap): pointer; begin With Image do begin if Height < 2 then Result := ScanLine[0] else if RtcIntPtr(ScanLine[0]) < RtcIntPtr(ScanLine[1]) then Result := ScanLine[0] Else Result := ScanLine[Height - 1]; End; end; function BitmapDataStride(const Image: TBitmap): integer; begin Result:=RtcIntPtr(Image.ScanLine[1])-RtcIntPtr(Image.ScanLine[0]); end; function GetBitmapInfo(const Bmp:TBitmap; toRead,toWrite,FromScreen:boolean):TRtcBitmapInfo; begin FillChar(Result,SizeOf(Result),0); Result.Data:=BitmapDataPtr(Bmp); Result.Width:=Bmp.Width; Result.Height:=Bmp.Height; Result.Reverse:=BitmapIsReverse(Bmp); Result.BytesPerLine:=BitmapBytesPerLine(Bmp); case Bmp.PixelFormat of pf24bit: begin Result.BuffType:=btBGR24; Result.BytesPerPixel:=3; end; pf32bit: begin Result.BuffType:=btBGRA32; Result.BytesPerPixel:=4; end; else begin Result.BytesPerPixel:=Result.BytesPerLine div Result.Width; case Result.BytesPerPixel of 4: Result.BuffType:=btBGRA32; 3: Result.BuffType:=btBGR24; else raise Exception.Create('Unsupported Bitmap Pixel Format'); end; end; end; CompleteBitmapInfo(Result); end; function NewBitmapInfo(FromScreen:boolean):TRtcBitmapInfo; var Bmp:TBitmap; begin FillChar(Result,SizeOf(Result),0); Bmp:=TBitmap.Create; try Bmp.PixelFormat:=pf32bit; Bmp.Width:=8; Bmp.Height:=8; Result.Reverse:=BitmapIsReverse(Bmp); Result.BuffType:=btBGRA32; Result.BytesPerPixel:=4; finally RtcFreeAndNil(Bmp); end; CompleteBitmapInfo(Result); end; function MakeBitmapInfo(Bmp:TBitmap):TRtcBitmapInfo; begin FillChar(Result,SizeOf(Result),0); Result.Reverse:=BitmapIsReverse(Bmp); Result.BuffType:=btBGRA32; Result.BytesPerPixel:=4; CompleteBitmapInfo(Result); end; procedure CopyInfoToBitmap(const SrcBmp:TRtcBitmapInfo; var DstBmp:TBitmap); var dstInfo:TRtcBitmapInfo; y,wid:integer; srcData,dstData:PByte; begin if not assigned(DstBmp) then begin DstBmp:=TBitmap.Create; DstBmp.PixelFormat:=pf32bit; end; DstBmp.Width:=SrcBmp.Width; DstBmp.Height:=SrcBmp.Height; if assigned(SrcBmp.Data) then begin DstInfo:=GetBitmapInfo(DstBmp,False,True,False); if assigned(dstInfo.Data) then begin if SrcBmp.BytesTotal>0 then begin if SrcBmp.BytesTotal = dstInfo.BytesTotal then Move(SrcBmp.Data^,DstInfo.Data^,SrcBmp.BytesTotal) else if (SrcBmp.Width=DstBmp.Width) and (SrcBmp.Height=DstBmp.Height) then begin wid:=srcBmp.Width*SrcBmp.BytesPerPixel; srcData:=PByte(srcBmp.TopData); dstData:=PByte(dstInfo.TopData); for Y := 0 to SrcBmp.Height-1 do begin Move(srcData^,dstData^,wid); Inc(srcData,SrcBmp.NextLine); Inc(dstData,dstInfo.NextLine); end; end else raise Exception.Create('DstBmp? '+IntToStr(dstInfo.BytesTotal)+'<>'+IntToStr(SrcBmp.BytesTotal)); end else raise Exception.Create('SrcBmp = 0?'); end else raise Exception.Create('DstBmp = NIL!'); end else raise Exception.Create('SrcBmp = NIL!'); end; // Make an in-memory Bitmap from a TBitmap (copies all info and image) procedure CopyBitmapToInfo(const SrcBmp:TBitmap; var DstBmp:TRtcBitmapInfo); var SrcInfo:TRtcBitmapInfo; begin SrcInfo:=GetBitmapInfo(SrcBmp,True,False,False); CopyBitmapInfo(SrcInfo,DstBmp); end; { TRtcVCLMouseCursorInfo } constructor TRtcVCLMouseCursorData.Create; begin inherited; FCursorImage:=nil; FCursorMask:=nil; end; destructor TRtcVCLMouseCursorData.Destroy; begin FreeAndNil(FCursorImage); FreeAndNil(FCursorMask); inherited; end; (* procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; NowMouseX, NowMouseY:integer; inControl:boolean); var cX,cY:integer; ImgData:PColorBGR32; Y: integer; cur:TRtcVCLMouseCursorData; begin Cursor.Lock; try if Cursor.Data=nil then Cursor.Data:=TRtcVCLMouseCursorData.Create; cur:=TRtcVCLMouseCursorData(Cursor.Data); if (length(Cursor.ImageData)>0) or (length(Cursor.MaskData)>0) then begin if assigned(cur.FCursorImage) then FreeAndNil(cur.FCursorImage); if assigned(cur.FCursorMask) then FreeAndNil(cur.FCursorMask); if length(Cursor.ImageData)>0 then begin cur.FCursorImage := TBitmap.Create; cur.FCursorImage.PixelFormat:=pf32bit; cur.FCursorImage.Width:=Cursor.ImageW; cur.FCursorImage.Height:=Cursor.ImageH; ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cur.FCursorImage.Height - 1 do begin Move(ImgData^, cur.FCursorImage.ScanLine[Y]^, cur.FCursorImage.Width*4); Inc(ImgData,cur.FCursorImage.Width); end; Cursor.ClearImageData; end; if length(Cursor.MaskData)>0 then begin cur.FCursorMask := TBitmap.Create; cur.FCursorMask.PixelFormat:=pf32bit; cur.FCursorMask.Width:=Cursor.MaskW; cur.FCursorMask.Height:=Cursor.MaskH; ImgData:=PColorBGR32(Addr(Cursor.MaskData[0])); for Y := 0 to cur.FCursorMask.Height - 1 do begin Move(ImgData^, cur.FCursorMask.ScanLine[Y]^, cur.FCursorMask.Width*4); Inc(ImgData,cur.FCursorMask.Width); end; Cursor.ClearMaskData; end; end; if Cursor.Visible and (assigned(cur.FCursorImage) or assigned(cur.FCursorMask)) then begin if inControl then begin cX:=NowMouseX-Cursor.HotX; cY:=NowMouseY-Cursor.HotY; end else begin cX:=Cursor.X-Cursor.HotX; cY:=Cursor.Y-Cursor.HotY; end; if assigned(cur.FCursorMask) then begin if assigned(cur.FCursorImage) and (cur.FCursorMask.Height = cur.FCursorImage.Height) then begin BmpCanvas.CopyMode:=cmSrcAnd; BmpCanvas.CopyRect(Rect(cX, cY, cX+cur.FCursorMask.Width, cY+cur.FCursorMask.Height), cur.FCursorMask.Canvas, Rect(0, 0, cur.FCursorMask.Width, cur.FCursorMask.Height)); end else if cur.FCursorMask.Height > 1 then begin BmpCanvas.CopyMode:=cmSrcAnd; BmpCanvas.CopyRect(Rect(cX,cY, cX+cur.FCursorMask.Width, cY+cur.FCursorMask.Height div 2), cur.FCursorMask.Canvas, Rect(0,0, cur.FCursorMask.Width, cur.FCursorMask.Height div 2)); BmpCanvas.CopyMode:=cmSrcInvert; BmpCanvas.CopyRect(Rect(cX,cY, cX+cur.FCursorMask.Width,cY+cur.FCursorMask.Height div 2), cur.FCursorMask.Canvas, Rect(0,cur.FCursorMask.Height div 2, cur.FCursorMask.Width, cur.FCursorMask.Height)); end; end; if assigned(cur.FCursorImage) then begin BmpCanvas.CopyMode:=cmSrcPaint; BmpCanvas.CopyRect(Rect(cX, cY, cX+cur.FCursorImage.Width, cY+cur.FCursorImage.Height), cur.FCursorImage.Canvas, Rect(0, 0, cur.FCursorImage.Width, cur.FCursorImage.Height)); end; BmpCanvas.CopyMode:=cmSrcCopy; end; finally Cursor.UnLock; end; end; *) procedure PaintCursor(Cursor:TRtcMouseCursorInfo; const BmpCanvas:TCanvas; const BmpOrig:TBitmap; NowMouseX, NowMouseY:integer; inControl:boolean); var cX,cY,cW,cH:integer; ImgData:PColorBGR32; FMXData, FMXOrig:TBitmap; Alpha:Double; cur:TRtcVCLMouseCursorData; procedure PaintMask_BGR; var SrcData,DstData:PColorBGR32; X,Y: integer; begin if (length(Cursor.MaskData)>0) then begin ImgData:=PColorBGR32(Addr(Cursor.MaskData[0])); // Apply "AND" mask for Y := 0 to cH - 1 do begin if ((Y+cY)>=0) and ((Y+cY)<FMXOrig.Height) then begin SrcData:=FMXOrig.Scanline[Y+cY]; Inc(SrcData,cX); DstData:=FMXData.Scanline[Y]; for X := 0 to cW-1 do begin if ((X+cX)>=0) and ((X+cX)<FMXOrig.Width) then begin DstData^.R:=SrcData^.R and ImgData^.R; DstData^.G:=SrcData^.G and ImgData^.G; DstData^.B:=SrcData^.B and ImgData^.B; DstData^.A:=255; end else begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; end; Inc(DstData); Inc(SrcData); Inc(ImgData); end; end else begin DstData:=FMXData.Scanline[Y]; for X := 0 to cW-1 do begin DstData^.R:=0; DstData^.G:=0; DstData^.B:=0; DstData^.A:=0; Inc(DstData); Inc(ImgData); end; end; end; // Apply "INVERT" Mask if cH<Cursor.MaskH then for Y := 0 to cH - 1 do begin DstData:=FMXData.Scanline[Y]; for X := 0 to cW-1 do begin if DstData^.A>0 then begin DstData^.R:=DstData^.R xor ImgData^.R; DstData^.G:=DstData^.G xor ImgData^.G; DstData^.B:=DstData^.B xor ImgData^.B; end; Inc(DstData); Inc(ImgData); end; end; end; // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.Scanline[Y]; for X := 0 to cW-1 do begin if (DstData^.A>0) and (ImgData^.A>0) then begin Alpha:=ImgData^.A/255; DstData^.R:=trunc((DstData^.R*(1-Alpha)) + (ImgData^.R*Alpha)); DstData^.G:=trunc((DstData^.G*(1-Alpha)) + (ImgData^.G*Alpha)); DstData^.B:=trunc((DstData^.B*(1-Alpha)) + (ImgData^.B*Alpha)); end; Inc(DstData); Inc(ImgData); end; end; end; end; procedure PaintImg_BGR; var DstData:PColorBGR32; X,Y: integer; begin // Paint NORMAL image with Alpha if (length(Cursor.ImageData)>0) and (length(Cursor.ImageData)=cH*cW*4) then begin ImgData:=PColorBGR32(Addr(Cursor.ImageData[0])); for Y := 0 to cH - 1 do begin DstData:=FMXData.Scanline[Y]; for X := 0 to cW-1 do begin DstData^.R:=ImgData^.R; DstData^.G:=ImgData^.G; DstData^.B:=ImgData^.B; DstData^.A:=ImgData^.A; Inc(DstData); Inc(ImgData); end; end; end; end; begin FMXData:=nil; FMXOrig:=nil; Cursor.Lock; try if Cursor.Data=nil then Cursor.Data:=TRtcVCLMouseCursorData.Create; cur:=TRtcVCLMouseCursorData(Cursor.Data); if Cursor.Visible and ( (length(Cursor.ImageData)>0) or (length(Cursor.MaskData)>0) ) then begin if inControl then begin cX:=NowMouseX-Cursor.HotX; cY:=NowMouseY-Cursor.HotY; end else begin cX:=Cursor.X-Cursor.HotX; cY:=Cursor.Y-Cursor.HotY; end; cW:=Cursor.ImageW; cH:=Cursor.ImageH; if (length(Cursor.MaskData)>0) and (length(Cursor.MaskData)=Cursor.MaskW*Cursor.MaskH*4) then begin if (length(Cursor.ImageData)>0) and (Cursor.MaskH = Cursor.ImageH) then begin cW:=Cursor.MaskW; cH:=Cursor.MaskH; end else if Cursor.MaskH > 1 then begin cW:=Cursor.MaskW; cH:=Cursor.MaskH div 2; end; if not assigned(cur.FCursorMask) then begin cur.FCursorMask := TBitmap.Create; cur.FCursorMask.PixelFormat:=pf32bit; end; cur.FCursorMask.Width:=cW; cur.FCursorMask.Height:=cH; FMXData:=cur.FCursorMask; FMXOrig:=BmpOrig; try PaintMask_BGR; finally FMXData:=nil; FMXOrig:=nil; end; end else if length(Cursor.ImageData)>0 then begin if not assigned(cur.FCursorMask) then cur.FCursorMask := TBitmap.Create; cur.FCursorMask.Width:=Cursor.ImageW; cur.FCursorMask.Height:=Cursor.ImageH; FMXData:=cur.FCursorMask; try PaintImg_BGR; finally FMXData:=nil; end; end else FreeAndNil(cur.FCursorMask); if assigned(cur.FCursorMask) then BmpCanvas.Draw(cX,cY,cur.FCursorMask); end; finally Cursor.UnLock; end; end; end.
unit MediaStream.DataSource.Proxy; interface uses Windows,Classes,SysUtils, SyncObjs, MediaStream.DataSource.Base, MediaProcessing.Definitions; type TMediaStreamDataSource_Proxy = class (TMediaStreamDataSource) private FDataLock: TCriticalSection; FChannel : TMediaStreamDataSource; protected procedure DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); override; procedure DoDisconnect; override; procedure OnDataSourceData(aSender: TMediaStreamDataSource; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); public constructor Create; override; destructor Destroy; override; class function CreateConnectParams: TMediaStreamDataSourceConnectParams; override; function GetConnectionErrorDescription(aError: Exception): string; override; procedure Start; override; procedure Stop; override; function LastStreamDataTime: TDateTime; override; end; TMediaStreamDataSourceConnectParams_Proxy = class (TMediaStreamDataSourceConnectParams) private FDataSource: TMediaStreamDataSource; FConnectionString: string; public constructor Create; overload; constructor Create(aDataSource: TMediaStreamDataSource); overload; procedure Assign(aSource: TMediaStreamDataSourceConnectParams); override; function ToString: string; override; function ToUrl(aIncludeAuthorizationInfo: boolean): string; override; procedure Parse(const aUrl: string); override; end; implementation uses uBaseClasses; { TMediaStreamDataSourceConnectParams_Proxy } procedure TMediaStreamDataSourceConnectParams_Proxy.Assign(aSource: TMediaStreamDataSourceConnectParams); begin TArgumentValidation.NotNil(aSource); if not (aSource is TMediaStreamDataSourceConnectParams_Proxy) then raise EInvalidArgument.CreateFmt('Тип параметров %s не совместим с типом %s',[aSource.ClassName,self.ClassName]); FDataSource:=TMediaStreamDataSourceConnectParams_Proxy(aSource).FDataSource; FConnectionString:=TMediaStreamDataSourceConnectParams_Proxy(aSource).FConnectionString; end; constructor TMediaStreamDataSourceConnectParams_Proxy.Create; begin end; constructor TMediaStreamDataSourceConnectParams_Proxy.Create( aDataSource: TMediaStreamDataSource); begin Create; FDataSource:=aDataSource; if FDataSource<>nil then FConnectionString:=FDataSource.ConnectionString; end; procedure TMediaStreamDataSourceConnectParams_Proxy.Parse(const aUrl: string); begin FConnectionString:=aUrl; end; function TMediaStreamDataSourceConnectParams_Proxy.ToString: string; begin result:=FConnectionString; end; function TMediaStreamDataSourceConnectParams_Proxy.ToUrl( aIncludeAuthorizationInfo: boolean): string; begin result:=FConnectionString; end; { TMediaStreamDataSource_Proxy } procedure TMediaStreamDataSource_Proxy.Start; begin FDataLock.Enter; try if FChannel<>nil then FChannel.OnData.Add(OnDataSourceData); finally FDataLock.Leave; end; end; procedure TMediaStreamDataSource_Proxy.Stop; begin FDataLock.Enter; try if FChannel<>nil then FChannel.OnData.Remove(OnDataSourceData); finally FDataLock.Leave; end; end; procedure TMediaStreamDataSource_Proxy.DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); begin FChannel:=nil; FChannel:=(aConnectParams as TMediaStreamDataSourceConnectParams_Proxy).FDataSource; end; procedure TMediaStreamDataSource_Proxy.DoDisconnect; begin if FChannel<>nil then FChannel.OnData.Remove(OnDataSourceData); FChannel:=nil; end; constructor TMediaStreamDataSource_Proxy.Create; begin inherited; FDataLock:=TCriticalSection.Create; end; class function TMediaStreamDataSource_Proxy.CreateConnectParams: TMediaStreamDataSourceConnectParams; begin result:=TMediaStreamDataSourceConnectParams_Proxy.Create; end; destructor TMediaStreamDataSource_Proxy.Destroy; begin Disconnect; inherited; FreeAndNil(FDataLock); end; function TMediaStreamDataSource_Proxy.GetConnectionErrorDescription(aError: Exception): string; begin result:=''; end; function TMediaStreamDataSource_Proxy.LastStreamDataTime: TDateTime; begin if FChannel<>nil then result:=Now else result:=0; end; procedure TMediaStreamDataSource_Proxy.OnDataSourceData(aSender: TMediaStreamDataSource; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin FDataLock.Enter; try RaiseOnData(aFormat,aData,aDataSize,aInfo,aInfoSize); finally FDataLock.Leave; end; end; end.
const fileinp = 'schedule.inp'; fileout = 'schedule.out'; maxN = 100001; type kh = record a,b,c:int64; end; var n:longint; k:array[1..maxN] of kh; sum:string; procedure Init; var i:longint; begin assign(input,fileinp); reset(input); readln(n); for i:=1 to n do read(k[i].a); readln; for i:=1 to n do read(k[i].b); for i:=1 to n do k[i].c:=i; close(input); end; function less(i,j : longint):boolean; var x,y : int64; begin x:=k[i].b*k[j].a; y:=k[i].a*k[j].b; exit(x<y); end; procedure QSort(l,r:longint); var i,j:longint; p:longint; tmp:kh; begin if l >= r then exit; i:=l; j:=r; p:=random(r-l+1)+l; k[n+1]:=k[p]; while i <= j do begin while Less(i,n+1) do inc(i); while Less(n+1,j) do dec(j); if i <= j then begin tmp:=k[i]; k[i]:=k[j]; k[j]:=tmp; inc(i); dec(j); end; end; QSort(l,j); QSort(i,r); end; function cong(s : string; x:int64):string; var t : string; l,r,mem,k,i : longint; c: char; begin str(x,t); l:=1; r:=length(t); while l<r do begin c:=t[l]; t[l]:=t[r]; t[r]:=c; inc(l); dec(r); end; for i:=length(t)+1 to length(s) do t:=t+'0'; for i:=length(s)+1 to length(t) do s:=s+'0'; mem:=0; for i:=1 to length(t) do begin k:=(ord(s[i])+ord(t[i])-96+mem) mod 10; mem:=(ord(s[i])+ord(t[i])-96+mem) div 10; s[i]:=chr(k+48); end; if mem>0 then s:=s+chr(mem+48); exit(s); end; procedure Analyse; var i:longint; day:int64; begin QSort(1,n); sum:=''; day:=0; for i:=1 to n do begin day:=day + k[i].b; sum:=cong(sum,k[i].a*day); end; end; procedure Print; var i:longint; begin assign(output,fileout); rewrite(output); for i:=length(sum) downto 1 do write(sum[i]); writeln; for i:=1 to n do write(k[i].c,' '); close(output); end; begin Init; Analyse; Print; end.
unit CBROrderPaytView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CustomView, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, ActnList, cxGroupBox, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxCheckBox, Menus, cxLabel, cxDBLabel, cxTextEdit, cxMemo, cxDBEdit, StdCtrls, cxButtons, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridBandedTableView, cxGridDBBandedTableView, cxClasses, cxGridCustomView, cxGrid, cxMaskEdit, cxDropDownEdit, cxCalc, UIClasses, CBROrderPaytPresenter, cxCurrencyEdit, dxCore; type TfrCBROrderPaytView = class(TfrCustomView, ICBROrderPaytView) cxGroupBox1: TcxGroupBox; cxGroupBox3: TcxGroupBox; grOrder: TcxGrid; grOrderView: TcxGridDBBandedTableView; grOrderViewColumnID: TcxGridDBBandedColumn; grOrderViewColumnRECNO: TcxGridDBBandedColumn; grOrderViewColumnMARK: TcxGridDBBandedColumn; grOrderViewColumnDISH: TcxGridDBBandedColumn; grOrderViewColumnUNT: TcxGridDBBandedColumn; grOrderViewColumnQTY: TcxGridDBBandedColumn; grOrderViewColumnPRICE: TcxGridDBBandedColumn; grOrderViewColumnSUMM: TcxGridDBBandedColumn; cxGridLevel1: TcxGridLevel; cxGroupBox2: TcxGroupBox; cxGroupBox7: TcxGroupBox; cxDBLabel4: TcxDBLabel; cxGroupBox8: TcxGroupBox; cxDBLabel1: TcxDBLabel; cxDBLabel5: TcxDBLabel; dsHead: TDataSource; dsItems: TDataSource; pnMenu: TcxGroupBox; cxGroupBox4: TcxGroupBox; btClose: TcxButton; cxLabel1: TcxLabel; cxLabel2: TcxLabel; btOrderClose: TcxButton; cxLabel3: TcxLabel; lbSummRet: TcxDBLabel; cxDBLabel2: TcxDBLabel; popupCalc: TcxPopupEdit; edSummPayt: TcxCurrencyEdit; pnCalc: TcxGroupBox; btCalc: TcxButton; cxButton1: TcxButton; cxButton2: TcxButton; cxButton3: TcxButton; cxButton4: TcxButton; cxButton5: TcxButton; cxButton6: TcxButton; cxButton7: TcxButton; cxButton8: TcxButton; cxButton9: TcxButton; cxButton10: TcxButton; cxButton11: TcxButton; cxButton12: TcxButton; cxButton13: TcxButton; btPrecheck: TcxButton; procedure edSummPaytPropertiesChange(Sender: TObject); procedure btCalcClick(Sender: TObject); procedure CalcButtonClick(Sender: TObject); procedure edSummPaytPropertiesEditValueChanged(Sender: TObject); private procedure doCalcButton(AButtonIndex: integer); protected //ICBROrderPaytView procedure LinkHeadData(ADataSet: TDataSet); procedure LinkItemsData(ADataSet: TDataSet); function GetSummPayt: double; procedure OnInitialize; override; end; var frCBROrderPaytView: TfrCBROrderPaytView; implementation {$R *.dfm} type TDummyCurrencyEdit = class(TcxCurrencyEdit) end; { TfrCBROrderPaytView } procedure TfrCBROrderPaytView.btCalcClick(Sender: TObject); begin popupCalc.DroppedDown := true; end; procedure TfrCBROrderPaytView.CalcButtonClick(Sender: TObject); begin doCalcButton(TComponent(Sender).Tag); end; procedure TfrCBROrderPaytView.doCalcButton(AButtonIndex: integer); const BUTTON_ENTER = 12; BUTTON_CHARS: array[0..11] of char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', Char(VK_BACK)); begin edSummPayt.SelStart := Length(edSummPayt.Text); case AButtonIndex of BUTTON_ENTER: popupCalc.DroppedDown := false; else SendKeyPress(edSummPayt, BUTTON_CHARS[AButtonIndex]); end; edSummPayt.EditValue := edSummPayt.Text; end; procedure TfrCBROrderPaytView.edSummPaytPropertiesChange(Sender: TObject); begin edSummPayt.PostEditValue; end; procedure TfrCBROrderPaytView.edSummPaytPropertiesEditValueChanged( Sender: TObject); begin WorkItem.Commands[COMMAND_PAYT_CHANGED].Execute; end; function TfrCBROrderPaytView.GetSummPayt: double; begin Result := edSummPayt.Value; end; procedure TfrCBROrderPaytView.LinkHeadData(ADataSet: TDataSet); begin LinkDataSet(dsHead, ADataSet); end; procedure TfrCBROrderPaytView.LinkItemsData(ADataSet: TDataSet); begin LinkDataSet(dsItems, ADataSet); end; procedure TfrCBROrderPaytView.OnInitialize; begin popupCalc.Height := 0; WorkItem.Commands[COMMAND_CLOSE].AddInvoker(btClose, 'OnClick'); WorkItem.Commands[COMMAND_ORDER_CLOSE].AddInvoker(btOrderClose, 'OnClick'); WorkItem.Commands[COMMAND_PRECHECK].AddInvoker(btPrecheck, 'OnClick'); end; end.
(** This module contains a modeless form for displaying the progress of the before or after compile information. @Author David Hoyle @Version 1.0 @Date 30 Dec 2017 **) Unit ITHelper.ProcessingForm; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; {$INCLUDE 'CompilerDefinitions.inc'} Type (** A class to represent the modeless form. **) TfrmITHProcessing = Class(TForm) Strict Private { Private declarations } FForm: TPanel; FInfo: TPanel; FFileName: TPanel; FMsg: TTimer; FCanHide: Boolean; Strict Protected Function TextWidth(Const AFont: TFont; Const strMsg: String): Integer; Procedure MsgTimer(Sender: TObject); Protected Procedure InitialiseControls; Public { Public declarations } Class Procedure ShowProcessing(Const strMsg: String; Const iColour: TColor = clBlue; Const boolWait: Boolean = False); Class Procedure HideProcessing; Class Procedure ProcessFileName(Const strFileName: String); (** This property determines if the form can be closed. @precon None. @postcon Determines if the form can be closed. @return a Boolean **) Property CanHide: Boolean Read FCanHide Write FCanHide; End; Implementation {$R *.dfm} Var (** A private varaiable to hold the Singleton reference to the form. **) FormInstance: TfrmITHProcessing; (** This method signifies that the form can be closed by the timer event handler. @precon None. @postcon Signifies that the form can be closed by the timer event handler. **) Class Procedure TfrmITHProcessing.HideProcessing; Begin FormInstance.CanHide := True; If Not FormInstance.FMsg.Enabled Then FormInstance.Hide; End; (** TYhis method creates all the controls on the form. For Delphi 7 backward compatibility. @precon None. @postcon Creates all the controls on the form. For Delphi 7 backward compatibility. **) Procedure TfrmITHProcessing.InitialiseControls; Const strPnlFormName = 'pnlForm'; strPnlInfoName = 'pnlInfo'; iInfoHeight = 28; strFontName = 'Tahoma'; iFontSize = 10; strPnlFileName = 'pnlFileName'; strTmMsgName = 'tmMsg'; iTimerInterval = 2500; Begin FForm := TPanel.Create(Self); FForm.Name := strPnlFormName; FForm.Parent := Self; FForm.Align := alClient; FForm.TabOrder := 0; FForm.Caption := ''; FForm.Font.Name := strFontName; FForm.Font.Size := iFontSize; FInfo := TPanel.Create(Self); FInfo.Name := strPnlInfoName; FInfo.Parent := FForm; FInfo.ParentFont := True; FInfo.Height := iInfoHeight; FInfo.Align := alTop; FInfo.BevelOuter := bvNone; FInfo.Caption := ''; FInfo.ParentFont := False; FInfo.Font.Style := [fsBold]; FInfo.TabOrder := 0; FInfo.VerticalAlignment := taAlignBottom; FFileName := TPanel.Create(Self); FFileName.Name := strPnlFileName; FFileName.Parent := FForm; FFileName.ParentFont := True; FFileName.Align := alClient; FFileName.BevelOuter := bvNone; FFileName.ParentFont := False; FFileName.TabOrder := 1; FFileName.Caption := ''; FFileName.Font.Color := clGreen; FFileName.VerticalAlignment := taAlignTop; FMsg := TTimer.Create(Self); FMsg.Name := strTmMsgName; FMsg.Enabled := False; FMsg.Interval := iTimerInterval; FMsg.OnTimer := MsgTimer; End; (** This is an on timer event handler for the form. @precon None. @postcon Disables the timer and hides the form if it can else shortens the timer interval. @param Sender as a TObject **) Procedure TfrmITHProcessing.MsgTimer(Sender: TObject); Const iMsgTimerInterval = 250; Begin If FormInstance.CanHide Then Begin FMsg.Enabled := False; Hide; End Else FMsg.Interval := iMsgTimerInterval; End; (** This method updates the filename panel on the form. @precon None. @postcon Updates the filename panel on the form. @param strFileName as a String as a constant **) Class Procedure TfrmITHProcessing.ProcessFileName(Const strFileName: String); Begin FormInstance.FFileName.Caption := strFileName; Application.ProcessMessages; End; (** This method displays the modeless form with the message and starts the timer so that the for is displayed for a minimum of 2.5 seconds. @precon None. @postcon Displays the modeless form with the message and starts the timer so that the for is displayed for a minimum of 2.5 seconds. @param strMsg as a String as a constant @param iColour as a TColor as a constant @param boolWait as a Boolean as a constant **) Class Procedure TfrmITHProcessing.ShowProcessing(Const strMsg: String; Const iColour: TColor = clBlue; Const boolWait: Boolean = False); Const iTextPadding = 50; Begin FormInstance.CanHide := False; FormInstance.FInfo.Caption := strMsg; FormInstance.FInfo.Font.Color := iColour; FormInstance.Width := iTextPadding + FormInstance.TextWidth(FormInstance.FInfo.Font, strMsg); FormInstance.Left := Screen.Width Div 2 - FormInstance.Width Div 2; If Not FormInstance.Visible Then FormInstance.Show; FormInstance.FFileName.Caption := ''; Application.ProcessMessages; If boolWait Then FormInstance.FMsg.Enabled := True; End; (** This method returns the width of the text on the Canvas. @precon None. @postcon Returns the width of the text on the Canvas. @param AFont as a TFont as a constant @param strMsg as a String as a constant @return an Integer **) Function TfrmITHProcessing.TextWidth(Const AFont: TFont; Const strMsg: String): Integer; Begin Canvas.Font.Assign(AFont); Result := Canvas.TextWidth(strMsg); End; (** Creates an instance of the form for use in the application. **) Initialization FormInstance := TfrmITHProcessing.Create(Nil); FormInstance.InitialiseControls; (** Frees the form at unloading. **) Finalization FormInstance.Free; End.
1 program KeizerKiezer; 2 { (c) 2002, Tom Verhoeff, versie 2 } 3 { Kies keizer uit opgegeven aantal kandidaten, genummerd vanaf 0. 4 Iedere 3e kandidaat valt af volgens aftelversje 'Geen kei-zer'. } 5 6 { 22 September 2006, Etiene van Delden, versie 2.5 } 7 8 const 9 MaxNKandidaten = 10000; // maximale aantal kandidaten, >= 1 10 MaxNCijfers = 0; // maximale aantal cijfers 11 // in kandidaatnummer 12 NLettergrepen = 3; // aantal lettergrepen, >=1 13 14 type 15 Kandidaat = 0 .. MaxNKandidaten - 1; // de kandidaten, eigenlijk 16 // 0 .. NKandidaten - 1 17 18 var 19 NKandidaten: 1 .. MaxNKandidaten; // aantal kandidaten (invoer) 20 rest: 1 .. MaxNKandidaten; // aantal overgebleven kandidaten 21 aangewezen: Kandidaat; // doorloopt kring 22 g: 1 .. NLettergrepen; // doorloopt lettergrepen 23 // lettergreep g valt op 24 // aangewezen kandidaat 25 keizer: Kandidaat; // wie keizer wordt (uitvoer) 26 opvolger: array [ Kandidaat ] of Integer; 27 // opvolger aanwijzen 28 i: Kandidaat; // hulpvar voor opvolger init. 29 vorige: Kandidaat; // de vorige persoon, voor de aangewezen 30 31 begin 32 ////////// 1. Lees aantal kandidaten ////////// 33 write( 'Aantal kandidaten? ' ); 34 readln( NKandidaten ); 35 writeln( NKandidaten, ' kandidaten' ); 36 37 ////////// 2. Initialiseer volle kring. Wijs eerste kandidaat aan ////////// 38 39 for i := 0 to NKandidaten - 1 do begin 40 opvolger[ i ] := (i + 1) mod Nkandidaten; 41 end; // alle opvolgers 42 43 rest := NKandidaten; // alle kandidaten doen (nog) mee 44 aangewezen := 0; // kandidaat 0 als eerste aangewezen 45 g := 1; // lettergreep g valt op 46 // aangewezen kandidaat 47 48 ////////// 3. Dun kring uit tot een enkele kandidaat resteert, die keizer wordt 49 50 51 while rest <> 1 do begin 52 53 ///// 3.1. Wijs kandidaat bij laatste lettergreep aan ///// 54 while g <> NLettergrepen do begin 55 56 vorige := aangewezen; 57 aangewezen := opvolger[ aangewezen ]; 58 // volgende kandidaat 59 g := g + 1 ; 60 end; 61 ///// 3.2 Pas de opvolger aan ///// 62 // laatste lettergreep is 63 // gevallen op de aangewezen kandidaat 64 opvolger[ vorige ] := opvolger[ aangewezen ]; 65 // andere opvolger word toegekend 66 67 aangewezen := opvolger[ aangewezen ]; 68 // de aangewezen persoon schuift door 69 g := 1; // lettergreep reset 70 rest := rest-1; // er is 1 iemand minder 71 end; 72 73 keizer := aangewezen; 74 75 ////////// 4. Schrijf keizer ////////// 76 writeln ( 'Kandidaat ', keizer : MaxNCijfers, ' wordt keizer' ); 77 end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, System.Actions, Vcl.ActnList, Vcl.Menus; type TForm1 = class(TForm) pnlTimer: TPanel; chkAllWayTop: TCheckBox; btn1Hour: TButton; Image1: TImage; Timer1: TTimer; L_couterTime: TLabel; L_couterTime2: TLabel; btn50M: TButton; btn30M: TButton; btn25M: TButton; btn10M: TButton; btn5M: TButton; TrayIcon1: TTrayIcon; PopupMenu1: TPopupMenu; ActionList1: TActionList; actClose: TAction; N3: TMenuItem; procedure chkAllWayTopClick(Sender: TObject); procedure btn1HourClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btn50MClick(Sender: TObject); procedure btn30MClick(Sender: TObject); procedure btn10MClick(Sender: TObject); procedure btn25MClick(Sender: TObject); procedure btn5MClick(Sender: TObject); procedure actCloseExecute(Sender: TObject); procedure FormPaint(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation var BarSize: Double = 600; globaltime: Integer; TimeThrow: Integer; defaultTime: Integer; {$R *.dfm} procedure TForm1.actCloseExecute(Sender: TObject); begin close; end; procedure TForm1.btn10MClick(Sender: TObject); begin L_couterTime.Caption := '00 : 10 : 00'; L_couterTime2.Caption := '00 : 10 : 00'; pnlTimer.Width := 100; BarSize := 100; globaltime := 600; defaultTime := 600; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.btn1HourClick(Sender: TObject); begin L_couterTime.Caption := '01 : 00 : 00'; L_couterTime2.Caption := '01 : 00 : 00'; pnlTimer.Width := 600; BarSize := 600; globaltime := 3600; defaultTime := 3600; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.btn25MClick(Sender: TObject); begin L_couterTime.Caption := '00 : 25 : 00'; L_couterTime2.Caption := '00 : 25 : 00'; pnlTimer.Width := 250; BarSize := 250; globaltime := 1500; defaultTime := 1500; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.btn30MClick(Sender: TObject); begin L_couterTime.Caption := '00 : 30 : 00'; L_couterTime2.Caption := '00 : 30 : 00'; pnlTimer.Width := 300; BarSize := 300; globaltime := 1800; defaultTime := 1800; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.btn50MClick(Sender: TObject); begin L_couterTime.Caption := '00 : 50 : 00'; L_couterTime2.Caption := '00 : 50 : 00'; pnlTimer.Width := 500; BarSize := 500; globaltime := 3000; defaultTime := 3000; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.btn5MClick(Sender: TObject); begin L_couterTime.Caption := '00 : 05 : 00'; L_couterTime2.Caption := '00 : 05 : 00'; pnlTimer.Width := 50; BarSize := 50; globaltime := 300; defaultTime := 300; TimeThrow := 0; Timer1.Enabled := True; end; procedure TForm1.chkAllWayTopClick(Sender: TObject); begin if chkAllWayTop.Checked then FormStyle := fsStayOnTop else formstyle := fsNormal; end; procedure TForm1.FormPaint(Sender: TObject); begin ShowWindow(Application.Handle, SW_HIDE); SetWindowLong(Application.Handle, GWL_EXSTYLE, GetWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW); end; procedure TForm1.Timer1Timer(Sender: TObject); begin timethrow := TimeThrow + 1; BarSize := ((defaultTime - timethrow) / 3600 * 100) * 6; pnlTimer.Width := Trunc(BarSize); globaltime := globaltime -1; L_couterTime.Caption := FormatFloat('00',globaltime div 3600) + ' : ' + FormatFloat('00',globaltime div 60 mod 60) + ' : ' + FormatFloat('00',globaltime mod 60); L_couterTime2.Caption := FormatFloat('00',globaltime div 3600) + ' : ' + FormatFloat('00',globaltime div 60 mod 60) + ' : ' + FormatFloat('00',globaltime mod 60); if globaltime <= 0 then begin Timer1.Enabled := false; end; end; end.
{*******************************************************} { } { Delphi VCL Extensions (RX) } { } { Copyright (c) 1995 AO ROSNO } { } {*******************************************************} unit rxHintProp; interface {$I RX.INC} uses {$IFDEF RX_D6} DesignIntf, VCLEditors {$ELSE} DsgnIntf {$ENDIF}; // Polaris type { THintProperty } THintProperty = class(TCaptionProperty) public function GetAttributes: TPropertyAttributes; override; function GetEditLimit: Integer; override; procedure Edit; override; end; implementation {$D-} uses SysUtils, Classes, {$IFDEF RX_D3} rxStrLEdit, {$ELSE} rxStrEdit, {$ENDIF} TypInfo, Forms, Controls, rxStrUtils; function THintProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog]; end; function THintProperty.GetEditLimit: Integer; begin if GetPropType^.Kind = tkString then Result := GetTypeData(GetPropType)^.MaxLength else Result := 1024; end; procedure THintProperty.Edit; var Temp: string; Comp: TPersistent; I, Cnt: Integer; begin with TStrEditDlg.Create(Application) do try Comp := GetComponent(0); if Comp is TComponent then Caption := TComponent(Comp).Name + '.' + GetName else Caption := GetName; Temp := GetStrValue; Cnt := WordCount(Temp, [#13, #10]); for I := 1 to Cnt do Memo.Lines.Add(ExtractWord(I, Temp, [#13, #10])); Memo.MaxLength := GetEditLimit; UpdateStatus(nil); if ShowModal = mrOk then begin Temp := Memo.Text; while (Length(Temp) > 0) and (Temp[Length(Temp)] < ' ') do System.Delete(Temp, Length(Temp), 1); SetStrValue(Temp); end; finally Free; end; end; end.
{$mode objfpc} unit dumbBinaryTree; interface type ENotFound = class end; type generic TBTreeNode<_K, _V> = class private _Key : _K; _Val : _V; _Left : TBTreeNode; _Right : TBTreeNode; public constructor CreateFromKV( k: _K; v: _V ); function GetValue : _V; procedure SetValue( v : _V ); procedure Inject( n : TBTreeNode ); function Find( k : _K ) : TBTreeNode; function PrintLevel( level : integer; myLevel: integer ) : integer; end; type generic TBTree<_K, _V> = class type TNode = specialize TBTreeNode<_K, _V>; private _Root: TNode; public constructor Create; function Exists( key : _K ) : boolean; function GetAt( key: _K ) : _V; procedure SetAt( key: _K; val: _V ); procedure PrintLevels; end; implementation constructor TBTreeNode.CreateFromKV( k: _K; v: _V ); begin _Key := k; _Val := v; _Left := nil; _Right := nil; end; function TBTreeNode.PrintLevel( level : integer; myLevel: integer ) : integer; begin if myLevel = level then begin Write(' {', _Key, ': ', _Val, '} '); Result := 1; end else begin Result := 0; if _Left <> nil then begin Result := Result + _Left.PrintLevel( level, myLevel + 1 ); end; if _Right <> nil then begin Result := Result + _Right.PrintLevel( level, myLevel + 1 ); end; end; end; procedure TBTree.PrintLevels; var level: integer; var count: integer; begin level := 1; while true do begin count := _Root.PrintLevel( level, 1 ); level := level + 1; WriteLn(); WriteLn('Level #', level, ' => ', count, ' nodes'); if count = 0 then halt; end; end; function TBTreeNode.GetValue : _V; begin Result := _Val; end; procedure TBTreeNode.SetValue( v : _V ); begin _Val := v; end; function TBTreeNode.Find( k : _K ) : TBTreeNode; begin if k = _Key then begin Result := self; end else if k < _Key then begin if _Left = nil then begin Result := nil; end else begin _Left.Find( k ); end; end else if k > _Key then begin if _Right = nil then begin Result := nil; end else begin _Right.Find( k ); end; end; end; procedure TBTreeNode.Inject( n : TBTreeNode ); begin if n._Key = _Key then begin _Val := n._Val; n.Free; end else if n._Key < _Key then begin if _Left = nil then begin _Left := n; end else begin _Left.Inject( n ); end; end else if n._Key > _Key then begin if _Right = nil then begin _Right := n; end else begin _Right.Inject( n ); end; end; end; constructor TBTree.Create; begin _Root := nil; end; function TBTree.Exists( key: _K ) : boolean; begin if _Root = nil then begin Result := false; end else begin Result := _Root.Find( key ) <> nil; end; end; function TBTree.GetAt( key: _K ) : _V; begin if not Exists( key ) then begin raise ENotFound.Create; end else begin _Root.Find( key ).GEtValue; end; end; procedure TBTree.SetAt( key: _K; val: _V ); begin if _Root = nil then begin _Root := TNode.CreateFromKV( key, val ); end else begin _Root.Inject( TNode.CreateFromKV( key, val ) ); end; end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Buttons, UFRAME1, Menus, uChoices, System.Generics.Collections, Vcl.CheckLst, Vcl.Imaging.jpeg, Vcl.Imaging.pngimage; type TForm1 = class(TForm) lbQuestions: TListBox; btnAddBool: TSpeedButton; btnAddSingleChoice: TSpeedButton; btnAddMultipleChoice: TSpeedButton; btnRemove: TSpeedButton; btnEdit: TSpeedButton; imDirty: TImage; Panel1: TPanel; Panel2: TPanel; btnSave: TSpeedButton; cb: TBitBtn; OB: TBitBtn; procedure FormCreate(Sender: TObject); procedure cbClick(Sender: TObject); procedure R1Change(Sender: TObject); procedure R2Change(Sender: TObject); procedure FormShow(Sender: TObject); procedure R2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAddBoolClick(Sender: TObject); procedure btnAddSingleChoiceClick(Sender: TObject); procedure btnAddMultipleChoiceClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure lbQuestionsClick(Sender: TObject); procedure OBClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private { Private declarations } public procedure SaveFile; procedure loadfile; procedure dirty; function convertCheckBoxListToIntegerList( c: TCheckListBox ): TList<Integer>; procedure convertIntegerListToCheckBoxList( il: TList<Integer>; c: TCheckListBox ); procedure addSingleChoice(d: String; a: Byte; k: String; o: String = ''); procedure addMultiChoice(d: String; a: TList<Integer>; o: String ); { Public declarations } end; const nf='New.sf'; var Form1: TForm1; f:TextFile; n,l,m:byte; fn:string; ext:string='.sf'; vert:0..1; SCTRL:boolean=false; choices: TList<TChoice>; procedure Split(s:string;var a,b:string); implementation uses uBool, uMultipleChoice, uChoice; {$R *.dfm} procedure Split(s:string;var a,b:string); begin if pos('|',s)>0 then begin a:=copy(s,1,pos('|',s)-1); b:=copy(s,pos('|',s)+1,length(s)); end else begin a:=s; b:=''; end; end; procedure TForm1.FormCreate(Sender: TObject); begin fn:=paramstr(1); if fn='' then fn:=nf; Application.Title:=fn; caption:=fn; choices := TList<TChoice>.Create(); end; procedure TForm1.addMultiChoice(d: String; a: TList<Integer>; o: String); var c: TChoice; begin c := TMultipleChoice.Create( d, a, o); choices.Add(c); lbQuestions.Items.AddObject( d, c ); end; procedure TForm1.addSingleChoice(d: String; a: Byte; k: String; o: String = ''); var c: TChoice; begin c := TSingleChoice.Create( d, a, k, o); choices.Add(c); lbQuestions.Items.AddObject( d, c ); end; procedure TForm1.btnAddBoolClick(Sender: TObject); begin frmBool.memDescription.Text := ''; frmBool.rgChoices.ItemIndex := -1; frmBool.Caption := 'New Boolean Choice Question'; if frmBool.ShowModal = mrOk then begin addSingleChoice( frmBool.memDescription.Text, frmBool.rgChoices.ItemIndex, 'b', frmBool.rgChoices.Items.Text ); end; Dirty; end; procedure TForm1.btnAddMultipleChoiceClick(Sender: TObject); begin frmMultipleChoice.memDescription.Text := ''; frmMultipleChoice.clbChoices.Clear; frmMultipleChoice.edtOption.Text := ''; frmMultipleChoice.Caption := 'New Multiple Choice Question'; if frmMultipleChoice.ShowModal = mrOk then begin addMultiChoice( frmMultipleChoice.memDescription.Text, convertCheckBoxListToIntegerList( frmMultipleChoice.clbChoices ), frmMultipleChoice.clbChoices.Items.Text ); end; Dirty; end; procedure TForm1.btnAddSingleChoiceClick(Sender: TObject); begin frmChoice.memDescription.Text := ''; frmChoice.rgChoices.Items.Clear; frmChoice.Caption := 'New Single Choice Question'; if frmChoice.ShowModal = mrOk then begin addSingleChoice( frmChoice.memDescription.Text, frmChoice.rgChoices.ItemIndex, 's', frmChoice.rgChoices.Items.Text ); end; Dirty; end; procedure TForm1.btnEditClick(Sender: TObject); var index: Integer; begin index := lbQuestions.ItemIndex; if choices[ index ].kind = 'b' then begin frmBool.memDescription.Text := choices[ index ].description; frmBool.rgChoices.ItemIndex := TSingleChoice(choices[ index ]).correctAnswer; frmBool.Caption := choices[ index ].description; if frmBool.ShowModal = mrOk then begin choices[ index ].description := frmBool.memDescription.Text; TSingleChoice(choices[ index ]).correctAnswer := frmBool.rgChoices.ItemIndex; end; end else if choices[ index ].kind = 's' then begin frmChoice.memDescription.Text := choices[ index ].description; frmChoice.rgChoices.Items.Text := choices[ index ].options; frmChoice.rgChoices.ItemIndex := TSingleChoice(choices[ index ]).correctAnswer; frmChoice.Caption := choices[ index ].description; if frmChoice.ShowModal = mrOk then begin choices[ index ].description := frmChoice.memDescription.Text; TSingleChoice(choices[ index ]).correctAnswer := frmChoice.rgChoices.ItemIndex; choices[ index ].options := frmChoice.rgChoices.Items.Text; end; end else if choices[ index ].kind = 'm' then begin frmMultipleChoice.memDescription.Text := choices[ index ].description; frmMultipleChoice.clbChoices.Items.Text := choices[ index ].options; convertIntegerListToCheckBoxList( TMultipleChoice(choices[ index ]).correctAnswer, frmMultipleChoice.clbChoices ); frmMultipleChoice.Caption := choices[ index ].description; if frmMultipleChoice.ShowModal = mrOk then begin choices[ index ].description := frmMultipleChoice.memDescription.Text; TMultipleChoice(choices[ index ]).correctAnswer := convertCheckBoxListToIntegerList( frmMultipleChoice.clbChoices ); choices[ index ].options := frmMultipleChoice.clbChoices.Items.Text; end; end; lbQuestions.Items[ index ] := choices[ index ].description; Dirty; { case choices[ index ].kind[1] of 'b': frmModal := frmBool; 's': frmModal := ; 'm': frmModal := ; end; case choices[ index ].kind[1] of 'b': t := TfrmBool; 's': t := TfrmChoice; 'm': t := TfrmMultipleChoice; end; (frmModal as t).memDescription.Text := '';} //updateChoice( index, frmModal.memDescription.Text, frmModal.rgChoices.ItemIndex, 's' ); end; procedure TForm1.btnRemoveClick(Sender: TObject); var index: Integer; begin index := lbQuestions.ItemIndex; choices.Delete( index ); lbQuestions.Items.Delete( index ); Dirty; end; procedure TForm1.btnSaveClick(Sender: TObject); begin savefile end; procedure TForm1.cbClick(Sender: TObject); begin close; end; function TForm1.convertCheckBoxListToIntegerList( c: TCheckListBox): TList<Integer>; var i: Integer; begin Result := TList<Integer>.Create(); for i := 0 to c.Items.Count - 1 do begin if c.Checked[i] then Result.Add( i ); end; end; procedure TForm1.convertIntegerListToCheckBoxList(il: TList<Integer>; c: TCheckListBox); var i: Integer; begin for i := 0 to c.Items.Count - 1 do begin c.Checked[i] := False; end; for i := 0 to il.Count - 1 do begin c.Checked[il[i]] := True; end; end; procedure TForm1.dirty; begin imDirty.Visible := True; end; procedure TForm1.R1Change(Sender: TObject); begin Application.Title:=fn+'*'; caption:=fn+'*'; // R2.CaretPos:=R1.CaretPos end; procedure TForm1.R2Change(Sender: TObject); begin Application.Title:=fn+'*'; caption:=fn+'*'; end; procedure TForm1.FormShow(Sender: TObject); begin LoadFile end; procedure TForm1.SaveFile; var i,j:Integer; sl: TStringList; il: TList<Integer>; begin fn:=ChangeFileExt(fn,ext); AssignFile(f,fn); rewrite(f); writeln(f, choices.Count); sl := TStringList.Create; //il := TList<Integer>.Create; for i := 0 to choices.Count - 1 do begin writeln(f, choices[i].kind); sl.Text := choices[i].description; writeln(f, sl.Count); write(f, sl.Text); if choices[i].kind <> 'b' then begin sl.Text := choices[i].options; writeln(f, sl.Count); write(f, sl.Text); end; end; for i := 0 to choices.Count - 1 do begin if choices[i].kind = 'm' then begin il := TMultipleChoice(choices[i]).correctAnswer; writeln(f, il.Count); for j := 0 to il.Count - 1 do write(f, il[j], ' '); writeln(f); end else begin writeln(f, TSingleChoice(choices[i]).correctAnswer); end; end; imDirty.Visible := False; closeFile(f); caption:=fn end; procedure TForm1.lbQuestionsClick(Sender: TObject); var e: Boolean; begin e := (lbQuestions.ItemIndex >=0) and (lbQuestions.ItemIndex < lbQuestions.Items.Count); btnRemove.Enabled := e; btnEdit.Enabled := e; end; procedure TForm1.loadfile; var i, j, l, m, n: Integer; kind, d, desc, opts: String; il: TList<Integer>; begin if fileexists(fn) then begin assignfile(f,fn); ext := LowerCase(ExtractFileExt(fn)); reset(f); choices.Clear(); try readln(f, l); for i := 0 to l - 1 do begin readln(f, kind); readln(f, m); desc := ''; for j := 0 to m - 1 do begin readln(f, d); desc := desc + d + #13#10; end; opts := ''; if kind <> 'b' then begin readln(f, m); for j := 0 to m - 1 do begin readln(f, d); opts := opts + d + #13#10; end; end; if kind = 'm' then addMultiChoice(desc, nil, opts) else addSingleChoice(desc, 0, kind, opts); end; for i := 0 to l - 1 do begin if choices[i].kind = 'm' then begin il := TList<Integer>.Create(); readln(f, m); for j := 0 to m - 1 do begin read(f, n); il.add(n); end; readln(f); TMultipleChoice(choices[i]).correctAnswer := il; end else begin readln(f, n); TSingleChoice(choices[i]).correctAnswer := n; end; end; finally closeFile(f); end; end; Application.Title:=fn; caption:=fn; end; procedure TForm1.OBClick(Sender: TObject); begin SaveFile; close; end; procedure TForm1.R2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin SCTRL:=false end; end.
program Sample; begin WriteLn('Pi: ', Pi); WriteLn('MaxInt: ', MaxInt); WriteLn('Ord(False): ', Ord(False)); WriteLn('Ord(True): ', Ord(True)); WriteLn('False: ', False); WriteLn('True: ', True); end.
unit UFigures; {$mode objfpc}{$H+} interface uses Classes, ExtCtrls, Graphics, types, math, LCLType, LCLIntf, UFloatPoint, UTransform; type TPointEditor = class(TObject) private FPoint: TFloatPoint; public Selected: Boolean; constructor Create(APoint: TFloatPoint); overload; function GetPoint: TFloatPoint; procedure SetPoint(APoint: TFloatPoint); function IsSelected(X, Y: Integer): Boolean; procedure Draw(ACanvas: TCanvas); property Point: TFloatPoint read GetPoint write SetPoint; end; TFigure = class(TObject) private FFigureWasUndo, FFiguresIsEmpty: Boolean; static; public Points: array of TFloatPoint; PointEditors: array of TPointEditor; Selected: Boolean; PointsCount: Integer; procedure AddPoint(APoint: TFloatPoint); function GetPoint(APos: Integer = -1): TFloatPoint; procedure SetPoint(APoint: TFloatPoint; APos: Integer = -1); virtual; class procedure AddFigure(AFigure: TFigure); class procedure LiftUpFigure; class procedure LiftDownFigure; class procedure DeleteFigure; class procedure DrawUndo; class procedure DrawRedo; class procedure ClearScreen; class function GetLastFigure: TFigure; class function GetLastUndidFigure: TFigure; class function IsFiguresEmpty: Boolean; procedure Draw(ACanvas: TCanvas); virtual; abstract; procedure DrawSelection(ACanvas: TCanvas); virtual; abstract; function BoundRect: TRect; virtual; function Region: HRGN; virtual; abstract; end; PFigure = ^TFigure; TPenFigure = class(TFigure) private FPenColor: TColor; FPenStyle: TPenStyle; FPenSize: Integer; function GetPenColor: TColor; procedure SetPenColor(AColor: TColor); public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; function Region: HRGN; override; published property PenColor: TColor read GetPenColor write SetPenColor; property PenStyle: TPenStyle read FPenStyle write FPenStyle; property PenSize: Integer read FPenSize write FPenSize; end; TBrushFigure = class(TPenFigure) private FBrushColor: TColor; FBrushStyle: TBrushStyle; function GetBrushColor: TColor; procedure SetBrushColor(AColor: TColor); public procedure Draw(ACanvas: TCanvas); override; published property BrushColor: TColor read GetBrushColor write SetBrushColor; property BrushStyle: TBrushStyle read FBrushStyle write FBrushStyle; end; TPen = class(TPenFigure) public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; end; TLine = class(TPenFigure) public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; end; TRectangle = class(TBrushFigure) public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; function Region: HRGN; override; end; TEllipse = class(TBrushFigure) public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; function Region: HRGN; override; end; TRoundRect = class(TBrushFigure) private FRX, FRY: Integer; public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; function Region: HRGN; override; published property RX: Integer read FRX write FRX; property RY: Integer read FRY write FRY; end; TPolyline = class(TPenFigure) public procedure Draw(ACanvas: TCanvas); override; procedure DrawSelection(ACanvas: TCanvas); override; end; procedure DrawBoundLines(ARect: TRect; ACanvas: TCanvas); procedure SwapFigures(var F1, F2: TFigure); const //SelectionColor = clLime; SelectionColor = clFuchsia; var Figures, UndidFigures: array of TFigure; CurrentFigure: PFigure; implementation { TPointEditor } const Size = 4; constructor TPointEditor.Create(APoint: TFloatPoint); begin inherited Create; FPoint := APoint; Selected := False; end; function TPointEditor.GetPoint: TFloatPoint; begin Result := FPoint; end; procedure TPointEditor.SetPoint(APoint: TFloatPoint); begin FPoint := APoint; end; function TPointEditor.IsSelected(X, Y: Integer): Boolean; begin Selected := ((abs(WorldToScreenX(FPoint.x - X)) < Size) and (abs(WorldToScreenY(FPoint.y - Y)) < Size)); Result := Selected; end; procedure TPointEditor.Draw(ACanvas: TCanvas); var P: TPoint; begin P := WorldToScreen(FPoint); with ACanvas do begin Pen.Style := psSolid; Pen.Color := SelectionColor; Rectangle(P.x - Size, P.y - Size, P.x + Size, P.y + Size); end; end; { TFigure } procedure TFigure.AddPoint(APoint: TFloatPoint); begin Inc(PointsCount); SetLength(Points, Length(Points) + 1); Points[High(Points)] := APoint; SetLength(PointEditors, Length(PointEditors) + 1); PointEditors[High(PointEditors)] := TPointEditor.Create(APoint); end; function TFigure.GetPoint(APos: Integer): TFloatPoint; begin if (APos < 0) or (APos > High(Points)) then APos := High(Points); Result := Points[APos]; end; procedure TFigure.SetPoint(APoint: TFloatPoint; APos: Integer); begin if (APos < 0) or (APos > High(Points)) then APos := High(Points); Points[APos] := APoint; PointEditors[APos].SetPoint(APoint); end; class procedure TFigure.AddFigure(AFigure: TFigure); begin if (FFigureWasUndo) then SetLength(UndidFigures, 0); SetLength(Figures, Length(Figures) + 1); Figures[High(Figures)] := AFigure; CurrentFigure := @Figures[High(Figures)]; CurrentFigure^ := AFigure; FFiguresIsEmpty := False; end; class procedure TFigure.LiftUpFigure; var i: Integer; begin for i := 0 to High(Figures) do if (Figures[i].Selected and (Figures[i] <> Figures[High(Figures)])) then SwapFigures(Figures[i + 1], Figures[i]); end; class procedure TFigure.LiftDownFigure; var i: Integer; begin for i := High(Figures) downto 0 do if (Figures[i].Selected and (Figures[i] <> Figures[0])) then SwapFigures(Figures[i - 1], Figures[i]); end; class procedure TFigure.DeleteFigure; var i: Integer = 0; j: Integer; begin while (i <= High(Figures)) do begin if (Figures[i].Selected) then begin Figures[i].Free; for j := i + 1 to High(Figures) do Figures[j - 1] := Figures[j]; SetLength(Figures, Length(Figures) - 1); end else Inc(i); end; end; class function TFigure.GetLastFigure: TFigure; begin if (FFiguresIsEmpty) then Result := nil else Result := Figures[High(Figures)]; end; class procedure TFigure.DrawUndo; begin if (FFiguresIsEmpty) then Exit; FFigureWasUndo := True; SetLength(UndidFigures, Length(UndidFigures) + 1); UndidFigures[High(UndidFigures)] := GetLastFigure; SetLength(Figures, Length(Figures) - 1); if (Length(Figures) = 0) then FFiguresIsEmpty := True; end; class procedure TFigure.DrawRedo; begin if (Length(UndidFigures) <= 0) then Exit; SetLength(Figures, Length(Figures) + 1); Figures[High(Figures)] := GetLastUndidFigure; SetLength(UndidFigures, Length(UndidFigures) - 1); end; class function TFigure.GetLastUndidFigure: TFigure; begin Result := UndidFigures[High(UndidFigures)]; end; class procedure TFigure.ClearScreen; begin SetLength(Figures, 0); SetLength(UndidFigures, 0); FFigureWasUndo := False; FFiguresIsEmpty := True; end; class function TFigure.IsFiguresEmpty: Boolean; begin Result := TFigure.FFiguresIsEmpty; end; function TFigure.BoundRect: TRect; var P: array of TPoint; i: Integer; begin P := WorldToScreen(Points); Result := Rect(P[0].x, P[0].y, P[0].x, P[0].y); for i := 0 to High(P) do begin Result := Rect(Min(Result.Left, P[i].x), Min(Result.Top, P[i].y), Max(Result.Right, P[i].x), Max(Result.Bottom, P[i].y)); end; end; { TPenFigure } procedure TPenFigure.Draw(ACanvas: TCanvas); begin with ACanvas.Pen do begin Color := FPenColor; Style := FPenStyle; Width := FPenSize; end; end; procedure TPenFigure.DrawSelection(ACanvas: TCanvas); var i: Integer; begin if (Selected) then begin DrawBoundLines(BoundRect, ACanvas); end; for i := 0 to High(PointEditors) do PointEditors[i].Draw(ACanvas); ACanvas.Pen.Style := psSolid; end; function TPenFigure.Region: HRGN; var FP: array of TPoint; RP: array of TPoint; i: Integer; begin SetLength(RP, Length(Points) * 2); SetLength(FP, Length(Points)); FP := WorldToScreen(Points); for i := 0 to High(FP) do begin RP[i].x := round(FP[i].x - 4 * Scale); RP[i].y := round(FP[i].y - 4 * Scale); RP[High(RP) - i].x := round(FP[i].x + 4 * Scale); RP[High(RP) - i].y := round(FP[i].y + 4 * Scale); end; Result := CreatePolygonRgn(@RP[0], Length(RP), WINDING); end; function TPenFigure.GetPenColor: TColor; begin Result := FPenColor; end; procedure TPenFigure.SetPenColor(AColor: TColor); begin FPenColor := AColor; end; { TBrushFigure } procedure TBrushFigure.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); with ACanvas.Brush do begin Color := FBrushColor; Style := FBrushStyle; end; end; function TBrushFigure.GetBrushColor: TColor; begin Result := FBrushColor; end; procedure TBrushFigure.SetBrushColor(AColor: TColor); begin FBrushColor := AColor; end; { TPen } procedure TPen.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.MoveTo(WorldToScreen(Points[0])); ACanvas.Polyline(WorldToScreen(Points)); end; procedure TPen.DrawSelection(ACanvas: TCanvas); begin inherited DrawSelection(ACanvas); ACanvas.Polyline(WorldToScreen(Points)); end; { TLine } procedure TLine.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.MoveTo(WorldToScreen(Points[0])); ACanvas.LineTo(WorldToScreen(Points[1])); end; procedure TLine.DrawSelection(ACanvas: TCanvas); var P: array of TPoint; begin inherited DrawSelection(ACanvas); P := WorldToScreen(Points); ACanvas.Line(P[0].x, P[0].y, P[1].x, P[1].y); end; { TRectangle } procedure TRectangle.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.Rectangle(BoundRect); end; procedure TRectangle.DrawSelection(ACanvas: TCanvas); begin inherited DrawSelection(ACanvas); ACanvas.Rectangle(BoundRect); end; function TRectangle.Region: HRGN; var P: array of TPoint; begin P := WorldToScreen(Points); Result := CreateRectRgn(P[0].x, P[0].y, P[1].x, P[1].y); end; { TEllipse } procedure TEllipse.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.Ellipse(BoundRect); end; procedure TEllipse.DrawSelection(ACanvas: TCanvas); begin inherited DrawSelection(ACanvas); ACanvas.Ellipse(BoundRect); end; function TEllipse.Region: HRGN; var P: array of TPoint; begin P := WorldToScreen(Points); Result := CreateEllipticRgn(P[0].x, P[0].y, P[1].x, P[1].y); end; { TRoundRect } procedure TRoundRect.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.RoundRect(BoundRect, FRX, FRY); end; procedure TRoundRect.DrawSelection(ACanvas: TCanvas); begin inherited DrawSelection(ACanvas); ACanvas.RoundRect(BoundRect, FRX, FRY); end; function TRoundRect.Region: HRGN; var P: array of TPoint; begin P := WorldToScreen(Points); Result := CreateRoundRectRgn(P[0].x, P[0].y, P[1].x, P[1].y, FRX, FRY); end; { TPolyline } procedure TPolyline.Draw(ACanvas: TCanvas); begin inherited Draw(ACanvas); ACanvas.Polyline(WorldToScreen(Points)); end; procedure TPolyline.DrawSelection(ACanvas: TCanvas); begin inherited DrawSelection(ACanvas); ACanvas.Polyline(WorldToScreen(Points)); end; procedure DrawBoundLines(ARect: TRect; ACanvas: TCanvas); begin with ACanvas do begin Pen.Color := SelectionColor; Pen.Width := 1; Pen.Style := psDot; Brush.Style := bsClear; Rectangle(ARect); end; end; procedure SwapFigures(var F1, F2: TFigure); var Temp: TFigure; begin Temp := F1; F1 := F2; F2 := Temp; end; initialization TFigure.FFiguresIsEmpty := True; end.
unit NIFUtils; { ******************************************************* sNIF Utilidad para buscar ficheros ofimáticos con cadenas de caracteres coincidentes con NIF/NIE. ******************************************************* 2012-2018 Ángel Fernández Pineda. Madrid. Spain. This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. ******************************************************* } interface const BYTES_PER_NIF = 18; // UTF-16 encoded function isNIF_UTF8(const data: PByte): boolean; function isNIF_UTF16(const data: PByte): boolean; implementation // uses // SysUtils; var NIFTable: array [0 .. 22] of byte; function isAsciiDigit(chr: byte): boolean; begin result := (chr >= 48) and (chr <= 57) end; function isAsciiCapitalLetter(chr: byte): boolean; begin result := (chr >= 65) and (chr <= 90); end; function ControlLetter(Value: integer): byte; var R: integer; begin R := (Value mod 23); result := NIFTable[R]; end; function isNIF(chr0, chr1, chr2, chr3, chr4, chr5, chr6, chr7, chr8: byte) : boolean; overload; var val: integer; begin result := isAsciiDigit(chr1) and isAsciiDigit(chr2) and isAsciiDigit(chr3) and isAsciiDigit(chr4) and isAsciiDigit(chr5) and isAsciiDigit(chr6) and isAsciiDigit(chr7); if (result) then begin val := (chr7 - 48) + ((chr6 - 48) * 10) + ((chr5 - 48) * 100) + ((chr4 - 48) * 1000) + ((chr3 - 48) * 10000) + ((chr2 - 48) * 100000) + ((chr1 - 48) * 1000000); if isAsciiDigit(chr0) then // DNI result := (chr8 = ControlLetter(val + ((chr0 - 48) * 10000000))) else if (chr0 >= byte('X')) and (chr0 <= byte('Z')) then // NIE result := (chr8 = ControlLetter(val + ((chr0 - byte('X')) * 10000000))) else if (chr0 >= byte('K')) and (chr0 <= byte('M')) then // NIF no es un DNI ni un NIE result := (chr8 = ControlLetter(val)) else result := false; end; end; function isNIF_UTF8(const data: PByte): boolean; begin result := isNIF(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]); end; function isNIF_UTF16(const data: PByte): boolean; begin result := ((data[1] = 0) and (data[3] = 0) and (data[5] = 0) and (data[7] = 0) and (data[9] = 0) and (data[11] = 0) and (data[13] = 0) and (data[15] = 0) and (data[17] = 0) and isNIF(data[0], data[2], data[4], data[6], data[8], data[10], data[12], data[14], data[16])); end; initialization NIFTable[0] := byte('T'); NIFTable[1] := byte('R'); NIFTable[2] := byte('W'); NIFTable[3] := byte('A'); NIFTable[4] := byte('G'); NIFTable[5] := byte('M'); NIFTable[6] := byte('Y'); NIFTable[7] := byte('F'); NIFTable[8] := byte('P'); NIFTable[9] := byte('D'); NIFTable[10] := byte('X'); NIFTable[11] := byte('B'); NIFTable[12] := byte('N'); NIFTable[13] := byte('J'); NIFTable[14] := byte('Z'); NIFTable[15] := byte('S'); NIFTable[16] := byte('Q'); NIFTable[17] := byte('V'); NIFTable[18] := byte('H'); NIFTable[19] := byte('L'); NIFTable[20] := byte('C'); NIFTable[21] := byte('K'); NIFTable[22] := byte('E'); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Android.ServiceApplication; interface uses System.SysUtils, System.Classes; type /// <summary>Component to use services like an application module</summary> TServiceApplication = class(TComponent) private class constructor Create; procedure OnExceptionHandler(Sender: TObject); protected /// <summary>Exception Handler for non user managed exceptions</summary> /// <remarks>Exceptions not managed by the user will be shown in the android logcat</remarks> procedure DoHandleException(E: Exception); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // The following uses the current behaviour of the IDE module manager /// <summary>Create an Instance of the class type from InstanceClass param</summary> procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual; /// <summary>Initializes the service application</summary> procedure Initialize; virtual; /// <summary>Main loop of the application service</summary> procedure Run; virtual; end; var /// <summary>Global var to acces to the Application Service</summary> Application: TServiceApplication = nil; implementation uses {$IFDEF ANDROID} Androidapi.Log, Posix.Dlfcn, Androidapi.Helpers, AndroidApi.JNI, AndroidApi.JNI.App, Androidapi.JNIBridge, Androidapi.JNI.Os, AndroidApi.JNI.GraphicsContentViewText, {$ENDIF ANDROID} System.Android.Service; type TAndroidServiceCallbacks = class(TServiceCallbacks); { TServiceApplication } constructor TServiceApplication.Create(AOwner: TComponent); begin inherited Create(AOwner); if not Assigned(System.Classes.ApplicationHandleException) then System.Classes.ApplicationHandleException := OnExceptionHandler; end; class constructor TServiceApplication.Create; begin Application := TServiceApplication.Create(nil); end; procedure TServiceApplication.CreateForm(InstanceClass: TComponentClass; var Reference); begin if InstanceClass.InheritsFrom(TAndroidBaseService) then begin try TComponent(Reference) := InstanceClass.Create(Self); if InstanceClass.InheritsFrom(TAndroidService) then TAndroidServiceCallbacks.FService := TAndroidService(Reference); if InstanceClass.InheritsFrom(TAndroidIntentService) then TAndroidServiceCallbacks.FIntentService := TAndroidIntentService(Reference); except TComponent(Reference) := nil; raise; end; end; end; destructor TServiceApplication.Destroy; begin inherited Destroy; end; procedure TServiceApplication.DoHandleException(E: Exception); {$IFDEF ANDROID} var M: TMarshaller; {$ENDIF ANDROID} begin {$IFDEF ANDROID} LOGE(M.AsUtf8(E.Message).ToPointer); {$ENDIF ANDROID} end; procedure TServiceApplication.Initialize; begin end; procedure TServiceApplication.OnExceptionHandler(Sender: TObject); begin DoHandleException(Exception(ExceptObject)); end; procedure TServiceApplication.Run; begin end; {$IFDEF ANDROID} ///////////////////// /// Glue code ///////////////////// procedure SystemEntry(const LibName: string); function StrToCStr(const Str: string; Dest: MarshaledAString): MarshaledAString; // Only ASCII chars var I: Integer; begin Result := Dest; for I := Low(Str) to High(Str) do begin Byte(Dest^) := Byte(Str[I]); Inc(Dest); end; Byte(Dest^) := 0; end; type TMainFunction = procedure; var CStr: MarshaledAString; DlsymPointer: Pointer; EntryPoint: TMainFunction; Lib: NativeUInt; begin CStr := System.AllocMem(512); Lib := dlopen(StrToCStr(LibName, CStr), RTLD_LAZY); System.FreeMem(CStr); if Lib <> 0 then begin DlsymPointer := dlsym(Lib, '_NativeMain'); dlclose(Lib); if DlsymPointer <> nil then begin EntryPoint := TMainFunction(DlsymPointer); EntryPoint; end; end; end; procedure OnCreateDelphi(PEnv: PJNIEnv; This: JNIObject; LibraryName: JNIString); cdecl; var LService: JService; begin if System.JavaContext = nil then begin PEnv^.GetJavaVM(PEnv, @System.JavaMachine); System.JavaContext := PEnv^.NewGlobalRef(PEnv, This); end; SystemEntry(JNIStringToString(PEnv, LibraryName)); LService := TJService.Wrap(System.JavaContext); TAndroidServiceCallbacks.OnCreateCallback(LService); end; procedure OnDestroyDelphi(PEnv: PJNIEnv; This: JNIObject; Service: JNIObject); cdecl; begin TAndroidServiceCallbacks.OnDestroyCallback; end; function OnStartCommandDelphi(PEnv: PJNIEnv; This: JNIObject; JNIStartIntent: JNIObject; Flags, StartID: Integer): Integer; cdecl; var Intent: JIntent; begin Intent := TJIntent.Wrap(JNIStartIntent); Result := TAndroidServiceCallbacks.OnStartCommandCallback(Intent, Flags, StartID); end; function OnBindDelphi(PEnv: PJNIEnv; This: JNIObject; JNIIntent: JNIObject): JNIObject; cdecl; var Intent: JIntent; LBinder: JIBinder; begin Intent := TJIntent.Wrap(JNIIntent); LBinder := TAndroidServiceCallbacks.OnBindCallback(Intent); Result := (LBinder as ILocalObject).GetObjectID; end; function onUnbindDelphi(PEnv: PJNIEnv; This: JNIObject; JNIIntent: JNIObject): Boolean; cdecl; var Intent: JIntent; begin Intent := TJIntent.Wrap(JNIIntent); Result := TAndroidServiceCallbacks.onUnbindCallback(Intent); end; procedure OnRebindDelphi(PEnv: PJNIEnv; This: JNIObject; JNIintent: JNIObject); cdecl; var Intent: JIntent; begin Intent := TJIntent.Wrap(JNIIntent); TAndroidServiceCallbacks.onRebindCallback(Intent); end; procedure OnTaskRemovedDelphi(PEnv: PJNIEnv; This: JNIObject; JNIrootIntent: JNIObject); cdecl; var RootIntent: JIntent; begin RootIntent := TJIntent.Wrap(JNIrootIntent); TAndroidServiceCallbacks.onTaskRemovedCallback(RootIntent); end; procedure OnConfigurationChangedDelphi(PEnv: PJNIEnv; This: JNIObject; JNInewConfig: JNIObject); cdecl; var LConfig: JConfiguration; begin LConfig := TJConfiguration.Wrap(JNInewConfig); TAndroidServiceCallbacks.onConfigurationChangedCallback(LConfig); end; procedure OnLowMemoryDelphi(PEnv: PJNIEnv; This: JNIObject); cdecl; begin TAndroidServiceCallbacks.onLowMemoryCallback; end; procedure OnTrimMemoryDelphi(PEnv: PJNIEnv; This: JNIObject; level: Integer); cdecl; begin TAndroidServiceCallbacks.onTrimMemoryCallback(level); end; procedure OnHandleIntentDelphi(PEnv: PJNIEnv; This: JNIObject; JNIintent: JNIObject); cdecl; var Intent: JIntent; begin Intent := TJIntent.Wrap(JNIIntent); TAndroidServiceCallbacks.onHandleIntentCallback(Intent); end; function getDelphiService: Int64 ; cdecl; begin Result := TAndroidServiceCallbacks.GetDelphiService; end; function OnHandleMessageDelphi(PEnv: PJNIEnv; This: JNIObject; JNIMessage: JNIObject): Boolean; cdecl; var LMessage: JMessage; begin LMessage := TJMessage.Wrap(JNIMessage); Result := TAndroidServiceCallbacks.onHandleMessageCallback(LMessage); end; exports OnCreateDelphi, OnDestroyDelphi, OnStartCommandDelphi, OnBindDelphi, OnUnbindDelphi, OnRebindDelphi, OnTaskRemovedDelphi, OnConfigurationChangedDelphi, OnLowMemoryDelphi, OnTrimMemoryDelphi, OnHandleIntentDelphi, OnHandleMessageDelphi, getDelphiService; {$ENDIF ANDROID} end.
// Designer : Arief Darmawan Tantriady (16518058) // Coder : Arief Darmawan Tantriady (16518058) // Tester : Morgen Sudyanto (16518380) unit F04; //pencarian buku berdasarkan tahun terbit interface uses typeList; var ketemu:boolean; tahun,i:integer; ktg:string;//kategori procedure searchTahunTerbit(lBuku : listBuku); implementation procedure searchTahunTerbit(lBuku : listBuku); begin ketemu:=false; write('Masukkan tahun: '); readln(tahun); write('Masukkan kategori: '); readln(ktg); //Asumsi input kategori selalu (= / < / > / >= / <=) selalu valid writeln; writeln('Buku yang terbit '+ktg+' ',tahun,':'); for i:=1 to lBuku.neff do begin if (ktg='=') then begin if(lBuku.list[i].tahun_penerbit = tahun) then begin ketemu:=true; writeln(lBuku.list[i].id_buku,' | '+lBuku.list[i].judul_buku+' | '+lBuku.list[i].author); end; end else if (ktg='<') then begin if(lBuku.list[i].tahun_penerbit < tahun) then begin ketemu:=true; writeln(lBuku.list[i].id_buku,' | '+lBuku.list[i].judul_buku+' | '+lBuku.list[i].author); end; end else if (ktg='>') then begin if(lBuku.list[i].tahun_penerbit > tahun) then begin ketemu:=true; writeln(lBuku.list[i].id_buku,' | '+lBuku.list[i].judul_buku+' | '+lBuku.list[i].author); end; end else if (ktg='>=') then begin if(lBuku.list[i].tahun_penerbit >= tahun) then begin ketemu:=true; writeln(lBuku.list[i].id_buku,' | '+lBuku.list[i].judul_buku+' | '+lBuku.list[i].author); end; end else if(lBuku.list[i].tahun_penerbit <= tahun) then begin ketemu:=true; writeln(lBuku.list[i].id_buku,' | '+lBuku.list[i].judul_buku+' | '+lBuku.list[i].author); end; end; if(ketemu=false) then begin writeln('Tidak ada buku dalam kategori ini.'); end; end; end.
unit g_class_sturrel; interface uses OpenGL, g_class_gameobject, g_game_objects, g_rockets, g_player, u_math, u_sound, g_sounds; type TSimpleTurrel = class (TGameObject) FireTime : Integer; procedure Render; override; procedure Move; override; procedure DoCollision(Vector : TGamePos; CoObject : TObject); override; procedure Death; override; constructor Create; end; TMiniTurrel = class (TSimpleTurrel) procedure Render; override; procedure Move; override; procedure DoCollision(Vector : TGamePos; CoObject : TObject); override; procedure Death; override; constructor Create; end; TWebTurrel = class (TSimpleTurrel) procedure Render; override; procedure Move; override; procedure DoCollision(Vector : TGamePos; CoObject : TObject); override; procedure Death; override; constructor Create; end; implementation uses g_world; { TSimpleTurrel } constructor TSimpleTurrel.Create; begin Health := 100; Radius := 0.5; Collision := True; FireTime := 500; end; procedure TSimpleTurrel.Death; var Expl : TExplosion; begin Expl := TExplosion.Create; Expl.Pos := Pos; ObjectsEngine.AddObject(Expl); inc(World.Score, 100); end; procedure TSimpleTurrel.DoCollision(Vector: TGamePos; CoObject: TObject); begin inherited; // end; procedure TSimpleTurrel.Move; var Rocket : TExtraRocket; begin if Distance(Pos, Player.Pos) <= 20 then begin Angle := 90-AngleTo(Pos.x, Pos.z, Player.Pos.x, Player.Pos.z); if FireTime = 0 then begin Rocket := TExtraRocket.Create; Rocket.Pos := AddVector(Pos, MakeNormalVector(Cosinus(90-Angle), 0.0, Sinus(90-Angle))); Rocket.LockOn := Player; Rocket.FiredBy := Self; ObjectsEngine.AddObject(Rocket); FireTime := 500; end; end; Dec(FireTime); if FireTime < 0 then FireTime := 0; end; procedure TSimpleTurrel.Render; begin glPushMatrix; glTranslatef(Pos.x, Pos.y, Pos.z); glColor3f(1 - Health / 100, Health/100, 0.2); glBegin(GL_LINE_LOOP); glVertex3f(-0.5, 0.0, -0.5); glVertex3f( 0.5, 0.0, -0.5); glVertex3f( 0.5, 0.0, 0.5); glVertex3f(-0.5, 0.0, 0.5); glEnd; glRotatef(Angle, 0.0, 1.0, 0.0); glColor3f(1.0 - (FireTime / 500), (FireTime / 500), 0.0); glBegin(GL_LINE_LOOP); glVertex3f(-0.1, 0.0, 0.0); glVertex3f( 0.1, 0.0, 0.0); glVertex3f( 0.1, 0.0, 1); glVertex3f(-0.1, 0.0, 1); glEnd; glPopMatrix; end; { TMiniTurrel } constructor TMiniTurrel.Create; begin Health := 50; Collision := True; Radius := 0.25; FireTime := 50; end; procedure TMiniTurrel.Death; begin inherited; inc(World.Score, 50); end; procedure TMiniTurrel.DoCollision(Vector: TGamePos; CoObject: TObject); begin inherited; end; procedure TMiniTurrel.Move; var Bullet : TAIMBullet; begin if Distance(Pos, Player.Pos) <= 30 then begin Angle := AngleTo(Pos.x, Pos.z, Player.Pos.x, Player.Pos.z); if FireTime = 0 then begin Bullet := TAIMBullet.Create; Bullet.Pos := AddVector(Pos, MakeVector(Cosinus(Angle), 0, Sinus(Angle))); Bullet.LockOn := Player; Bullet.FiredBy := Self; ObjectsEngine.AddObject(Bullet); FireTime := 50; end; end; Dec(FireTime); if FireTime < 0 then FireTime := 0; end; procedure TMiniTurrel.Render; begin glPushMatrix; glTranslatef(Pos.x, Pos.y, Pos.z); glColor3f(1 - (Health / 50), Health / 50, 0.0); glBegin(GL_LINE_LOOP); glVertex3f(-0.25, 0, -0.25); glVertex3f( 0.25, 0, -0.25); glVertex3f( 0.25, 0, 0.25); glVertex3f(-0.25, 0, 0.25); glEnd; glRotatef(90-Angle, 0.0, 1.0, 0.0); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_LOOP); glVertex3f( 0, 0, 0); glVertex3f(-0.1, 0, 1); glVertex3f( 0.1, 0, 1); glEnd; glPopMatrix; end; { TWebTurrel } constructor TWebTurrel.Create; begin Health := 100; Collision := True; Radius := 0.5; FireTime := 500; end; procedure TWebTurrel.Death; var Expl : TExplosion; begin Expl := TExplosion.Create; Expl.Pos := Pos; ObjectsEngine.AddObject(Expl); inc(World.Score, 150); end; procedure TWebTurrel.DoCollision(Vector: TGamePos; CoObject: TObject); begin inherited; end; procedure TWebTurrel.Move; var WebRocket : TWebRocket; begin if Distance(Pos, Player.Pos) < 30 then begin Angle := AngleTo(Pos.x, Pos.z, Player.Pos.x, Player.Pos.z); if (FireTime = 0) and not (Player.Freeze) then begin WebRocket := TWebRocket.Create; WebRocket.Pos := AddVector(Pos, MakeNormalVector(Cosinus(90-Angle)*2, 0.0, Sinus(90-Angle)*2)); WebRocket.LockOn := Player; WebRocket.FiredBy := Self; ObjectsEngine.AddObject(WebRocket); FireTime := 500; Sound_PlayStream(Shot_2); end; end; Dec(FireTime); if FireTime < 0 then FireTime := 0; end; procedure TWebTurrel.Render; var a : Integer; begin glPushMatrix; glTranslatef(Pos.x, Pos.y, Pos.z); glColor3f(1 - (Health / 100), Health / 100, 0); glBegin(GL_LINE_LOOP); for a := 0 to 18 do begin glVertex3f(Cosinus(a * 20), 0, Sinus(a * 20)); end; glEnd; glRotatef(90-Angle, 0, 1, 0); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_LOOP); glVertex3f( 0, 0, 0); glVertex3f(-0.5, 0, 2); glVertex3f( 0.5, 0, 2); glEnd; glPopMatrix; end; end.
{********************************************} { TeeChart Pro Charting Library } { Custom TeeFunction Editor } { Copyright (c) 2002-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeCustomFuncEditor; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} SysUtils, Classes, TeEngine, TeeFunci; type TCustomFunctionEditor = class(TForm) Label1: TLabel; EStart: TEdit; Label2: TLabel; EStep: TEdit; ENum: TEdit; Label3: TLabel; procedure FormShow(Sender: TObject); procedure EStartChange(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } TheFunction : TCustomTeeFunction; Function Series:TChartSeries; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.dfm} {$ELSE} {$R *.xfm} {$ENDIF} uses TeeFuncEdit; procedure TCustomFunctionEditor.FormShow(Sender: TObject); begin TheFunction:=TCustomTeeFunction(Tag); if Assigned(TheFunction) then begin EStart.Text:=FloatToStr(TheFunction.StartX); EStep.Text:=FloatToStr(TheFunction.Period); ENum.Text:=IntToStr(TheFunction.NumPoints); end; end; procedure TCustomFunctionEditor.EStartChange(Sender: TObject); begin TTeeFuncEditor(Owner).BApply.Enabled:=True; end; Function TCustomFunctionEditor.Series:TChartSeries; begin result:=TTeeFuncEditor(Owner).TheSeries; end; procedure TCustomFunctionEditor.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if not Assigned(TheFunction) then TheFunction:=TCustomTeeFunction.Create(Series.Owner); TheFunction.StartX:=StrToFloat(EStart.Text); TheFunction.Period:=StrToFloat(EStep.Text); TheFunction.NumPoints:=StrToInt(ENum.Text); if not Assigned(Series.FunctionType) then Series.SetFunction(TheFunction); CanClose:=True; end; initialization RegisterClass(TCustomFunctionEditor); end.
unit ModelMainU; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SQLite3Conn, SQLDB, Dialogs; type { TModelMain } TModelMain = class(TDataModule) SQLite3Connection1: TSQLite3Connection; QueryCustomers: TSQLQuery; SQLTransaction1: TSQLTransaction; procedure DataModuleCreate(Sender: TObject); private FCustomerCompany: String; function GetCustomerCompany: String; procedure SetCustomerCompany(AValue: String); public property CompanyName : String read GetCustomerCompany; procedure GetFilteredCustomers(const aFilterText : String); end; var ModelMain: TModelMain; implementation {$R *.lfm} { TModelMain } procedure TModelMain.DataModuleCreate(Sender: TObject); begin SQLite3Connection1.DatabaseName:='data\Aussendienst.sqlite'; // SQLite3Connection1.DatabaseName:='data\dejaoffice.db'; SQLTransaction1.Database:=SQLite3Connection1; QueryCustomers.Transaction:=SQLTransaction1; SQLite3Connection1.Open; end; procedure TModelMain.SetCustomerCompany(AValue: String); begin if FCustomerCompany=AValue then Exit; FCustomerCompany:=AValue; end; function TModelMain.GetCustomerCompany: String; begin result := QueryCustomers.FieldByName('company').AsString; end; procedure TModelMain.GetFilteredCustomers(const aFilterText: String); begin QueryCustomers.Close; QueryCustomers.ParamByName('Filter').AsString := '%'+aFilterText+'%'; // ShowMessage(QueryCustomers.SQL.Text); QueryCustomers.Open; end; end.
unit ClientListParams; interface uses SysUtils; type TClientListParams = class(TObject) private FSearchKey: string; FShowNonClients: boolean; public property SearchKey: string read FSearchKey write FSearchKey; property ShowNonClients: boolean read FShowNonClients write FShowNonClients; constructor Create; destructor Destroy; override; end; var clp: TClientListParams; implementation constructor TClientListParams.Create; begin if clp <> nil then Abort else clp := self; end; destructor TClientListParams.Destroy; begin if clp = self then clp := nil; inherited; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSComputingRegister<p> Registration unit for GLScene Computing package.<p> <b>History : </b><font size=-1><ul> <li>05/03/11 - Yar - Added TCUDAConstant, TCUDAFuncParam <li>22/08/10 - Yar - Some improvements for FPC (thanks Predator) <li>09/06/10 - Yar - Added dropdown list ProjectModule for TGLSCUDACompiler <li>19/03/10 - Yar - Creation </ul></font> } unit GLSComputingRegister; interface uses Classes, SysUtils, DesignIntf, DesignEditors, STREDIT, ToolsAPI, GLSceneRegister; procedure Register; type TGLSCUDAEditor = class(TComponentEditor) public { Public Declarations } procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TGLSCUDACompilerEditor = class(TComponentEditor) public { Public Declarations } procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TGLSCUDACompilerSourceProperty = class(TStringProperty) private FModuleList: TStringList; procedure RefreshModuleList; public { Public Declarations } constructor Create(const ADesigner: IDesigner; APropCount: Integer); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: String); override; end; TGLSCUDADeviceProperty = class(TStringProperty) private FDeviceList: TStringList; public { Public Declarations } constructor Create(const ADesigner: IDesigner; APropCount: Integer); override; destructor Destroy; override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: String); override; end; implementation uses GLSCUDARunTime, GLSCUDAContext, GLSCUDA, GLSCUDACompiler, GLSCUDAFFTPlan, GLSCUDAGraphics, GLSCUDAParser, FCUDAEditor; procedure Register; begin RegisterComponents('GLScene Computing', [TGLSCUDA, TGLSCUDADevice, TGLSCUDACompiler]); RegisterComponentEditor(TGLSCUDA, TGLSCUDAEditor); RegisterComponentEditor(TGLSCUDACompiler, TGLSCUDACompilerEditor); RegisterPropertyEditor(TypeInfo(string), TGLSCUDACompiler, 'ProjectModule', TGLSCUDACompilerSourceProperty); RegisterPropertyEditor(TypeInfo(string), TGLSCUDADevice, 'SelectDevice', TGLSCUDADeviceProperty); RegisterNoIcon([TCUDAModule, TCUDAMemData, TCUDAFunction, TCUDATexture, TCUDAFFTPlan, TCUDAGLImageResource, TCUDAGLGeometryResource, TCUDAConstant, TCUDAFuncParam]); ObjectManager.RegisterSceneObject(TGLFeedBackMesh, 'GPU generated mesh', 'Computing', HInstance); end; function FindCuFile(var AModuleName: string): Boolean; var proj: IOTAProject; I: Integer; LModule: IOTAModuleInfo; LName: string; begin proj := GetActiveProject; if proj <> nil then begin for I := 0 to proj.GetModuleCount - 1 do begin LModule := proj.GetModule(I); LName := ExtractFileName(LModule.FileName); if LName = AModuleName then begin AModuleName := LModule.FileName; exit(True); end; end; end; Result := False; end; // ------------------ // ------------------ TGLSCUDAEditor ------------------ // ------------------ procedure TGLSCUDAEditor.Edit; begin with GLSCUDAEditorForm do begin SetCUDAEditorClient(TGLSCUDA(Self.Component), Self.Designer); Show; end; end; procedure TGLSCUDAEditor.ExecuteVerb(Index: Integer); begin case Index of 0: Edit; end; end; function TGLSCUDAEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Show CUDA Items Editor'; end; end; function TGLSCUDAEditor.GetVerbCount: Integer; begin Result := 1; end; // ------------------ // ------------------ TGLSCUDACompilerEditor ------------------ // ------------------ procedure TGLSCUDACompilerEditor.Edit; var CUDACompiler: TGLSCUDACompiler; I, J: Integer; func: TCUDAFunction; tex: TCUDATexture; cnst: TCUDAConstant; param: TCUDAFuncParam; parent: TCUDAModule; info: TCUDAModuleInfo; bUseless: Boolean; useless: array of TCUDAComponent; CTN: TChannelTypeAndNum; procedure CreateFuncParams; var K: Integer; begin for K := 0 to High(info.Func[I].Args) do begin param := TCUDAFuncParam(Designer.CreateComponent(TCUDAFuncParam, func, 0, 0, 0, 0)); param.Master := TCUDAComponent(func); param.KernelName := info.Func[I].Args[K].Name; param.Name := func.KernelName+'_'+param.KernelName; param.DataType := info.Func[I].Args[K].DataType; param.CustomType := info.Func[I].Args[K].CustomType; param.Reference := info.Func[I].Args[K].Ref; end; end; begin CUDACompiler := TGLSCUDACompiler(Self.Component); if CUDACompiler.Compile then begin info := CUDACompiler.ModuleInfo; parent := TCUDAModule(info.Owner); // Create kernel's functions for I := 0 to High(info.Func) do begin func := parent.KernelFunction[info.Func[I].KernelName]; if not Assigned(func) then begin func := TCUDAFunction(Designer.CreateComponent(TCUDAFunction, info.Owner, 0, 0, 0, 0)); func.Master := TCUDAComponent(info.Owner); func.KernelName := info.Func[I].KernelName; func.Name := TCUDAComponent(info.Owner).MakeUniqueName(info.Func[I].Name); end else begin // destroy old parameters while func.ItemsCount > 0 do func.Items[0].Destroy; end; try bUseless := func.Handle = nil; except bUseless := True; end; if bUseless then begin Designer.SelectComponent(func); Designer.DeleteSelection(True); func := nil; end else CreateFuncParams; end; // Create kernel's textures for I := 0 to High(info.TexRef) do begin tex := parent.KernelTexture[info.TexRef[I].Name]; if not Assigned(tex) then begin tex := TCUDATexture(Designer.CreateComponent(TCUDATexture, info.Owner, 0, 0, 0, 0)); tex.Master := TCUDAComponent(info.Owner); tex.KernelName := info.TexRef[I].Name; tex.Name := tex.KernelName; tex.ReadAsInteger := (info.TexRef[I].ReadMode = cudaReadModeElementType); CTN := GetChannelTypeAndNum(info.TexRef[I].DataType); tex.Format := CTN.F; end; tex.ChannelNum := CTN.C; try bUseless := tex.Handle = nil; except bUseless := True; end; if bUseless then begin Designer.SelectComponent(tex); Designer.DeleteSelection(True); end; end; // Create kernel's constants for I := 0 to High(info.Constant) do begin cnst := parent.KernelConstant[info.Constant[I].Name]; if not Assigned(cnst) then begin cnst := TCUDAConstant(Designer.CreateComponent(TCUDAConstant, info.Owner, 0, 0, 0, 0)); cnst.Master := TCUDAComponent(info.Owner); cnst.KernelName := info.Constant[I].Name; cnst.Name := cnst.KernelName; cnst.DataType := info.Constant[I].DataType; cnst.CustomType := info.Constant[I].CustomType; cnst.IsValueDefined := info.Constant[I].DefValue; end; try bUseless := cnst.DeviceAddress = nil; except bUseless := True; end; if bUseless then begin Designer.SelectComponent(cnst); Designer.DeleteSelection(True); end; end; // Delete useless components SetLength(useless, parent.ItemsCount); j := 0; for i := 0 to parent.ItemsCount - 1 do begin if not TCUDAComponent(parent.Items[i]).IsAllocated then begin useless[j] := parent.Items[i]; inc(j); end; end; for i := 0 to j - 1 do useless[i].Destroy; end; Designer.Modified; end; procedure TGLSCUDACompilerEditor.ExecuteVerb(Index: Integer); begin case Index of 0: Edit; end; end; function TGLSCUDACompilerEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Compile Module'; end; end; function TGLSCUDACompilerEditor.GetVerbCount: Integer; begin Result := 1; end; // ------------------ // ------------------ TGLSCUDACompilerSourceProperty ------------------ // ------------------ constructor TGLSCUDACompilerSourceProperty.Create( const ADesigner: IDesigner; APropCount: Integer); begin inherited; FModuleList := TStringList.Create; end; // Destroy // destructor TGLSCUDACompilerSourceProperty.Destroy; begin FModuleList.Destroy; inherited; end; // RefreshModuleList // procedure TGLSCUDACompilerSourceProperty.RefreshModuleList; var proj: IOTAProject; I: Integer; LModule: IOTAModuleInfo; LName: string; begin FModuleList.Clear; FModuleList.Add('none'); proj := GetActiveProject; if proj <> nil then begin for I := 0 to proj.GetModuleCount - 1 do begin LModule := proj.GetModule(I); LName := UpperCase(ExtractFileExt(LModule.FileName)); if LName = '.CU' then FModuleList.Add(LModule.FileName); end; end; end; // GetAttributes // function TGLSCUDACompilerSourceProperty.GetAttributes; begin Result := [paValueList]; end; // GetValues // procedure TGLSCUDACompilerSourceProperty.GetValues(Proc: TGetStrProc); var I : Integer; begin RefreshModuleList; for I := 0 to FModuleList.Count - 1 do Proc(ExtractFileName(FModuleList[I])); end; // SetValue // procedure TGLSCUDACompilerSourceProperty.SetValue(const Value: String); var I, J: Integer; begin RefreshModuleList; J := -1; for I := 1 to FModuleList.Count - 1 do if Value = ExtractFileName(FModuleList[I]) then begin J := I; Break; end; if J > 0 then begin TGLSCUDACompiler(GetComponent(0)).SetSourceCodeFile(FModuleList[J]); SetStrValue(ExtractFileName(Value)); end else begin SetStrValue('none'); end; Modified; end; // ------------------ // ------------------ TGLSCUDADeviceProperty ------------------ // ------------------ constructor TGLSCUDADeviceProperty.Create(const ADesigner: IDesigner; APropCount: Integer); begin inherited; FDeviceList := TStringList.Create; end; destructor TGLSCUDADeviceProperty.Destroy; begin FDeviceList.Destroy; inherited; end; function TGLSCUDADeviceProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TGLSCUDADeviceProperty.GetValues(Proc: TGetStrProc); begin CUDAContextManager.FillUnusedDeviceList(FDeviceList); end; procedure TGLSCUDADeviceProperty.SetValue(const Value: String); var I: Integer; begin for I := 0 to FDeviceList.Count - 1 do if Value = FDeviceList[I] then begin SetStrValue(Value); Break; end; Modified; end; initialization vFindCuFileFunc := FindCuFile; end.
procedure SetDCPixelFormat; var nPixelFormat : Integer; pfd : TPixelFormatDescriptor; begin FillChar(pfd, SizeOf (pfd), 0); with pfd do begin nSize := SizeOf (pfd); nVersion := 1; dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType:= PFD_TYPE_RGBA; cColorBits:= 16; cAccumBits:= 32; cDepthBits:= 32; cStencilBits := 8; iLayerType:= PFD_MAIN_PLANE; end; nPixelFormat := ChoosePixelFormat (DC, @pfd); SetPixelFormat (DC, nPixelFormat, @pfd); end;
{ MIT License Copyright (c) 2016-2020 Yevhen Loza 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. } program SnakeGame; {to hide DOS window in Windows use $AppType GUI compiler directive} //{$IFDEF windows}{$AppType GUI}{$ENDIF} {I highly recommend preforming range-checking during development} {$R+}{$Q+} uses SysUtils, Math, CastleWindow, CastleKeysMouse, CastleGLImages, CastleGLUtils, CastleVectors, CastleControls, CastleLog, SnakeUnit; { scale of the source sprites and their scaled version size at the screen } const SourceScale = 16; DestinationScale = SourceScale * 2; var { basic CastleWindow } Window: TCastleWindowBase; { All 16 sprites in one image } SnakeImage, SnakeFlipImage: TDrawableImage; {create some cheap animation effect} FlipImage: boolean; { this procedure is called each render } Procedure WindowRender(Container: TUIContainer); var i, ix, iy: Integer; CurrentSnakeImage: TDrawableImage; begin //draw grassland for ix := 0 to MaxX do for iy := 0 to MaxY do SnakeFlipImage.Draw(ix * DestinationScale, iy * DestinationScale, DestinationScale, DestinationScale, 3 * SourceScale, 0, SourceScale, SourceScale); {we use Draw(screenx, screeny, screenwidth, screenheight, sourcex, sourcey, soucrewidth, sourceheight) version of TDrawableImage.Draw procedure which allows working with spritesheets} //show game Score If not GameOver then begin if Score <= BestScore then UIFont.Print(0, 0, Vector4(0.4, 0.3, 0.1, 1), 'Score: ' + IntToStr(Score) + ' best: ' + IntToStr(BestScore)) else UIFont.Print(0, 0, Vector4(1, 0.8, 0, 1), 'Score: ' + IntToStr(Score) + '(best!)'); end; {We use UIFont defined in CastleControls unit as a "basic" font} {Show music CC-BY-SA credit :)} UIFont.Print(0, Window.Height - 18, Vector4(0, 0.6, 0.2, 1), LicenseString); //draw Rabbit SnakeImage.Draw(Rabbit.x * DestinationScale, Rabbit.y * DestinationScale, DestinationScale, DestinationScale, 2 * SourceScale, 0, SourceScale, SourceScale); //draw Snake {flipping image once per 300ms gives some cheap animation to the Snake.} if FlipImage then CurrentSnakeImage := SnakeImage else CurrentSnakeImage := SnakeFlipImage; for i := 0 to Snake.Tail.Count - 1 do with Snake.Tail[i] do case TailKind of tkHead : CurrentSnakeImage.Draw(x * DestinationScale, y * DestinationScale, DestinationScale, DestinationScale, Direction * SourceScale, 3 * SourceScale, SourceScale, SourceScale); tkTail : CurrentSnakeImage.Draw(x * DestinationScale, y * DestinationScale, DestinationScale, DestinationScale, Direction * SourceScale, 2 * SourceScale, SourceScale, SourceScale); tkTurn : CurrentSnakeImage.Draw(x * DestinationScale, y * DestinationScale, DestinationScale, DestinationScale, Direction * SourceScale, 1 * SourceScale, SourceScale, SourceScale); tkStraight: CurrentSnakeImage.Draw(x * DestinationScale, y * DestinationScale, DestinationScale, DestinationScale, Direction * SourceScale, 0, SourceScale, SourceScale); end; //give a endgame message if GameOver then begin if Score <= BestScore then begin UIFont.Print(Window.Width div 2 - 80, Window.Height div 2 + 15, Vector4(0.2, 0.1, 0, 1), 'GAME OVER!'); UIFont.Print(Window.Width div 2 - 80, Window.Height div 2 - 15, Vector4(0.2, 0.1, 0, 1), 'Your Score was: ' + IntToStr(Score)); end else begin UIFont.Print(Window.Width div 2 - 80, Window.Height div 2 + 15, Vector4(1, 1, 0, 1), 'GAME OVER!'); UIFont.Print(Window.Width div 2 - 80, Window.Height div 2 - 15, Vector4(1, 1, 0, 1), 'BEST Score: ' + IntToStr(Score)); end end; end; {this procedure is called very 300 miliseconds} procedure DoTimer; begin if not GameOver then begin Snake.Move; FlipImage := not FlipImage; end; end; {this procedure handles mouse and key presses} procedure KeyPress(Container: TUIContainer; const Event: TInputPressRelease); var dx, dy: Integer; begin if not GameOver then begin if Event.EventType = itKey then {this event is a keyboard event. Detect which button has been pressed} case Event.Key of keyUp: Snake.SetDirection(0, 1); keyDown: Snake.SetDirection(0, -1); keyLeft: Snake.SetDirection(-1, 0); keyRight: Snake.SetDirection(1, 0); keyM: ToggleMusic; end else if Event.EventType = itMouseButton then begin {this event is a mouse button or touch event. get click/touch coordinates. event.Position[0] is x and event.Position[1] is y} dx := Round(Event.Position[0] - (Snake.x + 0.5) * DestinationScale); dy := Round(Event.Position[1] - (Snake.y + 0.5) * DestinationScale); {and set the direction accordingly} if Abs(dx) > Abs(dy) then begin if not Snake.SetDirection(Sign(dx), 0) then Snake.SetDirection(0, Sign(dy)); end else begin if not Snake.SetDirection(0, Sign(dy)) then Snake.SetDirection(Sign(dx), 0); end; end; end else NewGame; end; begin {initialize log. Without parameters it goes directly into console on Linux or DOS window in Windows, see documentation for more details.} InitializeLog; {write something into Log} WriteLnLog('Hello','World!'); {create window} Window := TCastleWindowBase.Create(Application); {initialize random sequence} Randomize; {map size is 16x16} MaxX := 15; MaxY := 15; {set the appropriate window size} Window.Width := (MaxX + 1) * DestinationScale; Window.Height := (MaxY + 1) * DestinationScale; {load spritesheet / no nice scaling because it's pixelart :)} {ApplicationData points to content "data" in a cross-platform way, so that it is correct in Windows, Linux, Android and any other OS} SnakeImage := TDrawableImage.Create('castle-data:/Snake.png', false); SnakeFlipImage := TDrawableImage.Create('castle-data:/SnakeFlip.png', false); FlipImage := true; {create Snake} Snake := TSnake.Create(Application); {create Rabbit} Rabbit := TRabbit.Create(Application); {set up window events callbacks} Window.OnRender := @WindowRender; Window.OnPress := @KeyPress; Window.ResizeAllowed := raNotAllowed; {set up application timer} {this event will fire once every TimerMilisec (i.e. 300 msec) It's not very accurate but hardly accuracy is significant} Application.TimerMilisec := 300; Application.OnTimer := @DoTimer; {Read High Score from a file} ReadHighScore; {Load music and sound} LoadMusic; {start a new game} Score := 0; NewGame; {and finally open the window and start the game} Window.OpenAndRun; WriteHighScore; {don't forget to free everything that is not freed automatically} FreeAndNil(SnakeImage); FreeAndNil(SnakeFlipImage); end.
unit uRelatorioAlunoGeral; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, 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, RLReport, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TfrmRelatorioAlunoGeral = class(TForm) rpListagemAluno: TRLReport; rlbHeader: TRLBand; rllTitulo: TRLLabel; qrProfessor: TFDQuery; qrProfessorID: TIntegerField; qrProfessorNOME: TStringField; qrProfessorCPF: TStringField; qrDisciplina: TFDQuery; qrDisciplinaID: TIntegerField; qrDisciplinaDISCIPLINA: TStringField; qrAlunos: TFDQuery; qrAlunosID: TIntegerField; qrAlunosNOME: TStringField; qrAlunosCPF: TStringField; qrDados: TFDQuery; qrDadosID: TIntegerField; qrDadosDISCIPLINA_ID: TIntegerField; qrDadosALUNO_ID: TIntegerField; qrDadosPROFESSOR_ID: TIntegerField; qrDadosNOTA_PERIODO_1: TSingleField; qrDadosNOTA_PERIODO_2: TSingleField; qrDadosNOTA_TRABLHO: TSingleField; qrDadosMEDIA: TSingleField; qrDadosSITUACAO: TStringField; qrDadosALUNO: TStringField; qrDadosDISCIPLINA: TStringField; qrDadosPROFESSOR: TStringField; dsDados: TDataSource; dsAlunos: TDataSource; dsDisciplina: TDataSource; dsProfessor: TDataSource; rlbBtHeader: TRLBand; rllAluno: TRLLabel; rllDisciplina: TRLLabel; rllProfessor: TRLLabel; rllNota1: TRLLabel; rllNota2: TRLLabel; rllNotaTrabalho: TRLLabel; rllMedia: TRLLabel; rllSituacao: TRLLabel; rbBtDetalhes: TRLBand; rbtAluno: TRLDBText; rbtNota2: TRLDBText; rbtNota1: TRLDBText; rbtNotaTrabalho: TRLDBText; rbtMedia: TRLDBText; rbtSituacao: TRLDBText; rbtDisciplina: TRLDBText; rbtProfessor: TRLDBText; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rpListagemAlunoBeforePrint(Sender: TObject; var PrintIt: Boolean); private { Private declarations } public { Public declarations } end; var frmRelatorioAlunoGeral: TfrmRelatorioAlunoGeral; implementation {$R *.dfm} procedure TfrmRelatorioAlunoGeral.FormClose(Sender: TObject; var Action: TCloseAction); begin frmRelatorioAlunoGeral := nil; end; procedure TfrmRelatorioAlunoGeral.rpListagemAlunoBeforePrint(Sender: TObject; var PrintIt: Boolean); begin qrDados.Open; qrAlunos.Open; qrProfessor.Open; qrDisciplina.Open; end; end.