text
stringlengths
14
6.51M
unit MarkdownMathCode; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MarkdownUtils; function checkMathCode(out_: TStringBuilder; s: String; start: integer): integer; implementation function checkMathCode(out_: TStringBuilder; s: String; start: integer ): integer; var temp: TStringBuilder; position: integer; code: String; begin temp := TStringBuilder.Create(); try // Check for mathcode {a^2+b^2=c^2} and generate link temp.Clear; position := TUtils.readUntil(temp, s, start + 1, [' ', '$', #10]); if (position <> -1) and (s[1 + position] = '$') and (s[position] <> '\') then begin code:= temp.ToString(); out_.append('<img src="https://chart.googleapis.com/chart?cht=tx&chl='); TUtils.codeEncode(out_, code, 0); out_.append('" alt="'); TUtils.appendValue(out_, code, 0, Length(code)); out_.append(' "/>'); exit(position); end; result := -1; finally temp.Free; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, FMX.StdCtrls, FMX.Controls.Presentation, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope; type TForm1 = class(TForm) RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TRESTResponse; ToolBar1: TToolBar; Label1: TLabel; Button1: TButton; Switch1: TSwitch; RESTRequest2: TRESTRequest; RESTResponse2: TRESTResponse; procedure Button1Click(Sender: TObject); procedure Switch1Switch(Sender: TObject); private { Private declarations } FUserName: string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses System.JSON; procedure TForm1.Button1Click(Sender: TObject); var Value: TJSONValue; ErrNo: Integer; begin RESTRequest1.Execute; Value := RESTResponse1.JSONValue; if Value.TryGetValue<Integer>('[0].error.type', ErrNo) then begin if ErrNo = 101 then begin ShowMessage('중앙의 버튼을 눌러주세요.'); Exit; end; end; if Value.TryGetValue<string>('[0].success.username', FUsername) then begin ShowMessage('등록되었습니다.'); end; end; procedure TForm1.Switch1Switch(Sender: TObject); var onoff: string; begin if Switch1.IsChecked then onoff := '{"on":true}' else onoff := '{"on":false}'; RESTRequest2.Params.ParameterByName('body').Value := onoff; RESTRequest2.Params.ParameterByName('username').Value := FUsername; RESTRequest2.Execute; end; end.
{------------------------------------------------------------------------------- scrcpy light launcher by Alvaro 'krono' Gonzalez Ferrer https://alvarogonzalezferrer.github.io/ Copyright (c) 2021 In loving memory of my father. Released under the MIT license. -------------------------------------------------------------------------------- This app is a launcher for: Scrcpy: Display and control your Android device Source of scrcpy https://github.com/Genymobile/scrcpy This application provides display and control of Android devices connected on USB (or over TCP/IP). It does not require any root access. -------------------------------------------------------------------------------- To compile: Source code for Lazarus > https://www.lazarus-ide.org/ -------------------------------------------------------------------------------} unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, StdCtrls, Process, LCLType, ComCtrls, about_form, help_form; type { Tform_main } Tform_main = class(TForm) btn_launch: TButton; bitrate_label: TLabel; check_video_orientation: TCheckBox; check_max_size_vid: TCheckBox; check_max_fps_vid: TCheckBox; check_video_recording: TCheckBox; combo_video_orientation: TComboBox; combo_max_size_vid: TComboBox; combo_max_fps_vid: TComboBox; menu_help: TMenuItem; select_scrcpy_exe_dialog: TOpenDialog; record_filename_video: TEdit; groupVideo: TGroupBox; menu_main1: TMainMenu; menu_menu: TMenuItem; menu_config: TMenuItem; menu_about: TMenuItem; menu_exit: TMenuItem; bitrate_bar: TTrackBar; video_record_save_dialog: TSaveDialog; procedure bitrate_barChange(Sender: TObject); procedure btn_launchClick(Sender: TObject); procedure check_max_fps_vidChange(Sender: TObject); procedure check_max_size_vidChange(Sender: TObject); procedure check_video_orientationChange(Sender: TObject); procedure check_video_recordingChange(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure menu_aboutClick(Sender: TObject); procedure menu_configClick(Sender: TObject); procedure menu_exitClick(Sender: TObject); procedure menu_helpClick(Sender: TObject); procedure record_filename_videoClick(Sender: TObject); private public end; var form_main: Tform_main; // config path_to_scrcpy : AnsiString = 'scrcpy.exe'; implementation {$R *.lfm} { Tform_main } procedure Tform_main.btn_launchClick(Sender: TObject); var s : AnsiString; // string return p: array[1..10] of AnsiString; // parameters tmp : AnsiString; // save button caption i: Integer; // iterator begin // todo init parameters for i := 1 to 10 do p[i] := ''; if (bitrate_bar.Position > 0) then begin p[1] := '--bit-rate'; p[2] := IntToStr(bitrate_bar.Position) +'M'; end; if (check_max_size_vid.Checked) then begin p[3] := '--max-size'; p[4] := combo_max_size_vid.Text; end; if (check_max_fps_vid.Checked) then begin p[5] := '--max-fps'; p[6] := combo_max_fps_vid.Text; end; if (check_video_orientation.Checked) then begin p[7] := '--lock-video-orientation'; p[8] := IntToStr(combo_video_orientation.ItemIndex); end; if (check_video_recording.Checked) then begin p[9] := '--record'; p[10] := record_filename_video.Text; end; // message while we wait tmp := btn_launch.Caption; btn_launch.Caption := 'WAITING!'; // run the scrcpy show // for some reason the try except is NOT WORKING / DEBUG / FIX THIS / TODO try RunCommand(path_to_scrcpy, p, s) except on E: EProcess do Application.MessageBox('Failed to lanch. Configure path first!', 'Failure', MB_ICONERROR + MB_OK); end; // restore caption btn_launch.Caption := tmp; end; procedure Tform_main.check_max_fps_vidChange(Sender: TObject); begin // enable disable combo box combo_max_fps_vid.Enabled := check_max_fps_vid.Checked; end; procedure Tform_main.check_max_size_vidChange(Sender: TObject); begin // enable / disable combo box combo_max_size_vid.Enabled := check_max_size_vid.Checked; end; procedure Tform_main.check_video_orientationChange(Sender: TObject); begin // enable disable combo box combo_video_orientation.Enabled := check_video_orientation.Checked; end; procedure Tform_main.check_video_recordingChange(Sender: TObject); begin // enable / disable record_filename_video.Enabled := check_video_recording.Checked; // if enabled, then select file if record_filename_video.Enabled then record_filename_videoClick(Sender); // fake click end; procedure Tform_main.FormClose(Sender: TObject; var CloseAction: TCloseAction); var reply : Integer; begin // confirm close // debug annyoing? // end app reply := Application.MessageBox('Exit, are you sure?', 'Exit', MB_ICONQUESTION + MB_YESNO); if reply = IDNO then CloseAction := caNone; end; procedure Tform_main.bitrate_barChange(Sender: TObject); begin // video bitrate changed, in megabytes // DEBUG 0 deberia ser valor default TODO if bitrate_bar.Position > 0 then bitrate_label.Caption := 'Bitrate ' + IntToStr(bitrate_bar.Position) + ' Mbps' else bitrate_label.Caption := 'Bitrate default'; end; procedure Tform_main.FormCreate(Sender: TObject); begin // TODO debug should load config here end; procedure Tform_main.menu_aboutClick(Sender: TObject); begin aboutForm.ShowModal; // about me form end; procedure Tform_main.menu_configClick(Sender: TObject); begin // config if select_scrcpy_exe_dialog.Execute then path_to_scrcpy := select_scrcpy_exe_dialog.FileName; end; procedure Tform_main.menu_exitClick(Sender: TObject); var reply: Integer; begin // end app reply := Application.MessageBox('Exit, are you sure?', 'Exit', MB_ICONQUESTION + MB_YESNO); if reply = IDYES then Application.Terminate; end; procedure Tform_main.menu_helpClick(Sender: TObject); begin // show help helpForm.Show; end; procedure Tform_main.record_filename_videoClick(Sender: TObject); begin // open dialog for file select // https://wiki.freepascal.org/Howto_Use_TSaveDialog if video_record_save_dialog.Execute then record_filename_video.Text := video_record_save_dialog.FileName // take tne file the user selected else check_video_recording.Checked := False; // cancelled the file selection, uncheck this end; end.
unit rhlGrindahl512; interface uses rhlCore; type { TrhlGrindahl512 } TrhlGrindahl512 = class(TrhlHash) private const ROWS = 8; COLUMNS = 13; BLANK_ROUNDS = 8; SIZE = (ROWS * COLUMNS) div 8; s_master_table: array[0..255] of QWord = ( $c6636397633551a2,$f87c7ceb7ccd1326,$ee7777c777952952,$f67b7bf77bf50102, $fff2f2e5f2d11a34,$d66b6bb76b7561c2,$de6f6fa76f5579f2,$91c5c539c572a84b, $603030c0309ba05b,$020101040108060c,$ce67678767154992,$562b2bac2b43faef, $e7fefed5feb13264,$b5d7d771d7e2c493,$4dabab9aab2fd7b5,$ec7676c3769d2f5e, $8fcaca05ca0a8a0f,$1f82823e827c2142,$89c9c909c912801b,$fa7d7def7dc5152a, $effafac5fa912a54,$b259597f59fecd81,$8e474707470e8909,$fbf0f0edf0c1162c, $41adad82ad1fc39d,$b3d4d47dd4face87,$5fa2a2bea267e1d9,$45afaf8aaf0fcf85, $239c9c469c8c65ca,$53a4a4a6a457f5f1,$e47272d372bd376e,$9bc0c02dc05ab677, $75b7b7eab7cf9f25,$e1fdfdd9fda93870,$3d93937a93f4478e,$4c262698262bd4b3, $6c3636d836abb473,$7e3f3ffc3fe3821f,$f5f7f7f1f7f90408,$83cccc1dcc3a9e27, $683434d034bbb86b,$51a5a5a2a55ff3fd,$d1e5e5b9e56968d0,$f9f1f1e9f1c91020, $e27171df71a53d7a,$abd8d84dd89ae6d7,$623131c43193a657,$2a15155415a87efc, $0804041004201830,$95c7c731c762a453,$4623238c2303ca8f,$9dc3c321c342bc63, $3018186018c050a0,$3796966e96dc59b2,$0a05051405281e3c,$2f9a9a5e9abc71e2, $0e07071c07381224,$2412124812906cd8,$1b808036806c2d5a,$dfe2e2a5e2517af4, $cdebeb81eb194c98,$4e27279c2723d2bf,$7fb2b2feb2e78119,$ea7575cf7585254a, $120909240948366c,$1d83833a8374274e,$582c2cb02c7be8cb,$341a1a681ad05cb8, $361b1b6c1bd85ab4,$dc6e6ea36e5d7ffe,$b45a5a735ae6c795,$5ba0a0b6a077edc1, $a452525352a6f7f5,$763b3bec3bc39a2f,$b7d6d675d6eac29f,$7db3b3fab3ef8715, $522929a42953f6f7,$dde3e3a1e3597cf8,$5e2f2fbc2f63e2df,$13848426844c356a, $a653535753aef1f9,$b9d1d169d1d2d0bb,$0000000000000000,$c1eded99ed2958b0, $40202080201bc09b,$e3fcfcddfca13e7c,$79b1b1f2b1ff8b0d,$b65b5b775beec199, $d46a6ab36a7d67ce,$8dcbcb01cb028c03,$67bebecebe87a949,$723939e439d39637, $944a4a334a66a755,$984c4c2b4c56b37d,$b058587b58f6cb8d,$85cfcf11cf229433, $bbd0d06dd0dad6b7,$c5efef91ef3954a8,$4faaaa9eaa27d1b9,$edfbfbc1fb992c58, $86434317432e9139,$9a4d4d2f4d5eb571,$663333cc3383aa4f,$1185852285443366, $8a45450f451e8511,$e9f9f9c9f9892040,$0402020802100c18,$fe7f7fe77fd51932, $a050505b50b6fbed,$783c3cf03cfb880b,$259f9f4a9f946fde,$4ba8a896a837dda1, $a251515f51befde1,$5da3a3baa36fe7d5,$8040401b40369b2d,$058f8f0a8f140f1e, $3f92927e92fc4182,$219d9d429d8463c6,$703838e038db903b,$f1f5f5f9f5e90810, $63bcbcc6bc97a551,$77b6b6eeb6c79929,$afdada45da8aeacf,$422121842113c697, $20101040108060c0,$e5ffffd1ffb93468,$fdf3f3e1f3d91c38,$bfd2d265d2cadaaf, $81cdcd19cd32982b,$180c0c300c602850,$2613134c13986ad4,$c3ecec9dec215ebc, $be5f5f675fced9a9,$3597976a97d45fbe,$8844440b4416831d,$2e17175c17b872e4, $93c4c43dc47aae47,$55a7a7aaa74fffe5,$fc7e7ee37edd1f3e,$7a3d3df43df38e07, $c864648b640d4386,$ba5d5d6f5dded5b1,$3219196419c856ac,$e67373d773b53162, $c060609b602d5bb6,$1981813281642b56,$9e4f4f274f4eb969,$a3dcdc5ddcbafee7, $44222288220bcc83,$542a2aa82a4bfce3,$3b90907690ec4d9a,$0b888816882c1d3a, $8c46460346068f05,$c7eeee95ee3152a4,$6bb8b8d6b8b7bd61,$2814145014a078f0, $a7dede55deaaf2ff,$bc5e5e635ec6dfa5,$160b0b2c0b583a74,$addbdb41db82ecc3, $dbe0e0ade04176ec,$643232c8328bac43,$743a3ae83acb9c23,$140a0a280a503c78, $9249493f497ead41,$0c06061806301428,$48242490243bd8ab,$b85c5c6b5cd6d3bd, $9fc2c225c24aba6f,$bdd3d361d3c2dca3,$43acac86ac17c591,$c4626293623d57ae, $3991917291e44b96,$3195956295c453a6,$d3e4e4bde4616edc,$f27979ff79e50d1a, $d5e7e7b1e77964c8,$8bc8c80dc81a8617,$6e3737dc37a3b27f,$da6d6daf6d4575ea, $018d8d028d040306,$b1d5d579d5f2c88b,$9c4e4e234e46bf65,$49a9a992a93fdbad, $d86c6cab6c4d73e6,$ac5656435686efc5,$f3f4f4fdf4e10e1c,$cfeaea85ea114a94, $ca65658f6505458a,$f47a7af37afd070e,$47aeae8eae07c989,$1008082008403060, $6fbabadebaa7b179,$f07878fb78ed0b16,$4a2525942533dea7,$5c2e2eb82e6be4d3, $381c1c701ce04890,$57a6a6aea647f9e9,$73b4b4e6b4d79531,$97c6c635c66aa25f, $cbe8e88de801468c,$a1dddd59ddb2f8eb,$e87474cb748d2346,$3e1f1f7c1ff84284, $964b4b374b6ea159,$61bdbdc2bd9fa35d,$0d8b8b1a8b34172e,$0f8a8a1e8a3c1122, $e07070db70ad3b76,$7c3e3ef83eeb8413,$71b5b5e2b5df933d,$cc666683661d4f9e, $9048483b4876ab4d,$0603030c03180a14,$f7f6f6f5f6f10204,$1c0e0e380e702448, $c261619f61255dba,$6a3535d435b3be67,$ae575747578ee9c9,$69b9b9d2b9bfbb6d, $1786862e865c3972,$99c1c129c152b07b,$3a1d1d741de84e9c,$279e9e4e9e9c69d2, $d9e1e1a9e14970e0,$ebf8f8cdf881264c,$2b98985698ac7dfa,$22111144118866cc, $d26969bf69656dda,$a9d9d949d992e0db,$078e8e0e8e1c0912,$3394946694cc55aa, $2d9b9b5a9bb477ee,$3c1e1e781ef04488,$1587872a87543f7e,$c9e9e989e9094080, $87cece15ce2a923f,$aa55554f559ee5d1,$502828a0285bf0fb,$a5dfdf51dfa2f4f3, $038c8c068c0c050a,$59a1a1b2a17febcd,$0989891289241b36,$1a0d0d340d682e5c, $65bfbfcabf8faf45,$d7e6e6b5e67162c4,$8442421342269735,$d06868bb686d6bd6, $8241411f413e9d21,$2999995299a47bf6,$5a2d2db42d73eec7,$1e0f0f3c0f782244, $7bb0b0f6b0f78d01,$a854544b5496e3dd,$6dbbbbdabbafb775,$2c16165816b074e8 ); var s_table_0, s_table_1, s_table_2, s_table_3, s_table_4, s_table_5, s_table_6, s_table_7: array[0..255] of QWord; m_state: array[0..SIZE - 1] of QWord; m_temp: array[0..SIZE - 1] of QWord; procedure InjectMsg(a_full_process: Boolean); protected procedure UpdateBlock(const AData); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlGrindahl512 } procedure TrhlGrindahl512.InjectMsg(a_full_process: Boolean); var u: array[0..SIZE - 1] of QWord; begin m_state[SIZE - 1] := m_state[SIZE - 1] xor $01; if (a_full_process) then begin m_temp[0] := s_table_0[Byte(m_state[12] shr 56)] xor s_table_1[Byte(m_state[11] shr 48)] xor s_table_2[Byte(m_state[10] shr 40)] xor s_table_3[Byte(m_state[9] shr 32)] xor s_table_4[Byte(m_state[8] shr 24)] xor s_table_5[Byte(m_state[7] shr 16)] xor s_table_6[Byte(m_state[6] shr 8)] xor s_table_7[Byte(m_state[5])]; end; m_temp[1] := s_table_0[Byte(m_state[0] shr 56)] xor s_table_1[Byte(m_state[12] shr 48)] xor s_table_2[Byte(m_state[11] shr 40)] xor s_table_3[Byte(m_state[10] shr 32)] xor s_table_4[Byte(m_state[9] shr 24)] xor s_table_5[Byte(m_state[8] shr 16)] xor s_table_6[Byte(m_state[7] shr 8)] xor s_table_7[Byte(m_state[6])]; m_temp[2] := s_table_0[Byte(m_state[1] shr 56)] xor s_table_1[Byte(m_state[0] shr 48)] xor s_table_2[Byte(m_state[12] shr 40)] xor s_table_3[Byte(m_state[11] shr 32)] xor s_table_4[Byte(m_state[10] shr 24)] xor s_table_5[Byte(m_state[9] shr 16)] xor s_table_6[Byte(m_state[8] shr 8)] xor s_table_7[Byte(m_state[7])]; m_temp[3] := s_table_0[Byte(m_state[2] shr 56)] xor s_table_1[Byte(m_state[1] shr 48)] xor s_table_2[Byte(m_state[0] shr 40)] xor s_table_3[Byte(m_state[12] shr 32)] xor s_table_4[Byte(m_state[11] shr 24)] xor s_table_5[Byte(m_state[10] shr 16)] xor s_table_6[Byte(m_state[9] shr 8)] xor s_table_7[Byte(m_state[8])]; m_temp[4] := s_table_0[Byte(m_state[3] shr 56)] xor s_table_1[Byte(m_state[2] shr 48)] xor s_table_2[Byte(m_state[1] shr 40)] xor s_table_3[Byte(m_state[0] shr 32)] xor s_table_4[Byte(m_state[12] shr 24)] xor s_table_5[Byte(m_state[11] shr 16)] xor s_table_6[Byte(m_state[10] shr 8)] xor s_table_7[Byte(m_state[9])]; m_temp[5] := s_table_0[Byte(m_state[4] shr 56)] xor s_table_1[Byte(m_state[3] shr 48)] xor s_table_2[Byte(m_state[2] shr 40)] xor s_table_3[Byte(m_state[1] shr 32)] xor s_table_4[Byte(m_state[0] shr 24)] xor s_table_5[Byte(m_state[12] shr 16)] xor s_table_6[Byte(m_state[11] shr 8)] xor s_table_7[Byte(m_state[10])]; m_temp[6] := s_table_0[Byte(m_state[5] shr 56)] xor s_table_1[Byte(m_state[4] shr 48)] xor s_table_2[Byte(m_state[3] shr 40)] xor s_table_3[Byte(m_state[2] shr 32)] xor s_table_4[Byte(m_state[1] shr 24)] xor s_table_5[Byte(m_state[0] shr 16)] xor s_table_6[Byte(m_state[12] shr 8)] xor s_table_7[Byte(m_state[11])]; m_temp[7] := s_table_0[Byte(m_state[6] shr 56)] xor s_table_1[Byte(m_state[5] shr 48)] xor s_table_2[Byte(m_state[4] shr 40)] xor s_table_3[Byte(m_state[3] shr 32)] xor s_table_4[Byte(m_state[2] shr 24)] xor s_table_5[Byte(m_state[1] shr 16)] xor s_table_6[Byte(m_state[0] shr 8)] xor s_table_7[Byte(m_state[12])]; m_temp[8] := s_table_0[Byte(m_state[7] shr 56)] xor s_table_1[Byte(m_state[6] shr 48)] xor s_table_2[Byte(m_state[5] shr 40)] xor s_table_3[Byte(m_state[4] shr 32)] xor s_table_4[Byte(m_state[3] shr 24)] xor s_table_5[Byte(m_state[2] shr 16)] xor s_table_6[Byte(m_state[1] shr 8)] xor s_table_7[Byte(m_state[0])]; m_temp[9] := s_table_0[Byte(m_state[8] shr 56)] xor s_table_1[Byte(m_state[7] shr 48)] xor s_table_2[Byte(m_state[6] shr 40)] xor s_table_3[Byte(m_state[5] shr 32)] xor s_table_4[Byte(m_state[4] shr 24)] xor s_table_5[Byte(m_state[3] shr 16)] xor s_table_6[Byte(m_state[2] shr 8)] xor s_table_7[Byte(m_state[1])]; m_temp[10] := s_table_0[Byte(m_state[9] shr 56)] xor s_table_1[Byte(m_state[8] shr 48)] xor s_table_2[Byte(m_state[7] shr 40)] xor s_table_3[Byte(m_state[6] shr 32)] xor s_table_4[Byte(m_state[5] shr 24)] xor s_table_5[Byte(m_state[4] shr 16)] xor s_table_6[Byte(m_state[3] shr 8)] xor s_table_7[Byte(m_state[2])]; m_temp[11] := s_table_0[Byte(m_state[10] shr 56)] xor s_table_1[Byte(m_state[9] shr 48)] xor s_table_2[Byte(m_state[8] shr 40)] xor s_table_3[Byte(m_state[7] shr 32)] xor s_table_4[Byte(m_state[6] shr 24)] xor s_table_5[Byte(m_state[5] shr 16)] xor s_table_6[Byte(m_state[4] shr 8)] xor s_table_7[Byte(m_state[3])]; m_temp[12] := s_table_0[Byte(m_state[11] shr 56)] xor s_table_1[Byte(m_state[10] shr 48)] xor s_table_2[Byte(m_state[9] shr 40)] xor s_table_3[Byte(m_state[8] shr 32)] xor s_table_4[Byte(m_state[7] shr 24)] xor s_table_5[Byte(m_state[6] shr 16)] xor s_table_6[Byte(m_state[5] shr 8)] xor s_table_7[Byte(m_state[4])]; Move(m_temp, u, SizeOf(m_temp)); Move(m_state, m_temp, SizeOf(m_state)); Move(u, m_state, SizeOf(u)); end; procedure TrhlGrindahl512.UpdateBlock(const AData); var x: QWord absolute AData; begin m_state[0] := SwapEndian(x); InjectMsg(false); end; constructor TrhlGrindahl512.Create; procedure CalcTable(i: Integer; var tab); var atab: array[0..0] of QWord absolute tab; j: Integer; begin for j := 0 to 255 do atab[j] := RorQWord(s_master_table[j], i*8); end; begin HashSize := 64; BlockSize := 8; Move(s_master_table, s_table_0, SizeOf(s_master_table)); CalcTable(1, s_table_1); CalcTable(2, s_table_2); CalcTable(3, s_table_3); CalcTable(4, s_table_4); CalcTable(5, s_table_5); CalcTable(6, s_table_6); CalcTable(7, s_table_7); end; procedure TrhlGrindahl512.Init; begin inherited Init; FillChar(m_state, SizeOf(m_state), 0); FillChar(m_temp, SizeOf(m_temp), 0); end; procedure TrhlGrindahl512.Final(var ADigest); var padding_size: DWord; msg_length: QWord; pad: TBytes; i: Integer; begin padding_size := 2 * BlockSize - (FProcessedBytes mod BlockSize); msg_length := (FProcessedBytes div ROWS) + 1; SetLength(pad, padding_size); pad[0] := $80; msg_length := SwapEndian(msg_length); Move(msg_length, pad[padding_size-8], SizeOf(msg_length)); UpdateBytes(pad[0], padding_size - BlockSize); Move(pad[padding_size - BlockSize], m_state[0], 8); m_state[0] := SwapEndian(m_state[0]); for i := 0 to BLANK_ROUNDS do InjectMsg(true); i := HashSize div ROWS; ConvertQWordsToBytesSwapOrder(m_state[COLUMNS - i], i, ADigest); end; end.
unit FC.Trade.Trader.Message; interface uses Classes, BaseUtils, SysUtils, FC.Definitions; type TStockTraderMessage = class (TInterfacedObject,IStockTraderMessage) private FDateTime: TDateTime; FText : string; FID : TGUID; public function GetDateTime: TDateTime; function GetID: TGUID; function GetText: string; constructor Create(const aDateTime: TDateTime; const aText:string); end; { TStockTraderMessageCollection } //Self Destruct | Not Self Destruct TStockTraderMessageCollection = class (TInterfaceProvider,IStockTraderMessageCollection) private FList: TInterfaceList; public // ISCTraderMessageCollection function GetItem(Index: Integer): IStockTraderMessage; function IndexOf(aTraderMessage: IStockTraderMessage): integer; overload; function IndexOf(const aDateTime: TDateTime): integer; overload; function IndexOf(aID: TGUID): integer; overload; procedure Delete(index: integer); virtual; function Remove(aTraderMessage:IStockTraderMessage): integer; procedure Clear; virtual; function Add(const aTraderMessage: IStockTraderMessage): integer; virtual; function Count: integer; property Items[Index: Integer]: IStockTraderMessage read GetItem; default; constructor Create(aSelfDestruct: boolean=true); destructor Destroy; override; end; implementation { TStockTraderMessageCollection } function TStockTraderMessageCollection.Add(const aTraderMessage: IStockTraderMessage): integer; begin result:=FList.Add(aTraderMessage); end; function TStockTraderMessageCollection.Count: integer; begin result:=FList.Count; end; function TStockTraderMessageCollection.GetItem(Index: Integer): IStockTraderMessage; begin result:=FList[index] as IStockTraderMessage; end; procedure TStockTraderMessageCollection.Delete(index: integer); begin FList.Delete(index); end; procedure TStockTraderMessageCollection.Clear; begin FList.Clear; end; constructor TStockTraderMessageCollection.Create(aSelfDestruct: boolean); begin inherited CReate; FSelfDestruct:=aSelfDestruct; FList:=TInterfaceList.Create; end; destructor TStockTraderMessageCollection.Destroy; begin FreeAndNil(FList); inherited; end; function TStockTraderMessageCollection.IndexOf(aTraderMessage: IStockTraderMessage): integer; var i: integer; begin result:=-1; for i:=0 to Count-1 do if IsEqualGUID(GetItem(i).GetID,aTraderMessage.GetID) then begin result:=i; break; end; end; function TStockTraderMessageCollection.Remove(aTraderMessage: IStockTraderMessage): integer; begin result:=IndexOf(aTraderMessage); if result<>-1 then Delete(result); end; function TStockTraderMessageCollection.IndexOf(const aDateTime: TDateTime): integer; var i: integer; begin result:=-1; for i:=0 to Count-1 do if (GetItem(i).GetDateTime=aDateTime) then begin result:=i; break; end; end; function TStockTraderMessageCollection.IndexOf(aID: TGUID): integer; var i: integer; begin result:=-1; for i:=0 to Count-1 do if IsEqualGUID(GetItem(i).GetID,aID) then begin result:=i; break; end; end; { TStockTraderMessage } constructor TStockTraderMessage.Create(const aDateTime: TDateTime; const aText: string); begin inherited Create; FDateTime:=aDateTime; FText:=aText; CreateGUID(FID); end; function TStockTraderMessage.GetID: TGUID; begin result:=FID; end; function TStockTraderMessage.GetDateTime: TDateTime; begin result:=FDateTime; end; function TStockTraderMessage.GetText: string; begin result:=FText; end; end.
unit UnitHydras; interface uses Classes, SysUtils, Forms, strUtils, DBTables; type THydras=class private procedure LogLine(Indent: Integer; AMessage: string); public function getAllStations(domaine: string; StationsList: TStrings): boolean; function getAllSensors(domaine: string; SensorList: TStrings): boolean; function getAllStationsForAutomatic(domaine: string; StationsList: TStrings): boolean; function getAllJobs(StationsList: TStrings): boolean; end; implementation uses UnitConfiguration, UnitExport, UnitDataModuleDatas, UnitVariables; procedure THydras.LogLine(Indent: Integer; AMessage: string); Begin export.LogLine(Indent, AMessage) End; function THydras.getAllStations(domaine: string; StationsList: TStrings): boolean; Var fichier : string; localTableRoot : TTable; Begin Result := False; localTableRoot := TTable.Create(nil); Try LogLine(0, 'Lecture des stations pour : ' + domaine); fichier := includeTrailingPathDelimiter(domaine) + _HYDRAS_TABLE_STATIONS; If DataModuleDatas.ouvreTable(fichier, localTableRoot) Then Begin localTableRoot.first; while Not localTableRoot.Eof Do Begin StationsList.Values[CleanName(localTableRoot.FieldByName('NR').AsString)] := CleanName(localTableRoot.FieldByName('NAME').AsString); localTableRoot.next; End; End Else LogLine(1, _POSTGRES_DATABASE_NOT_CONNECTED); Finally localTableRoot.Free; End; Result := True; End; function THydras.getAllSensors(domaine: string; SensorList: TStrings): boolean; Var fichier, ligne, unite : string; localTableRoot, localTableStations, localTableCapteurs : TTable; Begin Result := False; LogLine(0, 'Lecture des capteurs pour : ' + domaine); localTableRoot := TTable.Create(nil); localTableStations := TTable.Create(nil); localTableCapteurs := TTable.Create(nil); Try fichier := includeTrailingPathDelimiter(domaine) + _HYDRAS_TABLE_ROOT; If DataModuleDatas.ouvreTable(fichier, localTableRoot) Then Begin localTableRoot.first; while Not localTableRoot.Eof Do Begin If Not localTableRoot.Fields[2].IsNull Then Begin fichier := includeTrailingPathDelimiter(domaine) + localTableRoot.FieldValues['GB_MDATEI'] + '.DB'; DataModuleDatas.ouvreTable(fichier, localTableStations); While Not localTableStations.Eof Do Begin fichier := localTableStations.FieldByName('GBM_MSNR').AsString; insert('.', fichier, 9); Ligne := fichier; fichier := includeTrailingPathDelimiter(domaine) + includeTrailingPathDelimiter(fichier) + _HYDRAS_TABLE_SENSOR; If DataModuleDatas.ouvreTable(fichier, localTableCapteurs) Then Begin While Not localTableCapteurs.Eof Do Begin //SensorList.add(format('%s/%s : %s', [localTableStations.FieldByName('GBM_MSNR').AsString, localTableCapteurs.FieldByName('NR').AsString, localTableCapteurs.FieldByName('NAME').AsString])); unite := trim(copy(localTableCapteurs.FieldByName('SS_1').AsString, 0, 6)); SensorList.Values[localTableCapteurs.FieldByName('NR').AsString] := localTableCapteurs.FieldByName('NAME').AsString + '|' + unite; localTableCapteurs.next; End; localTableStations.next; End else exit; End; End; localTableRoot.next; End; End Else LogLine(1, _POSTGRES_DATABASE_NOT_CONNECTED); Finally localTableRoot.Free; localTableStations.Free; localTableCapteurs.Free; End; Result := True; End; function THydras.getAllStationsForAutomatic(domaine: string; StationsList: TStrings): boolean; Var fichier, ligne : string; localTableRoot, localTableStations, localTableCapteurs : TTable; Begin Result := False; LogLine(0, format('Lecture des stations pour : %s pour la configuration automatique', [domaine])); localTableRoot := TTable.Create(nil); localTableStations := TTable.Create(nil); localTableCapteurs := TTable.Create(nil); Try Fichier := includeTrailingPathDelimiter(domaine) + 'GB_DATEI.DB'; If DataModuleDatas.ouvreTable(fichier, localTableRoot) Then Begin while Not localTableRoot.Eof Do Begin If Not localTableRoot.Fields[2].IsNull Then Begin fichier := includeTrailingPathDelimiter(domaine) + localTableRoot.FieldValues['GB_MDATEI'] + '.DB'; DataModuleDatas.ouvreTable(fichier, localTableStations); While Not localTableStations.Eof Do Begin fichier := localTableStations.FieldByName('GBM_MSNR').AsString; insert('.', fichier, 9); Ligne := fichier; fichier := includeTrailingPathDelimiter(domaine) + includeTrailingPathDelimiter(fichier) + 'SS_DATEI.DB'; If DataModuleDatas.ouvreTable(fichier, localTableCapteurs) Then Begin While Not localTableCapteurs.Eof Do Begin StationsList.add(format('%s/%s : %s', [localTableStations.FieldByName('GBM_MSNR').AsString, localTableCapteurs.FieldByName('NR').AsString, localTableCapteurs.FieldByName('NAME').AsString])); localTableCapteurs.next; End; localTableStations.next; End else exit; End; End; localTableRoot.next; End; End Else LogLine(1, '_DATABASENOTCONNECTED'); Result := True; Finally localTableRoot.Free; localTableStations.Free; localTableCapteurs.Free; End; End; function THydras.getAllJobs(StationsList: TStrings): boolean; Var fichier : string; localTableRoot : TTable; Begin Result := False; localTableRoot := TTable.Create(nil); Try LogLine(0, 'Lecture des jobs pour : '); If DataModuleDatas.ouvreTable(PATH_APPDATAS_HYDRAS + 'EXP_JOBS.DB', localTableRoot) Then Begin localTableRoot.first; while Not localTableRoot.Eof Do Begin StationsList.Add(localTableRoot.FieldByName('JOBNAME').AsString); localTableRoot.next; End; End Else LogLine(1, 'Table Non Trouv'); Finally localTableRoot.Free; End; Result := True; End; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.FilterCatGeometry; interface {$I FMX.Defines.inc} uses FMX.Filter; type TAffineMatrix = packed record m11, m12, m31: Single; m21, m22, m32: Single; m13, m23, m33: Single; end; TAffineFilter = class(TShaderFilter) protected FMatrix, FInvMatrix: TAffineMatrix; procedure CalcMatrix(W, H: Integer); virtual; procedure LoadShader; override; procedure CalcSize(var W, H: Integer); override; public constructor Create; override; class function FilterAttr: TFilterRec; override; end; TPerspectiveFilter = class(TShaderFilter) protected FMatrix, FInvMatrix: TAffineMatrix; procedure LoadShader; override; procedure CalcSize(var W, H: Integer); override; procedure CalcMatrix(W, H: Integer); virtual; public class function FilterAttr: TFilterRec; override; constructor Create; override; end; TCropFilter = class(TShaderFilter) protected procedure CalcSize(var W, H: Integer); override; public class function FilterAttr: TFilterRec; override; constructor Create; override; end; implementation uses System.Types, FMX.Types3D{$IFDEF FPC}, FMX.Types{$ENDIF}; { TAffineFilter } const Epsilon: Single = 1e-40; cPIdiv180: Single = 0.017453292; IdentityMatrix: TAffineMatrix = (m11:1.0; m12:0.0; m31:0.0; m21:0.0; m22:1.0; m32:0.0; m13:0.0; m23:0.0; m33:1.0); function fxMatrixMultiply(const M1, M2: TAffineMatrix): TAffineMatrix; begin Result.m11 := M1.m11 * M2.m11 + M1.m12 * M2.m21 + M1.m13 * M2.m31; Result.m12 := M1.m11 * M2.m12 + M1.m12 * M2.m22 + M1.m13 * M2.m32; Result.m13 := M1.m11 * M2.m13 + M1.m12 * M2.m23 + M1.m13 * M2.m33; Result.m21 := M1.m21 * M2.m11 + M1.m22 * M2.m21 + M1.m23 * M2.m31; Result.m22 := M1.m21 * M2.m12 + M1.m22 * M2.m22 + M1.m23 * M2.m32; Result.m23 := M1.m21 * M2.m13 + M1.m22 * M2.m23 + M1.m23 * M2.m33; Result.m31 := M1.m31 * M2.m11 + M1.m32 * M2.m21 + M1.m33 * M2.m31; Result.m32 := M1.m31 * M2.m12 + M1.m32 * M2.m22 + M1.m33 * M2.m32; Result.m33 := M1.m31 * M2.m13 + M1.m32 * M2.m23 + M1.m33 * M2.m33; end; function fxCreateRotationMatrix(angle: Single): TAffineMatrix; var cosine, sine: Single; begin sine := sin(angle); cosine := cos(angle); Result := IdentityMatrix; Result.m11 := cosine; Result.m12 := sine; Result.m21 := -sine; Result.m22 := cosine; end; function vgPointTransform(const V: TPointF; const M: TAffineMatrix): TPointF; var z: Single; begin Result.X := V.X * M.m11 + V.Y * M.m21 + M.m31; Result.Y := V.X * M.m12 + V.Y * M.m22 + M.m32; z := M.m13 * V.x + M.m23 * V.y + 1; if z = 0 then Exit; if z = 1 then begin Result.X := V.X * M.m11 + V.Y * M.m21 + M.m31; Result.Y := V.X * M.m12 + V.Y * M.m22 + M.m32; end else begin z := 1 / z; Result.X := (V.X * M.m11 + V.Y * M.m21 + M.m31) * z; Result.Y := (V.X * M.m12 + V.Y * M.m22 + M.m32) * z; end; end; function fxShaderMatrixDeterminant(const M: TAffineMatrix): Single; begin Result := M.m11 * (M.m22 * M.m33 - M.m32 * M.m23) - M.m12 * (M.m21 * M.m33 - M.m31 * M.m23) + M.m13 * (M.m21 * M.m32 - M.m31 * M.m22); end; procedure fxAdjointMatrix(var M: TAffineMatrix); var a1, a2, a3, b1, b2, b3, c1, c2, c3: Single; begin a1:= M.m11; a2:= M.m12; a3 := M.m13; b1:= M.m21; b2:= M.m22; b3 := M.m23; c1:= M.m31; c2:= M.m32; c3 := M.m33; M.m11 := (b2*c3-c2*b3); M.m21 :=-(b1*c3-c1*b3); M.m31 := (b1*c2-c1*b2); M.m12 :=-(a2*c3-c2*a3); M.m22 := (a1*c3-c1*a3); M.m32 :=-(a1*c2-c1*a2); M.m13 := (a2*b3-b2*a3); M.m23 :=-(a1*b3-b1*a3); M.m33 := (a1*b2-b1*a2); end; procedure fxScaleMatrix(var M: TAffineMatrix; const factor: Single); begin M.m11 := M.m11 * Factor; M.m12 := M.m12 * Factor; M.m21 := M.m21 * Factor; M.m22 := M.m22 * Factor; M.m31 := M.m31 * Factor; M.m32 := M.m32 * Factor; M.m13 := M.m13 * Factor; M.m23 := M.m23 * Factor; M.m33 := M.m33 * Factor; end; procedure fxInvertMatrix(var M: TAffineMatrix); var det : Single; begin det := fxShaderMatrixDeterminant(M); if Abs(Det) < EPSILON then M := IdentityMatrix else begin fxAdjointMatrix(M); fxScaleMatrix(M, 1/det); end; end; constructor TAffineFilter.Create; const DX9PS2BIN: array [0..571] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $32, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $9F, $00, $00, $00, $00, $02, $FF, $FF, $03, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $98, $00, $00, $00, $58, $00, $00, $00, $02, $00, $02, $00, $01, $00, $0A, $00, $60, $00, $00, $00, $00, $00, $00, $00, $70, $00, $00, $00, $02, $00, $03, $00, $01, $00, $0E, $00, $60, $00, $00, $00, $00, $00, $00, $00, $78, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $88, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $72, $69, $78, $31, $00, $01, $00, $03, $00, $01, $00, $03, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $72, $69, $78, $32, $00, $69, $6D, $70, $6C, $69, $63, $69, $74, $49, $6E, $70, $75, $74, $00, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $00, $00, $0F, $A0, $00, $00, $80, $3F, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $05, $00, $00, $03, $00, $00, $08, $80, $00, $00, $55, $B0, $02, $00, $55, $A0, $04, $00, $00, $04, $00, $00, $01, $80, $00, $00, $00, $B0, $02, $00, $00, $A0, $00, $00, $FF, $80, $02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $02, $00, $AA, $A0, $02, $00, $00, $03, $00, $00, $04, $80, $00, $00, $00, $81, $00, $00, $00, $A0, $58, $00, $00, $04, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $00, $A0, $00, $00, $55, $A0, $58, $00, $00, $04, $00, $00, $08, $80, $00, $00, $00, $80, $00, $00, $00, $A0, $00, $00, $55, $A0, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $FF, $80, $05, $00, $00, $03, $00, $00, $08, $80, $00, $00, $55, $B0, $03, $00, $55, $A0, $04, $00, $00, $04, $00, $00, $08, $80, $00, $00, $00, $B0, $03, $00, $00, $A0, $00, $00, $FF, $80, $02, $00, $00, $03, $00, $00, $02, $80, $00, $00, $FF, $80, $03, $00, $AA, $A0, $58, $00, $00, $04, $00, $00, $08, $80, $00, $00, $55, $80, $00, $00, $00, $A0, $00, $00, $55, $A0, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $FF, $80, $02, $00, $00, $03, $00, $00, $08, $80, $00, $00, $55, $81, $00, $00, $00, $A0, $42, $00, $00, $03, $01, $00, $0F, $80, $00, $00, $E4, $80, $00, $08, $E4, $A0, $58, $00, $00, $04, $00, $00, $01, $80, $00, $00, $FF, $80, $00, $00, $00, $A0, $00, $00, $55, $A0, $05, $00, $00, $03, $00, $00, $01, $80, $00, $00, $AA, $80, $00, $00, $00, $80, $58, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $00, $81, $00, $00, $55, $A0, $01, $00, $E4, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'PARAM c[5] = { program.local[0..3],'#13+ ' { 1, 0 } };'#13+ 'TEMP R0;'#13+ 'TEMP R1;'#13+ 'MUL R0.x, fragment.texcoord[0].y, c[2].y;'#13+ 'MAD R0.y, fragment.texcoord[0].x, c[2].x, R0.x;'#13+ 'ADD R0.x, R0.y, c[2].z;'#13+ 'MUL R0.z, fragment.texcoord[0].y, c[3].y;'#13+ 'MAD R0.w, fragment.texcoord[0].x, c[3].x, R0.z;'#13+ 'ADD R1.x, R0.w, c[3].z;'#13+ 'SGE R0.z, c[4].x, R0.x;'#13+ 'SGE R0.y, R0, -c[2].z;'#13+ 'MUL R0.y, R0, R0.z;'#13+ 'SGE R0.z, R0.w, -c[3];'#13+ 'MUL R0.y, R0, R0.z;'#13+ 'SGE R0.w, c[4].x, R1.x;'#13+ 'MUL R0.z, R0.y, R0.w;'#13+ 'MOV R0.y, R1.x;'#13+ 'ABS R1.x, R0.z;'#13+ 'TEX R0, R0, texture[0], 2D;'#13+ 'CMP R1.x, -R1, c[4].y, c[4];'#13+ 'CMP result.color, -R1.x, c[4].y, R0;'#13+ 'END'; GLSLF: PAnsiChar = 'vec4 _TMP0;'#13+ 'vec2 _newval0008;'#13+ 'varying vec4 TEX0;'#13+ 'uniform sampler2D texture0;'#13+ 'uniform vec4 PSParam2;'#13+ 'uniform vec4 PSParam3;'#13+ 'void main()'#13+ '{'#13+ ' bool _isValid;'#13+ ' _newval0008.x = TEX0.x*PSParam2.x + TEX0.y*PSParam2.y + PSParam2.z;'#13+ ' _newval0008.y = TEX0.x*PSParam3.x + TEX0.y*PSParam3.y + PSParam3.z;'#13+ ' _isValid = _newval0008.x >= 0.0 && _newval0008.x <= 1.00000000E+000 && _newval0008.y >= 0.0 && _newval0008.y <= 1.00000000E+000;'#13+ ' if (_isValid) { '#13+ ' _TMP0 = texture2D(texture0, _newval0008);'#13+ ' } else {'#13+ ' _TMP0 = vec4( 0.0, 0.0, 0.0, 0.0);'#13+ ' } // end if'#13+ ' gl_FragColor = _TMP0;'#13+ ' return;'#13+ '} '; begin inherited; FAntiAlise := True; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; procedure TAffineFilter.CalcSize(var W, H: Integer); var P: TPointF; W1, H1, WW, HH: Single; S: TAffineMatrix; begin CalcMatrix(FInput.Width, FInput.Height); W1 := -100; H1 := -100; WW := 100; HH := 100; P.x := 1; P.y := 1; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 0; P.y := 1; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 0; P.y := 0; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 1; P.y := 0; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; W := round((W1 - WW) * FInput.Width); H := round((H1 - HH) * FInput.Height); // Recalc matrix S := IdentityMatrix; S.m11 := FInput.Width / W; S.m22 := FInput.Height / H; S.m31 := -WW * S.m11; S.m32 := -HH * S.m22; FMatrix := fxMatrixMultiply(FMatrix, S); FInvMatrix := FMatrix; fxInvertMatrix(FInvMatrix); end; procedure TAffineFilter.CalcMatrix(W, H: Integer); var S, US, T, R, UT: TAffineMatrix; begin S := IdentityMatrix; S.m11 := W; S.m22 := H; T := IdentityMatrix; T.m31 := -VarToPoint(Values['Center']).X / FInput.Width; T.m32 := -VarToPoint(Values['Center']).Y / FInput.Height; R := fxCreateRotationMatrix(Values['Rotation'] * cPIdiv180); UT := IdentityMatrix; UT.m31 := VarToPoint(Values['Center']).X / FInput.Width; UT.m32 := VarToPoint(Values['Center']).Y / FInput.Height; US := IdentityMatrix; US.m11 := 1 / W; US.m22 := 1 / H; FMatrix := fxMatrixMultiply(T, S); FMatrix := fxMatrixMultiply(FMatrix, R); FMatrix := fxMatrixMultiply(FMatrix, US); FMatrix := fxMatrixMultiply(FMatrix, UT); S := IdentityMatrix; S.m11 := Values['Scale']; S.m22 := Values['Scale']; FMatrix := fxMatrixMultiply(FMatrix, S); end; procedure TAffineFilter.LoadShader; begin ShaderDevice.SetPixelShader(FShaders[FPass]); ShaderDevice.SetPixelShaderVector(2, Vector3D(FInvMatrix.m11, FInvMatrix.m21, FInvMatrix.m31, 0)); ShaderDevice.SetPixelShaderVector(3, Vector3D(FInvMatrix.m12, FInvMatrix.m22, FInvMatrix.m32, 0)); end; class function TAffineFilter.FilterAttr: TFilterRec; begin Result := FilterRec('AffineTransform', 'Applies an affine transform to an image.', [ FilterValueRec('Center', 'The center point of the rotation.', TShaderValueType.vtPoint, VarFromPointXY(150, 150), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)), FilterValueRec('Rotation', 'Rotation angle in degrees.', TShaderValueType.vtFloat, 0, -180, 180), FilterValueRec('Scale', 'Scale value as floating.', TShaderValueType.vtFloat, 1, 0.05, 4) ]); end; { TPerspectiveFilter } constructor TPerspectiveFilter.Create; const DX9PS2BIN: array [0..747] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $39, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $BB, $00, $00, $00, $00, $02, $FF, $FF, $04, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $B4, $00, $00, $00, $6C, $00, $00, $00, $02, $00, $02, $00, $01, $00, $0A, $00, $74, $00, $00, $00, $00, $00, $00, $00, $84, $00, $00, $00, $02, $00, $03, $00, $01, $00, $0E, $00, $74, $00, $00, $00, $00, $00, $00, $00, $8C, $00, $00, $00, $02, $00, $04, $00, $01, $00, $12, $00, $74, $00, $00, $00, $00, $00, $00, $00, $94, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $A4, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $72, $69, $78, $31, $00, $01, $00, $03, $00, $01, $00, $03, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $72, $69, $78, $32, $00, $4D, $61, $74, $72, $69, $78, $33, $00, $69, $6D, $70, $6C, $69, $63, $69, $74, $49, $6E, $70, $75, $74, $00, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $00, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $80, $3F, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $05, $00, $00, $03, $00, $00, $08, $80, $00, $00, $55, $B0, $04, $00, $55, $A0, $04, $00, $00, $04, $00, $00, $01, $80, $04, $00, $00, $A0, $00, $00, $00, $B0, $00, $00, $FF, $80, $02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $04, $00, $AA, $A0, $02, $00, $00, $03, $00, $00, $02, $80, $00, $00, $00, $80, $00, $00, $00, $A0, $06, $00, $00, $02, $00, $00, $01, $80, $00, $00, $00, $80, $05, $00, $00, $03, $00, $00, $02, $80, $00, $00, $55, $80, $00, $00, $55, $80, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $55, $B0, $02, $00, $55, $A0, $04, $00, $00, $04, $00, $00, $04, $80, $00, $00, $00, $B0, $02, $00, $00, $A0, $00, $00, $AA, $80, $02, $00, $00, $03, $01, $00, $01, $80, $00, $00, $AA, $80, $02, $00, $AA, $A0, $05, $00, $00, $03, $02, $00, $01, $80, $00, $00, $00, $80, $01, $00, $00, $80, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $55, $B0, $03, $00, $55, $A0, $04, $00, $00, $04, $00, $00, $04, $80, $00, $00, $00, $B0, $03, $00, $00, $A0, $00, $00, $AA, $80, $02, $00, $00, $03, $01, $00, $02, $80, $00, $00, $AA, $80, $03, $00, $AA, $A0, $05, $00, $00, $03, $02, $00, $02, $80, $00, $00, $00, $80, $01, $00, $55, $80, $58, $00, $00, $04, $00, $00, $03, $80, $00, $00, $55, $81, $01, $00, $E4, $80, $02, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $04, $80, $00, $00, $00, $81, $00, $00, $55, $A0, $58, $00, $00, $04, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $55, $A0, $00, $00, $AA, $A0, $58, $00, $00, $04, $00, $00, $08, $80, $00, $00, $00, $80, $00, $00, $55, $A0, $00, $00, $AA, $A0, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $FF, $80, $58, $00, $00, $04, $00, $00, $08, $80, $00, $00, $55, $80, $00, $00, $55, $A0, $00, $00, $AA, $A0, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $AA, $80, $00, $00, $FF, $80, $02, $00, $00, $03, $00, $00, $08, $80, $00, $00, $55, $81, $00, $00, $55, $A0, $42, $00, $00, $03, $01, $00, $0F, $80, $00, $00, $E4, $80, $00, $08, $E4, $A0, $58, $00, $00, $04, $00, $00, $01, $80, $00, $00, $FF, $80, $00, $00, $55, $A0, $00, $00, $AA, $A0, $05, $00, $00, $03, $00, $00, $01, $80, $00, $00, $AA, $80, $00, $00, $00, $80, $58, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $00, $81, $00, $00, $AA, $A0, $01, $00, $E4, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'PARAM c[6] = { program.local[0..4],'#13+ ' { 1, 0 } };'#13+ 'TEMP R0;'#13+ 'TEMP R1;'#13+ 'MUL R0.x, fragment.texcoord[0].y, c[4].y;'#13+ 'MAD R0.x, fragment.texcoord[0], c[4], R0;'#13+ 'ADD R0.w, R0.x, c[4].z;'#13+ 'RCP R0.z, R0.w;'#13+ 'MUL R0.y, fragment.texcoord[0], c[3];'#13+ 'MAD R0.y, fragment.texcoord[0].x, c[3].x, R0;'#13+ 'ADD R0.x, R0.y, c[3].z;'#13+ 'ADD R0.w, R0, -c[5].x;'#13+ 'MUL R1.x, fragment.texcoord[0].y, c[2].y;'#13+ 'ABS R0.w, R0;'#13+ 'MAD R1.x, fragment.texcoord[0], c[2], R1;'#13+ 'CMP R0.w, -R0, c[5].y, c[5].x;'#13+ 'ABS R0.w, R0;'#13+ 'MUL R0.y, R0.z, R0.x;'#13+ 'ADD R1.x, R1, c[2].z;'#13+ 'CMP R0.w, -R0, c[5].y, c[5].x;'#13+ 'MUL R0.z, R1.x, R0;'#13+ 'CMP R0.z, -R0.w, R0, R1.x;'#13+ 'CMP R0.x, -R0.w, R0.y, R0;'#13+ 'SGE R0.w, c[5].x, R0.z;'#13+ 'SGE R0.y, R0.z, c[5];'#13+ 'MUL R0.y, R0, R0.w;'#13+ 'SGE R0.w, R0.x, c[5].y;'#13+ 'MUL R0.y, R0, R0.w;'#13+ 'SGE R1.x, c[5], R0;'#13+ 'MUL R0.y, R0, R1.x;'#13+ 'ABS R1.x, R0.y;'#13+ 'MOV R0.w, R0.x;'#13+ 'TEX R0, R0.zwzw, texture[0], 2D;'#13+ 'CMP R1.x, -R1, c[5].y, c[5];'#13+ 'CMP result.color, -R1.x, c[5].y, R0;'#13+ 'END'; GLSLF: PAnsiChar = 'vec4 _TMP0;'#13+ 'float _z0009;'#13+ 'vec2 _newval0009;'#13+ 'varying vec4 TEX0;'#13+ 'uniform sampler2D texture0;'#13+ 'uniform vec4 PSParam2;'#13+ 'uniform vec4 PSParam3;'#13+ 'uniform vec4 PSParam4;'#13+ 'void main()'#13+ '{'#13+ ' bool _isValid;'#13+ ' _z0009 = PSParam4.x*TEX0.x + PSParam4.y*TEX0.y + PSParam4.z;'#13+ ' if (_z0009 == 1.00000000E+000) { // if begin'#13+ ' _newval0009.x = TEX0.x*PSParam2.x + TEX0.y*PSParam2.y + PSParam2.z;'#13+ ' _newval0009.y = TEX0.x*PSParam3.x + TEX0.y*PSParam3.y + PSParam3.z;'#13+ ' } else {'#13+ ' _z0009 = 1.00000000E+000/_z0009;'#13+ ' _newval0009.x = (TEX0.x*PSParam2.x + TEX0.y*PSParam2.y + PSParam2.z)*_z0009;'#13+ ' _newval0009.y = (TEX0.x*PSParam3.x + TEX0.y*PSParam3.y + PSParam3.z)*_z0009;'#13+ ' } // end if'#13+ ' _isValid = _newval0009.x >= 0.00000000E+000 && _newval0009.x <= 1.00000000E+000 && _newval0009.y >= 0.00000000E+000 && _newval0009.y <= 1.00000000E+000;'#13+ ' if (_isValid) { // if begin'#13+ ' _TMP0 = texture2D(texture0, _newval0009);'#13+ ' } else {'#13+ ' _TMP0 = vec4( 0.00000000E+000, 0.00000000E+000, 0.00000000E+000, 0.00000000E+000);'#13+ ' } // end if'#13+ ' gl_FragColor = _TMP0;'#13+ ' return;'#13+ '}'; begin inherited; FAntiAlise := True; FShaders[FPassCount] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; procedure TPerspectiveFilter.CalcSize(var W, H: Integer); var P: TPointF; W1, H1, WW, HH: Single; S: TAffineMatrix; begin CalcMatrix(FInput.Width, FInput.Height); W1 := -100; H1 := -100; WW := 100; HH := 100; P.x := 1; P.y := 1; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 0; P.y := 1; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 0; P.y := 0; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; P.x := 1; P.y := 0; P := vgPointTransform(P, FMatrix); if P.x > W1 then W1 := P.x; if P.y > H1 then H1 := P.y; if P.x < WW then WW := P.x; if P.y < HH then HH := P.y; W := FInput.Width; H := FInput.Height; W := round((W1 - WW) * FInput.Width); H := round((H1 - HH) * FInput.Height); // Recalc matrix S := IdentityMatrix; S.m11 := FInput.Width / W; S.m22 := FInput.Height / H; S.m31 := -WW * S.m11; S.m32 := -HH * S.m22; FMatrix := fxMatrixMultiply(FMatrix, S); FInvMatrix := FMatrix; fxInvertMatrix(FInvMatrix); end; procedure TPerspectiveFilter.CalcMatrix(W, H: Integer); var Wx0, Wy0, Wx1, Wy1, Wx2, Wy2, Wx3, Wy3: Single; dx1, dx2, px, dy1, dy2, py: Single; g, hh, k: Single; begin with ValuesAsPoint['TopLeft'] do begin Wx0 := x / W; Wy0 := y / H; end; with ValuesAsPoint['TopRight'] do begin Wx1 := x / W; Wy1 := y / H; end; with ValuesAsPoint['BottomRight'] do begin Wx2 := x / W; Wy2 := y / H; end; with ValuesAsPoint['BottomLeft'] do begin Wx3 := x / W; Wy3 := y / H; end; px := Wx0 - Wx1 + Wx2 - Wx3; py := Wy0 - Wy1 + Wy2 - Wy3; dx1 := Wx1 - Wx2; dx2 := Wx3 - Wx2; dy1 := Wy1 - Wy2; dy2 := Wy3 - Wy2; k := dx1 * dy2 - dx2 * dy1; if k <> 0 then begin g := (px * dy2 - py * dx2) / k; hh := (dx1 * py - dy1 * px) / k; FMatrix.m11 := Wx1 - Wx0 + g * Wx1; FMatrix.m21 := Wx3 - Wx0 + hh * Wx3; FMatrix.m31 := Wx0; FMatrix.m12 := Wy1 - Wy0 + g * Wy1; FMatrix.m22 := Wy3 - Wy0 + hh * Wy3; FMatrix.m32 := Wy0; FMatrix.m13 := g; FMatrix.m23 := hh; FMatrix.m33 := 1; end else FillChar(FMatrix, SizeOf(FMatrix), 0); end; procedure TPerspectiveFilter.LoadShader; begin ShaderDevice.SetPixelShader(FShaders[FPass]); ShaderDevice.SetPixelShaderVector(2, Vector3D(FInvMatrix.m11, FInvMatrix.m21, FInvMatrix.m31, 0)); ShaderDevice.SetPixelShaderVector(3, Vector3D(FInvMatrix.m12, FInvMatrix.m22, FInvMatrix.m32, 0)); ShaderDevice.SetPixelShaderVector(4, Vector3D(FInvMatrix.m13, FInvMatrix.m23, FInvMatrix.m33, 0)); end; class function TPerspectiveFilter.FilterAttr: TFilterRec; begin Result := FilterRec('PerspectiveTransform', 'Applies an perspective transform to an image.', [ FilterValueRec('TopLeft', 'Top left point of result transformation.', TShaderValueType.vtPoint, VarFromPointXY(0, 0), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)), FilterValueRec('TopRight', 'Top right point of result transformation.', TShaderValueType.vtPoint, VarFromPointXY(300, 0), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)), FilterValueRec('BottomRight', 'Bottom right point of result transformation.', TShaderValueType.vtPoint, VarFromPointXY(350, 300), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)), FilterValueRec('BottomLeft', 'Bottom left point of result transformation.', TShaderValueType.vtPoint, VarFromPointXY(0, 300), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)) ]); end; { TCropFilter } constructor TCropFilter.Create; const DX9PS2BIN: array [0..527] of byte = ( $00, $02, $FF, $FF, $FE, $FF, $30, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $97, $00, $00, $00, $00, $02, $FF, $FF, $03, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $90, $00, $00, $00, $58, $00, $00, $00, $02, $00, $00, $00, $01, $00, $02, $00, $5C, $00, $00, $00, $00, $00, $00, $00, $6C, $00, $00, $00, $02, $00, $01, $00, $01, $00, $06, $00, $5C, $00, $00, $00, $00, $00, $00, $00, $6F, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $80, $00, $00, $00, $00, $00, $00, $00, $4C, $54, $00, $AB, $01, $00, $03, $00, $01, $00, $02, $00, $01, $00, $00, $00, $00, $00, $00, $00, $52, $42, $00, $69, $6D, $70, $6C, $69, $63, $69, $74, $49, $6E, $70, $75, $74, $00, $AB, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00, $01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $02, $00, $0F, $A0, $00, $00, $80, $3F, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $02, $00, $00, $03, $00, $00, $03, $80, $00, $00, $E4, $B0, $00, $00, $E4, $A0, $01, $00, $00, $02, $01, $00, $03, $80, $00, $00, $E4, $A0, $02, $00, $00, $03, $01, $00, $03, $80, $01, $00, $E4, $81, $01, $00, $E4, $A0, $05, $00, $00, $03, $02, $00, $03, $80, $00, $00, $E4, $80, $01, $00, $E4, $80, $58, $00, $00, $04, $00, $00, $04, $80, $02, $00, $00, $80, $02, $00, $00, $A0, $02, $00, $55, $A0, $58, $00, $00, $04, $00, $00, $08, $80, $02, $00, $55, $80, $02, $00, $00, $A0, $02, $00, $55, $A0, $42, $00, $00, $03, $02, $00, $0F, $80, $02, $00, $E4, $80, $00, $08, $E4, $A0, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $FF, $80, $00, $00, $AA, $80, $04, $00, $00, $04, $00, $00, $01, $80, $00, $00, $00, $80, $01, $00, $00, $81, $02, $00, $00, $A0, $04, $00, $00, $04, $00, $00, $02, $80, $00, $00, $55, $80, $01, $00, $55, $81, $02, $00, $00, $A0, $58, $00, $00, $04, $00, $00, $01, $80, $00, $00, $00, $80, $02, $00, $00, $A0, $02, $00, $55, $A0, $05, $00, $00, $03, $00, $00, $01, $80, $00, $00, $AA, $80, $00, $00, $00, $80, $58, $00, $00, $04, $00, $00, $02, $80, $00, $00, $55, $80, $02, $00, $00, $A0, $02, $00, $55, $A0, $05, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $00, $00, $55, $80, $58, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $00, $81, $02, $00, $55, $A0, $02, $00, $E4, $80, $01, $00, $00, $02, $00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00 ); ARBFP1: PAnsiChar = '!!ARBfp1.0'#13+ 'PARAM c[3] = { program.local[0..1],'#13+ ' { 1, 0 } };'#13+ 'TEMP R0;'#13+ 'TEMP R1;'#13+ 'MOV R0.xy, c[0];'#13+ 'ADD R0.zw, -R0.xyxy, c[1].xyxy;'#13+ 'ADD R0.xy, fragment.texcoord[0], c[0];'#13+ 'MUL R0.xy, R0, R0.zwzw;'#13+ 'SGE R0.w, R0.y, c[2].y;'#13+ 'SGE R0.z, R0.x, c[2].y;'#13+ 'MUL R1.x, R0.z, R0.w;'#13+ 'SGE R0.z, c[2].x, R0.x;'#13+ 'SGE R0.w, c[2].x, R0.y;'#13+ 'MUL R0.z, R1.x, R0;'#13+ 'MUL R0.z, R0, R0.w;'#13+ 'ABS R1.x, R0.z;'#13+ 'TEX R0, R0, texture[0], 2D;'#13+ 'CMP R1.x, -R1, c[2].y, c[2];'#13+ 'CMP result.color, -R1.x, c[2].y, R0;'#13+ 'END'; GLSLF: PAnsiChar = 'vec4 _TMP0;'#13+ 'varying vec4 TEX0;'#13+ 'uniform sampler2D texture0;'#13+ 'uniform vec4 PSParam0;'#13+ 'uniform vec4 PSParam1;'#13+ 'void main()'#13+ '{'#13+ ' vec2 _newCoord;'#13+ ' bool _isValid;'#13+ ' _newCoord = TEX0.xy + PSParam0.xy;'#13+ ' _newCoord = _newCoord*(PSParam1.xy - PSParam0.xy);'#13+ ' _isValid = _newCoord.x >= 0.00000000E+000 && _newCoord.y >= 0.00000000E+000 && _newCoord.x <= 1.00000000E+000 && _newCoord.y <= 1.00000000E+000;'#13+ ' if (_isValid) { // if begin'#13+ ' _TMP0 = texture2D(texture0, _newCoord);'#13+ ' } else {'#13+ ' _TMP0 = vec4( 0.00000000E+000, 0.00000000E+000, 0.00000000E+000, 0.00000000E+000);'#13+ ' } // end if'#13+ ' gl_FragColor = _TMP0;'#13+ ' return;'#13+ '}'; begin inherited; FShaders[1] := ShaderDevice.CreatePixelShader(@DX9PS2BIN, ARBFP1, GLSLF); end; procedure TCropFilter.CalcSize(var W, H: Integer); begin W := round((VarToPoint(Values['RightBottom']).x - VarToPoint(Values['LeftTop']).x)); H := round((VarToPoint(Values['RightBottom']).y - VarToPoint(Values['LeftTop']).y)); end; class function TCropFilter.FilterAttr: TFilterRec; begin Result := FilterRec('Crop', 'The size and shape of the cropped image depend on the rectangle you specify.', [ FilterValueRec('LeftTop', 'Left-top corner of cropping rect', TShaderValueType.vtPoint, VarFromPointXY(0, 0), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)), FilterValueRec('RightBottom', 'Left-top corner of cropping rect', TShaderValueType.vtPoint, VarFromPointXY(150, 150), VarFromPointXY(0, 0), VarFromPointXY(65535, 65535)) ]); end; initialization RegisterFilter('Geometry', TAffineFilter); RegisterFilter('Geometry', TPerspectiveFilter); RegisterFilter('Geometry', TCropFilter); end.
unit PhoneNumbers; interface uses System.Classes,System.SysUtils,System.StrUtils ,WinApi.Windows,Vcl.Dialogs,System.UITypes; type TLibPhoneNumber = class private type TParseFunction = function (phonenumber : WideString; country : WideString; out formatetNumber : WideString) : Boolean; stdcall; private dll : HMODULE; parseFunction : TParseFunction; private const DLLNAME = 'PhoneNumbersUnmanaged.dll'; public constructor Create; destructor Destroy; override; class function Parse(const phonenumber, country : String; E164notation : Boolean = true) : String; end; implementation var instance : TLibPhoneNumber; { TLibPhoneNumber } constructor TLibPhoneNumber.Create; begin dll := 0; parseFunction := nil; if not FileExists(ExtractFilePath(ParamStr(0))+DLLNAME) then begin MessageDlg(Format('"%s" not found.',[DLLNAME])+#10+ExtractFilePath(ParamStr(0)), mtError, [mbOK], 0); exit; end; dll := LoadLibrary(PChar(ExtractFilePath(ParamStr(0))+DLLNAME)); if dll <> 0 then begin parseFunction := GetProcAddress(dll, 'Parse'); end else MessageDlg(Format('error loading "%s".',[DLLNAME])+#10+ExtractFilePath(ParamStr(0)), mtError, [mbOK], 0); end; destructor TLibPhoneNumber.Destroy; begin if dll <> 0 then FreeLibrary(dll); dll := 0; inherited; end; class function TLibPhoneNumber.Parse(const phonenumber, country: String; E164notation : Boolean = true): String; var hstr : WideString; splitted: TArray<String>; i : Integer; begin Result := ''; if instance = nil then instance := TLibPhoneNumber.Create; if not Assigned(instance.parseFunction) then begin Result := phonenumber; exit; end; if instance.parseFunction(PhoneNumber,country,hstr) then Result := hstr; if Result = '' then exit; if E164notation then begin Result := ReplaceText(Result,' ',''); exit; end; splitted := Result.Split([' ']); if Length(splitted) < 2 then exit; for i := Low(splitted) to high(splitted) do begin if i = Low(splitted) then Result := splitted[i] else if i = Low(splitted)+1 then Result := Result + ' ('+splitted[i]+')' else Result := Result + ' '+splitted[i]; end; end; initialization instance := nil; finalization if Assigned(instance) then begin instance.Free; instance := nil; end; end.
unit GridExtension; interface uses cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, StdCtrls, cxCustomData, cxGridBandedTableView, System.Classes, cxGridDBBandedTableView, Data.DB; type TcxMyGridMasterDataRow = class(TcxGridMasterDataRow) CanExpand: boolean; function GetExpandable: boolean; override; public procedure MyCollapse(ARecurse: boolean); procedure MyExpand(ARecurse: boolean); end; TcxMyGridViewData = class(TcxGridViewData) function GetRecordClass(const ARecordInfo: TcxRowInfo) : TcxCustomGridRecordClass; override; end; TcxGridDBBandedTableViewWithoutExpand = class(TcxGridDBBandedTableView) protected function GetViewDataClass: TcxCustomGridViewDataClass; override; end; implementation uses cxDBLookupComboBox, System.SysUtils; { TcxMyGridMasterDataRow } function TcxMyGridMasterDataRow.GetExpandable: boolean; begin Result := inherited GetExpandable and CanExpand; end; procedure TcxMyGridMasterDataRow.MyCollapse(ARecurse: boolean); begin CanExpand := True; Collapse(ARecurse); CanExpand := False; end; procedure TcxMyGridMasterDataRow.MyExpand(ARecurse: boolean); begin CanExpand := True; Expand(ARecurse); CanExpand := False; end; { TcxMyGridViewData } function TcxMyGridViewData.GetRecordClass(const ARecordInfo: TcxRowInfo) : TcxCustomGridRecordClass; begin Result := nil; if Inherited GetRecordClass(ARecordInfo) = TcxGridMasterDataRow then Result := TcxMyGridMasterDataRow; end; function TcxGridDBBandedTableViewWithoutExpand.GetViewDataClass : TcxCustomGridViewDataClass; begin Result := TcxMyGridViewData; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 报表中心 //主要实现: // 报表的增加、设计等 // 系统的所有报表均在此管理 //-----------------------------------------------------------------------------} unit untEasyReportTemplateDesign; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateDBBaseForm; //插件导出函数 function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm; type TfrmEasyReportTemplateDesign = class(TfrmEasyPlateDBBaseForm) private { Private declarations } public { Public declarations } end; var frmEasyReportTemplateDesign: TfrmEasyReportTemplateDesign; implementation {$R *.dfm} //引出函数实现 function ShowBplForm(AParamList: TStrings): TForm; begin frmEasyReportTemplateDesign := TfrmEasyReportTemplateDesign.Create(Application); if frmEasyReportTemplateDesign.FormStyle <> fsMDIChild then frmEasyReportTemplateDesign.FormStyle := fsMDIChild; if frmEasyReportTemplateDesign.WindowState <> wsMaximized then frmEasyReportTemplateDesign.WindowState := wsMaximized; Result := frmEasyReportTemplateDesign; end; end.
{ @html(<b>) TCP/IP Server Connection @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) Introducing the @html(<b>) @Link(TRtcTcpServer) @html(</b>) component: @html(<br>) Server connection component for TCP/IP communication using raw data. There will be no special pre-set formatting when sending or receiving data through this server connection component. } unit rtcTcpSrv; {$INCLUDE rtcDefs.inc} interface uses rtcConn; type { @Abstract(Server Connection component for TCP/IP communication using raw data) There is no predefined formatting when sending and receiving data through @Link(TRtcTcpServer) connection component. Everything that comes through the connection, will be received exactly as it was sent (byte-wise). The same goes for sending data out through the component. This makes the component universal, so it can be used to write virtualy any TCP/IP Server application. @html(<br><br>) Properties to check first: @html(<br>) @Link(TRtcConnection.ServerAddr) - Local Address to bind the server to (leave empty for ALL) @html(<br>) @Link(TRtcConnection.ServerPort) - Port to listen on and wait for connections @html(<br><br>) Methods to check first: Most important TRtcTcpServer's methods are: @html(<br>) @Link(TRtcServer.Listen) - Start server @html(<br>) @Link(TRtcConnection.Read) - Read data @html(<br>) @Link(TRtcConnection.Write) - Write data @html(<br>) @Link(TRtcConnection.Disconnect) - Disconnect client @html(<br>) @Link(TRtcServer.StopListen) - Stop server @html(<br><br>) Events to check first: @html(<br>) @Link(TRtcServer.OnListenStart) - Server started @html(<br>) @Link(TRtcConnection.OnConnect) - new Client connected @html(<br>) @Link(TRtcConnection.OnDataReceived) - Data received from client (need to read) @html(<br>) @Link(TRtcConnection.OnDataSent) - Data sent to client (buffer now empty) @html(<br>) @Link(TRtcConnection.OnDisconnect) - one Client disconnected @html(<br>) @Link(TRtcServer.OnListenStop) - Server stopped @html(<br><br>) @html(<b>function Read:string;</b><br>) Use Read to get all the data that is waiting for you in this connection component's receiving buffer. A call to Read will also clear the buffer, which means that you have to store the string received from Read, before you start to process it. @html(<br><br>) Keep in mind that when using TCP/IP, data is received as a stream (or rather, peaces of it), without pre-defined end-marks for each package sent or received. This means that the client could have sent a big chunk of data in just one call, but the server will receive several smaller packages of different sizes. It could also happen that client sends multiple smaller packages, which your server connection could receive as one big package. A combination of those circumstances is also possible. @html(<br><br>) So, before you start processing the data you receive, make sure that you have received everything you need. You could create a buffer for storing temporary data, so you can react on multiple OnDataReceived events and put all data received inside your buffer, before you actually start processing the data. @html(<br><br>) IMPORTANT: ONLY CALL Read from OnDataReceived event handler. OnDataReceived will be automatically triggered by the connection component, every time new data becomes available. @html(<br><br>) @html(<b>procedure Write(const s:string='');</b><br>) Use Write to send data out. Write will not block your code execution, it will only put the string into sending buffer and return immediatelly. @html(<br><br>) Keep in mind that all the data you put into the sending buffer will remain there until it was sent out or the connection through it was to be sent closed. To avoid filling your buffer with data that will not be sent out for some time, try sending a small peace at a time and then react on the @Link(TRtcConnection.OnDataSent) event to continue and send the next one. Packages you send out at once shouldn't be larger that 64 KB. @html(<br><br>) Check @Link(TRtcServer) and @Link(TRtcConnection) for more info. } TRtcTcpServer = class(TRtcServer) protected { Creates a new connection provider @exclude} function CreateProvider:TObject; override; public { Use this class function to create a new TRtcTcpServer component at runtime. DO NOT USE the Create constructor. } class function New:TRtcTcpServer; published { This event will be triggered every time this connection component's buffer is completely empty and the other side has just become ready to accept new data. It is good to wait for this event before starting to send data out, even though you can start sending data directly from the @Link(TRtcConnection.OnConnect) event. @html(<br><br>) By responding to this event and sending the data only after it was triggered, you avoid keeping the data in the send buffer, especially if the data you are sending is being read from a file on disk, which wouldn't occupy any memory until loaded. } property OnReadyToSend; { This event will be triggered every time a chunk of your data prepared for sending has just been sent out. To know exactly how much of it is on the way, use the @Link(TRtcConnection.DataOut) property. @html(<br><br>) NOTE: Even though data has been sent out, it doesn't mean that the other side already received it. It could also be that connection will break before this package reaches the other end. } property OnDataOut; { This event will be triggered when all data prepared for sending has been sent out and the sending buffer has become empty again. @html(<br><br>) When sending large data blocks, try slicing them in small chunks, sending a chunk at a time and responding to this event to prepare and send the next chunk. This will keep your memory needs low. } property OnDataSent; { When this event triggers, it means that the other side has sent you some data and you can now read it. Check the connection component's description to see which properties and methods you can use to read the data received. } property OnDataReceived; end; implementation uses SysUtils, rtcWSockSrvProv; // WSocket Server Provider type TMyProvider = TRtcWSockServerProvider; class function TRtcTcpServer.New: TRtcTcpServer; begin Result:=Create(nil); end; function TRtcTcpServer.CreateProvider:TObject; begin if not assigned(Con) then begin Con:=TMyProvider.Create; TMyProvider(Con).Proto:=proTCP; SetTriggers; end; Result:=Con; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { Web server application components } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} // Parse an HTTP header. unit Web.HTTPParse; interface uses System.SysUtils, System.Classes; const toEOF = UTF8Char(0); toSymbol = UTF8Char(1); toString = UTF8Char(2); toInteger = UTF8Char(3); toFloat = UTF8Char(4); toEOL = UTF8Char(5); toGET = UTF8Char(6); toHEAD = UTF8Char(7); toPUT = UTF8Char(8); toDELETE = UTF8Char(9); toPOST = UTF8Char(10); toPATCH = UTF8Char(11); toCOPY = UTF8Char(12); toUserAgent = UTF8Char(13); toAccept = UTF8Char(14); toContentType = UTF8Char(15); toContentLength = UTF8Char(16); toReferer = UTF8Char(17); toAuthorization = UTF8Char(18); toCacheControl = UTF8Char(19); toDate = UTF8Char(20); toFrom = UTF8Char(21); toHost = UTF8Char(22); toIfModified = UTF8Char(23); toContentEncoding = UTF8Char(24); toContentVersion= UTF8Char(25); toAllow = UTF8Char(26); toConnection = UTF8Char(27); toCookie = UTF8Char(28); toContentDisposition = UTF8Char(29); hcGET = $14F5; hcPUT = $4AF5; hcDELETE = $92B2; hcPOST = $361D; hcCacheControl = $4FF6; hcDate = $0EE6; hcFrom = $418F; hcHost = $3611; hcIfModified = $DDF0; hcAllow = $3D80; hcUserAgent = $E890; hcAccept = $1844; hcContentEncoding= $C586; hcContentVersion = $EDF4; hcContentType = $F0E0; hcContentLength = $B0C4; hcReferer = $CEA5; hcAuthorization = $ABCA; hcConnection = $0EDE; hcCookie = $27B3; hcContentDisposition = $CBEB; type { THTTPParser } THTTPParser = class(TObject) private FStream: TStream; FOrigin: Int64; FBuffer: PUTF8Char; FBufPtr: PUTF8Char; FBufEnd: PUTF8Char; FSourcePtr: PUTF8Char; FSourceEnd: PUTF8Char; FStringPtr: PUTF8Char; FSourceLine: Integer; FSaveChar: UTF8Char; FToken: UTF8Char; FHeaderField: Boolean; FTokenPtr: PUTF8Char; procedure ReadBuffer; procedure SkipBlanks; public constructor Create(Stream: TStream); destructor Destroy; override; procedure CheckToken(T: UTF8Char); procedure CheckTokenSymbol(const S: UTF8String); function CopyTo(Length: Integer): UTF8String; function CopyToEOL: UTF8String; function CopyToEOF: UTF8String; procedure Error(const Ident: string); procedure ErrorFmt(const Ident: string; const Args: array of const); procedure ErrorStr(const Message: string); procedure HexToBinary(Stream: TStream); function NextToken: UTF8Char; procedure SkipEOL; function SourcePos: Int64; function TokenFloat: Extended; function TokenInt: Longint; function TokenString: UTF8String; function TokenSymbolIs(const S: UTF8String): Boolean; function BufferRequest(Length: Integer): TStream; property SourceLine: Integer read FSourceLine; property Token: UTF8Char read FToken; property HeaderField: Boolean read FHeaderField write FHeaderField; property SourcePtr: PUTF8Char read FSourcePtr write FSourcePtr; property TokenPtr: PUTF8Char read FTokenPtr write FTokenPtr; property Stream: TStream read FStream; property SourceEnd: PUTF8Char read FSourceEnd; end; implementation uses System.RTLConsts; const ParseBufSize = 4096; //{$IFDEF xxxNEXTGEN} function LineStart(Buffer, BufPos: PUTF8Char): PUTF8Char; var C: NativeInt; begin Result := Buffer; C := (BufPos - Buffer) - 1; while (C > 0) and (Buffer[C] <> #10) do Dec(C); if C > 0 then Result := @Buffer[C + 1]; end; function StrComp(const Str1, Str2: PUTF8Char): Integer; var P1, P2: PUTF8Char; begin P1 := Str1; P2 := Str2; while True do begin if (P1^ <> P2^) or (P1^ = #0) then Exit(Ord(P1^) - Ord(P2^)); Inc(P1); Inc(P2); end; end; function StrIComp(const Str1, Str2: PUTF8Char): Integer; var P1, P2: PUTF8Char; C1, C2: UTF8Char; begin P1 := Str1; P2 := Str2; while True do begin if P1^ in ['a'..'z'] then C1 := UTF8Char(Word(P1^) xor $20) else C1 := P1^; if P2^ in ['a'..'z'] then C2 := UTF8Char(Word(P2^) xor $20) else C2 := P2^; if (C1 <> C2) or (C1 = #0) then Exit(Ord(C1) - Ord(C2)); Inc(P1); Inc(P2); end; end; //{$ENDIF} { THTTPParser } constructor THTTPParser.Create(Stream: TStream); begin FStream := Stream; GetMem(FBuffer, ParseBufSize); FBuffer[0] := #0; FBufPtr := FBuffer; FBufEnd := FBuffer + ParseBufSize; FSourcePtr := FBuffer; FSourceEnd := FBuffer; FTokenPtr := FBuffer; FSourceLine := 1; FHeaderField := True; NextToken; end; function THTTPParser.BufferRequest(Length: Integer): TStream; const BufSize = 1000; var Buffer: array[0..BufSize-1] of byte; Count: Integer; L, R, T, C: Integer; P1, P2: PUTF8Char; begin // Get processed contents of parser buffer Result := TMemoryStream.Create; Count := FSourcePtr - FBuffer; Result.Write(Pointer(FBuffer)^, Count); // Find end of parser buffer if Length > 0 then begin P1 := FSourcePtr; P2 := P1; while (P2^ <> #0) do Inc(P2); while Length > 0 do begin if Length > BufSize then L := BufSize else L := Length; if P1 < P2 then begin // Read from parser buffer if L > P2 - P1 then R := P2 - P1 else R := L; Move(P1^, Buffer, R); L := R; P1 := P1 + R; end else begin T := 0; R := L; repeat C := FStream.Read(Buffer[T], R-T); T := T + C; until (C = 0) or (T = R); end; Result.Write(Buffer, L); Length := Length - R; end; end; Result.Seek(Count, soBeginning); FStream := Result; end; destructor THTTPParser.Destroy; begin if FBuffer <> nil then begin FStream.Seek(IntPtr(FTokenPtr) - IntPtr(FSourceEnd), soCurrent); FreeMem(FBuffer, ParseBufSize); end; end; procedure THTTPParser.CheckToken(T: UTF8Char); begin if Token <> T then case T of toSymbol: Error(SIdentifierExpected); System.Classes.toString: Error(SStringExpected); toInteger, toFloat: Error(SNumberExpected); else ErrorFmt(SCharExpected, [T]); end; end; procedure THTTPParser.CheckTokenSymbol(const S: UTF8String); begin if not TokenSymbolIs(S) then ErrorFmt(SSymbolExpected, [S]); end; function THTTPParser.CopyTo(Length: Integer): UTF8String; var P: PUTF8Char; Temp: UTF8String; begin Result := ''; repeat P := FTokenPtr; while (Length > 0) and (P^ <> #0) do begin Inc(P); Dec(Length); end; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; if Length > 0 then ReadBuffer; until (Length = 0) or (Token = toEOF); FSourcePtr := P; end; function THTTPParser.CopyToEOL: UTF8String; var P: PUTF8Char; begin P := FTokenPtr; while not (P^ in [#13, #10, #0]) do Inc(P); SetString(Result, FTokenPtr, P - FTokenPtr); if P^ = #13 then Inc(P); FSourcePtr := P; if P^ <> #0 then NextToken else FToken := #0; end; function THTTPParser.CopyToEOF: UTF8String; var P: PUTF8Char; Temp: UTF8String; begin repeat P := FTokenPtr; while P^ <> #0 do Inc(P); FSourcePtr := P; ReadBuffer; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; NextToken; until Token = toEOF; end; procedure THTTPParser.Error(const Ident: string); begin ErrorStr(Ident); end; procedure THTTPParser.ErrorFmt(const Ident: string; const Args: array of const); begin ErrorStr(Format(Ident, Args)); end; procedure THTTPParser.ErrorStr(const Message: string); begin raise EParserError.CreateResFmt(@SParseError, [Message, FSourceLine]); end; //{$IFNDEF NEXTGEN} //procedure THTTPParser.HexToBinary(Stream: TStream); //var // Count: Integer; // Buffer: array[0..255] of UTF8Char; //begin // SkipBlanks; // while FSourcePtr^ <> '}' do // begin // Count := HexToBin(FSourcePtr, Buffer, SizeOf(Buffer)); // if Count = 0 then Error(SInvalidBinary); // Stream.Write(Buffer, Count); // Inc(FSourcePtr, Count * 2); // SkipBlanks; // end; // NextToken; //end; //{$ELSE} procedure THTTPParser.HexToBinary(Stream: TStream); var Count: Integer; {$IFDEF NEXTGEN} LSource: TBytes; LSourceCount: Integer; LStart: PUTF8Char; Buffer: TBytes; {$ELSE} Buffer: array[0..255] of UTF8Char; {$ENDIF} begin SkipBlanks; {$IFDEF NEXTGEN} LSourceCount := 0; while FSourcePtr[LSourceCount] <> '}' do Inc(LSourceCount); LSource := BytesOf(FSourcePtr, LSourceCount); LStart := FSourcePtr; SetLength(Buffer, 255); {$ENDIF} while FSourcePtr^ <> '}' do begin {$IFDEF NEXTGEN} //function HexToBin(const Text: TBytes; TextOffset: Integer; // var Buffer: TBytes; BufOffset: Integer; Count: Integer): Integer; Count := HexToBin(LSource, FSourcePtr - LStart, Buffer, 0, Length(Buffer)); {$ELSE} Count := HexToBin(FSourcePtr, Buffer, SizeOf(Buffer)); {$ENDIF} if Count = 0 then Error(SInvalidBinary); Stream.Write(Buffer, Count); Inc(FSourcePtr, Count * 2); SkipBlanks; end; NextToken; end; //procedure TXSHexBinary.XSToNative(const Value: InvString); //{$IFDEF NEXTGEN} //var // SourceBytes, DestBytes: TBytes; // V: string; // L : Integer; //begin // // TODO -oAntonioT -cFIXME: This is a nonsense function? Think Twice? // V := Value; // if V.IndexOf(SHexMarker) = -1 then // V := SHexMarker + V; // SourceBytes := TEncoding.UTF8.GetBytes(V); // L := Length(SourceBytes); // SetLEngth(DestBytes, (L+1) div 2); // if HexToBin(SourceBytes, 0, DestBytes, 0, L) > 0 then // SoapHexBinaryErrorFmt(SInvalidHexValue, [Value]); // FHexBinaryString := Value; //end; //{$ELSE !NEXTGEN} //var // PText: PChar; // V: string; // L : Integer; //begin // V := Value; // L := Length(V); // PText := AllocMem((L * 2 + 1) * sizeof(Char)); // try // if Pos(SHexMarker, V) = 0 then // V := SHexMarker + V; // if HexToBin(PChar(V), PText, L) > 0 then // SoapHexBinaryErrorFmt(SInvalidHexValue, [Value]); // FHexBinaryString := Value; // finally // FreeMem(PText); // end; //end; //{$ENDIF NEXTGEN} const CharValue: array[Byte] of Byte = ( $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$00,$00,$00,$00,$00,$00, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$5F, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); function GetHashCode(Ident: PUTF8Char; Length: Integer): Word; const MAXWORD = $FFFF; begin Result := 0; while Length > 0 do begin // when SHL, exclude high-order bits to prevent range check error Result := ((Result and (MaxWord SHR 5)) SHL 5) or (Result SHR (16 - 5)); PByte(@Result)[0] := PByte(@Result)[0] XOR CharValue[Byte(Ident^)]; Dec(Length); Inc(Ident); end; end; type TSymbolEntry = record HashCode: Word; Symbol: PUTF8Char; Token: UTF8Char; end; const SymbolTable: array[0..20] of TSymbolEntry = ( (HashCode: hcGet; Symbol: 'GET'; Token: toGET), (HashCode: hcPut; Symbol: 'PUT'; Token: toPUT), (HashCode: hcDelete; Symbol: 'DELETE'; Token: toDELETE), (HashCode: hcPost; Symbol: 'POST'; Token: toPOST), (HashCode: hcCacheControl; Symbol: 'Cache-Control'; Token: toCacheControl), (HashCode: hcDate; Symbol: 'Date'; Token: toDate), (HashCode: hcFrom; Symbol: 'From'; Token: toFrom), (HashCode: hcHost; Symbol: 'Host'; Token: toHost), (HashCode: hcIfModified; Symbol: 'If-Modified-Since'; Token: toIfModified), (HashCode: hcAllow; Symbol: 'Allow'; Token: toAllow), (HashCode: hcUserAgent; Symbol: 'User-Agent'; Token: toUserAgent), (HashCode: hcAccept; Symbol: 'Accept'; Token: toAccept), (HashCode: hcContentEncoding; Symbol: 'Content-Encoding'; Token: toContentEncoding), (HashCode: hcContentVersion; Symbol: 'Content-Version'; Token: toContentVersion), (HashCode: hcContentType; Symbol: 'Content-Type'; Token: toContentType), (HashCode: hcContentLength; Symbol: 'Content-Length'; Token: toContentLength), (HashCode: hcReferer; Symbol: 'Referer'; Token: toReferer), (HashCode: hcConnection; Symbol: 'Connection'; Token: toConnection), (HashCode: hcCookie; Symbol: 'Cookie'; Token: toCookie), (HashCode: hcAuthorization; Symbol: 'Authorization'; Token: toAuthorization), (HashCode: hcContentDisposition; Symbol: 'Content-Disposition'; Token: toContentDisposition)); function LookupToken(Sym: PUTF8Char): UTF8Char; var HCode: Word; I: Integer; begin Result := toSymbol; HCode := GetHashCode(Sym, Length(Sym)); for I := Low(SymbolTable) to High(SymbolTable) do with SymbolTable[I] do if HCode = HashCode then if StrIComp(Symbol, Sym) = 0 then begin Result := Token; Break; end; end; function THTTPParser.NextToken: UTF8Char; var I: Integer; P, S: PUTF8Char; SaveChar: UTF8Char; TokenChars: set of UTF8Char; begin SkipBlanks; P := FSourcePtr; FTokenPtr := P; if FHeaderField then TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] else TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_']; case P^ of 'A'..'Z', 'a'..'z', '_': begin Inc(P); while P^ in TokenChars do Inc(P); SaveChar := P^; try P^ := #0; Result := LookupToken(FTokenPtr); finally P^ := SaveChar; end; end; #10: begin Inc(P); Inc(FSourceLine); Result := toEOL; end; '#', '''': begin S := P; while True do case P^ of '#': begin Inc(P); I := 0; while P^ in ['0'..'9'] do begin I := I * 10 + (Ord(P^) - Ord('0')); Inc(P); end; S^ := UTF8Char(I); Inc(S); end; '''': begin Inc(P); while True do begin case P^ of #0, #10, #13: Error(SInvalidString); '''': begin Inc(P); if P^ <> '''' then Break; end; end; S^ := P^; Inc(S); Inc(P); end; end; else Break; end; FStringPtr := S; Result := System.Classes.toString; end; '$': begin Inc(P); while P^ in ['0'..'9', 'A'..'F', 'a'..'f'] do Inc(P); Result := toInteger; end; '0'..'9': begin Inc(P); while P^ in ['0'..'9'] do Inc(P); Result := toInteger; while P^ in ['0'..'9', '.', 'e', 'E', '+'] do begin Inc(P); Result := toFloat; end; end; else Result := P^; if Result <> toEOF then Inc(P); end; FSourcePtr := P; FToken := Result; end; procedure THTTPParser.ReadBuffer; var Count: Int64; P: PUTF8Char; begin Inc(FOrigin, FSourcePtr - FBuffer); FSourceEnd[0] := FSaveChar; Count := FBufPtr - FSourcePtr; if Count <> 0 then Move(FSourcePtr[0], FBuffer[0], Count); FBufPtr := FBuffer + Count; Inc(FBufPtr, FStream.Read(FBufPtr[0], FBufEnd - FBufPtr)); FSourcePtr := FBuffer; FSourceEnd := FBufPtr; if FSourceEnd = FBufEnd then begin FSourceEnd := LineStart(FBuffer, FSourceEnd - 1); if FSourceEnd = FBuffer then Error(SLineTooLong); end; P := FBuffer; while P < FSourceEnd do begin Inc(P); end; FSaveChar := FSourceEnd[0]; FSourceEnd[0] := #0; end; procedure THTTPParser.SkipBlanks; begin while True do begin case FSourcePtr^ of #0: begin ReadBuffer; if FSourcePtr^ = #0 then Exit; Continue; end; #10: Exit; #33..#255: Exit; end; Inc(FSourcePtr); end; end; function THTTPParser.SourcePos: Int64; begin Result := FOrigin + (FTokenPtr - FBuffer); end; procedure THTTPParser.SkipEOL; begin if Token = toEOL then begin while FTokenPtr^ in [#13, #10] do Inc(FTokenPtr); FSourcePtr := FTokenPtr; if FSourcePtr^ <> #0 then NextToken else FToken := #0; end; end; function THTTPParser.TokenFloat: Extended; begin Result := StrToFloat(string(TokenString)); end; function THTTPParser.TokenInt: Longint; begin Result := StrToInt(string(TokenString)); end; function THTTPParser.TokenString: UTF8String; var L: Int64; begin if FToken = Web.HTTPParse.toString then L := FStringPtr - FTokenPtr else L := FSourcePtr - FTokenPtr; SetString(Result, FTokenPtr, L); end; function THTTPParser.TokenSymbolIs(const S: UTF8String): Boolean; begin Result := (Token = toSymbol) and (StrComp(PUTF8Char(S), PUTF8Char(TokenString)) = 0); end; end.
unit CachedBuffers; {******************************************************************************} { Copyright (c) Dmitry Mozulyov } { } { 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. } { } { email: softforyou@inbox.ru } { skype: dimandevil } { repository: https://github.com/d-mozulyov/CachedBuffers } {******************************************************************************} // compiler directives {$ifdef FPC} {$MODE DELPHIUNICODE} {$ASMMODE INTEL} {$define INLINESUPPORT} {$define INLINESUPPORTSIMPLE} {$define OPERATORSUPPORT} {$define STATICSUPPORT} {$define GENERICSUPPORT} {$define ANSISTRSUPPORT} {$define SHORTSTRSUPPORT} {$define WIDESTRSUPPORT} {$ifdef MSWINDOWS} {$define WIDESTRLENSHIFT} {$endif} {$define INTERNALCODEPAGE} {$ifdef CPU386} {$define CPUX86} {$endif} {$ifdef CPUX86_64} {$define CPUX64} {$endif} {$if Defined(CPUARM) or Defined(UNIX)} {$define POSIX} {$ifend} {$else} {$if CompilerVersion >= 24} {$LEGACYIFEND ON} {$ifend} {$if CompilerVersion >= 15} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ifend} {$if CompilerVersion >= 20} {$define INLINESUPPORT} {$ifend} {$if CompilerVersion >= 17} {$define INLINESUPPORTSIMPLE} {$ifend} {$if CompilerVersion >= 18} {$define OPERATORSUPPORT} {$ifend} {$if CompilerVersion >= 18.5} {$define STATICSUPPORT} {$ifend} {$if CompilerVersion >= 20} {$define GENERICSUPPORT} {$define SYSARRAYSUPPORT} {$ifend} {$if CompilerVersion < 23} {$define CPUX86} {$ifend} {$if CompilerVersion >= 23} {$define UNITSCOPENAMES} {$define RETURNADDRESS} {$ifend} {$if CompilerVersion >= 21} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$define EXTENDEDRTTI} {$ifend} {$if CompilerVersion >= 33} {$define MANAGEDRECORDS} {$ifend} {$if (not Defined(NEXTGEN)) or (CompilerVersion >= 31)} {$define ANSISTRSUPPORT} {$ifend} {$ifNdef NEXTGEN} {$define SHORTSTRSUPPORT} {$endif} {$if Defined(MSWINDOWS) or (Defined(MACOS) and not Defined(IOS))} {$define WIDESTRSUPPORT} {$ifend} {$if Defined(MSWINDOWS) or (Defined(WIDESTRSUPPORT) and (CompilerVersion <= 21))} {$define WIDESTRLENSHIFT} {$ifend} {$if Defined(ANSISTRSUPPORT) and (CompilerVersion >= 20)} {$define INTERNALCODEPAGE} {$ifend} {$if Defined(NEXTGEN)} {$POINTERMATH ON} {$ifend} {$endif} {$U-}{$V+}{$B-}{$X+}{$T+}{$P+}{$H+}{$J-}{$Z1}{$A4} {$O+}{$R-}{$I-}{$Q-}{$W-} {$ifdef CPUX86} {$if not Defined(NEXTGEN)} {$define CPUX86ASM} {$define CPUINTELASM} {$ifend} {$define CPUINTEL} {$endif} {$ifdef CPUX64} {$if (not Defined(POSIX)) or Defined(FPC)} {$define CPUX64ASM} {$define CPUINTELASM} {$ifend} {$define CPUINTEL} {$endif} {$if Defined(CPUINTEL) and Defined(POSIX)} {$ifdef CPUX86} {$define POSIXINTEL32} {$else} {$define POSIXINTEL64} {$endif} {$ifend} {$if Defined(CPUX64) or Defined(CPUARM64)} {$define LARGEINT} {$else} {$define SMALLINT} {$ifend} {$ifdef KOL_MCK} {$define KOL} {$endif} {$ifdef POSIX} {$undef CPUX86ASM} {$undef CPUX64ASM} {$undef CPUINTELASM} {$endif} interface uses {$ifdef UNITSCOPENAMES}System.Types{$else}Types{$endif}, {$ifdef MSWINDOWS}{$ifdef UNITSCOPENAMES}Winapi.Windows{$else}Windows{$endif},{$endif} {$ifdef POSIX} {$ifdef FPC} BaseUnix, {$else} Posix.String_, Posix.SysStat, Posix.Unistd, {$endif} {$endif} {$ifdef KOL} KOL, err {$else} {$ifdef UNITSCOPENAMES}System.SysUtils{$else}SysUtils{$endif} {$endif}; type // RTL types {$ifdef FPC} PUInt64 = ^UInt64; PBoolean = ^Boolean; PString = ^string; {$else} {$if CompilerVersion < 16} UInt64 = Int64; PUInt64 = ^UInt64; {$ifend} {$if CompilerVersion < 21} NativeInt = Integer; NativeUInt = Cardinal; {$ifend} {$if CompilerVersion < 22} PNativeInt = ^NativeInt; PNativeUInt = ^NativeUInt; {$ifend} PWord = ^Word; {$endif} {$if not Defined(FPC) and (CompilerVersion < 20)} TDate = type TDateTime; TTime = type TDateTime; {$ifend} PDate = ^TDate; PTime = ^TTime; {$if SizeOf(Extended) >= 10} {$define EXTENDEDSUPPORT} {$ifend} TBytes = {$ifdef SYSARRAYSUPPORT}TArray<Byte>{$else}array of Byte{$endif}; PBytes = ^TBytes; {$if Defined(NEXTGEN) and (CompilerVersion >= 31)} AnsiChar = type System.UTF8Char; PAnsiChar = ^AnsiChar; AnsiString = type System.RawByteString; PAnsiString = ^AnsiString; {$ifend} { TCachedObject class } TCachedObject = class; TCachedObjectCallback = procedure (const ASender: TCachedObject; const AParam: Pointer); ICachedObject = interface function GetSelf: TCachedObject {$ifdef AUTOREFCOUNT}unsafe{$endif}; function GetPreallocated: Boolean; function GetRefCount: Integer; property Self: TCachedObject read GetSelf; property Preallocated: Boolean read GetPreallocated; property RefCount: Integer read GetRefCount; end; TCachedObject = class(TObject, IInterface, ICachedObject) {$ifdef INLINESUPPORTSIMPLE} protected const objDestroyingFlag = Integer($80000000); objDisposedFlag = Integer($40000000); objPreallocatedFlag = Integer($20000000); REFCOUNT_MASK = not (objPreallocatedFlag or {$ifdef AUTOREFCOUNT}objDisposedFlag{$else}objDestroyingFlag{$endif}); {$endif} protected {$ifNdef AUTOREFCOUNT} {$if (not Defined(FPC)) and (CompilerVersion >= 29)}[Volatile]{$ifend} FRefCount: Integer; {$endif} function GetSelf: TCachedObject {$ifdef AUTOREFCOUNT}unsafe{$endif}; function GetPreallocated: Boolean; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} function GetRefCount: Integer; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} function QueryInterface({$ifdef FPC}constref{$else}const{$endif} IID: TGUID; out Obj): {$if (not Defined(FPC)) or Defined(MSWINDOWS)}HResult; stdcall{$else}Longint; cdecl{$ifend}; function _AddRef: {$if (not Defined(FPC)) or Defined(MSWINDOWS)}Integer; stdcall{$else}Longint; cdecl{$ifend}; function _Release: {$if (not Defined(FPC)) or Defined(MSWINDOWS)}Integer; stdcall{$else}Longint; cdecl{$ifend}; public class function NewInstance: TObject {$ifdef AUTOREFCOUNT}unsafe{$ENDIF}; override; class function PreallocatedInstance(const AMemory: Pointer; const ASize: Integer): TObject {$ifdef AUTOREFCOUNT}unsafe{$ENDIF}; virtual; class procedure PreallocatedCall(const AParam: Pointer; const ACallback: TCachedObjectCallback); overload; class procedure PreallocatedCall(const AParam: Pointer; const ASize: Integer; const ACallback: TCachedObjectCallback); overload; procedure FreeInstance; override; procedure AfterConstruction; override; procedure BeforeDestruction; override; destructor Destroy; override; {$ifdef AUTOREFCOUNT} function __ObjAddRef: Integer; override; function __ObjRelease: Integer; override; {$endif} property Preallocated: Boolean read GetPreallocated; property RefCount: Integer read GetRefCount; end; TCachedObjectClass = class of TCachedObject; { ECachedBuffer class } ECachedBuffer = class(Exception) {$ifdef KOL} constructor Create(const Msg: string); constructor CreateFmt(const Msg: string; const Args: array of const); constructor CreateRes(Ident: NativeUInt); overload; constructor CreateRes(ResStringRec: PResStringRec); overload; constructor CreateResFmt(Ident: NativeUInt; const Args: array of const); overload; constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const); overload; {$endif} end; { TCachedBufferMemory record } TCachedBufferMemory = {$ifdef OPERATORSUPPORT}record{$else}object{$endif} public Handle: Pointer; PreviousSize: NativeUInt; Data: Pointer; Size: NativeUInt; Additional: Pointer; AdditionalSize: NativeUInt; private function GetEmpty: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} function GetFixed: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} function GetPreallocated: Boolean; {$ifdef INLINESUPPORT}inline;{$endif} public property Empty: Boolean read GetEmpty; property Fixed: Boolean read GetFixed; property Preallocated: Boolean read GetPreallocated; end; PCachedBufferMemory = ^TCachedBufferMemory; { TCachedBuffer abstract class } TCachedBufferKind = (cbReader, cbWriter); TCachedBuffer = class; TCachedBufferCallback = function(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt of object; TCachedBufferProgress = procedure(const ASender: TCachedBuffer; var ACancel: Boolean) of object; TCachedBuffer = class(TCachedObject) protected FMemory: TCachedBufferMemory; FKind: TCachedBufferKind; FFinishing: Boolean; FEOF: Boolean; FLimited: Boolean; FPositionBase: Int64; FLimit: Int64; FStart: PByte; FOverflow: PByte; FHighWritten: PByte; FCallback: TCachedBufferCallback; FOnProgress: TCachedBufferProgress; class function GetOptimalBufferSize(const AValue, ADefValue: NativeUInt; const ALimit: Int64 = 0): NativeUInt; function GetMargin: NativeInt; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} function GetPosition: Int64; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure SetEOF(const AValue: Boolean); procedure SetLimit(const AValue: Int64); function CheckLimit(const AValue: Int64): Boolean; virtual; function DoFlush: NativeUInt; function DoWriterFlush: Boolean; function DoReaderFlush: Boolean; function DoProgress: Boolean; {$ifdef FPC} public {$endif} constructor Create(const AKind: TCachedBufferKind; const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt = 0); public class function PreallocatedInstance(const AMemory: Pointer; const ASize: Integer): TObject; override; class procedure PreallocatedCall(const AParam: Pointer; const ABufferSize: NativeUInt; const ACallback: TCachedObjectCallback); reintroduce; procedure AfterConstruction; override; procedure BeforeDestruction; override; destructor Destroy; override; public Current: PByte; function Flush: NativeUInt; property Kind: TCachedBufferKind read FKind; property Overflow: PByte read FOverflow; property Margin: NativeInt read GetMargin; property EOF: Boolean read FEOF write SetEOF; property Limited: Boolean read FLimited; property Limit: Int64 read FLimit write SetLimit; property Memory: TCachedBufferMemory read FMemory; property Position: Int64 read GetPosition; property OnProgress: TCachedBufferProgress read FOnProgress write FOnProgress; end; TCachedBufferClass = class of TCachedBuffer; { TCachedReader class } TCachedWriter = class; TCachedReader = class(TCachedBuffer) protected procedure OverflowRead(var ABuffer; ASize: NativeUInt); function DoDirectPreviousRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; virtual; function DoDirectFollowingRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; virtual; procedure OverflowSkip(ASize: NativeUInt); public constructor Create(const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt = 0); procedure DirectRead(const APosition: Int64; var ABuffer; const ACount: NativeUInt); property Finishing: Boolean read FFinishing; procedure Skip(const ACount: NativeUInt); {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure Export(const AWriter: TCachedWriter; const ACount: NativeUInt = 0); {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} // TStream-like data reading procedure Read(var ABuffer; const ACount: NativeUInt); procedure ReadData(var AValue: Boolean); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifdef ANSISTRSUPPORT} procedure ReadData(var AValue: AnsiChar); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$endif} procedure ReadData(var AValue: WideChar); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: ShortInt); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Byte); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: SmallInt); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Word); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Integer); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Cardinal); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Int64); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$if Defined(FPC) or (CompilerVersion >= 16)} procedure ReadData(var AValue: UInt64); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} procedure ReadData(var AValue: Single); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: Double); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$if (not Defined(FPC)) or Defined(EXTENDEDSUPPORT)} procedure ReadData(var AValue: Extended); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} {$if not Defined(FPC) and (CompilerVersion >= 23)} procedure ReadData(var AValue: TExtended80Rec); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} procedure ReadData(var AValue: Currency); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: TPoint); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure ReadData(var AValue: TRect); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifdef SHORTSTRSUPPORT} procedure ReadData(var AValue: ShortString); overload; {$endif} {$ifdef ANSISTRSUPPORT} procedure ReadData(var AValue: AnsiString{$ifdef INTERNALCODEPAGE}; ACodePage: Word = 0{$endif}); overload; {$endif} {$ifdef MSWINDOWS} procedure ReadData(var AValue: WideString); overload; {$endif} {$ifdef UNICODE} procedure ReadData(var AValue: UnicodeString); overload; {$endif} procedure ReadData(var AValue: TBytes); overload; procedure ReadData(var AValue: Variant); overload; end; { TCachedWriter class } TCachedWriter = class(TCachedBuffer) protected procedure OverflowWrite(const ABuffer; ASize: NativeUInt); function DoDirectPreviousWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; virtual; function DoDirectFollowingWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; virtual; public constructor Create(const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt = 0); procedure DirectWrite(const APosition: Int64; const ABuffer; const ACount: NativeUInt); procedure Import(const AReader: TCachedReader; const ACount: NativeUInt = 0); // TStream-like data writing procedure Write(const ABuffer; const ACount: NativeUInt); procedure WriteData(const AValue: Boolean); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifdef ANSISTRSUPPORT} procedure WriteData(const AValue: AnsiChar); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$endif} procedure WriteData(const AValue: WideChar); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: ShortInt); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Byte); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: SmallInt); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Word); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Integer); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Cardinal); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Int64); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$if Defined(FPC) or (CompilerVersion >= 16)} procedure WriteData(const AValue: UInt64); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} procedure WriteData(const AValue: Single); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Double); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$if (not Defined(FPC)) or Defined(EXTENDEDSUPPORT)} procedure WriteData(const AValue: Extended); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} {$if not Defined(FPC) and (CompilerVersion >= 23)} procedure WriteData(const AValue: TExtended80Rec); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifend} procedure WriteData(const AValue: Currency); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: TPoint); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: TRect); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$ifdef SHORTSTRSUPPORT} procedure WriteData(const AValue: ShortString); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$endif} {$ifdef ANSISTRSUPPORT} procedure WriteData(const AValue: AnsiString); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$endif} {$ifdef MSWINDOWS} procedure WriteData(const AValue: WideString); overload; {$endif} {$ifdef UNICODE} procedure WriteData(const AValue: UnicodeString); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} {$endif} procedure WriteData(const AValue: TBytes); overload; {$ifdef INLINESUPPORTSIMPLE}inline;{$endif} procedure WriteData(const AValue: Variant); overload; end; { TCachedReReader class } TCachedReReader = class(TCachedReader) protected FSource: TCachedReader; FOwner: Boolean; public constructor Create(const ACallback: TCachedBufferCallback; const ASource: TCachedReader; const AOwner: Boolean = False; const ABufferSize: NativeUInt = 0); destructor Destroy; override; property Source: TCachedReader read FSource; property Owner: Boolean read FOwner write FOwner; end; { TCachedReWriter class } TCachedReWriter = class(TCachedWriter) protected FTarget: TCachedWriter; FOwner: Boolean; public constructor Create(const ACallback: TCachedBufferCallback; const ATarget: TCachedWriter; const AOwner: Boolean = False; const ABufferSize: NativeUInt = 0); destructor Destroy; override; property Target: TCachedWriter read FTarget; property Owner: Boolean read FOwner write FOwner; end; { TCachedFileReader class } TCachedFileReader = class(TCachedReader) protected FFileName: string; FHandle: THandle; FHandleOwner: Boolean; FOffset: Int64; procedure InternalCreate(const ASize: Int64; const ASeeked: Boolean); function CheckLimit(const AValue: Int64): Boolean; override; function DoDirectPreviousRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; override; function DoDirectFollowingRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; override; function InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; public constructor Create(const AFileName: string; const AOffset: Int64 = 0; const ASize: Int64 = 0); constructor CreateHandled(const AHandle: THandle; const ASize: Int64 = 0; const AHandleOwner: Boolean = False); destructor Destroy; override; property FileName: string read FFileName; property Handle: THandle read FHandle; property HandleOwner: Boolean read FHandleOwner write FHandleOwner; property Offset: Int64 read FOffset; end; { TCachedFileWriter class } TCachedFileWriter = class(TCachedWriter) protected FFileName: string; FHandle: THandle; FHandleOwner: Boolean; FOffset: Int64; function DoDirectPreviousWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; override; function DoDirectFollowingWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; override; function InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; public constructor Create(const AFileName: string; const ASize: Int64 = 0); constructor CreateHandled(const AHandle: THandle; const ASize: Int64 = 0; const AHandleOwner: Boolean = False); destructor Destroy; override; property FileName: string read FFileName; property Handle: THandle read FHandle; property HandleOwner: Boolean read FHandleOwner write FHandleOwner; property Offset: Int64 read FOffset; end; { TCachedMemoryReader class } TCachedMemoryReader = class(TCachedReader) protected FPtr: Pointer; FSize: NativeUInt; FPtrMargin: NativeUInt; function CheckLimit(const AValue: Int64): Boolean; override; function InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; function FixedCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; public constructor Create(const APtr: Pointer; const ASize: NativeUInt; const AFixed: Boolean = False); property Ptr: Pointer read FPtr; property Size: NativeUInt read FSize; end; { TCachedMemoryWriter class } TCachedMemoryWriter = class(TCachedWriter) protected FTemporary: Boolean; FPtr: Pointer; FSize: NativeUInt; FPtrMargin: NativeUInt; function CheckLimit(const AValue: Int64): Boolean; override; function InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; function InternalTemporaryCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; function FixedCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; public constructor Create(const APtr: Pointer; const ASize: NativeUInt; const AFixed: Boolean = False); constructor CreateTemporary; destructor Destroy; override; property Temporary: Boolean read FTemporary; property Ptr: Pointer read FPtr; property Size: NativeUInt read FSize; end; { TCachedResourceReader class } TCachedResourceReader = class(TCachedMemoryReader) protected HGlobal: THandle; procedure InternalCreate(AInstance: THandle; AName, AResType: PChar; AFixed: Boolean); public constructor Create(const AInstance: THandle; const AResName: string; const AResType: PChar; const AFixed: Boolean = False); constructor CreateFromID(const AInstance: THandle; const AResID: Word; const AResType: PChar; const AFixed: Boolean = False); destructor Destroy; override; end; // fast non-collision Move realization procedure NcMove(const Source; var Dest; const Size: NativeUInt); {$ifNdef CPUINTELASM}inline;{$endif} implementation {$ifNdef ANSISTRSUPPORT} type AnsiChar = type Byte; PAnsiChar = ^AnsiChar; {$endif} {$ifdef FPC} const INVALID_HANDLE_VALUE = THandle(-1); {$endif} const KB_SIZE = 1024; MEMORY_PAGE_SIZE = 4 * KB_SIZE; DEFAULT_CACHED_SIZE = 64 * KB_SIZE; MAX_PREALLOCATED_SIZE = 20 * MEMORY_PAGE_SIZE; // 80KB { Exceptions } procedure RaisePointers; begin raise ECachedBuffer.Create('Invalid current, overflow or buffer memory values'); end; procedure RaiseEOF; begin raise ECachedBuffer.Create('EOF buffer data modified'); end; procedure RaiseReading; begin raise ECachedBuffer.Create('Data reading error'); end; procedure RaiseWriting; begin raise ECachedBuffer.Create('Data writing error'); end; procedure RaiseLimitValue(const AValue: Int64); begin raise ECachedBuffer.CreateFmt('Invalid limit value %d', [AValue]); end; procedure RaiseVaraintType(const VType: Word); begin raise ECachedBuffer.CreateFmt('Invalid variant type 0x%.4x', [VType]); end; { Utilitarian functions } {$if Defined(FPC) or (CompilerVersion < 24)} {$ifdef FPC} function AtomicIncrement(var Target: Integer): Integer; inline; begin Result := InterLockedIncrement(Target); end; {$else .DELPHI} function AtomicIncrement(var Target: Integer): Integer; asm {$ifdef CPUX86} mov edx, 1 lock xadd [eax], edx lea eax, [edx - 1] {$else .CPUX64} mov eax, 1 lock xadd [RCX], eax dec eax {$endif} end; {$endif} {$ifdef FPC} function AtomicDecrement(var Target: Integer): Integer; inline; begin Result := InterLockedDecrement(Target); end; {$else .DELPHI} function AtomicDecrement(var Target: Integer): Integer; asm {$ifdef CPUX86} or edx, -1 lock xadd [eax], edx lea eax, [edx - 1] {$else .CPUX64} or eax, -1 lock xadd [RCX], eax dec eax {$endif} end; {$endif} {$ifend} function AllocateCachedBufferMemory(const APreviousSize, ABufferSize: NativeUInt): TCachedBufferMemory; var LOffset: NativeUInt; begin // detect sizes Result.PreviousSize := (APreviousSize + MEMORY_PAGE_SIZE - 1) and -MEMORY_PAGE_SIZE; Result.AdditionalSize := MEMORY_PAGE_SIZE; if (ABufferSize = 0) then begin Result.Size := DEFAULT_CACHED_SIZE; end else begin Result.Size := (ABufferSize + MEMORY_PAGE_SIZE - 1) and -MEMORY_PAGE_SIZE; end; // allocate GetMem(Result.Handle, Result.PreviousSize + Result.Size + Result.AdditionalSize + MEMORY_PAGE_SIZE); // align LOffset := NativeUInt(Result.Handle) and (MEMORY_PAGE_SIZE - 1); Inc(Result.PreviousSize, MEMORY_PAGE_SIZE - LOffset); Inc(Result.AdditionalSize, LOffset); Result.Data := Pointer(NativeUInt(Result.Handle) + Result.PreviousSize); Result.Additional := Pointer(NativeUInt(Result.Data) + Result.Size); end; function GetFileSize(AHandle: THandle): Int64; var {$ifdef MSWINDOWS} P: TPoint; {$endif} {$ifdef POSIX} S: {$ifdef FPC}Stat{$else}_stat{$endif}; {$endif} begin {$ifdef MSWINDOWS} P.X := {$ifdef UNITSCOPENAMES}Winapi.{$endif}Windows.GetFileSize(AHandle, Pointer(@P.Y)); if (P.Y = -1) then P.X := -1; Result := PInt64(@P)^; {$endif} {$ifdef POSIX} if ({$ifdef FPC}FpFStat{$else}fstat{$endif}(AHandle, S) = 0) then Result := S.st_size else Result := -1; {$endif} end; function DirectCachedFileMethod(const AInstance: TCachedBuffer; const AInstanceHandle: THandle; const AInstanceOffset, APosition: Int64; const AData: PByte; const ASize: NativeUInt): Boolean; var LSeekValue: Int64; LPositionValue: Int64; begin LSeekValue := FileSeek(AInstanceHandle, Int64(0), 1{soFromCurrent}); try LPositionValue := APosition + AInstanceOffset; if (LPositionValue <> FileSeek(AInstanceHandle, LPositionValue, 0{soFromBeginning})) then begin Result := False; end else begin Result := (ASize = AInstance.FCallback(AInstance, AData, ASize)); end; finally FileSeek(AInstanceHandle, LSeekValue, 0{soFromBeginning}); end; end; { TCachedObject } {$ifNdef INLINESUPPORTSIMPLE} const objDestroyingFlag = Integer($80000000); objDisposedFlag = Integer($40000000); objPreallocatedFlag = Integer($20000000); REFCOUNT_MASK = not (objPreallocatedFlag or {$ifdef AUTOREFCOUNT}objDisposedFlag{$else}objDestroyingFlag{$endif}); {$endif} class function TCachedObject.NewInstance: TObject; var LSize: Integer; LMemory: Pointer; begin LSize := PInteger(NativeInt(Self) + vmtInstanceSize)^; GetMem(LMemory, LSize); Result := InitInstance(LMemory); TCachedObject(Result).FRefCount := 1; end; class function TCachedObject.PreallocatedInstance(const AMemory: Pointer; const ASize: Integer): TObject; var LSize: Integer; LMemory: Pointer; begin LSize := PInteger(NativeInt(Self) + vmtInstanceSize)^; if (ASize >= LSize) then begin LMemory := Pointer((NativeInt(AMemory) + 15) and -16); if (ASize < LSize + (NativeInt(LMemory) - NativeInt(AMemory))) then begin LMemory := Pointer((NativeInt(AMemory) + 7) and -8); if (ASize < LSize + (NativeInt(LMemory) - NativeInt(AMemory))) then begin LMemory := Pointer((NativeInt(AMemory) + 3) and -4); if (ASize < LSize + (NativeInt(LMemory) - NativeInt(AMemory))) then begin LMemory := Pointer((NativeInt(AMemory) + 1) and -2); if (ASize < LSize + (NativeInt(LMemory) - NativeInt(AMemory))) then begin LMemory := AMemory; end; end; end; end; Result := InitInstance(LMemory); TCachedObject(Result).FRefCount := 1 or objPreallocatedFlag; end else begin GetMem(LMemory, LSize); Result := InitInstance(LMemory); TCachedObject(Result).FRefCount := 1; end; end; procedure CachedPreallocatedCall_1(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..1 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_2(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..2 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_3(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..3 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_4(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..4 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_5(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..5 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_6(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..6 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_7(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..7 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_8(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..8 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_9(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..9 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_10(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..10 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_11(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..11 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_12(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..12 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_13(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..13 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_14(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..14 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_15(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..15 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_16(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..16 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_17(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..17 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_18(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..18 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_19(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..19 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; procedure CachedPreallocatedCall_20(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); var LBuffer: array[0..20 * MEMORY_PAGE_SIZE + 15] of Byte; begin ACallback(TCachedObject(AClass.PreallocatedInstance(@LBuffer, SizeOf(LBuffer))), AParam); end; type TCachedPreallocatedCall = procedure(const AClass: TCachedObjectClass; const AParam: Pointer; const ACallback: TCachedObjectCallback); const CACHED_PREALLOCATED_CALLS: array[1..MAX_PREALLOCATED_SIZE div MEMORY_PAGE_SIZE] of TCachedPreallocatedCall = ( CachedPreallocatedCall_1, CachedPreallocatedCall_2, CachedPreallocatedCall_3, CachedPreallocatedCall_4, CachedPreallocatedCall_5, CachedPreallocatedCall_6, CachedPreallocatedCall_7, CachedPreallocatedCall_8, CachedPreallocatedCall_9, CachedPreallocatedCall_10, CachedPreallocatedCall_11, CachedPreallocatedCall_12, CachedPreallocatedCall_13, CachedPreallocatedCall_14, CachedPreallocatedCall_15, CachedPreallocatedCall_16, CachedPreallocatedCall_17, CachedPreallocatedCall_18, CachedPreallocatedCall_19, CachedPreallocatedCall_20 ); class procedure TCachedObject.PreallocatedCall(const AParam: Pointer; const ACallback: TCachedObjectCallback); var LSize: Integer; begin LSize := PInteger(NativeInt(Self) + vmtInstanceSize)^; PreallocatedCall(AParam, LSize, ACallback); end; class procedure TCachedObject.PreallocatedCall(const AParam: Pointer; const ASize: Integer; const ACallback: TCachedObjectCallback); begin case ASize of 1..MAX_PREALLOCATED_SIZE: begin CACHED_PREALLOCATED_CALLS[ASize shr 12](Self, AParam, ACallback); end; else ACallback(TCachedObject(Self.NewInstance), AParam); end; end; procedure TCachedObject.FreeInstance; begin CleanupInstance; if (FRefCount and objPreallocatedFlag = 0) then FreeMem(Pointer(Self)); end; procedure TCachedObject.AfterConstruction; begin {$ifNdef AUTOREFCOUNT} if (FRefCount and REFCOUNT_MASK = 1) then begin Dec(FRefCount); end else begin AtomicDecrement(FRefCount); end; {$endif} end; procedure TCachedObject.BeforeDestruction; var LRefCount: Integer; begin LRefCount := FRefCount; {$ifdef AUTOREFCOUNT} if (LRefCount and objDestroyingFlag = 0) and (LRefCount and REFCOUNT_MASK = 0) then {$else} if (LRefCount and REFCOUNT_MASK <> 0) then {$endif} System.Error(reInvalidPtr); end; destructor TCachedObject.Destroy; begin inherited; end; function TCachedObject.GetSelf: TCachedObject; begin Result := Self; end; function TCachedObject.GetPreallocated: Boolean; begin Result := (FRefCount and objPreallocatedFlag <> 0); end; function TCachedObject.GetRefCount: Integer; begin Result := FRefCount and REFCOUNT_MASK; end; function TCachedObject.QueryInterface({$ifdef FPC}constref{$else}const{$endif} IID: TGUID; out Obj): {$if (not Defined(FPC)) or Defined(MSWINDOWS)}HResult{$else}Longint{$ifend}; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TCachedObject._AddRef: {$if (not Defined(FPC)) or Defined(MSWINDOWS)}Integer{$else}Longint{$ifend}; begin {$ifdef AUTOREFCOUNT} if (PPointer(PNativeInt(Self)^ + vmtObjAddRef)^ <> @TCachedObject.__ObjAddRef) then begin Result := __ObjAddRef; Exit; end; {$endif} Result := FRefCount; if (Cardinal(Result and REFCOUNT_MASK) <= 1) then begin Inc(Result); FRefCount := Result; end else begin Result := AtomicIncrement(FRefCount); end; Result := Result and REFCOUNT_MASK; end; function TCachedObject._Release: {$if (not Defined(FPC)) or Defined(MSWINDOWS)}Integer{$else}Longint{$ifend}; {$ifdef AUTOREFCOUNT} var LRefCount: Integer; {$endif} begin {$ifdef AUTOREFCOUNT} if (PPointer(PNativeInt(Self)^ + vmtObjRelease)^ <> @TCachedObject.__ObjRelease) then begin Result := __ObjRelease; Exit; end; {$endif} Result := FRefCount; if (Result and REFCOUNT_MASK = 1) then begin Dec(Result); FRefCount := Result; Result := 0; end else begin Result := AtomicDecrement(FRefCount) and REFCOUNT_MASK; if (Result <> 0) then Exit; end; {$ifdef AUTOREFCOUNT} repeat LRefCount := FRefCount; if (LRefCount and objDisposedFlag <> 0) then Break; if (AtomicCmpExchange(FRefCount, LRefCount or (objDestroyingFlag or objDisposedFlag), LRefCount) = LRefCount) then begin Destroy; Exit; end; until (False); FreeInstance; {$else} FRefCount := FRefCount or objDestroyingFlag; Destroy; {$endif} end; {$ifdef AUTOREFCOUNT} function TCachedObject.__ObjAddRef: Integer; begin Result := FRefCount; if (Cardinal(Result and REFCOUNT_MASK) <= 1) then begin Inc(Result); FRefCount := Result; end else begin Result := AtomicIncrement(FRefCount); end; Result := Result and REFCOUNT_MASK; end; function TCachedObject.__ObjRelease: Integer; var LRefCount: Integer; begin Result := FRefCount; if (Result and REFCOUNT_MASK = 1) then begin Dec(Result); FRefCount := Result; Result := 0; end else begin Result := AtomicDecrement(FRefCount) and REFCOUNT_MASK; if (Result <> 0) then Exit; end; repeat LRefCount := FRefCount; if (LRefCount and objDisposedFlag <> 0) then Break; if (AtomicCmpExchange(FRefCount, LRefCount or (objDestroyingFlag or objDisposedFlag), LRefCount) = LRefCount) then begin Destroy; Exit; end; until (False); FreeInstance; end; {$endif} { ECachedBuffer } {$ifdef KOL} constructor ECachedBuffer.Create(const Msg: string); begin inherited Create(e_Custom, Msg); end; constructor ECachedBuffer.CreateFmt(const Msg: string; const Args: array of const); begin inherited CreateFmt(e_Custom, Msg, Args); end; type PStrData = ^TStrData; TStrData = record Ident: Integer; Str: string; end; function EnumStringModules(Instance: NativeInt; Data: Pointer): Boolean; var Buffer: array [0..1023] of Char; begin with PStrData(Data)^ do begin SetString(Str, Buffer, Windows.LoadString(Instance, Ident, Buffer, sizeof(Buffer))); Result := Str = ''; end; end; function FindStringResource(Ident: Integer): string; var StrData: TStrData; Func: TEnumModuleFunc; begin StrData.Ident := Ident; StrData.Str := ''; Pointer(@Func) := @EnumStringModules; EnumResourceModules(Func, @StrData); Result := StrData.Str; end; function LoadStr(Ident: Integer): string; begin Result := FindStringResource(Ident); end; constructor ECachedBuffer.CreateRes(Ident: NativeUInt); begin inherited Create(e_Custom, LoadStr(Ident)); end; constructor ECachedBuffer.CreateRes(ResStringRec: PResStringRec); begin inherited Create(e_Custom, System.LoadResString(ResStringRec)); end; constructor ECachedBuffer.CreateResFmt(Ident: NativeUInt; const Args: array of const); begin inherited CreateFmt(e_Custom, LoadStr(Ident), Args); end; constructor ECachedBuffer.CreateResFmt(ResStringRec: PResStringRec; const Args: array of const); begin inherited CreateFmt(e_Custom, System.LoadResString(ResStringRec), Args); end; {$endif} { TCachedBufferMemory } function TCachedBufferMemory.GetEmpty: Boolean; begin Result := (Data = nil); end; function TCachedBufferMemory.GetFixed: Boolean; begin Result := (PreviousSize = 0) or (AdditionalSize = 0); end; function TCachedBufferMemory.GetPreallocated: Boolean; begin Result := (Handle = nil); end; { TCachedBuffer } class function TCachedBuffer.GetOptimalBufferSize(const AValue, ADefValue: NativeUInt; const ALimit: Int64): NativeUInt; var LSize: NativeUInt; begin if (AValue <> 0) then begin Result := AValue; if (ALimit > 0) and (Result > ALimit) then Result := ALimit; Exit; end; if (ALimit <= 0) or (ALimit >= (ADefValue * 4)) then begin Result := ADefValue; Exit; end; LSize := ALimit; LSize := LSize shr 2; if (LSize = 0) then begin Result := MEMORY_PAGE_SIZE; end else begin Result := (LSize + MEMORY_PAGE_SIZE - 1) and -MEMORY_PAGE_SIZE; end; end; constructor TCachedBuffer.Create(const AKind: TCachedBufferKind; const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt); var LSize: NativeUInt; begin inherited Create; FKind := AKind; FCallback := ACallback; if (not Assigned(FCallback)) then raise ECachedBuffer.Create('Flush callback not defined'); if (FMemory.Empty) then begin LSize := ABufferSize; if (LSize <> 0) and (AKind = cbWriter) and (LSize <= MEMORY_PAGE_SIZE) then Inc(LSize, MEMORY_PAGE_SIZE); FMemory := AllocateCachedBufferMemory(Ord(AKind = cbReader){4kb}, LSize); end; FOverflow := FMemory.Additional; if (AKind = cbWriter) then begin Current := FMemory.Data; FHighWritten := Current; end else begin Current := FOverflow; FPositionBase := -Int64(FMemory.Size); end; FStart := Current; end; class function TCachedBuffer.PreallocatedInstance(const AMemory: Pointer; const ASize: Integer): TObject; var LAlign: NativeInt; LInstanceSize: NativeUInt; LInstanceMemory: Pointer; LMemory: TCachedBufferMemory; begin if (ASize < MEMORY_PAGE_SIZE) then begin Result := inherited PreallocatedInstance(AMemory, ASize); Exit; end; if (ASize < 8 * MEMORY_PAGE_SIZE) then begin LAlign := KB_SIZE; end else begin LAlign := MEMORY_PAGE_SIZE; end; LMemory.Handle := nil; LMemory.Data := Pointer((NativeInt(AMemory) + (LAlign + LAlign - 1)) and -LAlign); LMemory.Additional := Pointer((NativeInt(AMemory) + (ASize - 1) - LAlign) and -LAlign); LMemory.Size := NativeUInt(LMemory.Additional) - NativeUInt(LMemory.Data); LMemory.PreviousSize := NativeUInt(LMemory.Data) - NativeUInt(AMemory); LMemory.AdditionalSize := NativeUInt(AMemory) + NativeUInt(Cardinal(ASize)) - NativeUInt(LMemory.Additional); LInstanceSize := PCardinal(NativeInt(Self) + vmtInstanceSize)^; if (LMemory.PreviousSize > LMemory.AdditionalSize) and (LMemory.PreviousSize - NativeUInt(LAlign) >= LInstanceSize) then begin Result := inherited PreallocatedInstance(AMemory, LMemory.PreviousSize - NativeUInt(LAlign)); LMemory.PreviousSize := LAlign; end else if (LMemory.AdditionalSize - NativeUInt(LAlign) >= LInstanceSize) then begin LInstanceMemory := Pointer(NativeInt(LMemory.Additional) + LAlign); Result := inherited PreallocatedInstance(LInstanceMemory, LMemory.AdditionalSize - NativeUInt(LAlign)); LMemory.AdditionalSize := LAlign; end else if (NativeInt(LMemory.Size + LMemory.AdditionalSize) - NativeInt(LInstanceSize) >= 2 * LAlign) then begin LMemory.Additional := Pointer(NativeInt(NativeUInt(LMemory.Additional) + LMemory.AdditionalSize - LInstanceSize) and -LAlign); LMemory.AdditionalSize := LAlign; LInstanceMemory := Pointer(NativeInt(LMemory.Additional) + LAlign); Result := inherited PreallocatedInstance(LInstanceMemory, NativeUInt(AMemory) + NativeUInt(Cardinal(ASize)) - NativeUInt(LInstanceMemory)); end else begin Result := NewInstance; end; TCachedBuffer(Result).FMemory := LMemory; end; class procedure TCachedBuffer.PreallocatedCall(const AParam: Pointer; const ABufferSize: NativeUInt; const ACallback: TCachedObjectCallback); var LSize, LInstanceSize: NativeUInt; begin case ABufferSize of 1..16 * KB_SIZE: begin LSize := NativeUInt((NativeInt(ABufferSize) + KB_SIZE - 1) and -KB_SIZE) + 3 * KB_SIZE; end; 16 * KB_SIZE + 1..DEFAULT_CACHED_SIZE: begin LSize := NativeUInt((NativeInt(ABufferSize) + MEMORY_PAGE_SIZE - 1) and -MEMORY_PAGE_SIZE) + 3 * MEMORY_PAGE_SIZE; end else LSize := 16 * KB_SIZE + 3 * KB_SIZE; end; LInstanceSize := PCardinal(NativeInt(Self) + vmtInstanceSize)^; LInstanceSize := NativeUInt((NativeInt(LInstanceSize) + KB_SIZE div 2 - 1) and -KB_SIZE); if (LSize + LInstanceSize <= MAX_PREALLOCATED_SIZE) then begin Inc(LSize, LInstanceSize); end; inherited PreallocatedCall(AParam, LSize, ACallback); end; procedure TCachedBuffer.AfterConstruction; begin inherited; DoProgress; end; procedure TCachedBuffer.BeforeDestruction; begin if (Kind = cbWriter) and (not FEOF) and (Assigned(FCallback)) then Flush; inherited; end; destructor TCachedBuffer.Destroy; begin if (not FMemory.Preallocated) then FreeMem(FMemory.Handle); inherited; end; procedure TCachedBuffer.SetEOF(const AValue{True}: Boolean); begin if (FEOF = AValue) then Exit; if (not AValue) then raise ECachedBuffer.Create('Can''t turn off EOF flag'); FEOF := True; FFinishing := False; FLimited := True; FLimit := Self.Position; FStart := Current; FOverflow := Current; end; function TCachedBuffer.DoProgress: Boolean; var LCancel: Boolean; begin if (Assigned(FOnProgress)) then begin LCancel := FEOF; FOnProgress(Self, LCancel); if (LCancel) then SetEOF(True); end; Result := (not FEOF); end; function TCachedBuffer.GetMargin: NativeInt; var P: NativeInt; begin // Result := NativeInt(FOverflow) - NativeInt(Current); P := NativeInt(Current); Result := NativeInt(FOverflow); Dec(Result, P); end; function TCachedBuffer.GetPosition: Int64; begin Result := FPositionBase + (NativeInt(Current) - NativeInt(FMemory.Data)); end; function TCachedBuffer.CheckLimit(const AValue: Int64): Boolean; begin Result := True; end; procedure TCachedBuffer.SetLimit(const AValue: Int64); var LPosition, LMarginLimit: Int64; LMargin: NativeInt; begin if (FLimited) and (AValue = FLimit) then Exit; // check limit value LPosition := Self.Position; if (FEOF) or (AValue < 0) or (LPosition > AValue) or ({IsReader and} FFinishing and (AValue > (LPosition + Self.Margin))) or (not CheckLimit(AValue)) then RaiseLimitValue(AValue); // fill parameters FLimited := True; FLimit := AValue; // detect margin limit is too small LMarginLimit := AValue - LPosition; LMargin := Self.Margin; if (LMarginLimit <= LMargin) then begin // correct Margin to MarginLimit value Dec(FOverflow, LMargin - NativeInt(LMarginLimit)); // Finishing & EOF if (Kind = cbReader) then begin FFinishing := True; if (Current = FOverflow) then begin SetEOF({EOF := }True); DoProgress; end; end; end; end; function TCachedBuffer.Flush: NativeUInt; var LDone: Boolean; begin LDone := False; try Result := DoFlush; LDone := True; finally if (not LDone) then begin SetEOF({EOF := }True); end; end; end; function TCachedBuffer.DoFlush: NativeUInt; var LCurrent, LOverflow, LMemoryLow, LMemoryHigh: NativeUInt; LNewPositionBase: Int64; LNewEOF: Boolean; begin // out of range test LCurrent := NativeUInt(Current); LOverflow := NativeUInt(FOverflow); LMemoryLow := NativeUInt(FStart); LMemoryHigh := NativeUInt(FMemory.Additional) + FMemory.AdditionalSize; if (LMemoryLow <= $ffff) or (LCurrent <= $ffff) or (LOverflow <= $ffff) or (LCurrent < LMemoryLow) or (LCurrent >= LMemoryHigh) or (LOverflow < LMemoryLow) or (LOverflow >= LMemoryHigh) then RaisePointers; // EOF if (FEOF) then begin if (Current <> FOverflow) then RaiseEOF; Result := 0; Exit; end; // valid data reading/writing if (Kind = cbWriter) then begin if (FLimited) and (FLimit < Self.Position) then RaiseWriting; end else begin if (LCurrent > LOverflow) then RaiseReading; end; // idle flush if {IsReader and} (FFinishing) then begin Result := (LOverflow - LCurrent); if (Result = 0) then begin SetEOF(True); DoProgress; end; Exit; end; // flush buffer LNewPositionBase := Self.Position; if (LCurrent > LOverflow) then LNewPositionBase := LNewPositionBase - Int64(LCurrent - LOverflow); LNewEOF := False; if (Kind = cbWriter) then begin if (DoWriterFlush) then LNewEOF := True; end else begin if (DoReaderFlush) then begin FFinishing := True; if (Current = FOverflow{Margin = 0}) then LNewEOF := True; end; end; FPositionBase := LNewPositionBase; if (LNewEOF) then SetEOF(True); DoProgress; // Result Result := Self.Margin; end; function TCachedBuffer.DoWriterFlush: Boolean; var LFlushSize, R: NativeUInt; LOverflowSize: NativeUInt; LMargin: NativeInt; LMarginLimit: Int64; begin // Current correction if (NativeUInt(FHighWritten) > NativeUInt(Current)) then Current := FHighWritten; // flush size LFlushSize := NativeUInt(Current) - NativeUInt(FMemory.Data); Result := (LFlushSize < FMemory.Size); LOverflowSize := 0; if (LFlushSize > FMemory.Size) then begin LOverflowSize := LFlushSize - FMemory.Size; LFlushSize := FMemory.Size; end; // detect margin limit LMarginLimit := High(Int64); if (FLimited) then LMarginLimit := FLimit - Position; // run callback if (LFlushSize <> 0) then begin R := FCallback(Self, FMemory.Data, LFlushSize); if (R <> LFlushSize) then RaiseWriting; end; // current Current := FMemory.Data; if (LOverflowSize <> 0) then begin NcMove(FOverflow^, Current^, LOverflowSize); Inc(Current, LOverflowSize); end; FHighWritten := Current; // overflow correction if (FLimited) then begin LMargin := Self.Margin; if (LMarginLimit < LMargin) then Dec(FOverflow, LMargin - NativeInt(LMarginLimit)); end; end; function TCachedBuffer.DoReaderFlush: Boolean; var LMargin: NativeUInt; LOldMemory, LNewMemory: TCachedBufferMemory; LMarginLimit: Int64; LFlushSize, R: NativeUInt; begin LMargin := Self.Margin; // move margin data to previous memory if (LMargin > 0) then begin if (LMargin > FMemory.PreviousSize) then begin LOldMemory := FMemory; LNewMemory := AllocateCachedBufferMemory(LMargin, FMemory.Size); try NcMove(Current^, Pointer(NativeUInt(LNewMemory.Data) - LMargin)^, LMargin); FMemory := LNewMemory; finally if (not LOldMemory.Preallocated) then FreeMem(LOldMemory.Handle); end; end else begin NcMove(Current^, Pointer(NativeUInt(FMemory.Data) - LMargin)^, LMargin); end; end; // flush size LFlushSize := FMemory.Size; Result := False; if (FLimited) then begin LMarginLimit := FLimit - Position; if (LMarginLimit <= LFlushSize) then begin LFlushSize := LMarginLimit; Result := True; end; end; // run callback if (LFlushSize = 0) then begin R := LFlushSize{0}; end else begin R := FCallback(Self, FMemory.Data, LFlushSize); if (R > LFlushSize) then RaiseReading; if (R < LFlushSize) then Result := True; end; // current/overflow FStart := Pointer(NativeUInt(FMemory.Data) - LMargin); Current := FStart; FOverflow := Pointer(NativeUInt(FMemory.Data) + R); end; {$ifdef CPUX86} var SSE_SUPPORT: Boolean; procedure NcMoveInternal(const Source; var Dest; const Size: NativeUInt); forward; {$endif} procedure TCachedWriter.Write(const ABuffer; const ACount: NativeUInt); {$ifNdef CPUINTELASM} var P: PByte; begin P := Current; Inc(P, ACount); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowWrite(ABuffer, ACount); end else begin Current := P; Dec(P, ACount); NcMove(ABuffer, P^, ACount); end; end; {$else .CPUX86 or .CPUX64} {$ifdef FPC}assembler; nostackframe;{$endif} asm {$ifdef CPUX86} xchg eax, ebx push eax mov eax, ecx add eax, [EBX].TCachedReader.Current cmp eax, [EBX].TCachedReader.FOverflow ja @Difficult mov [EBX].TCachedReader.Current, eax sub eax, ecx xchg eax, edx movzx ebx, byte ptr [SSE_SUPPORT] jmp NcMoveInternal {$else .CPUX64} mov rax, rcx mov rcx, r8 add rcx, [RAX].TCachedReader.Current cmp rcx, [RAX].TCachedReader.FOverflow ja @Difficult mov [RAX].TCachedReader.Current, rcx sub rcx, r8 xchg rcx, rdx jmp NcMove {$endif} @Difficult: {$ifdef CPUX86} xchg eax, ebx pop ebx {$else .CPUX64} xchg rax, rcx {$endif} jmp OverflowWrite end; {$endif} procedure TCachedReader.Read(var ABuffer; const ACount: NativeUInt); {$ifNdef CPUINTELASM} var P: PByte; begin P := Current; Inc(P, ACount); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(ABuffer, ACount); end else begin Current := P; Dec(P, ACount); NcMove(P^, ABuffer, ACount); end; end; {$else .CPUX86 or .CPUX64} {$ifdef FPC}assembler; nostackframe;{$endif} asm {$ifdef CPUX86} xchg eax, ebx push eax mov eax, ecx add eax, [EBX].TCachedReader.Current cmp eax, [EBX].TCachedReader.FOverflow ja @Difficult mov [EBX].TCachedReader.Current, eax sub eax, ecx movzx ebx, byte ptr [SSE_SUPPORT] jmp NcMoveInternal {$else .CPUX64} mov rax, rcx mov rcx, r8 add rcx, [RAX].TCachedReader.Current cmp rcx, [RAX].TCachedReader.FOverflow ja @Difficult mov [RAX].TCachedReader.Current, rcx sub rcx, r8 jmp NcMove {$endif} @Difficult: {$ifdef CPUX86} xchg eax, ebx pop ebx {$else .CPUX64} xchg rax, rcx {$endif} jmp OverflowRead end; {$endif} {$ifNdef CPUINTELASM} // System memcpy recall procedure NcMove(const Source; var Dest; const Size: NativeUInt); begin {$ifdef FPC} Move(Source, Dest, Size); {$else} memcpy(Dest, Source, Size); {$endif} end; {$else .CPUX86 or .CPUX64} // SSE-based non-collision Move realization procedure NcMove(const Source; var Dest; const Size: NativeUInt); {$ifdef FPC}assembler; nostackframe;{$endif} {$ifdef CPUX86} asm push ebx movzx ebx, byte ptr [SSE_SUPPORT] jmp NcMoveInternal end; procedure NcMoveInternal(const Source; var Dest; const Size: NativeUInt); {$ifdef FPC}assembler; nostackframe;{$endif} {$endif} asm // basic routine {$ifdef CPUX86} test ebx, ebx jz @x86_non_SSE cmp ecx, 32 {$else .CPUX64} cmp r8, 32 // make Source = eax/rax, Dest = edx/rdx, Size = ecx/rcx mov rax, rcx xchg rcx, r8 // r9 as pointer to @move_03_items mov r9, offset @move_03_items {$endif} // is big/large (32...inf) jae @move_big // is small (0..3) cmp ecx, 4 jb @move_03 // move middle(4..31) = move 16(0..16) + move dwords(0..12) + move small(0..3) cmp ecx, 16 jb @move_015 {$ifdef CPUX86} movups xmm0, [eax] movups [edx], xmm0 jne @move_015_offset pop ebx ret @move_015_offset: sub ecx, 16 add eax, 16 add edx, 16 @move_015: mov ebx, ecx and ecx, -4 and ebx, 3 add eax, ecx add edx, ecx jmp [ecx + @move_dwords] @move_dwords: DD @rw_0,@rw_4,@rw_8,@rw_12 @rw_12: mov ecx, [eax-12] mov [edx-12], ecx @rw_8: mov ecx, [eax-8] mov [edx-8], ecx @rw_4: mov ecx, [eax-4] mov [edx-4], ecx @rw_0: xchg ecx, ebx {$else .CPUX64} movups xmm0, [rax] movups [rdx], xmm0 jne @move_015_offset ret @move_015_offset: sub rcx, 16 add rax, 16 add rdx, 16 @move_015: // make r9 = dest 0..3 pointer, rcx = dwords count mov r8, rcx shr rcx, 2 and r8, 3 lea r9, [r9 + r8*8] // case jump mov r8, offset @move_dwords jmp qword ptr [r8 + rcx*8] @move_dwords: DQ @rw_0,@rw_4,@rw_8,@rw_12 @rw_8: mov rcx, [rax] mov [rdx], rcx add rax, 8 add rdx, 8 jmp qword ptr [r9] @rw_12: mov rcx, [rax] mov [rdx], rcx add rax, 8 add rdx, 8 @rw_4: mov ecx, [rax] mov [rdx], ecx add rax, 4 add rdx, 4 @rw_0: jmp qword ptr [r9] {$endif} @move_03: {$ifdef CPUX86} jmp [offset @move_03_items + ecx*4] @move_03_items: DD @0,@1,@2,@3 @2: mov cx, [eax] mov [edx], cx pop ebx ret @3: mov cx, [eax] mov [edx], cx add eax, 2 add edx, 2 @1: mov cl, [eax] mov [edx], cl @0: pop ebx ret @x86_non_SSE: // non-SSE 0..15 cmp ecx, 4 jb @move_03 cmp ecx, 16 jb @move_015 // non-SSE dwords mov ebx, ecx shr ecx, 2 xchg esi, eax xchg edi, edx and ebx, 3 rep movsd // non-SSE last 0..3 xchg esi, eax xchg edi, edx jmp [offset @move_03_items + ebx*4] {$else .CPUX64} jmp qword ptr [r9 + rcx*8] @move_03_items: DQ @0,@1,@2,@3 @2: mov cx, [rax] mov [rdx], cx ret @3: mov cx, [rax] mov [rdx], cx add rax, 2 add rdx, 2 @1: mov cl, [rax] mov [rdx], cl @0: ret {$endif} @move_big: {$ifdef CPUX86} cmp ecx, 16*4 {$else .CPUX64} cmp rcx, 16*4 {$endif} jae @move_large // big memory move by SSE (32..63) = (32..48) + (0..15) {$ifdef CPUX86} test ecx, 15 jz @move_32_48 mov ebx, ecx and ecx, 15 movups xmm0, [eax] movups [edx], xmm0 add eax, ecx add edx, ecx and ebx, -16 xchg ecx, ebx {$else .CPUX64} mov r8, rcx test rcx, 15 jz @move_32_48 and r8, 15 movups xmm0, [rax] movups [rdx], xmm0 add rax, r8 add rdx, r8 and rcx, -16 {$endif} @move_32_48: {$ifdef CPUX86} add eax, ecx add edx, ecx cmp ecx, 48 jb @rw_32 @rw_48: movups xmm2, [eax - 2*16 - 16] movups [edx - 2*16 - 16], xmm2 @rw_32: movups xmm1, [eax - 1*16 - 16] movups xmm0, [eax - 0*16 - 16] movups [edx - 1*16 - 16], xmm1 movups [edx - 0*16 - 16], xmm0 pop ebx {$else .CPUX64} add rax, rcx add rdx, rcx cmp rcx, 48 jb @rw_32 @rw_48: movups xmm2, [rax - 2*16 - 16] movups [rdx - 2*16 - 16], xmm2 @rw_32: movups xmm1, [rax - 1*16 - 16] movups xmm0, [rax - 0*16 - 16] movups [rdx - 1*16 - 16], xmm1 movups [rdx - 0*16 - 16], xmm0 {$endif} ret @move_large: // large memory move by SSE (64..inf) // destination alignment {$ifdef CPUX86} test edx, 15 jz @move_16128_initialize mov ebx, edx movups xmm0, [eax] movups [ebx], xmm0 add edx, 15 and edx, -16 sub ebx, edx sub eax, ebx add ecx, ebx {$else .CPUX64} test rdx, 15 jz @move_16128_initialize mov r8, rdx movups xmm0, [rax] movups [r8], xmm0 add rdx, 15 and rdx, -16 sub r8, rdx sub rax, r8 add rcx, r8 {$endif} @move_16128_initialize: {$ifdef CPUX86} push ecx mov ebx, offset @aligned_reads shr ecx, 4 test eax, 15 jz @move_16128 mov ebx, offset @unaligned_reads {$else .CPUX64} movaps [rsp-8-16], xmm6 movaps [rsp-8-32], xmm7 mov r8, rcx mov r9, offset @aligned_reads shr rcx, 4 test rax, 15 jz @move_16128 mov r9, offset @unaligned_reads {$endif} @move_16128: {$ifdef CPUX86} cmp ecx, 8 jae @move_128 lea ecx, [ecx + ecx] lea eax, [eax + ecx*8] lea edx, [edx + ecx*8] lea ebx, [ebx + 8*4] neg ecx lea ebx, [ebx + ecx*2] jmp ebx @move_128: lea eax, [eax + 128] lea edx, [edx + 128] lea ecx, [ecx - 8] jmp ebx {$else .CPUX64} cmp rcx, 8 jae @move_128 lea rcx, [rcx + rcx] lea rax, [rax + rcx*8] lea rdx, [rdx + rcx*8] lea r9, [r9 + 8*4] neg rcx lea r9, [r9 + rcx*2] jmp r9 @move_128: lea rax, [rax + 128] lea rdx, [rdx + 128] lea rcx, [rcx - 8] jmp r9 {$endif} // aligned sse read @aligned_reads: {$ifdef CPUX86} movaps xmm7, [eax - 7*16 - 16] movaps xmm6, [eax - 6*16 - 16] movaps xmm5, [eax - 5*16 - 16] movaps xmm4, [eax - 4*16 - 16] movaps xmm3, [eax - 3*16 - 16] movaps xmm2, [eax - 2*16 - 16] movaps xmm1, [eax - 1*16 - 16] movaps xmm0, [eax - 0*16 - 16] {$else .CPUX64} movaps xmm7, [rax - 7*16 - 16] movaps xmm6, [rax - 6*16 - 16] movaps xmm5, [rax - 5*16 - 16] movaps xmm4, [rax - 4*16 - 16] movaps xmm3, [rax - 3*16 - 16] movaps xmm2, [rax - 2*16 - 16] movaps xmm1, [rax - 1*16 - 16] movaps xmm0, [rax - 0*16 - 16] {$endif} jae @aligned_writes jmp @write_16112 // unaligned sse read @unaligned_reads: {$ifdef CPUX86} movups xmm7, [eax - 7*16 - 16] movups xmm6, [eax - 6*16 - 16] movups xmm5, [eax - 5*16 - 16] movups xmm4, [eax - 4*16 - 16] movups xmm3, [eax - 3*16 - 16] movups xmm2, [eax - 2*16 - 16] movups xmm1, [eax - 1*16 - 16] movups xmm0, [eax - 0*16 - 16] jae @aligned_writes @write_16112: lea ebx, [offset @aligned_writes + 8*4 + ecx*2] jmp ebx {$else .CPUX64} movups xmm7, [rax - 7*16 - 16] movups xmm6, [rax - 6*16 - 16] movups xmm5, [rax - 5*16 - 16] movups xmm4, [rax - 4*16 - 16] movups xmm3, [rax - 3*16 - 16] movups xmm2, [rax - 2*16 - 16] movups xmm1, [rax - 1*16 - 16] movups xmm0, [rax - 0*16 - 16] jae @aligned_writes @write_16112: mov r9, offset @aligned_writes + 8*4 lea r9, [r9 + rcx*2] jmp r9 {$endif} // aligned sse write, loop @aligned_writes: {$ifdef CPUX86} movaps [edx - 7*16 - 16], xmm7 movaps [edx - 6*16 - 16], xmm6 movaps [edx - 5*16 - 16], xmm5 movaps [edx - 4*16 - 16], xmm4 movaps [edx - 3*16 - 16], xmm3 movaps [edx - 2*16 - 16], xmm2 movaps [edx - 1*16 - 16], xmm1 movaps [edx - 0*16 - 16], xmm0 test ecx, ecx {$else .CPUX64} movaps [rdx - 7*16 - 16], xmm7 movaps [rdx - 6*16 - 16], xmm6 movaps [rdx - 5*16 - 16], xmm5 movaps [rdx - 4*16 - 16], xmm4 movaps [rdx - 3*16 - 16], xmm3 movaps [rdx - 2*16 - 16], xmm2 movaps [rdx - 1*16 - 16], xmm1 movaps [rdx - 0*16 - 16], xmm0 test rcx, rcx {$endif} jg @move_16128 // last 0..15 bytes {$ifdef CPUX86} pop ecx pop ebx and ecx, 15 jnz @move_115 ret @move_115: add eax, ecx add edx, ecx movups xmm0, [eax - 0*16 - 16] movups [edx - 0*16 - 16], xmm0 {$else .CPUX64} movaps xmm6, [rsp-8-16] movaps xmm7, [rsp-8-32] and r8, 15 jnz @move_115 ret @move_115: add rax, r8 add rdx, r8 movups xmm0, [rax - 0*16 - 16] movups [rdx - 0*16 - 16], xmm0 {$endif} end; {$endif .CPUINTEL} { TCachedReader } constructor TCachedReader.Create(const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt); begin inherited Create(cbReader, ACallback, ABufferSize); end; procedure TCachedReader.DirectRead(const APosition: Int64; var ABuffer; const ACount: NativeUInt); var LDone: Boolean; LPositionHigh: Int64; LCachedLow, LCachedHigh: Int64; LCachedOffset, LBufferOffset, LSize: NativeUInt; {$ifdef SMALLINT} LSize64: Int64; {$endif} begin if (ACount = 0) then Exit; LPositionHigh := APosition + Int64(ACount); LDone := (not FEOF) and (APosition >= 0) and ((not Limited) or (Limit >= LPositionHigh)); if (LDone) then begin LCachedLow := FPositionBase - (NativeInt(FMemory.Data) - NativeInt(FStart)); LCachedHigh := FPositionBase + (NativeInt(FOverflow) - NativeInt(FMemory.Data)); // cached data copy LCachedOffset := 0; LBufferOffset := 0; LSize := 0; if (APosition >= LCachedLow) and (APosition < LCachedHigh) then begin LCachedOffset := (APosition - LCachedLow); LSize := (LCachedHigh - APosition); end else if (LPositionHigh > LCachedLow) and (APosition < LCachedHigh) then begin LBufferOffset := (LCachedLow - APosition); LSize := (LPositionHigh - LCachedLow); end; if (LSize <> 0) then begin if (LSize > ACount) then LSize := ACount; NcMove(Pointer(NativeUInt(FStart) + LCachedOffset)^, Pointer(NativeUInt(@ABuffer) + LBufferOffset)^, LSize); end; // before cached if (APosition < LCachedLow) then begin {$ifdef LARGEINT} LSize := (LCachedLow - APosition); {$else .SMALLINT} LSize64 := (LCachedLow - APosition); LSize := LSize64; if (LSize <> LSize64) then LSize := ACount; {$endif} if (LSize > ACount) then LSize := ACount; LDone := DoDirectPreviousRead(APosition, @ABuffer, LSize); end; // after cached if (LDone) and (LPositionHigh > LCachedHigh) then begin {$ifdef LARGEINT} LSize := (LPositionHigh - LCachedHigh); {$else .SMALLINT} LSize64 := (LPositionHigh - LCachedHigh); LSize := LSize64; if (LSize <> LSize64) then LSize := ACount; {$endif} if (LSize > ACount) then LSize := ACount; LDone := DoDirectFollowingRead(LPositionHigh - Int64(LSize), Pointer(NativeUInt(@ABuffer) + (ACount - LSize)), LSize); end; end; if (not LDone) then raise ECachedBuffer.Create('Direct read failure'); end; function TCachedReader.DoDirectPreviousRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := False; end; function TCachedReader.DoDirectFollowingRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; var LPreviousSize, LFilledSize, LAllocatingSize: NativeUInt; {$ifdef SMALLINT} LAllocatingSize64: Int64; {$endif} LRemovableMemory, LNewMemory: TCachedBufferMemory; LNewStart: Pointer; LFlushSize, R: NativeUInt; LMarginLimit: Int64; begin Result := False; if (NativeUInt(FStart) > NativeUInt(FMemory.Data)) or (NativeUInt(Current) < NativeUInt(FStart)) then Exit; LPreviousSize := NativeUInt(FMemory.Data) - NativeUInt(FStart); LFilledSize := NativeUInt(FOverflow) - NativeUInt(FMemory.Data); {$ifdef LARGEINT} LAllocatingSize := NativeUInt(APosition - Self.FPositionBase) + ASize; {$else .SMALLINT} LAllocatingSize64 := (APosition - Self.FPositionBase) + ASize; LAllocatingSize := LAllocatingSize64; if (LAllocatingSize <> LAllocatingSize64) then Exit; {$endif} // allocate try LNewMemory := AllocateCachedBufferMemory(LPreviousSize or {4kb minimum}1, LAllocatingSize); Result := True; except end; if (not Result) then Exit; // copy data, change pointers LRemovableMemory := LNewMemory; try LNewStart := Pointer(NativeUInt(LNewMemory.Data) - LPreviousSize); NcMove(FStart^, LNewStart^, LPreviousSize + LFilledSize); FStart := LNewStart; Current := Pointer(NativeInt(Current) - NativeInt(FMemory.Data) + NativeInt(LNewMemory.Data)); FOverflow := Pointer(NativeUInt(LNewMemory.Data) + LFilledSize); LRemovableMemory := FMemory; FMemory := LNewMemory; finally if (not LRemovableMemory.Preallocated) then FreeMem(LRemovableMemory.Handle); end; // fill buffer LFlushSize := NativeUInt(FMemory.Additional) - NativeUInt(FOverflow); if (FLimited) then begin LMarginLimit := FLimit - (Self.FPositionBase + Int64(LFilledSize)); if (LMarginLimit <= LFlushSize) then begin LFlushSize := LMarginLimit; FFinishing := True; end; end; R := FCallback(Self, FOverflow, LFlushSize); if (R > LFlushSize) then RaiseReading; if (R < LFlushSize) then FFinishing := True; Inc(FOverflow, R); if (APosition + Int64(ASize) > Self.FPositionBase + Int64(NativeUInt(FOverflow) - NativeUInt(Memory.Data))) then begin Result := False; Exit; end; // data read NcMove(Pointer(NativeUInt(APosition - Self.FPositionBase) + NativeUInt(FMemory.Data))^, AData^, ASize); end; // Margin < Size procedure TCachedReader.OverflowRead(var ABuffer; ASize: NativeUInt); var S: NativeUInt; LData: PByte; LMargin: NativeUInt; begin LData := Pointer(@ABuffer); // last time failure reading if (NativeUInt(Current) > NativeUInt(FOverflow)) then RaiseReading; // limit test if (FLimited) and (Self.Position + Int64(ASize) > FLimit) then RaiseReading; // read Margin if (Current <> FOverflow) then begin LMargin := Self.Margin; NcMove(Current^, LData^, LMargin); Inc(LData, LMargin); Inc(Current, LMargin); Dec(ASize, LMargin); end; // if read data is too large, we can read data directly if (ASize >= FMemory.Size) then begin S := ASize - (ASize mod FMemory.Size); Dec(ASize, S); if (Assigned(FOnProgress)) then begin while (S <> 0) do begin if (FMemory.Size <> FCallback(Self, LData, FMemory.Size)) then RaiseReading; Dec(S, FMemory.Size); Inc(LData, FMemory.Size); Inc(FPositionBase, FMemory.Size); DoProgress; if (FEOF) and ((S <> 0) or (ASize <> 0)) then RaiseReading; end; end else begin if (S <> FCallback(Self, LData, S)) then RaiseReading; Inc(LData, S); Inc(FPositionBase, S); end; end; // last Data bytes if (ASize <> 0) then begin Flush; if (NativeUInt(Self.Margin) < ASize) then RaiseReading; NcMove(Current^, LData^, ASize); Inc(Current, ASize); end; end; procedure TCachedReader.ReadData(var AValue: Boolean); var P: ^Boolean; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$ifdef ANSISTRSUPPORT} procedure TCachedReader.ReadData(var AValue: AnsiChar); var P: ^AnsiChar; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$endif} procedure TCachedReader.ReadData(var AValue: WideChar); var P: ^WideChar; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: ShortInt); var P: ^ShortInt; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Byte); var P: ^Byte; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: SmallInt); var P: ^SmallInt; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Word); var P: ^Word; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Integer); var P: ^Integer; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Cardinal); var P: ^Cardinal; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Int64); var P: ^Int64; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$if Defined(FPC) or (CompilerVersion >= 16)} procedure TCachedReader.ReadData(var AValue: UInt64); var P: ^UInt64; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$ifend} procedure TCachedReader.ReadData(var AValue: Single); var P: ^Single; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: Double); var P: ^Double; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$if (not Defined(FPC)) or Defined(EXTENDEDSUPPORT)} procedure TCachedReader.ReadData(var AValue: Extended); var P: ^Extended; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$ifend} {$if not Defined(FPC) and (CompilerVersion >= 23)} procedure TCachedReader.ReadData(var AValue: TExtended80Rec); var P: ^TExtended80Rec; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$ifend} procedure TCachedReader.ReadData(var AValue: Currency); var P: ^Currency; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: TPoint); var P: ^TPoint; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; procedure TCachedReader.ReadData(var AValue: TRect); var P: ^TRect; begin P := Pointer(Current); Inc(P); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowRead(AValue, SizeOf(AValue)); end else begin Pointer(Current) := P; Dec(P); AValue := P^; end; end; {$ifdef SHORTSTRSUPPORT} procedure TCachedReader.ReadData(var AValue: ShortString{; MaxLength: Byte}); var P: PByte; L, M, S: NativeInt; begin P := Current; if (NativeUInt(P) >= NativeUInt(Self.Overflow)) then begin if (Flush < SizeOf(Byte)) then RaiseReading; P := Current; end; L := P^; Inc(P); Current := P; M := High(AValue); if (M < L) then begin PByte(@AValue)^ := M; S := L - M; Read(AValue[1], M); P := Current; Inc(P, S); Current := P; if (NativeUInt(P) >= NativeUInt(Self.Overflow)) then Flush; end else begin PByte(@AValue)^ := L; Read(AValue[1], L); end; end; {$endif} {$ifdef ANSISTRSUPPORT} procedure TCachedReader.ReadData(var AValue: AnsiString{$ifdef INTERNALCODEPAGE}; ACodePage: Word{$endif}); {$ifdef INTERNALCODEPAGE} const ASTR_OFFSET_CODEPAGE = {$ifdef FPC}SizeOf(NativeInt) * 3{$else .DELPHI}12{$endif}; {$endif} var L: Integer; begin ReadData(L); SetLength(AValue, L); if (L <> 0) then begin {$ifdef INTERNALCODEPAGE} PWord(PAnsiChar(Pointer(AValue)) - ASTR_OFFSET_CODEPAGE)^ := ACodePage; {$endif} Read(Pointer(AValue)^, L); end; end; {$endif} {$ifdef MSWINDOWS} procedure TCachedReader.ReadData(var AValue: WideString); var L: Integer; begin ReadData(L); SetLength(AValue, L); if (L <> 0) then Read(Pointer(AValue)^, L*2); end; {$endif} {$ifdef UNICODE} procedure TCachedReader.ReadData(var AValue: UnicodeString); var L: Integer; begin ReadData(L); SetLength(AValue, L); if (L <> 0) then Read(Pointer(AValue)^, L*2); end; {$endif} procedure TCachedReader.ReadData(var AValue: TBytes); var L: Integer; begin ReadData(L); SetLength(AValue, L); if (L <> 0) then Read(Pointer(AValue)^, L); end; procedure TCachedReader.ReadData(var AValue: Variant); const varDeepData = $BFE8; var LVarData: PVarData; begin LVarData := @TVarData(AValue); if (LVarData.VType and varDeepData <> 0) then begin case LVarData.VType of {$ifdef ANSISTRSUPPORT} varString: begin AnsiString(LVarData.VString) := ''; Exit; end; {$endif} {$ifdef WIDESTRSUPPORT} varOleStr: begin WideString(LVarData.VPointer{VOleStr}) := ''; Exit; end; {$endif} {$ifdef UNICODE} varUString: begin UnicodeString(LVarData.VString) := ''; Exit; end; {$endif} else {$if Defined(FPC) or (CompilerVersion >= 15)} if (Assigned(VarClearProc)) then begin VarClearProc(LVarData^); end else RaiseVaraintType(LVarData.VType); {$else} VarClear(Value); {$ifend} end; end; LVarData.VPointer := nil; ReadData(LVarData.VType); case LVarData.VType of varBoolean, varShortInt, varByte: ReadData(LVarData.VByte); varSmallInt, varWord: ReadData(LVarData.VWord); varInteger, varLongWord, varSingle: ReadData(LVarData.VInteger); varDouble, varCurrency, varDate, varInt64, $15{varUInt64}: ReadData(LVarData.VInt64); {$ifdef ANSISTRSUPPORT} varString: begin ReadData(AnsiString(LVarData.VPointer)); Exit; end; {$endif} {$ifdef WIDESTRSUPPORT} varOleStr: begin ReadData(WideString(LVarData.VPointer)); Exit; end; {$endif} {$ifdef UNICODE} varUString: begin ReadData(UnicodeString(LVarData.VPointer)); Exit; end; {$endif} else RaiseVaraintType(LVarData.VType); end; end; procedure TCachedReader.Skip(const ACount: NativeUInt); var P: PByte; begin P := Current; Inc(P, ACount); if (NativeUInt(P) > NativeUInt(Self.FOverflow)) then begin OverflowSkip(ACount); end else begin Current := P; end; end; procedure TCachedReader.OverflowSkip(ASize: NativeUInt); var S: NativeUInt; LDone: Boolean; begin LDone := False; if (not FEOF) and ((not FLimited) or (FLimit >= (Self.Position + Int64(ASize)))) then begin repeat S := NativeUInt(FOverflow) - NativeUInt(Current); if (S > ASize) then S := ASize; Current := FOverflow; Dec(ASize, S); if (ASize <> 0) then Flush; until (FEOF) or (ASize = 0); LDone := (ASize = 0); end; if (not LDone) then raise ECachedBuffer.Create('Cached reader skip failure'); end; procedure TCachedReader.Export(const AWriter: TCachedWriter; const ACount: NativeUInt); begin AWriter.Import(Self, ACount); end; { TCachedWriter } constructor TCachedWriter.Create(const ACallback: TCachedBufferCallback; const ABufferSize: NativeUInt); begin inherited Create(cbWriter, ACallback, ABufferSize); end; procedure TCachedWriter.DirectWrite(const APosition: Int64; const ABuffer; const ACount: NativeUInt); var LDone: Boolean; LPositionHigh: Int64; LCachedLow, LCachedHigh: Int64; LCachedOffset, LBufferOffset, LSize: NativeUInt; {$ifdef SMALLINT} LSize64: Int64; {$endif} LHighWritten: NativeUInt; begin if (ACount = 0) then Exit; LPositionHigh := APosition + Int64(ACount); LDone := (not FEOF) and (APosition >= 0) and ((not Limited) or (Limit >= LPositionHigh)); if (LDone) then begin LCachedLow := FPositionBase - (NativeInt(FMemory.Data) - NativeInt(FStart)); LCachedHigh := FPositionBase + (NativeInt(FOverflow) - NativeInt(FMemory.Data)); // cached data copy LCachedOffset := 0; LBufferOffset := 0; LSize := 0; if (APosition >= LCachedLow) and (APosition < LCachedHigh) then begin LCachedOffset := (APosition - LCachedLow); LSize := (LCachedHigh - APosition); end else if (LPositionHigh > LCachedLow) and (APosition < LCachedHigh) then begin LBufferOffset := (LCachedLow - APosition); LSize := (LPositionHigh - LCachedLow); end; if (LSize <> 0) then begin if (LSize > ACount) then LSize := ACount; NcMove(Pointer(NativeUInt(@ABuffer) + LBufferOffset)^, Pointer(NativeUInt(FStart) + LCachedOffset)^, LSize); LHighWritten := NativeUInt(FStart) + LCachedOffset + LSize; if (LHighWritten > NativeUInt(Self.FHighWritten)) then Self.FHighWritten := Pointer(LHighWritten); end; // before cached if (APosition < LCachedLow) then begin {$ifdef LARGEINT} LSize := (LCachedLow - APosition); {$else .SMALLINT} LSize64 := (LCachedLow - APosition); LSize := LSize64; if (LSize <> LSize64) then LSize := ACount; {$endif} if (LSize > ACount) then LSize := ACount; LDone := DoDirectPreviousWrite(APosition, @ABuffer, LSize); end; // after cached if (LDone) and (LPositionHigh > LCachedHigh) then begin {$ifdef LARGEINT} LSize := (LPositionHigh - LCachedHigh); {$else .SMALLINT} LSize64 := (LPositionHigh - LCachedHigh); LSize := LSize64; if (LSize <> LSize64) then LSize := ACount; {$endif} if (LSize > ACount) then LSize := ACount; LDone := DoDirectFollowingWrite(LPositionHigh - Int64(LSize), Pointer(NativeUInt(@ABuffer) + (ACount - LSize)), LSize); end; end; if (not LDone) then raise ECachedBuffer.Create('Direct write failure'); end; function TCachedWriter.DoDirectPreviousWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := False; end; function TCachedWriter.DoDirectFollowingWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; var LPreviousSize, LFilledSize, LAllocatingSize: NativeUInt; {$ifdef SMALLINT} LAllocatingSize64: Int64; {$endif} LRemovableMemory, LNewMemory: TCachedBufferMemory; begin Result := False; if (NativeUInt(Current) < NativeUInt(FMemory.Data)) then begin LPreviousSize := NativeUInt(FMemory.Data) - NativeUInt(Current); LFilledSize := 0; end else begin LPreviousSize := 0; LFilledSize := NativeUInt(Current) - NativeUInt(FMemory.Data); end; {$ifdef LARGEINT} LAllocatingSize := NativeUInt(APosition - Self.FPositionBase) + ASize; {$else .SMALLINT} LAllocatingSize64 := (APosition - Self.FPositionBase) + ASize; LAllocatingSize := LAllocatingSize64; if (LAllocatingSize <> LAllocatingSize64) then Exit; {$endif} // allocate try LNewMemory := AllocateCachedBufferMemory(LPreviousSize{default = 0}, LAllocatingSize); Result := True; except end; if (not Result) then Exit; // copy data, change pointers LRemovableMemory := LNewMemory; try NcMove(Pointer(NativeUInt(FMemory.Data) - LPreviousSize)^, Pointer(NativeUInt(LNewMemory.Data) - LPreviousSize)^, LPreviousSize + LFilledSize); Current := Pointer(NativeInt(Current) - NativeInt(FMemory.Data) + NativeInt(LNewMemory.Data)); FOverflow := LNewMemory.Additional; LRemovableMemory := FMemory; FMemory := LNewMemory; finally if (not LRemovableMemory.Preallocated) then FreeMem(LRemovableMemory.Handle); end; // data write FHighWritten := Pointer(NativeUInt(APosition - Self.FPositionBase) + NativeUInt(FMemory.Data)); NcMove(AData^, Pointer(NativeUInt(FHighWritten) - ASize)^, ASize); end; // Margin < Size procedure TCachedWriter.OverflowWrite(const ABuffer; ASize: NativeUInt); var S: NativeUInt; LData: PByte; LMargin: NativeInt; begin LData := Pointer(@ABuffer); // limit test if (FLimited) and (Self.Position + Int64(ASize) > FLimit) then RaiseWriting; // write margin to buffer if used if (Current <> FMemory.Data) then begin if (NativeUInt(Current) < NativeUInt(FOverflow)) then begin LMargin := Self.Margin; NcMove(LData^, Current^, LMargin); Current := Self.Overflow; Inc(LData, LMargin); Dec(ASize, LMargin); end; Flush(); end; // if written data is too large, we can write data directly if (ASize >= FMemory.Size) then begin S := ASize - (ASize mod FMemory.Size); Dec(ASize, S); if (Assigned(FOnProgress)) then begin while (S <> 0) do begin if (FMemory.Size <> FCallback(Self, LData, FMemory.Size)) then RaiseWriting; Dec(S, FMemory.Size); Inc(LData, FMemory.Size); Inc(FPositionBase, FMemory.Size); DoProgress; if (FEOF) and ((S <> 0) or (ASize <> 0)) then RaiseWriting; end; end else begin if (S <> FCallback(Self, LData, S)) then RaiseWriting; Inc(LData, S); Inc(FPositionBase, S); end; end; // last Data bytes if (ASize <> 0) then begin NcMove(LData^, Current^, ASize); Inc(Current, ASize); end; end; procedure TCachedWriter.WriteData(const AValue: Boolean); var P: ^Boolean; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$ifdef ANSISTRSUPPORT} procedure TCachedWriter.WriteData(const AValue: AnsiChar); var P: ^AnsiChar; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$endif} procedure TCachedWriter.WriteData(const AValue: WideChar); var P: ^WideChar; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: ShortInt); var P: ^ShortInt; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Byte); var P: ^Byte; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: SmallInt); var P: ^SmallInt; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Word); var P: ^Word; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Integer); var P: ^Integer; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Cardinal); var P: ^Cardinal; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Int64); var P: ^Int64; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$if Defined(FPC) or (CompilerVersion >= 16)} procedure TCachedWriter.WriteData(const AValue: UInt64); var P: ^UInt64; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$ifend} procedure TCachedWriter.WriteData(const AValue: Single); var P: ^Single; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: Double); var P: ^Double; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$if (not Defined(FPC)) or Defined(EXTENDEDSUPPORT)} procedure TCachedWriter.WriteData(const AValue: Extended); var P: ^Extended; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$ifend} {$if not Defined(FPC) and (CompilerVersion >= 23)} procedure TCachedWriter.WriteData(const AValue: TExtended80Rec); var P: ^TExtended80Rec; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$ifend} procedure TCachedWriter.WriteData(const AValue: Currency); var P: ^Currency; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: TPoint); var P: ^TPoint; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; procedure TCachedWriter.WriteData(const AValue: TRect); var P: ^TRect; begin P := Pointer(Current); P^ := AValue; Inc(P); Pointer(Current) := P; if (NativeUInt(P) >= NativeUInt(Self.FOverflow)) then Flush; end; {$ifdef SHORTSTRSUPPORT} procedure TCachedWriter.WriteData(const AValue: ShortString); begin Write(AValue, Length(AValue) + 1); end; {$endif} {$ifdef ANSISTRSUPPORT} procedure TCachedWriter.WriteData(const AValue: AnsiString); var P: PInteger; begin P := Pointer(AValue); if (P = nil) then begin WriteData(Integer(0)); end else begin {$if Defined(FPC) and Defined(LARGEINT)} Dec(NativeInt(P), SizeOf(NativeInt)); WriteData(P^); Write(Pointer(PAnsiChar(P) + SizeOf(NativeInt))^, P^); {$else} Dec(P); Write(P^, P^ + SizeOf(Integer)); {$ifend} end; end; {$endif} {$ifdef MSWINDOWS} procedure TCachedWriter.WriteData(const AValue: WideString); var P: PInteger; begin P := Pointer(AValue); if (P = nil) then begin WriteData(Integer(0)); end else begin Dec(P); WriteData(P^ shr 1); Write(Pointer(PAnsiChar(P) + SizeOf(Integer))^, P^); end; end; {$endif} {$ifdef UNICODE} procedure TCachedWriter.WriteData(const AValue: UnicodeString); var P: PInteger; begin P := Pointer(AValue); if (P = nil) then begin WriteData(Integer(0)); end else begin {$if Defined(FPC) and Defined(LARGEINT)} Dec(NativeInt(P), SizeOf(NativeInt)); WriteData(P^); Write(Pointer(PAnsiChar(P) + SizeOf(NativeInt))^, P^ shl 1); {$else} Dec(P); Write(P^, P^ shl 1 + SizeOf(Integer)); {$ifend} end; end; {$endif} procedure TCachedWriter.WriteData(const AValue: TBytes); var P: PNativeInt; {$if Defined(FPC) and Defined(LARGEINT)} L: Integer; {$ifend} begin P := Pointer(AValue); if (P = nil) then begin WriteData(Integer(0)); end else begin Dec(P); {$if Defined(FPC) and Defined(LARGEINT)} L := P^ {$ifdef FPC}+ 1{$endif}; Inc(P); WriteData(L); Write(P^, L); {$else} Write(P^, P^ + SizeOf(Integer)); {$ifend} end; end; procedure TCachedWriter.WriteData(const AValue: Variant); var VType: Word; VPtr: Pointer; begin VType := TVarData(AValue).VType; VPtr := @TVarData(AValue).VByte; if (VType and varByRef <> 0) then begin VType := VType and (not varByRef); VPtr := PPointer(VPtr)^; end; WriteData(VType); case VType of varBoolean, varShortInt, varByte: WriteData(PByte(VPtr)^); varSmallInt, varWord: WriteData(PWord(VPtr)^); varInteger, varLongWord, varSingle: WriteData(PInteger(VPtr)^); varDouble, varCurrency, varDate, varInt64, $15{varUInt64}: WriteData(PInt64(VPtr)^); {$ifdef ANSISTRSUPPORT} varString: begin WriteData(PAnsiString(VPtr)^); Exit; end; {$endif} {$ifdef WIDESTRSUPPORT} varOleStr: begin WriteData(PWideString(VPtr)^); Exit; end; {$endif} {$ifdef UNICODE} varUString: begin WriteData(PUnicodeString(VPtr)^); Exit; end; {$endif} else RaiseVaraintType(VType); end; end; procedure TCachedWriter.Import(const AReader: TCachedReader; const ACount: NativeUInt); var LSize, LReadLimit: NativeUInt; begin LReadLimit := ACount; if (ACount = 0) then LReadLimit := High(NativeUInt); if (AReader <> nil) then while (not AReader.EOF) and (LReadLimit <> 0) do begin if (NativeUInt(AReader.Current) > NativeUInt(AReader.Overflow)) then Break; LSize := NativeUInt(AReader.Overflow) - NativeUInt(AReader.Current); if (LSize > LReadLimit) then LSize := LReadLimit; Self.Write(AReader.Current^, LSize); Inc(AReader.Current, LSize); Dec(LReadLimit, LSize); if (LReadLimit <> 0) then AReader.Flush; end; if (LReadLimit <> 0) and (ACount <> 0) then raise ECachedBuffer.Create('Cached writer import failure'); end; { TCachedReReader } constructor TCachedReReader.Create(const ACallback: TCachedBufferCallback; const ASource: TCachedReader; const AOwner: Boolean; const ABufferSize: NativeUInt); begin FSource := ASource; FOwner := AOwner; inherited Create(ACallback, GetOptimalBufferSize(ABufferSize, DEFAULT_CACHED_SIZE, ASource.Limit)); end; destructor TCachedReReader.Destroy; begin if (FOwner) then FSource.Free; inherited; end; { TCachedReWriter } constructor TCachedReWriter.Create(const ACallback: TCachedBufferCallback; const ATarget: TCachedWriter; const AOwner: Boolean; const ABufferSize: NativeUInt); begin FTarget := ATarget; FOwner := AOwner; inherited Create(ACallback, GetOptimalBufferSize(ABufferSize, DEFAULT_CACHED_SIZE, ATarget.Limit)); end; destructor TCachedReWriter.Destroy; begin if (FOwner) then FTarget.Free; inherited; end; { TCachedFileReader } constructor TCachedFileReader.Create(const AFileName: string; const AOffset, ASize: Int64); begin FFileName := AFileName; FHandleOwner := True; FOffset := AOffset; {$ifdef MSWINDOWS} FHandle := {$ifdef UNITSCOPENAMES}Winapi.{$endif}Windows.{$ifdef UNICODE}CreateFileW{$else}CreateFile{$endif} (PChar(AFileName), $0001{FILE_READ_DATA}, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0); {$else} FHandle := FileOpen(AFileName, fmOpenRead or fmShareDenyNone); {$endif} if (FHandle = INVALID_HANDLE_VALUE) then raise ECachedBuffer.CreateFmt('Cannot open file:'#13'%s', [AFileName]); InternalCreate(ASize, (AOffset = 0)); end; constructor TCachedFileReader.CreateHandled(const AHandle: THandle; const ASize: Int64; const AHandleOwner: Boolean); begin FHandle := AHandle; FHandleOwner := AHandleOwner; FOffset := FileSeek(FHandle, Int64(0), 1{soFromCurrent}); if (FHandle = INVALID_HANDLE_VALUE) or (FOffset < 0) then raise ECachedBuffer.Create('Invalid file handle'); InternalCreate(ASize, True); end; procedure TCachedFileReader.InternalCreate(const ASize: Int64; const ASeeked: Boolean); var LFileSize: Int64; begin LFileSize := GetFileSize(FHandle); if (FOffset < 0) or (FOffset > LFileSize) or ((not ASeeked) and (FOffset <> FileSeek(FHandle, FOffset, 0{soFromBeginning}))) then raise ECachedBuffer.CreateFmt('Invalid offset %d in %d bytes file'#13'%s', [FOffset, LFileSize, FFileName]); LFileSize := LFileSize - Offset; if (LFileSize = 0) then begin FKind := cbReader; // inherited Create; EOF := True; end else begin if (ASize > 0) and (ASize < LFileSize) then LFileSize := ASize; inherited Create(InternalCallback, GetOptimalBufferSize(0, DEFAULT_CACHED_SIZE, LFileSize)); Limit := LFileSize; end; end; destructor TCachedFileReader.Destroy; begin inherited; if (FHandleOwner) and (FHandle <> 0) and (FHandle <> INVALID_HANDLE_VALUE) then FileClose(FHandle); end; function TCachedFileReader.CheckLimit(const AValue: Int64): Boolean; begin Result := (AValue <= (GetFileSize(FHandle) - FOffset)); end; function TCachedFileReader.InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; var LCount, LReadingSize: Integer; begin Result := 0; repeat if (ASize > NativeUInt(High(Integer))) then LReadingSize := High(Integer) else LReadingSize := ASize; LCount := FileRead(FHandle, AData^, LReadingSize); if (LCount < 0) then {$ifdef KOL}RaiseLastWin32Error{$else}RaiseLastOSError{$endif}; Inc(AData, LCount); Dec(ASize, LCount); Inc(Result, LCount); until (LCount <> LReadingSize) or (ASize = 0); end; function TCachedFileReader.DoDirectPreviousRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := DirectCachedFileMethod(Self, FHandle, FOffset, APosition, AData, ASize); end; function TCachedFileReader.DoDirectFollowingRead(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := DirectCachedFileMethod(Self, FHandle, FOffset, APosition, AData, ASize); end; { TCachedFileWriter } constructor TCachedFileWriter.Create(const AFileName: string; const ASize: Int64); var LHandle: THandle; begin FFileName := AFileName; {$ifdef MSWINDOWS} LHandle := {$ifdef UNITSCOPENAMES}Winapi.{$endif}Windows.{$ifdef UNICODE}CreateFileW{$else}CreateFile{$endif} (PChar(AFileName), $0002{FILE_WRITE_DATA}, FILE_SHARE_READ, nil, CREATE_ALWAYS, 0, 0); {$else} LHandle := FileCreate(AFileName); {$endif} if (LHandle = INVALID_HANDLE_VALUE) then raise ECachedBuffer.CreateFmt('Cannot create file:'#13'%s', [AFileName]); CreateHandled(LHandle, ASize, True); end; constructor TCachedFileWriter.CreateHandled(const AHandle: THandle; const ASize: Int64; const AHandleOwner: Boolean); begin FHandle := AHandle; FHandleOwner := AHandleOwner; FOffset := FileSeek(FHandle, Int64(0), 1{soFromCurrent}); if (FHandle = INVALID_HANDLE_VALUE) or (FOffset < 0) then raise ECachedBuffer.Create('Invalid file handle'); inherited Create(InternalCallback, GetOptimalBufferSize(0, DEFAULT_CACHED_SIZE, ASize)); if (ASize > 0) then Limit := ASize; end; destructor TCachedFileWriter.Destroy; begin inherited; if (FHandleOwner) and (FHandle <> 0) and (FHandle <> INVALID_HANDLE_VALUE) then FileClose(FHandle); end; function TCachedFileWriter.InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; var LCount, LWritingSize: Integer; begin Result := 0; repeat if (ASize > NativeUInt(High(Integer))) then LWritingSize := High(Integer) else LWritingSize := ASize; LCount := FileWrite(FHandle, AData^, LWritingSize); if (LCount < 0) then {$ifdef KOL}RaiseLastWin32Error{$else}RaiseLastOSError{$endif}; Inc(AData, LCount); Dec(ASize, LCount); Inc(Result, LCount); until (LCount <> LWritingSize) or (ASize = 0); end; function TCachedFileWriter.DoDirectPreviousWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := DirectCachedFileMethod(Self, FHandle, FOffset, APosition, AData, ASize); end; function TCachedFileWriter.DoDirectFollowingWrite(APosition: Int64; AData: PByte; ASize: NativeUInt): Boolean; begin Result := DirectCachedFileMethod(Self, FHandle, FOffset, APosition, AData, ASize); end; { TCachedMemoryReader } constructor TCachedMemoryReader.Create(const APtr: Pointer; const ASize: NativeUInt; const AFixed: Boolean); begin FPtr := APtr; FSize := ASize; FPtrMargin := ASize; if (APtr = nil) or (ASize = 0) then begin FKind := cbReader; // inherited Create; EOF := True; end else if (AFixed) then begin FKind := cbReader; FCallback := FixedCallback; FMemory.Data := APtr; FMemory.Size := ASize; FMemory.Additional := Pointer(NativeUInt(APtr) + ASize); Current := APtr; FOverflow := FMemory.Additional; FStart := APtr; FFinishing := True; Limit := ASize; end else begin inherited Create(InternalCallback, GetOptimalBufferSize(0, DEFAULT_CACHED_SIZE, ASize)); Limit := ASize; end; end; function TCachedMemoryReader.CheckLimit(const AValue: Int64): Boolean; begin Result := (AValue <= Size); end; function TCachedMemoryReader.InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; begin Result := ASize; if (Result > FPtrMargin) then Result := FPtrMargin; NcMove(Pointer(NativeUInt(FPtr) + Self.FSize - FPtrMargin)^, AData^, Result); Dec(FPtrMargin, Result); end; function TCachedMemoryReader.FixedCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; begin RaiseReading; Result := 0; end; { TCachedMemoryWriter } constructor TCachedMemoryWriter.Create(const APtr: Pointer; const ASize: NativeUInt; const AFixed: Boolean); begin FPtr := APtr; FSize := ASize; FPtrMargin := ASize; if (APtr = nil) or (ASize = 0) then begin FKind := cbWriter; // inherited Create; EOF := True; end else if (AFixed) then begin FKind := cbWriter; FCallback := FixedCallback; FMemory.Data := APtr; FMemory.Size := ASize; FMemory.Additional := Pointer(NativeUInt(APtr) + ASize); Current := APtr; FOverflow := FMemory.Additional; FHighWritten := Current; FStart := APtr; Limit := ASize; end else begin inherited Create(InternalCallback, GetOptimalBufferSize(0, DEFAULT_CACHED_SIZE, ASize)); Limit := ASize; end; end; constructor TCachedMemoryWriter.CreateTemporary; begin inherited Create(InternalTemporaryCallback); end; destructor TCachedMemoryWriter.Destroy; begin inherited; if (FTemporary) then FreeMem(FPtr); end; function TCachedMemoryWriter.CheckLimit(const AValue: Int64): Boolean; begin if (not FTemporary) then begin Result := (AValue <= Size); end else begin Result := True; end; end; function TCachedMemoryWriter.InternalCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; begin Result := ASize; if (Result > FPtrMargin) then Result := FPtrMargin; NcMove(AData^, Pointer(NativeUInt(FPtr) + Self.FSize - FPtrMargin)^, Result); Dec(FPtrMargin, Result); end; function TCachedMemoryWriter.InternalTemporaryCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; var LNewPtrSize: NativeUInt; begin if (ASize <> 0) then begin LNewPtrSize := Self.FSize + ASize; Self.FSize := LNewPtrSize; ReallocMem(FPtr, LNewPtrSize); NcMove(AData^, Pointer(NativeUInt(FPtr) + LNewPtrSize - ASize)^, ASize); end; Result := ASize; end; function TCachedMemoryWriter.FixedCallback(const ASender: TCachedBuffer; AData: PByte; ASize: NativeUInt): NativeUInt; begin Result := ASize; end; { TCachedResourceReader } {$ifdef FPC} function FindResource(AModuleHandle: TFPResourceHMODULE; AResourceName, AResourceType: PChar): TFPResourceHandle; {$ifdef MSWINDOWS} begin Result := Windows.FindResourceW(AModuleHandle, AResourceName, AResourceType); end; {$else} var LBufferString: string; LBufferName, LBufferType: UTF8String; LResourceName, LResourceType: PAnsiChar; begin LResourceName := Pointer(AResourceName); if (NativeUInt(AResourceName) <= High(Word)) then begin LBufferString := AResourceName; LBufferName := UTF8String(LBufferString); LResourceName := PAnsiChar(LBufferName); end; LResourceType := Pointer(AResourceType); if (NativeUInt(AResourceType) <= High(Word)) then begin LBufferString := AResourceType; LBufferType := UTF8String(LBufferString); LResourceType := PAnsiChar(LBufferType); end; Result := System.FindResource(AModuleHandle, LResourceName, LResourceType); end; {$endif} {$endif} procedure TCachedResourceReader.InternalCreate(AInstance: THandle; AName, AResType: PChar; AFixed: Boolean); procedure RaiseNotFound; var V: NativeUInt; N, T: string; begin V := NativeUInt(AName); if (V <= High(Word)) then N := '#' + string({$ifdef KOL}Int2Str{$else}IntToStr{$endif}(Integer(V))) else N := '"' + string(AName) + '"'; V := NativeUInt(AResType); if (V <= High(Word)) then T := '#' + string({$ifdef KOL}Int2Str{$else}IntToStr{$endif}(Integer(V))) else T := '"' + string(AResType) + '"'; raise ECachedBuffer.CreateFmt('Resource %s (%s) not found', [N, T]); end; var HResInfo: THandle; begin HResInfo := FindResource(AInstance, AName, AResType); if (HResInfo = 0) then RaiseNotFound; HGlobal := LoadResource(AInstance, HResInfo); if (HGlobal = 0) then RaiseNotFound; inherited Create(LockResource(HGlobal), SizeOfResource(AInstance, HResInfo), AFixed); end; constructor TCachedResourceReader.Create(const AInstance: THandle; const AResName: string; const AResType: PChar; const AFixed: Boolean); begin InternalCreate(AInstance, PChar(AResName), AResType, AFixed); end; constructor TCachedResourceReader.CreateFromID(const AInstance: THandle; const AResID: Word; const AResType: PChar; const AFixed: Boolean); begin InternalCreate(AInstance, PChar(NativeUInt(AResID)), AResType, AFixed); end; destructor TCachedResourceReader.Destroy; begin inherited; UnlockResource(HGlobal); FreeResource(HGlobal); end; {$ifdef CPUX86} procedure CheckSSESupport; {$ifdef FPC}assembler; nostackframe;{$endif} asm push ebx mov eax, 1 cpuid test edx, 02000000h setnz [SSE_SUPPORT] pop ebx end; initialization CheckSSESupport; {$endif} end.
unit ncaFrmDevolucao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxBarBuiltInMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxRadioGroup, cxTextEdit, cxMaskEdit, cxSpinEdit, cxPC, Vcl.ComCtrls, dxCore, cxDateUtils, cxDropDownEdit, cxCalendar, cxButtonEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, nxdb, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, cxLabel, kbmMemTable, cxCheckBox, cxCurrencyEdit, ncaFrmEditContato, ncaFrmEditContatoPeq; type TFrmDev = class(TForm) panBottom: TLMDSimplePanel; btnAvancar: TcxButton; btnVoltar: TcxButton; Q: TnxQuery; DS: TDataSource; QID: TLongWordField; QUID: TGuidField; QDataHora: TDateTimeField; QCliente: TLongWordField; QTipo: TByteField; QFunc: TStringField; QTotal: TCurrencyField; QDesconto: TCurrencyField; QDescPerc: TFloatField; QDescPorPerc: TBooleanField; QTotLiq: TCurrencyField; QPagEsp: TWordField; QPago: TCurrencyField; QDebitoAnt: TCurrencyField; QDebito: TCurrencyField; QDebitoPago: TCurrencyField; QCreditoAnt: TCurrencyField; QCredito: TCurrencyField; QCreditoUsado: TCurrencyField; QTroco: TCurrencyField; QObs: TnxMemoField; QCancelado: TBooleanField; QCanceladoPor: TStringField; QCanceladoEm: TDateTimeField; QCaixa: TLongWordField; QCaixaPag: TLongWordField; QMaq: TWordField; QNomeCliente: TWideStringField; QSessao: TLongWordField; QQtdTempo: TFloatField; QCredValor: TBooleanField; QFidResgate: TBooleanField; QPagFunc: TStringField; QPagPend: TBooleanField; QRecVer: TLongWordField; tItens: TnxTable; dsItens: TDataSource; tItensID: TUnsignedAutoIncField; tItensTran: TLongWordField; tItensProduto: TLongWordField; tItensQuant: TFloatField; tItensUnitario: TCurrencyField; tItensTotal: TCurrencyField; tItensCustoU: TCurrencyField; tItensItem: TByteField; tItensDesconto: TCurrencyField; tItensPago: TCurrencyField; tItensPagoPost: TCurrencyField; tItensDescPost: TCurrencyField; tItensDataHora: TDateTimeField; tItensEntrada: TBooleanField; tItensCancelado: TBooleanField; tItensAjustaCusto: TBooleanField; tItensEstoqueAnt: TFloatField; tItensCliente: TLongWordField; tItensCaixa: TIntegerField; tItensCategoria: TStringField; tItensNaoControlaEstoque: TBooleanField; tItensITran: TIntegerField; tItensTipoTran: TByteField; tItensSessao: TIntegerField; tItensComissao: TCurrencyField; tItensComissaoPerc: TFloatField; tItensComissaoLucro: TBooleanField; tItensPermSemEstoque: TBooleanField; tItensFidResgate: TBooleanField; tItensFidPontos: TFloatField; tItensRecVer: TLongWordField; tItensNomeProd: TStringField; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; LMDSimplePanel1: TLMDSimplePanel; Paginas: TcxPageControl; tsLocalizar: TcxTabSheet; tsSelecionar: TcxTabSheet; LMDSimplePanel3: TLMDSimplePanel; Grid: TcxGrid; TV: TcxGridDBTableView; TVID: TcxGridDBColumn; TVDataHora: TcxGridDBColumn; TVNomeCliente: TcxGridDBColumn; TVTotal: TcxGridDBColumn; TVDesconto: TcxGridDBColumn; TVTotLiq: TcxGridDBColumn; TVFunc: TcxGridDBColumn; TVObs: TcxGridDBColumn; TVCancelado: TcxGridDBColumn; GL: TcxGridLevel; tsItens: TcxTabSheet; LMDSimplePanel4: TLMDSimplePanel; tsDevolucaoDin: TcxTabSheet; LMDSimplePanel7: TLMDSimplePanel; edCli: TcxButtonEdit; edVenda: TcxSpinEdit; rbFindVenda: TcxRadioButton; rbFindCliente: TcxRadioButton; rbFindData: TcxRadioButton; edData: TcxDateEdit; edProd: TcxButtonEdit; rbFindProduto: TcxRadioButton; lbLocalize: TcxLabel; LMDSimplePanel6: TLMDSimplePanel; gridItens: TcxGrid; tvItens: TcxGridDBTableView; glItens: TcxGridLevel; panTopItens: TLMDSimplePanel; cxLabel4: TcxLabel; rbTotal: TcxRadioButton; rbParcial: TcxRadioButton; LMDSimplePanel2: TLMDSimplePanel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; MT: TkbmMemTable; MTitem: TIntegerField; MTproduto: TIntegerField; MTdescr: TStringField; MTsel: TBooleanField; MTquant: TFloatField; MTquant_dev: TFloatField; MTunitario: TCurrencyField; MTtotal: TCurrencyField; dsMT: TDataSource; tvItenssel: TcxGridDBColumn; tvItensproduto: TcxGridDBColumn; tvItensdescr: TcxGridDBColumn; tvItensquant: TcxGridDBColumn; tvItensquant_dev: TcxGridDBColumn; tvItensunitario: TcxGridDBColumn; tvItenstotal: TcxGridDBColumn; tvItenstotal_dev: TcxGridDBColumn; MTid: TIntegerField; MTtotal_dev: TCurrencyField; panTotal: TLMDSimplePanel; lbTotal: TcxLabel; LMDSimplePanel8: TLMDSimplePanel; rbCreditar: TcxRadioButton; rbDevolver: TcxRadioButton; tvEsp: TcxGridDBTableView; glEsp: TcxGridLevel; gridEsp: TcxGrid; mtEsp: TkbmMemTable; mtEspID: TIntegerField; mtEspNome: TStringField; dsEsp: TDataSource; tvEspNome: TcxGridDBColumn; panCli: TLMDSimplePanel; panTopDin: TLMDSimplePanel; cxLabel3: TcxLabel; lbTotal2: TcxLabel; tItensID_ref: TLongWordField; QUID_ref: TGuidField; QOpDevValor: TByteField; tOK: TnxTable; tOKID_ref: TLongWordField; tOKQuant: TFloatField; tOKCancelado: TBooleanField; tOKTipoTran: TByteField; tDeb: TnxTable; panEdit: TLMDSimplePanel; btnOk: TcxButton; tPagEsp: TnxTable; tPagEspID: TUnsignedAutoIncField; tPagEspCaixa: TLongWordField; tPagEspDataHora: TDateTimeField; tPagEspTran: TLongWordField; tPagEspEspecie: TWordField; tPagEspTipo: TByteField; tPagEspValor: TCurrencyField; tPagEspTroco: TCurrencyField; tPagEspDoc: TStringField; tPagEspCancelado: TBooleanField; tPagEspDevolucao: TBooleanField; tPagEspRecVer: TLongWordField; tItenstax_id: TLongWordField; tItenstax_incluido: TCurrencyField; tItenstax_incluir: TCurrencyField; tItensTotalFinal: TCurrencyField; tItensPend: TBooleanField; tItensIncluidoEm: TDateTimeField; tItensDescr: TWideStringField; tItensDescr2: TWideStringField; QDescricao: TWideMemoField; tvItensvalordeb: TcxGridDBColumn; MTvalor_pago: TCurrencyField; MTvalor_deb: TCurrencyField; tDebData: TDateTimeField; tDebCliente: TLongWordField; tDebValor: TCurrencyField; tDebTipo: TByteField; tDebID: TLongWordField; tDebRecVer: TLongWordField; MTvalor_debdev: TCurrencyField; QVendedor: TStringField; procedure FormCreate(Sender: TObject); procedure edCliPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edCliEnter(Sender: TObject); procedure rbFindClienteClick(Sender: TObject); procedure edProdPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure edProdEnter(Sender: TObject); procedure rbFindProdutoClick(Sender: TObject); procedure btnAvancarClick(Sender: TObject); procedure rbFindVendaClick(Sender: TObject); procedure rbSemVendaClick(Sender: TObject); procedure rbFindDataClick(Sender: TObject); procedure edDataEnter(Sender: TObject); procedure edVendaEnter(Sender: TObject); procedure PaginasChange(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure tItensCalcFields(DataSet: TDataSet); procedure tvItensDescrCustomDrawHeader(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridColumnHeaderViewInfo; var ADone: Boolean); procedure TVCustomDrawColumnHeader(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridColumnHeaderViewInfo; var ADone: Boolean); procedure rbParcialClick(Sender: TObject); procedure rbTotalClick(Sender: TObject); procedure tvItensEditChanged(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); procedure MTCalcFields(DataSet: TDataSet); procedure tvItensCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure FormShow(Sender: TObject); procedure rbCreditarClick(Sender: TObject); procedure rbDevolverClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnOkClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } FCli : TFrmEditContato; FCliID : Cardinal; FProdID : Cardinal; FTotal : Currency; FLoading : Boolean; FEdit : Boolean; FLastOp : Byte; procedure SetCliID(const Value: Cardinal); procedure SetProdID(const Value: Cardinal); procedure ValidaLocalizar; procedure ValidaSelecionar; procedure ValidaItens; procedure ValidaDev; procedure Validar; procedure wmEntraCliente(var Msg: TMessage); message wm_user; procedure wmEntraProduto(var Msg: TMessage); message wm_user+1; procedure Atualiza; procedure Totalizar; procedure Salvar; procedure devOk; public procedure Editar(aTran: Cardinal); property CliID: Cardinal read FCliID write SetCliID; property ProdID: Cardinal read FProdID write SetProdID; { Public declarations } end; var FrmDev: TFrmDev; implementation {$R *.dfm} uses ncaFrmPri, ncaDM, ncaFrmCliPesq2, ncaFrmProdPesq2, ncClassesBase, ufmImagens, ncaFrmQtdDev, ncEspecie, ncMovEst, ncaDMComp, ncaStrings; { TFrmDev } resourcestring rsInformeCriterioBusca = 'É necessário informar um critério para busca da venda a ser cancelada'; rsVendaNaoExiste = 'Não foi encotrado uma venda com o número informado'; rsTransacaoNaoEncontrada = 'Essa transação não foi encontrada no banco de dados'; rsNaoEDev = 'Essa transação não é uma devolução'; rsItemEmDebito = 'O produto "%s" está em débito. Não é possível devolver um produto que esteja em débito!'; rsNenhumaVendaEncontrada = 'Nenhuma venda foi encontrada!'; rsProdutoJaDevolvido = 'O produto "%s" já foi devolvido anteriormente!'; rsProdutoJaDevolvidoParcial = 'O produto "%s" já foi devolvido parcialmente (%s). A quantidade máxima que ainda pode ser devolvida é %s'; rsClienteEmBranco = 'É necessário selecionar um cliente para receber o crédito.'; rsTabItensCaption = 'Itens devolvidos'; rsTabDevolucaoDin = 'Devolução Pagamento'; rsTotal = 'Total'; rsAvancar = 'Avançar'; rsConcluir = 'Concluir!'; rsNenhumItem = 'Você não selecionou nenhum produto para ser devolvido'; procedure TFrmDev.Atualiza; const Cor : Array[Boolean] of TColor = (clBlack, clBlue); begin if FCliID=0 then begin panCli.Color := clWhite; panCli.Enabled := True; end else begin panCli.Color := clBtnFace; panCli.Enabled := False; end; Totalizar; if rbDevolver.Checked then begin rbDevolver.Font.Name := 'Segoe UI Semibold'; rbDevolver.Font.Color := clHotLight; rbCreditar.Font.Name := 'Segoe UI'; rbCreditar.Font.Color := clBlack; rbCreditar.Font.Style := []; tvEsp.Styles.Background := nil; gridEsp.Visible := True; end else begin rbDevolver.Font.Name := 'Segoe UI'; rbDevolver.Font.Color := clBlack; rbDevolver.Font.Style := []; rbCreditar.Font.Name := 'Segoe UI Semibold'; rbCreditar.Font.Color := clHotLight; tvEsp.Styles.Background := FrmPri.cxStyle37; gridEsp.Visible := False; end; if FEdit then Exit; tsSelecionar.Enabled := (Paginas.ActivePageIndex>0); tsItens.Enabled := (Paginas.ActivePageIndex>1); tsDevolucaoDin.Enabled := (Paginas.ActivePageIndex>2); rbFindVenda.Font.Color := Cor[rbFindVenda.Checked]; rbFindCliente.Font.Color := Cor[rbFindCliente.Checked]; rbFindProduto.Font.Color := Cor[rbFindProduto.Checked]; rbFindData.Font.Color := Cor[rbFindData.Checked]; if rbTotal.Checked then begin rbParcial.Font.Color := clBlack; rbParcial.Font.Style := []; rbParcial.Font.Name := 'Segoe UI'; rbTotal.Font.Color := clHotLight; rbTotal.Font.Style := [fsUnderline]; rbTotal.Font.Name := 'Segoe UI Semibold'; end else begin rbParcial.Font.Color := clHotLight; rbParcial.Font.Style := [fsUnderline]; rbParcial.Font.Name := 'Segoe UI Semibold'; rbTotal.Font.Color := clBlack; rbTotal.Font.Style := []; rbTotal.Font.Name := 'Segoe UI'; end; end; procedure TFrmDev.btnAvancarClick(Sender: TObject); begin Validar; if Paginas.ActivePage=tsDevolucaoDin then begin Salvar; Close; end else repeat Paginas.ActivePageIndex := Paginas.ActivePageIndex + 1; until Paginas.ActivePage.Enabled; end; procedure TFrmDev.btnOkClick(Sender: TObject); begin Close; end; procedure TFrmDev.btnVoltarClick(Sender: TObject); begin repeat Paginas.ActivePageIndex := Paginas.ActivePageIndex-1; until Paginas.ActivePage.Enabled; end; function QuantStr(Q: Extended): String; var P: Integer; begin Str(Q:0:10, Result); P := Pos('.', Result); if P>0 then begin while Result[Length(Result)]='0' do Delete(Result, Length(Result), 1); if Result[Length(Result)] = '.' then Delete(Result, Length(Result), 1); Result := Copy(Result, 1, P+3); end; end; procedure TFrmDev.devOk; var Q: Double; begin if MTquant_dev.Value < 0.001 then Exit; tDeb.Active := True; if tDeb.FindKey([1, mtID.Value]) then TVItensvalordeb.Visible := False; // raise Exception.Create(Format(rsItemEmDebito, [mtDescr.Value])); tOK.Active := True; tOK.SetRange([mtID.Value, trEstDevolucao, false], [mtID.Value, trEstDevolucao, false]); Q := 0; tOK.First; while not tOK.Eof do begin Q := Q + tOKQuant.Value; tOK.Next; end; if Q>0 then if (MTquant.Value-Q) < 0.0001 then begin Paginas.ActivePageIndex := 2; raise Exception.Create(Format(rsProdutoJaDevolvido, [mtDescr.Value])); end else if (MTQuant.Value-(Q+MTquant_dev.Value) < -0.0001) then begin Paginas.ActivePageIndex := 2; raise Exception.Create(Format(rsProdutoJaDevolvidoParcial, [mtDescr.Value, QuantStr(Q), QuantStr(mtquant.Value-Q)])); end; end; procedure TFrmDev.edCliEnter(Sender: TObject); begin rbFindCliente.Checked := True; edCliPropertiesButtonClick(nil, 0); end; procedure TFrmDev.edCliPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var F: TFrmCliPesq2; aID : Integer; aNome : String; aDeb, aCred : Currency; aPontos : Double; begin F := gCliPesq2List.GetFrm; try aID := FCliID; aNome := edCli.Text; aDeb := 0; aCred := 0; aPontos := 0; if F.Pesquisar(aID, aNome, aPontos, aCred, aDeb) then CliID := aID; finally gCliPesq2List.ReleaseFrm(F); end; end; procedure TFrmDev.edDataEnter(Sender: TObject); begin rbFindData.Checked := True; Atualiza; end; procedure TFrmDev.Editar(aTran: Cardinal); begin FEdit := True; tvItenssel.Visible := False; tvItensquant.Visible := False; panEdit.Visible := True; tsLocalizar.TabVisible := False; tsSelecionar.TabVisible := False; Paginas.ActivePageIndex := 2; Paginas.HideTabs := False; panBottom.Visible := False; panTopItens.Visible := False; panTopDin.Visible := False; tsItens.Enabled := True; tsDevolucaoDin.Enabled := True; Q.SQL.Text := 'select * from Tran where id = ' + IntToStr(aTran); Q.Active := True; if Q.IsEmpty then begin Free; raise Exception.Create(rsTransacaoNaoEncontrada); end; if QTipo.Value<>trEstDevolucao then begin Free; raise Exception.Create(rsNaoEDev); end; tItens.Active := True; ValidaSelecionar; rbCreditar.Checked := (QOpDevValor.Value=0); rbDevolver.Checked := (QOpDevValor.Value=1); gridEsp.Enabled := False; tPagEsp.Active := True; if tPagEsp.FindKey([aTran]) then mtEsp.Locate('ID', tPagEspEspecie.Value, []); Atualiza; ShowModal; end; procedure TFrmDev.edProdEnter(Sender: TObject); begin rbFindProduto.Checked := True; edProdPropertiesButtonClick(nil, 0); end; procedure TFrmDev.edProdPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var F: TFrmProdPesq2; aID: Cardinal; begin F := gProdPesq2List.GetFrm; try aID := FProdID; if F.Pesquisar(aID) then ProdID := aID; finally gProdPesq2List.ReleaseFrm(F); end; end; procedure TFrmDev.edVendaEnter(Sender: TObject); begin rbFindVenda.Checked := True; Atualiza; end; procedure TFrmDev.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmDev.FormCreate(Sender: TObject); var I: integer; begin FEdit := False; TVDesconto.Caption := rsDesconto; FCli := TFrmEditContatoPeq.Create(Self); FCli.panPri.Parent := panCli; FCli.panPri.ParentColor := True; FCli.ShowCliInfo := False; FLastOp := 0; FLoading := True; FTotal := 0; Paginas.ActivePageIndex := 0; Paginas.HideTabs := True; FCliID := 0; FProdID := 0; mtEsp.Active := True; for I := 0 to gEspecies.Count - 1 do begin mtEsp.Append; mtEspID.Value := gEspecies.Itens[i].ID; mtEspNome.Value := gEspecies.Itens[i].Nome; mtEsp.Post; end; mtEsp.First; end; procedure TFrmDev.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of Key_F2 : if FEdit then Close; Key_Esc : ModalResult := mrCancel; Key_F5 : if (Paginas.ActivePage=tsDevolucaoDin) then begin if panCli.Enabled then FCli.Pesquisa; end else if Paginas.ActivePageIndex=0 then PostMessage(Handle, wm_user, 0, 0); end; end; procedure TFrmDev.FormKeyPress(Sender: TObject; var Key: Char); begin if (Key in [#13, #27]) then Key := #0; end; procedure TFrmDev.FormShow(Sender: TObject); begin FLoading := False; end; procedure TFrmDev.MTCalcFields(DataSet: TDataSet); var T: Currency; begin if MTquant_dev.IsNull or (MTquant_dev.Value<=0) or (not mtSel.Value) then MTtotal_dev.Clear else begin T := MTquant_dev.Value * MTunitario.Value; if MTvalor_deb.Value >= T then begin MTvalor_debdev.Value := T; MTtotal_dev.Value := 0; end else begin MTvalor_debdev.Value := MTvalor_deb.Value; MTtotal_dev.Value := T - MTvalor_deb.Value; end; end; end; procedure TFrmDev.PaginasChange(Sender: TObject); begin if FEdit then Exit; panTopItens.Visible := MT.Active and (MT.RecordCount>1); Atualiza; btnVoltar.Enabled := (Paginas.ActivePageIndex>0); if Paginas.ActivePage=tsDevolucaoDin then btnAvancar.Caption := rsConcluir else btnAvancar.Caption := rsAvancar + ' >>'; end; procedure TFrmDev.rbCreditarClick(Sender: TObject); begin Atualiza; if rbCreditar.Focused then FLastOp := 0; end; procedure TFrmDev.rbDevolverClick(Sender: TObject); begin Atualiza; if rbDevolver.Focused then begin FLastOp := 1; gridEsp.SetFocus; end; end; procedure TFrmDev.rbFindClienteClick(Sender: TObject); begin Atualiza; PostMessage(Handle, wm_user, 0, 0); end; procedure TFrmDev.rbFindDataClick(Sender: TObject); begin Atualiza; edData.SetFocus; end; procedure TFrmDev.rbFindProdutoClick(Sender: TObject); begin Atualiza; PostMessage(Handle, wm_user+1, 0, 0); end; procedure TFrmDev.rbFindVendaClick(Sender: TObject); begin Atualiza; edVenda.SetFocus; end; procedure TFrmDev.rbParcialClick(Sender: TObject); begin if rbParcial.Focused then begin mt.First; while not mt.Eof do begin mt.Edit; MTquant_dev.Clear; MTsel.Value := False; mt.Post; mt.Next; end; mt.First; end; Atualiza; end; procedure TFrmDev.rbSemVendaClick(Sender: TObject); begin Atualiza; end; procedure TFrmDev.rbTotalClick(Sender: TObject); begin if rbTotal.Focused then begin mt.First; while not mt.Eof do begin mt.Edit; MTquant_dev.Value := MTquant.Value; MTsel.Value := True; mt.Post; mt.Next; end; mt.First; end; Atualiza; end; procedure TFrmDev.Salvar; var M : TncMovEst; I : Integer; begin M := TncMovEst.Create; try M.CriaUID; M.UID_Ref := QUID.Value; M.Tipo := trEstDevolucao; M.Cliente := FCli.ID; M.Func := Dados.CM.UA.Username; M.Vendedor := QVendedor.Value; M.DataHora := Now; M.Operacao := osIncluir; if rbCreditar.Checked then M.OpDevValor := 0 else M.OpDevValor := 1; M.Total := FTotal; M.PagPend := False; mt.First; while not mt.Eof do begin devOk; mt.Next; end; mt.First; while not mt.Eof do begin if MTsel.Value then with M.NewIME do begin imID_Ref := MTid.Value; imProduto := MTproduto.Value; imQuant := MTquant_dev.Value; imUnitario := MTunitario.Value; imTotal := MTtotal_dev.Value; imDebDev := MTValor_debdev.Value; _Operacao := osIncluir; end; mt.Next; end; if (FTotal > 0) and rbDevolver.Checked then with M.PagEsp.NewItem do begin peValor := -1 * FTotal; peEspecie := mtEspID.Value; peTipo := gEspecies.PorID[mtEspID.Value].Tipo; end; Dados.CM.SalvaMovEst(M); try if not Assigned(dmComp) then Application.CreateForm(TdmComp, dmComp); dmComp.Imprime(M.NativeUID); except on E: Exception do ShowMessage(E.Message); end; Paginas.ActivePageIndex := 2; finally M.Free; end; end; procedure TFrmDev.SetCliID(const Value: Cardinal); begin FCliID := Value; if (FCliID>0) and Dados.tbCli.Locate('ID', FCliID, []) then edCli.Text := Dados.tbCliNome.Value else begin edCli.Text := ''; FCliID := 0; end; end; procedure TFrmDev.SetProdID(const Value: Cardinal); begin FProdID := Value; if (FProdID>0) and Dados.tbPro.Locate('ID', FProdID, []) then edProd.Text := Dados.tbProDescricao.Value else begin edProd.Text := ''; FProdID := 0; end; end; procedure TFrmDev.tItensCalcFields(DataSet: TDataSet); begin tItensDescr2.Value := ' ' + tItensQuant.AsString + ' X ' + tItensNomeProd.Value + ' = ' + CurrencyToStr(tItensTotal.Value); end; function VarBoolean(V: Variant): Boolean; begin Result := (not VarIsNull(V)) and (V=True); end; procedure TFrmDev.Totalizar; var i: integer; Todos : Boolean; begin Todos := True; FTotal := 0; with tvItens.DataController do for i := 0 to RecordCount-1 do begin if VarBoolean(Values[i, tvItenssel.index]) then begin FTotal := FTotal + Values[i, tvItenstotal_dev.Index]; if Values[i, tvItensquant_dev.Index] < Values[i, tvItensquant.Index] then Todos := False; end else Todos := False; end; lbTotal.Caption := rsTotal + ' = ' + CurrencyToStr(FTotal); lbTotal2.Caption := lbTotal.Caption; rbTotal.Checked := Todos; rbParcial.Checked := not Todos; if (FTotal<0.01) then begin rbDevolver.Checked := False; rbCreditar.Checked := False; rbDevolver.Enabled := False; rbCreditar.Enabled := False; end else begin rbDevolver.Enabled := True; rbCreditar.Enabled := True; if (not rbDevolver.Checked) and (not rbCreditar.Checked) then if FLastOp=0 then rbCreditar.Checked := True else rbDevolver.Checked := True; end; end; procedure TFrmDev.TVCustomDrawColumnHeader(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridColumnHeaderViewInfo; var ADone: Boolean); begin FrmPri.CustomDrawGridHeader(Sender, ACanvas, AViewInfo, ADone); end; procedure TFrmDev.tvItensCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); var V: Variant; begin V := AViewInfo.GridRecord.Values[tvitenssel.Index]; if (V=null) or (V=False) then ACanvas.Font.Style := [] else ACanvas.Font.Style := [fsBold]; end; procedure TFrmDev.tvItensDescrCustomDrawHeader(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridColumnHeaderViewInfo; var ADone: Boolean); var I: Integer; S: String; begin AViewInfo.AlignmentVert := cxClasses.vaTop; ACanvas.Brush.Color := clWhite; ACanvas.FillRect(AViewInfo.Bounds); with AViewInfo, Bounds do begin I := tItens.RecordCount; if I>1 then S := IntToStr(I)+' itens:' else S := IntToStr(I)+' item:'; ACanvas.DrawTexT(S, Rect(Left+2, Top+2, Right-2, Bottom-2), AlignmentHorz, cxClasses.vaTop, True {Multiline}, False); { for I := 0 to AreaViewInfoCount - 1 do begin if AreaViewInfos[I] is TcxGridColumnHeaderFilterButtonViewInfo then if TMYcxGridColumnHeaderFilterButtonViewInfo(AreaViewInfos[I]).GetVisible then LookAndFeelPainter.DrawFilterDropDownButton(ACanvas, AreaViewInfos[I].Bounds, GridCellStateToButtonState(AreaViewInfos[I].State), TcxGridColumnHeaderFilterButtonViewInfo(AreaViewInfos[I]).Active); end;} end; ADone := True; end; procedure TFrmDev.tvItensEditChanged(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem); var aQtd: Double; begin if mtsel.value then begin if TFrmQtdDev.Create(Self).ObtemQtd(MTproduto.Value, MTquant.Value, aQtd) then MTquant_dev.Value := aQtd else begin MTsel.value := False; MTquant_dev.Clear; end; end else MTquant_dev.Clear; Totalizar; end; procedure TFrmDev.ValidaDev; begin if (FCli.ID=0) and rbCreditar.Checked then Raise exception.Create(rsClienteEmBranco); end; procedure TFrmDev.ValidaItens; var i: integer; Algum : Boolean; begin Algum := False; with tvItens.DataController do for i := 0 to RecordCount-1 do if VarBoolean(Values[i, tvItenssel.index]) then begin Algum := True; Break; end; if not Algum then raise Exception.Create(rsNenhumItem); devOk; end; procedure TFrmDev.ValidaLocalizar; procedure Erro(S: String; C: TWinControl); begin if Assigned(C) then C.SetFocus; raise Exception.Create(S); end; begin Q.Active := False; if rbFindVenda.Checked then begin if VarIsNull(edVenda.Value) or (edVenda.Value=0) then Erro(rsInformeCriterioBusca, edVenda); if (not Dados.tbTran.Locate('ID', edVenda.Value, [])) or (Dados.tbTranTipo.Value<>trEstVenda) then Erro(rsVendaNaoExiste, edVenda) else Q.SQL.Text := 'select * from tran where (id = ' + IntToStr(edVenda.Value) + ') and (tipo=4) and ((cancelado is null) or (cancelado=false)) and (PagPend=False)' ; end; if rbFindCliente.Checked then begin if (CliID=0) then Erro(rsInformeCriterioBusca, nil) else Q.SQL.Text := 'select * from tran where cliente = ' + IntToStr(CliID) + ' and (tipo=4) and ((cancelado is null) or (cancelado=false)) and (PagPend=False) order by datahora desc'; end; if rbFindProduto.Checked then begin if (ProdID=0) then Erro(rsInformeCriterioBusca, nil) else begin Q.SQL.Text := 'select * from tran where id in (select tran from movest where produto='+IntToStr(ProdID)+') and (tipo=4) and (PagPend=False) and ((cancelado is null) or (cancelado=false)) '+ 'order by datahora desc'; end; end; if rbFindData.Checked then begin if (edData.Date<=EncodeDate(1980, 1, 1)) then Erro(rsInformeCriterioBusca, edData) else begin Q.SQL.Text := 'select * from tran where (tipo=4) and ((cancelado is null) or (cancelado=false)) and (datahora >= timestamp '+ QuotedStr(FormatDateTime('yyyy-mm-dd', edData.Date)+' 00:00:00')+') and (datahora < timestamp '+ QuotedStr(FormatDateTime('yyyy-mm-dd', edData.Date+1)+' 00:00:00')+') '+ 'order by datahora desc'; end; end; Q.Active := True; if Q.IsEmpty then raise Exception.Create(rsNenhumaVendaEncontrada); end; procedure TFrmDev.Validar; begin Atualiza; if FLoading then Exit; case Paginas.ActivePageIndex of 0 : ValidaLocalizar; 1 : ValidaSelecionar; 2 : ValidaItens; 3 : ValidaDev; end; end; procedure TFrmDev.ValidaSelecionar; begin mt.Active := False; mt.Active := True; TVItensvalordeb.Visible := False; tItens.First; while not tItens.Eof do begin mt.Append; mtID.Value := tItensID.Value; mtSel.Value := FEdit; MTproduto.Value := tItensProduto.Value; MTdescr.Value := tItensNomeProd.Value; MTquant.Value := tItensQuant.Value; MTvalor_pago.value := tItensPago.Value + tItensPagoPost.Value; if tDeb.FindKey([1, tItensID.Value]) then MTvalor_deb.Value := tDebValor.Value else MTvalor_deb.Value := 0; if MTvalor_deb.Value>0 then TVItensvalordeb.Visible := True; if FEdit then begin MTunitario.Value := DuasCasas(tItensTotal.Value / tItensQuant.Value); MTtotal.Value := tItensTotal.Value; MTquant_dev.Value := MTquant.Value; if MTvalor_deb.Value >= MTtotal.Value then begin MTvalor_debdev.Value := MTtotal.Value; MTtotal_dev.Value := 0; end else begin MTvalor_debdev.Value := MTvalor_deb.Value; MTtotal_dev.Value := MTtotal.Value - MTvalor_deb.Value; end; // MTtotal_dev.Value := MTtotal.Value; end else begin MTquant.Value := tItensQuant.Value; MTunitario.Value := DuasCasas((tItensTotal.Value - tItensDesconto.Value) / tItensQuant.Value); MTtotal.Value := MTquant.Value * MTunitario.Value; end; MT.Post; tItens.Next; end; MT.First; tItens.First; FCliID := QCliente.Value; FCli.ID := QCliente.Value; end; procedure TFrmDev.wmEntraCliente(var Msg: TMessage); begin edCli.SetFocus; end; procedure TFrmDev.wmEntraProduto(var Msg: TMessage); begin edProd.SetFocus; end; end.
unit Rle; {$mode objfpc}{$H+}{$J-} interface uses Classes, SysUtils, Universe, streamex; type { TRleParser } TRleParser = class private FStreamReader: TStreamReader; FName: string; FComment: string; FWidth: Integer; FHeight: Integer; FRule: string; function ReadInteger(var P: PChar): Integer; public constructor Create(const Stream: TStream); reintroduce; destructor Destroy; override; procedure LoadInUniverse(const Universe: TUniverse; const AX, AY: Integer); property Name: string read FName; property Comment: string read FComment; property Width: Integer read FWidth; property Height: Integer read FHeight; property Rule: String read FRule; end; implementation { TRleParser } function TRleParser.ReadInteger(var P: PChar): Integer; begin Result := 0; while P^ = ' ' do Inc(P); while (P^ <> #0) do begin case P^ of '0'..'9': Result := Result * 10 + (Ord(P^) - Ord('0')); else Break; end; Inc(P); end; end; constructor TRleParser.Create(const Stream: TStream); function GetNextIdentifier(var P: PChar): string; begin Result := ''; while P^ = ' ' do Inc(P); while not (P^ in [#0, ' ', '=']) do begin Result := Result + P^; Inc(P); end; while P^ in [' ', '='] do Inc(P); end; var Line: string; P: PChar; begin inherited Create; FStreamReader := TStreamReader.Create(Stream); while not FStreamReader.Eof do begin FStreamReader.ReadLine(Line); if Line.IsEmpty then Continue else if Line.StartsWith('#') then begin case Line.Substring(0, 3) of '#N ': FName := FName + Line.Substring(3); '#C ': FComment := FComment + Line.Substring(3); end; end else if Line.StartsWith('x') then begin P := @Line[1]; while P^ <> #0 do begin case GetNextIdentifier(P) of 'x': FWidth := ReadInteger(P); 'y': FHeight := ReadInteger(P); 'rule': begin while P^ = ' ' do Inc(P); while not (P^ in [#0, ' ', ',']) do begin FRule := FRule + P^; Inc(P); end; end; end; while P^ in [' ', ','] do Inc(P); end; Break; end; end; end; destructor TRleParser.Destroy; begin FStreamReader.Free; inherited; end; procedure TRleParser.LoadInUniverse(const Universe: TUniverse; const AX, AY: Integer); var Count: Integer; X, Y: Integer; Line: String; P: PChar; i: Integer; begin X := AX; Y := AY; while not FStreamReader.Eof do begin FStreamReader.ReadLine(Line); P := @Line[1]; while P^ <> #0 do begin Count := ReadInteger(P); if Count = 0 then Count := 1; case P^ of 'b': Inc(X, Count); 'o': begin for i := 1 to Count do begin Universe.SetBit(X, Y); Inc(X); end; end; '$': begin X := AX; Dec(Y, Count); end; '!': Break; end; Inc(P); end; end; end; end.
unit Module.DataSet.ConfigMemento.Index; interface uses FireDac.Comp.Client, Module.DataSet.ConfigMemento; type TConfigIndex = class(TInterfacedObject, IInterface) private FIndexActive: boolean; FIndexName: string; FDataSet: TFDMemTable; public constructor Create(const ADataSet: TFDMemTable); destructor Destroy; override; end; implementation { TConfigIndex } constructor TConfigIndex.Create(const ADataSet: TFDMemTable); begin FDataSet := ADataSet; FIndexName := FDataSet.IndexName; FIndexActive := FDataSet.IndexesActive; end; destructor TConfigIndex.Destroy; begin FDataSet.IndexName := FIndexName; FDataSet.IndexesActive := FIndexActive; inherited; end; end.
{ "Client Connection Provider (WinSock)" - Copyright (c) Danijel Tkalcec @html(<br>) Client connection provider implementation using a modified TWSocket class from F.Piette's Internet Component Suite (ICS). @exclude } unit rtcWSockCliProv; {$INCLUDE rtcDefs.inc} interface uses rtcTrashcan, Classes, SysUtils, // Windows, Messages, // Windows and Messages units are used only in Multithreading, to send messages rtcSyncObjs, {$IFDEF CLR} DTkalcec.Ics.WSocket, {$ELSE} WSocket_rtc, // Client Socket {$ENDIF} rtcLog, rtcConnProv, // Basic connection provider wrapper rtcConnLimit, rtcPlugins, rtcThrPool, rtcThrConnProv; // Threaded connection provider wrapper type TRtcWSockClientProvider = class; TRtcWSockClientProtocol = (proTCP, proUDP); TRtcWSockClientThread = class(TRtcThread) public RtcConn: TRtcWSockClientProvider; Releasing: boolean; public constructor Create; override; destructor Destroy; override; procedure OpenConn; procedure CloseConn(_lost:boolean); function Work(Job:TObject):boolean; override; procedure Kill(Job:TObject); override; end; TRtcWSocketClient = class(TWSocketClient) public Thr: TRtcWSockClientThread; procedure Call_FD_CONNECT(Err:word); override; procedure Call_FD_CLOSE(Err:word); override; procedure Call_FD_READ; override; procedure Call_FD_WRITE; override; end; TRtcWSockClientProvider = class(TRtcThrClientProvider) private FConnID:longint; Conn:TWSocket; FProtocol: TRtcWSockClientProtocol; FRawOut, FPlainOut:int64; FCryptPlugin: TRtcCryptPlugin; FReadBuff:string; FCS:TRtcCritSec; Client_Thread : TRtcWSockClientThread; FMultiCast : Boolean; FMultiCastIpTTL : Integer; FReuseAddr : Boolean; procedure wsOnBgException(Sender: TObject; E: Exception; var CanClose: Boolean); procedure wsOnChangeState(Sender: TObject; OldState,NewState: TSocketState); procedure wsOnSessionClosed(Sender: TObject; ErrorCode: Word); procedure wsOnDataReceived(Sender: TObject; ErrCode: Word); procedure wsOnDataSent(Sender: TObject; ErrCode: Word); procedure wsOnDataOut(Sender: TObject; Len: cardinal); procedure wsOnDataIn(Sender: TObject; Len: cardinal); procedure OpenConnection(Force:boolean); protected procedure Enter; override; procedure Leave; override; function _Active:boolean; function _Visible:boolean; function PostWrite(HighPriority:boolean=False):boolean; function PostRead(HighPriority:boolean=False):boolean; function GetClientThread:TRtcThread; override; procedure DirectWrite(const s:string); procedure BufferWrite(const s:string); public constructor Create; override; destructor Destroy; override; procedure Release; override; procedure Connect(Force:boolean=False); override; procedure InternalDisconnect; override; procedure Disconnect; override; procedure Check; override; function Read: string; override; procedure Write(const s: string; sendNow:boolean=True); override; property Proto:TRtcWSockClientProtocol read FProtocol write FProtocol; property UdpMultiCast : Boolean read FMultiCast write FMultiCast; property UdpMultiCastMaxHops: Integer read FMultiCastIpTTL write FMultiCastIpTTL; property UdpReuseAddr : Boolean read FReuseAddr write FReuseAddr; property CryptPlugin : TRtcCryptPlugin read FCryptPlugin write FCryptPlugin; end; implementation {$IFDEF CLR} uses System.Security; {$ENDIF} { TRtcWSockClientThread } type TRtcBaseMessage=class end; TRtcInfoMessage=class(TRtcBaseMessage) public Error:word; constructor Create(Value:word); end; TRtcCloseMessage=class(TRtcInfoMessage) end; TRtcConnectMessage=class(TRtcInfoMessage) end; var Message_WSStop, Message_WSRelease, Message_WSOpenConn, Message_WSCloseConn, Message_WSConnect, Message_WSClose, Message_WSRead, Message_WSWrite:TRtcBaseMessage; { TRtcWSockClientProvider } constructor TRtcWSockClientProvider.Create; begin inherited; FRawOut:=0; FPlainOut:=0; FConnID:=GetNextConnID; FCS:=TRtcCritSec.Create; Closing:=False; FPeerPort:=''; FPeerAddr:='0.0.0.0'; FLocalPort:=''; FLocalAddr:='0.0.0.0'; FProtocol:=proTCP; UdpMultiCastMaxHops:=1; FReadBuff:=''; SetLength(FReadBuff, WSOCK_READ_BUFFER_SIZE); Conn:=nil; end; destructor TRtcWSockClientProvider.Destroy; begin { Before destroying this connection object, we will disconnect this and all related open connections. } Closing:=True; Silent:=True; if assigned(Conn) then InternalDisconnect; TriggerConnectionClosing; if assigned(Client_Thread) then TRtcThread.PostJob(Client_Thread, Message_WSStop, True); SetLength(FReadBuff,0); FCS.Free; inherited; end; procedure TRtcWSockClientProvider.Enter; begin FCS.Enter; end; procedure TRtcWSockClientProvider.Leave; begin FCS.Leave; end; function TRtcWSockClientProvider.Read: string; var len:longint; s_in, s_out:string; begin if Proto=proTCP then begin len:=Conn.Receive(FReadBuff[1], length(FReadBuff)); if len<=0 then Result:='' else if assigned(FCryptPlugin) then begin // Decrypt input data ... SetLength(s_in,len); Move(FReadBuff[1],s_in[1],len); s_out:=''; Result:=''; FCryptPlugin.DataReceived(FConnID, s_in, s_out, Result); if length(Result)>0 then begin // Trigger the "OnDataIn" event ... FDataIn:=length(Result); TriggerDataIn; end; if s_out<>'' then DirectWrite(s_out); end else begin SetLength(Result,len); Move(FReadBuff[1],Result[1],len); end; end else begin Result:=FReadBuff; FReadBuff:=''; end; end; procedure TRtcWSockClientProvider.Write(const s: string; SendNow:boolean=True); var s_out:string; begin if Closing then Exit; if Conn=nil then Error('Not connected.'); if assigned(FCryptPlugin) then begin FCryptPlugin.DataToSend(FConnID,s,s_out); Inc(FPlainOut, length(s)); if s_out<>'' then DirectWrite(s_out); end else if SendNow then DirectWrite(s) else BufferWrite(s); end; procedure TRtcWSockClientProvider.DirectWrite(const s: string); var len:integer; begin if RTC_LIMIT_CONN and assigned(Client_Thread) then if not rtcStartAction(Client_Thread, RTC_ACTION_WRITE) then begin if assigned(FCryptPlugin) then Inc(FRawOut, length(s)); len:=Conn.BuffStr(s); if len<0 then Error('Error #'+IntToStr(Conn.LastError)+': '+WSocketErrorDesc(Conn.LastError)) else if len<length(s) then Error('Wanted to write '+IntToStr(length(s))+' bytes, written only '+IntToStr(len)+' bytes.'); PostWrite(True); Exit; end; if assigned(FCryptPlugin) then Inc(FRawOut, length(s)); len:=Conn.SendStr(s); if len<0 then Error('Error #'+IntToStr(Conn.LastError)+': '+WSocketErrorDesc(Conn.LastError)) else if len<length(s) then Error('Wanted to write '+IntToStr(length(s))+' bytes, written only '+IntToStr(len)+' bytes.'); end; procedure TRtcWSockClientProvider.BufferWrite(const s: string); var len:integer; begin if assigned(FCryptPlugin) then Inc(FRawOut, length(s)); len:=Conn.BuffStr(s); if len<0 then Error('Error #'+IntToStr(Conn.LastError)+': '+WSocketErrorDesc(Conn.LastError)) else if len<length(s) then Error('Wanted to write '+IntToStr(length(s))+' bytes, written only '+IntToStr(len)+' bytes.'); end; procedure TRtcWSockClientProvider.wsOnChangeState(Sender: TObject; OldState, NewState: TSocketState); var s_out:string; begin if Closing then Exit; if assigned(Conn) then if NewState=wsConnected then begin if Proto=proTCP then begin FLocalAddr:=Conn.GetXAddr; if FLocalAddr<>'0.0.0.0' then begin FLocalPort:=Conn.GetXPort; FPeerAddr:=Conn.GetPeerAddr; FPeerPort:=Conn.GetPeerPort; TriggerConnecting; end; end else begin FLocalAddr:='127.0.0.1'; FLocalPort:=Conn.GetXPort; FPeerAddr:=Conn.GetPeerAddr; FPeerPort:=Conn.GetPeerPort; TriggerConnecting; State:=conActive; if assigned(FCryptPlugin) then begin s_out:=''; FCryptPlugin.AfterConnect(FConnID,s_out); if s_out<>'' then begin DirectWrite(s_out); s_out:=''; end; end; TriggerConnect; end; end else if NewState=wsClosed then wsOnSessionClosed(Sender, 0); end; procedure TRtcWSockClientProvider.wsOnSessionClosed(Sender: TObject; ErrorCode:Word); begin { Client connection closed. This method is called when one of the active connections get closed. It handles connections closing for all active connection types (incomming and outgoing connections). } TriggerDisconnecting; if assigned(Conn) and not Closing then // Connection object still here ? begin Closing:=True; // Let everyone know we are closing now ... try TriggerConnectionClosing; if State in [conInactive,conActivating] then // Connection still not activated, TriggerConnectFail // we have a "Failed connection" here, rather then a Disconnect. else begin if assigned(FCryptPlugin) then FCryptPlugin.AfterDisconnect(FConnID); TriggerDisconnect; if Lost then TriggerConnectLost; end; finally State:=conInactive; { We need to remove all events from this connection before we can actually destroy our own connection object. } with Conn do begin OnBgException:=nil; OnChangeState:=nil; OnDataReceived:=nil; OnDataSent:=nil; OnDataOut:=nil; OnDataIn:=nil; end; try Conn.Close; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClientProvider.OnSessionClosed: Conn.Close',E); // ignore all errors here end; try Conn.Release; except on E:Exception do if LOG_AV_ERRORS then Log('WSockClientProvider.OnSessionClosed: Conn.Release',E); // ignore all errors here end; Conn:=nil; TriggerReadyToRelease; end; end; end; procedure TRtcWSockClientProvider.wsOnDataReceived(Sender: TObject; ErrCode: Word); var len:integer; s_out:string; begin if _Visible then begin if (State=conActivating) then // call "Connected" only after we know that we can relly send data. begin if FLocalAddr<>'0.0.0.0' then begin State:=conActive; if assigned(FCryptPlugin) then begin s_out:=''; FCryptPlugin.AfterConnect(FConnID,s_out); if s_out<>'' then begin DirectWrite(s_out); s_out:=''; end; end; TriggerConnect; end; end; if State=conActive then begin if Proto=proUDP then begin len:=Conn.GetRcvdCount; if len>=0 then begin SetLength(FReadBuff,len); len:=Conn.Receive(FReadBuff[1], length(FReadBuff)); FPeerPort:=Conn.GetSrcPort; FPeerAddr:=Conn.GetSrcAddr; if len<0 then begin FReadBuff:=''; TriggerDataLost; TriggerReadyToRelease; end else begin if len<>length(FReadBuff) then SetLength(FReadBuff,len); TriggerDataReceived; TriggerReadyToRelease; end; end else begin FReadBuff:=''; TriggerDataLost; TriggerReadyToRelease; end; end else begin TriggerDataReceived; TriggerReadyToRelease; end; end; end; end; procedure TRtcWSockClientProvider.wsOnDataSent(Sender: TObject; ErrCode: Word); var s_out:string; begin if _Visible then begin if (State=conActivating) then // call "Connected" only after we know that we can relly send data. begin if FLocalAddr<>'0.0.0.0' then begin State:=conActive; if assigned(FCryptPlugin) then begin s_out:=''; FCryptPlugin.AfterConnect(FConnID,s_out); if s_out<>'' then begin DirectWrite(s_out); s_out:=''; end; end; TriggerConnect; end; end; if State=conActive then // do not call this when it comes for the first time, if we haven't been sending anything out yet. begin TriggerDataSent; TriggerReadyToRelease; end; end; end; procedure TRtcWSockClientProvider.wsOnDataOut(Sender: TObject; Len: cardinal); begin if _Visible then begin if State=conActive then begin if assigned(FCryptPlugin) then begin Dec(FRawOut,Len); if (FRawOut=0) and (FPlainOut>0) then begin FDataOut:=FPlainOut; FPlainOut:=0; TriggerDataOut; TriggerReadyToRelease; end; end else begin FDataOut:=Len; TriggerDataOut; TriggerReadyToRelease; end; end; end; end; procedure TRtcWSockClientProvider.wsOnDataIn(Sender: TObject; Len: cardinal); begin if _Visible then begin if State=conActive then begin if not assigned(FCryptPlugin) then begin FDataIn:=Len; TriggerDataIn; TriggerReadyToRelease; end; end; end; end; procedure TRtcWSockClientProvider.wsOnBgException(Sender: TObject; E: Exception; var CanClose: Boolean); begin if (E is EClientLimitReached) then CanClose:=False else begin CanClose:=True; try TriggerException(E); except on E:Exception do if LOG_EVENT_ERRORS then Log('WSockClientProvider.OnBgException: TriggerException',E); // ignore all exceptions here end; end; end; function TRtcWSockClientProvider._Active: boolean; begin Result:=not Closing and (FState in [conActive,conActivating]) and assigned(Conn); end; function TRtcWSockClientProvider._Visible: boolean; begin Result:=not Closing and (FState in [conActive,conActivating]) and assigned(Conn); end; procedure TRtcWSockClientProvider.Check; var addr:string; begin if assigned(Conn) then begin addr:=Conn.GetXAddr; if addr='0.0.0.0' then begin if LOG_SOCKET_ERRORS then Log('CLOSING from Check. Socket not connected to local address.'); Conn.Close; raise EWinSockException.Create('Socket not connected to local address.'); end; addr:=Conn.GetPeerAddr; if addr='0.0.0.0' then begin if LOG_SOCKET_ERRORS then Log('CLOSING from Check. Socket not connected to peer address.'); Conn.Close; raise EWinSockException.Create('Socket not connected to peer address.'); end; end; end; function TRtcWSockClientProvider.GetClientThread: TRtcThread; begin Result:=Client_Thread; end; procedure TRtcWSockClientProvider.Connect(Force:boolean=False); begin if assigned(Client_Thread) then TRtcThread.PostJob(Client_Thread, Message_WSOpenConn) else if GetMultiThreaded then begin Client_Thread := TRtcWSockClientThread.Create; Client_Thread.RtcConn:= self; TRtcThread.PostJob(Client_Thread, Message_WSOpenConn); end else OpenConnection(Force); end; procedure TRtcWSockClientProvider.OpenConnection(Force:boolean); begin if (State=conActive) or (State=conActivating) then Exit; // already connected !!! if State<>conInactive then raise Exception.Create('Can not connect again. Connection in use.'); try if Proto=proUDP then FReadBuff:=''; Lost:=True; Closing:=False; Silent:=False; FDataOut:=0; FDataIn:=0; FLocalAddr:='0.0.0.0'; FPeerAddr:='0.0.0.0'; TriggerConnectionOpening(Force); try if assigned(Client_Thread) then begin Conn:=TRtcWSocketClient.Create(nil); TRtcWSocketClient(Conn).Thr:=Client_Thread; end else Conn:=TWSocket.Create(nil); with Conn do begin case Proto of proTCP:Protocol:=spTcp; proUDP: begin Protocol:=spUdp; UdpMultiCast:=Self.UdpMultiCast; UdpMultiCastIpTTL:=Self.UdpMultiCastMaxHops; UdpReuseAddr:=Self.UdpReuseAddr; end; end; Addr:=self.GetAddr; Port:=self.GetPort; MultiThreaded:=assigned(Client_Thread); {$IFDEF FPC} OnBgException:=@wsOnBgException; OnChangeState:=@wsOnChangeState; OnDataReceived:=@wsOnDataReceived; OnDataSent:=@wsOnDataSent; OnDataOut:=@wsOnDataOut; OnDataIn:=@wsOnDataIn; {$ELSE} OnBgException:=wsOnBgException; OnChangeState:=wsOnChangeState; OnDataReceived:=wsOnDataReceived; OnDataSent:=wsOnDataSent; OnDataOut:=wsOnDataOut; OnDataIn:=wsOnDataIn; {$ENDIF} end; try State:=conActivating; Conn.Connect; except on E:Exception do begin if _Active then begin State:=conInactive; try with Conn do begin OnBgException:=nil; OnChangeState:=nil; OnDataReceived:=nil; OnDataSent:=nil; OnDataOut:=nil; OnDataIn:=nil; end; Conn.Free; finally Conn:=nil; end; end; raise; end; end; except TriggerConnectionClosing; raise; end; except on E:EClientLimitReached do // connection limit reached begin TriggerConnectError(E); TriggerReadyToRelease; end; on E:EWinSockException do // any kind of socket error begin TriggerConnectError(E); TriggerReadyToRelease; end; on E:Exception do begin TriggerReadyToRelease; raise; end; end; end; procedure TRtcWSockClientProvider.Disconnect; begin if assigned(Client_Thread) then TRtcThread.PostJob(Client_Thread, Message_WSCloseConn) else begin Lost:=False; InternalDisconnect; end; end; procedure TRtcWSockClientProvider.InternalDisconnect; var s_out:string; begin if not assigned(Conn) then // not connected begin Closing:=True; Exit; // silent exit if nothing to do. end; if State in [conActive,conActivating] then begin if State=conActive then State:=conClosing else State:=conInactive; with Conn do // deactivate all events for this client connection begin OnBgException:=nil; OnDataReceived:=nil; OnDataSent:=nil; OnDataOut:=nil; OnDataIn:=nil; end; if not Closing then begin if assigned(FCryptPlugin) then begin s_out:=''; FCryptPlugin.BeforeDisconnect(FConnID,s_out); if s_out<>'' then begin DirectWrite(s_out); s_out:=''; end; end; wsOnSessionClosed(self,0); end else begin try Conn.Close; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClientProvider.InternalDisconnect: Conn.Close',E); // ignore all errors here end; try Conn.Release; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClientProvider.InternalDisconnect: Conn.Release',E); // ignore all errors here end; Conn:=nil; end; end; end; procedure TRtcWSockClientProvider.Release; begin if assigned(Client_Thread) then TRtcThread.PostJob(Client_Thread, Message_WSRelease, True) else inherited; end; function TRtcWSockClientProvider.PostWrite(HighPriority:boolean=False):boolean; begin if assigned(Client_Thread) then begin TRtcThread.PostJob(Client_Thread,Message_WSWrite,HighPriority); Result:=True; end else Result:=False; end; function TRtcWSockClientProvider.PostRead(HighPriority:boolean=False):boolean; begin if assigned(Client_Thread) then begin TRtcThread.PostJob(Client_Thread,Message_WSRead,HighPriority); Result:=True; end else Result:=False; end; constructor TRtcWSockClientThread.Create; begin inherited; Releasing:=False; RtcConn:=nil; end; procedure TRtcWSockClientThread.OpenConn; begin RtcConn.OpenConnection(False); end; procedure TRtcWSockClientThread.CloseConn(_lost:boolean); begin if RTC_LIMIT_CONN then rtcCloseAction(self); if assigned(RtcConn) then begin try RtcConn.Lost:=_lost; if not Releasing then RtcConn.InternalDisconnect; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClientThread.CloseConn : RtConn.InternalDisconnect',E); // ignore exceptions end; end; end; destructor TRtcWSockClientThread.Destroy; begin CloseConn(false); if assigned(RtcConn) then begin try if Releasing then RtcConn.Free else if assigned(RtcConn.Client_Thread) then RtcConn.Client_Thread:=nil; finally RtcConn:=nil; end; end; inherited; end; function TRtcWSockClientThread.Work(Job: TObject):boolean; begin Result:=False; try if Job=Message_WSRead then begin if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN and not rtcStartAction(self, RTC_ACTION_READ) then TRtcThread.PostJob(self,Job,True) else RtcConn.Conn.Do_FD_READ; end else if Job=Message_WSWrite then begin if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN then if not RtcConn.Conn.AllSent then // data waiting to be sent begin if not rtcStartAction(self, RTC_ACTION_WRITE) then begin TRtcThread.PostJob(self,Job,True); Exit; end; end else rtcCloseAction(self); RtcConn.Conn.Do_FD_WRITE; end else if Job=Message_WSConnect then begin if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN then rtcCloseAction(self); RtcConn.Conn.Do_FD_CONNECT(0); end else if Job=Message_WSClose then begin if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN then rtcCloseAction(self); RtcConn.Conn.Do_FD_CLOSE(0); end else if Job=Message_WSOpenConn then begin if RTC_LIMIT_CONN and not rtcStartAction(self, RTC_ACTION_CONNECT) then TRtcThread.PostJob(self,job,True) else OpenConn; end else if Job=Message_WSCloseConn then begin CloseConn(false); end else if Job=Message_WSStop then begin RtcConn:=nil; Result:=True; Free; end else if Job=Message_WSRelease then begin Releasing:=True; Result:=True; Free; end else if Job is TRtcCloseMessage then begin try if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN then rtcCloseAction(self); RtcConn.Conn.Do_FD_CLOSE(TRtcCloseMessage(Job).Error); finally Job.Free; end; end else if Job is TRtcConnectMessage then begin try if not assigned(RtcConn) or not assigned(RtcConn.Conn) then Exit; if RTC_LIMIT_CONN then rtcCloseAction(self); RtcConn.Conn.Do_FD_CONNECT(TRtcConnectMessage(Job).Error); finally Job.Free; end; end else Result:=inherited Work(Job); except on E:Exception do begin if LOG_AV_ERRORS then Log('WSockClientThread.Work',E); try CloseConn(true); except on E:Exception do if LOG_AV_ERRORS then Log('WSockClientThread.Wor: CloseConn()',E); end; // raise; end; end; end; procedure TRtcWSockClientThread.Kill(Job: TObject); begin if (Job is TRtcCloseMessage) or (Job is TRtcConnectMessage) then Job.Free else inherited Kill(Job); end; { TRtcWSocketClient } procedure TRtcWSocketClient.Call_FD_READ; begin try TRtcThread.PostJob(Thr,Message_WSRead); except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClient.Call_FD_READ',E); end; end; procedure TRtcWSocketClient.Call_FD_WRITE; begin try TRtcThread.PostJob(Thr,Message_WSWrite); except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClient.Call_FD_WRITE',E); end; end; procedure TRtcWSocketClient.Call_FD_CLOSE(Err: word); var cjob:TObject; begin try if Err=0 then TRtcThread.PostJob(Thr,Message_WSClose,True,True) else begin cjob:=TRtcCloseMessage.Create(Err); if not TRtcThread.PostJob(Thr,cjob,True,True) then cjob.Free; end; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClient.Call_FD_CLOSE',E); end; end; procedure TRtcWSocketClient.Call_FD_CONNECT(Err: word); var cjob:TObject; begin try if Err=0 then TRtcThread.PostJob(Thr,Message_WSConnect) else begin cjob:=TRtcConnectMessage.Create(Err); if not TRtcThread.PostJob(Thr,cjob) then cjob.Free; end; except on E:Exception do if LOG_SOCKET_ERRORS then Log('WSockClient.Call_FD_CONNECT',E); end; end; { TRtcInfoMessage } constructor TRtcInfoMessage.Create(Value: word); begin inherited Create; Error:=Value; end; initialization Message_WSOpenConn:=TRtcBaseMessage.Create; Message_WSCloseConn:=TRtcBaseMessage.Create; Message_WSConnect:=TRtcBaseMessage.Create; Message_WSRead:=TRtcBaseMessage.Create; Message_WSWrite:=TRtcBaseMessage.Create; Message_WSClose:=TRtcBaseMessage.Create; Message_WSStop:=TRtcBaseMessage.Create; Message_WSRelease:=TRtcBaseMessage.Create; finalization Garbage(Message_WSOpenConn); Garbage(Message_WSCloseConn); Garbage(Message_WSConnect); Garbage(Message_WSRead); Garbage(Message_WSWrite); Garbage(Message_WSClose); Garbage(Message_WSStop); Garbage(Message_WSRelease); end.
unit record_properties_2; interface type TRec = record a, b: int32; function GetA: Int32; function GetB: Int32; procedure SetA(Value: Int32); procedure SetB(Value: Int32); property AR: Int32 read GetA; property ARW: Int32 read GetA write SetA; property BR: Int32 read GetB; property BRW: Int32 read GetB write SetB; end; var R: TRec; GA, GB: Int32; implementation function TRec.GetA: Int32; begin Result := a; end; function TRec.GetB: Int32; begin Result := b; end; procedure TRec.SetA(Value: Int32); begin a := Value; end; procedure TRec.SetB(Value: Int32); begin b := Value; end; procedure Test; begin R.A := 5; R.B := 6; GA := R.AR; GB := R.BR; end; initialization Test(); finalization Assert(GA = 5); Assert(GB = 6); end.
unit uFormParent; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls,PNGImage, ExtCtrls, gdipapi,gdipobj,GDIPUTIL,IniFiles; type TRectangle = class public x:Integer; y:integer; width : integer; height : integer; procedure Position(x,y,width,Height: integer); function contains(x,y:integer):boolean; end; TFormParent = class(TForm) protected procedure SetLayerForm(bitmap: tgpbitmap;show:boolean); procedure SetWindowModel(Desktop : Boolean); private oldpoint : TPoint; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public isMouseDown : Boolean; isMouseMove : Boolean; isMouseIn : boolean; CurrentDate : TDateTime; closeIconRect : TRectangle; menuIconRect : TRectangle; FFile: TIniFile; procedure DrawMenuButton(Graphics: GPGraphics); constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InitPosition(); procedure PositionManagement(x,y:integer); end; implementation { TFormParent } procedure TFormParent.CMMouseEnter(var Message: TMessage); begin isMouseIn := true; Repaint; end; procedure TFormParent.CMMouseLeave(var Message: TMessage); begin isMouseIn := false; Repaint; end; constructor TFormParent.create(AOwner: TComponent); begin inherited; isMouseMove := false; closeIconRect := TRectangle.Create; menuIconRect := TRectangle.Create; CurrentDate := Date; InitPosition; end; procedure TFormParent.DrawMenuButton(Graphics: GpGraphics); var Image: tgpbitmap; begin Image:= tgpbitmap.Create('BlackGlass\close.png'); TGpGraphics(Graphics).DrawImage(Image,195,11); Image:= tgpbitmap.Create('BlackGlass\menu.png'); TGpGraphics(Graphics).DrawImage(Image,55,13); closeIconRect.Position(195,11,16,16); menuIconRect.Position(55,13,16,16); end; procedure TFormParent.InitPosition; var FormCalendarPosX, FormCalendarPosY : integer; FormWeatherPosX, FormWeatherPosY : integer; begin FFile:= TIniFile.Create(GetCurrentDir + '\initializer.ini'); // FFile.WriteInteger('FormCalendar', 'CurrentPosX', 5); FormCalendarPosX := FFile.ReadInteger('FormCalendar', 'CurrentPosX', 0); FormCalendarPosY := FFile.ReadInteger('FormCalendar', 'CurrentPosY', 0); FormWeatherPosX := FFile.ReadInteger('FormWeather', 'CurrentPosX', 0); FormWeatherPosY := FFile.ReadInteger('FormWeather', 'CurrentPosY', 0); if(Name = 'FormCalendar') then PositionManagement(FormCalendarPosX,FormCalendarPosY) else if(Name = 'FormEvent') then begin PositionManagement(10,10); end else begin PositionManagement(FormWeatherPosX,FormWeatherPosY); end; end; procedure TFormParent.SetLayerForm(bitmap: tgpbitmap;show:boolean); var pt1, pt2 : TPoint; sz : TSize; bf : TBlendFunction; nTran : Integer; bmp, old_bmp : HBITMAP; DC : HDC; begin nTran := 255; pt1 := Point(left,top); pt2 := Point(0, 0); sz.cx := {bitmap.Get}Width; sz.cy := {bitmap.Get}Height; bf.BlendOp := AC_SRC_OVER; bf.BlendFlags := 0; if (nTran<0) or (nTran>255) then nTran:=255; bf.SourceConstantAlpha := nTran; bf.AlphaFormat := AC_SRC_ALPHA; DeleteObject(bmp); bitmap.GetHBITMAP(0,bmp); DeleteDC(DC); DC := CreateCompatibleDC(Canvas.Handle); old_bmp := SelectObject(DC, bmp); UpdateLayeredWindow(Handle, Canvas.Handle, @pt1, @sz, DC, @pt2,0, @bf,ULW_ALPHA); end; procedure TFormParent.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; isMouseDown := true; oldpoint.X := X; oldpoint.Y := Y; if (closeIconRect.Contains(x,y)) then begin Close(); end; end; procedure TFormParent.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if (isMouseDown and (ssLeft in shift) and (oldpoint.X <> X) and (oldpoint.Y <> Y)) then begin isMouseMove := true; Left := Left+x-oldpoint.X; top := top+Y-oldpoint.Y; end; end; procedure TFormParent.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; isMouseDown := false; isMouseMove := false; end; procedure TFormParent.PositionManagement(x, y: integer); begin Left := X; Top := Y; end; procedure TFormParent.SetWindowModel(Desktop: Boolean); begin //hwndParent := FindWindowEx(Handle,Handle,'WorkerW', ''); //SetParent(Application.Handle, Handle); //SetWindowLong(application.handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); //SetWindowPos(Self.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE); if SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED) = 0 then ShowMessage(SysErrorMessage(GetLastError)); end; destructor TFormParent.Destroy; begin inherited; FFile.Free; end; { TRectangle } function TRectangle.contains(x, y: integer): boolean; begin Result := (self.X <= x) and (x < self.X + self.Width) and (self.Y <= y) and (y < self.Y + self.Height); end; procedure TRectangle.Position(x, y, width, Height: integer); begin Self.x := X; Self.y := Y; Self.width := width; Self.height := height; end; end.
unit MediaProcessing.Convertor.H264.RGB; interface uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global, MediaProcessing.Common.Processor.FPS, MediaProcessing.Common.Processor.FPS.ImageSize, MediaProcessing.Convertor.H264.RGB.SettingsDialog; type TMediaProcessor_Convertor_H264_Rgb=class (TMediaProcessor_FpsImageSize<TfmMediaProcessingSettingsH264_Rgb>,IMediaProcessor_Convertor_H264_Rgb) protected procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; class function MetaInfo:TMediaProcessorInfo; override; public constructor Create; override; destructor Destroy; override; end; implementation uses Controls,uBaseClasses; { TMediaProcessor_Convertor_H264_Rgb } constructor TMediaProcessor_Convertor_H264_Rgb.Create; begin inherited; FImageSizeScale:=2; FImageSizeMode:=cismNone; FImageSizeWidth:=640; FImageSizeHeight:=480; end; destructor TMediaProcessor_Convertor_H264_Rgb.Destroy; begin inherited; end; class function TMediaProcessor_Convertor_H264_Rgb.MetaInfo: TMediaProcessorInfo; begin result.Clear; result.TypeID:=IMediaProcessor_Convertor_H264_Rgb; result.Name:='Конвертор H.264->RGB'; result.Description:='Преобразует видеокадры формата H.264 в формат RGB'; result.SetInputStreamTypes( [stH264, $34363268, //h264 $34363258, //X264 $34363278, //x264 $31637661, //avc1 $43564144, //DAVC $48535356, //VSSH $34363251 //Q264 ]); result.OutputStreamType:=stRGB; result.ConsumingLevel:=9; end; procedure TMediaProcessor_Convertor_H264_Rgb.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; end; procedure TMediaProcessor_Convertor_H264_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; end; initialization MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_H264_Rgb); end.
(****************************************************** AdvLed by Jurassic Pork 2013 for Lazarus created from TComled of ComPort Library ver. 3.00 written by Dejan Crnila, 1998 - 2002 email: dejancrn@yahoo.com **************************************************************************** This file is part of Lazarus See the file COPYING.modifiedLGPL.txt, included in this distribution, for details about the license. **************************************************************************** Unit: AdvLed.pas ******************************************************) unit AdvLed; {$mode objfpc}{$H+} interface uses LCLType, Classes, ExtCtrls, Controls, Graphics; type // property types TLedBitmap = Graphics.TPicture; // TLedKind = (lkRedLight, lkGreenLight, lkBlueLight, lkYellowLight, lkPurpleLight, lkBulb, lkCustom); TLedKind = (lkRedLight, lkGreenLight, lkYellowLight, lkBulb, lkCustom); TLedState = (lsDisabled, lsOff, lsOn); TAdvLedGlyphs = array[TLedState] of TLedBitmap; TLedStateEvent = procedure(Sender: TObject; AState: TLedState) of object; // led control that shows the state of serial signals TAdvLed = class(TCustomImage) private FKind: TLedKind; FState: TLedState; FBlink: Boolean; FOnChange: TLedStateEvent; FGlyphs: TAdvLedGlyphs; FBlinkTimer: TTimer; function GetGlyph(const Index: Integer): TLedBitmap; function GetBlinkDuration: Integer; procedure SetKind(const Value: TLedKind); procedure SetState(const Value: TLedState); procedure SetGlyph(const Index: Integer; const Value: TLedBitmap); procedure SetBlinkDuration(const Value: Integer); procedure SetBlink(const Value: Boolean); function StoredGlyph(const {%H-}Index: Integer): Boolean; procedure SelectLedBitmap(const LedKind: TLedKind); function BitmapToDraw: TLedBitmap; procedure BitmapNeeded; procedure DoTimer(Sender: TObject); procedure GlyphChanged(Sender: TObject); protected FlipFLop : Boolean; procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); override; procedure DoChange(AState: TLedState); dynamic; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published // kind property must be published before GlyphOn, GlyphOff,GlyphDisable property Kind: TLedKind read FKind write SetKind default lkRedLight; property GlyphDisabled: TLedBitmap index 0 read GetGlyph write SetGlyph stored StoredGlyph; property GlyphOff: TLedBitmap index 1 read GetGlyph write SetGlyph stored StoredGlyph; property GlyphOn: TLedBitmap index 2 read GetGlyph write SetGlyph stored StoredGlyph; property State: TLedState read FState write SetState; property Blink: Boolean read FBlink write SetBlink; property BlinkDuration: Integer read GetBlinkDuration write SetBlinkDuration default 1000; property Align; property AutoSize default true; property Center; property Constraints; // property Picture; property Visible; property OnClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property Stretch; property Showhint; property Transparent; property Proportional; property OnPictureChanged; property OnChange: TLedStateEvent read FOnChange write FOnChange; { property Align; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property Anchors; property Constraints; property DragKind; property ParentBiDiMode; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnEndDock; property OnResize; property OnStartDock; property OnContextPopup; } end; implementation {$R ledbuttons.res} (***************************************** * auxilary functions * *****************************************) function Min(A, B: Integer): Integer; begin if A < B then Result := A else Result := B; end; function Max(A, B: Integer): Integer; begin if A > B then Result := A else Result := B; end; (***************************************** * TAdvLed control * *****************************************) // create control constructor TAdvLed.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csSetCaption]; AutoSize:=True; FGlyphs[lsOn] := TLedBitmap.Create; FGlyphs[lsOff] := TLedBitmap.Create; FGlyphs[lsDisabled] := TLedBitmap.Create; FGlyphs[lsOn].OnChange:= @GlyphChanged; FGlyphs[lsOff].OnChange:= @GlyphChanged; FGlyphs[lsDisabled].OnChange:= @GlyphChanged; FBlinkTimer := TTimer.Create(nil); FBlinkTimer.OnTimer := @DoTimer; FBlinkTimer.Enabled := false; //if (csDesigning in ComponentState) then BitmapNeeded; end; // destroy control destructor TAdvLed.Destroy; begin FBlinkTimer.Free; FGlyphs[lsOn].Free; FGlyphs[lsOff].Free; FGlyphs[lsDisabled].Free; inherited Destroy; end; // loaded procedure TAdvLed.Loaded; begin inherited; if FKind <> lkCustom then BitmapNeeded; end; procedure TAdvLed.DoAutoAdjustLayout( const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); begin inherited DoAutoAdjustLayout(AMode, AXProportion, AYProportion); if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then begin BitmapNeeded; end; end; // timer procedure TAdvLed.DoTimer(Sender: TObject); begin if FlipFlop then SetState(lsOn ) else SetState(lsoff); FlipFlop := Not FlipFlop; end; // trigger OnChangeEvent procedure TAdvLed.DoChange(AState: TLedState); begin if Assigned(FOnChange) then FOnChange(Self, AState); invalidate; end; // if bitmap is empty, load it procedure TAdvLed.BitmapNeeded; begin if (FGlyphs[lsOn].Bitmap.Empty) or (FGlyphs[lsOff].Bitmap.Empty) or (FGlyphs[lsDisabled].Bitmap.Empty) then begin SelectLedBitmap(FKind); Picture.Assign(BitmapToDraw); end; end; procedure TAdvLed.SelectLedBitmap(const LedKind: TLedKind); const { OnBitmaps: array[TLedKind] of string = ('LEDREDON', 'LEDGREENON', 'LEDBLUEON', 'LEDYELLOWON', 'LEDPURPLEON', 'LEDBULBON', ''); OffBitmaps: array[TLedKind] of string = ('LEDREDOFF', 'LEDGREENOFF', 'LEDBLUEOFF', 'LEDYELLOWOFF', 'LEDPURPLEOFF', 'LEDBULBOFF' ,''); DisabledBitmaps: array[TLedKind] of string = ('LEDREDOFF', 'LEDGREENOFF', 'LEDBLUEOFF', 'LEDYELLOWOFF', 'LEDPURPLEOFF', 'LEDBULBOFF' ,''); } OnBitmaps: array[TLedKind] of string = ('RED', 'GREEN', 'YELLOW', 'BULBON', ''); OffBitmaps: array[TLedKind] of string = ('REDOFF', 'GREENOFF', 'YELLOWOFF','BULBOFF', ''); DisabledBitmaps: array[TLedKind] of string = ('BLACK', 'BLACK', 'BLACK','BULBDISABLED' ,''); var resName: String; begin if LedKind <> lkCustom then begin if Font.PixelsPerInch >=168 then resName := '_200' else if Font.PixelsPerInch >= 120 then resName := '_150' else resName := ''; FGlyphs[lsOn].LoadFromResourceName(HInstance, OnBitmaps[LedKind] + resName); FGlyphs[lsOff].LoadFromResourceName(HInstance, OffBitmaps[LedKind] + resName); FGlyphs[lsDisabled].LoadFromResourceName(HInstance, DisabledBitmaps[LedKind] + resName); end; end; // set led kind procedure TAdvLed.SetKind(const Value: TLedKind); begin if FKind <> Value then begin FKind := Value; SelectLedBitmap(FKind); Picture.Assign(BitmapToDraw); end; end; // set led state procedure TAdvLed.SetState(const Value: TLedState); begin FState := Value; if not (csLoading in ComponentState) then DoChange(FState); Picture.Assign(BitmapToDraw); end; function TAdvLed.GetGlyph(const Index: Integer): TLedBitmap; begin case Index of 0: Result := FGlyphs[lsDisabled]; 1: Result := FGlyphs[lsOff]; 2: Result := FGlyphs[lsOn]; else Result := nil; end; end; procedure TAdvLed.GlyphChanged(Sender: TObject ); begin // if (csDesigning in ComponentState) then Picture.Assign(Sender as TPicture); if (csDesigning in ComponentState) then begin if Sender = FGlyphs[lsDisabled] then FState := lsDisabled; if Sender = FGlyphs[lsOff] then FState := lsOff; if Sender = FGlyphs[lsOn] then FState := lsOn; Picture.Assign(Sender as TPicture); end; end; // set custom bitmap procedure TAdvLed.SetGlyph(const Index: Integer; const Value: TLedBitmap); begin if FKind = lkCustom then begin case Index of 0: FGlyphs[lsDisabled].Assign(Value); 1: FGlyphs[lsOff].Assign(Value); 2: FGlyphs[lsOn].Assign(Value); end; end; Picture.Assign(BitmapToDraw); end; function TAdvLed.StoredGlyph(const Index: Integer): Boolean; begin Result := FKind = lkCustom; end; // get bitmap for drawing function TAdvLed.BitmapToDraw: TLedBitmap; var ToDraw: TLedState; begin if not Enabled then ToDraw := lsOff else ToDraw := FState; Result := FGlyphs[ToDraw]; end; function TAdvLed.GetBlinkDuration: Integer; begin Result := FBlinkTimer.Interval; end; procedure TAdvLed.SetBlinkDuration(const Value: Integer); begin FBlinkTimer.Interval := Value; end; // set led blink procedure TAdvLed.SetBlink(const Value: Boolean); begin FBlink :=Value; if (csDesigning in ComponentState) then Exit; FBlinkTimer.Enabled := FBlink; end; end.
unit HCFloatBarCodeItem; interface uses Windows, Classes, Controls, SysUtils, Graphics, HCStyle, HCCustomData, HCXml, HCItem, HCCustomFloatItem, HCCode128B, HCCommon; type THCFloatBarCodeItem = class(THCCustomFloatItem) private FText: string; protected function GetText: string; override; procedure SetText(const Value: string); override; public constructor Create(const AOwnerData: THCCustomData); override; procedure Assign(Source: THCCustomItem); override; procedure DoPaint(const AStyle: THCStyle; const ADrawRect: TRect; const ADataDrawTop, ADataDrawBottom, ADataScreenTop, ADataScreenBottom: Integer; const ACanvas: TCanvas; const APaintInfo: TPaintInfo); override; procedure SaveToStream(const AStream: TStream; const AStart, AEnd: Integer); override; procedure LoadFromStream(const AStream: TStream; const AStyle: THCStyle; const AFileVersion: Word); override; procedure ToXml(const ANode: IHCXMLNode); override; procedure ParseXml(const ANode: IHCXMLNode); override; end; implementation { THCFloatBarCodeItem } procedure THCFloatBarCodeItem.Assign(Source: THCCustomItem); begin inherited Assign(Source); FText := (Source as THCFloatBarCodeItem).Text; end; constructor THCFloatBarCodeItem.Create(const AOwnerData: THCCustomData); begin inherited Create(AOwnerData); Self.StyleNo := Ord(THCStyle.FloatBarCode); Width := 80; Height := 60; SetText('0000'); end; procedure THCFloatBarCodeItem.DoPaint(const AStyle: THCStyle; const ADrawRect: TRect; const ADataDrawTop, ADataDrawBottom, ADataScreenTop, ADataScreenBottom: Integer; const ACanvas: TCanvas; const APaintInfo: TPaintInfo); var vCode128B: THCCode128B; vBitmap: TBitmap; begin vBitmap := TBitmap.Create; try vCode128B := THCCode128B.Create; try vCode128B.Margin := 2; vCode128B.Height := Height; vCode128B.CodeKey := FText; vBitmap.SetSize(vCode128B.Width, vCode128B.Height); vCode128B.PaintToEx(vBitmap.Canvas); ACanvas.StretchDraw(ADrawRect, vBitmap); finally FreeAndNil(vCode128B); end; finally vBitmap.Free; end; inherited DoPaint(AStyle, ADrawRect, ADataDrawTop, ADataDrawBottom, ADataScreenTop, ADataScreenBottom, ACanvas, APaintInfo); end; function THCFloatBarCodeItem.GetText: string; begin Result := FText; end; procedure THCFloatBarCodeItem.LoadFromStream(const AStream: TStream; const AStyle: THCStyle; const AFileVersion: Word); begin inherited LoadFromStream(AStream, AStyle, AFileVersion); HCLoadTextFromStream(AStream, FText, AFileVersion); end; procedure THCFloatBarCodeItem.ParseXml(const ANode: IHCXMLNode); begin inherited ParseXml(ANode); FText := ANode.Text; end; procedure THCFloatBarCodeItem.SaveToStream(const AStream: TStream; const AStart, AEnd: Integer); begin inherited SaveToStream(AStream, AStart, AEnd); HCSaveTextToStream(AStream, FText); end; procedure THCFloatBarCodeItem.SetText(const Value: string); var vBarCode: THCCode128B; begin if FText <> Value then begin FText := Value; vBarCode := THCCode128B.Create; try vBarCode.Margin := 2; vBarCode.CodeKey := FText; Width := vBarCode.Width; finally vBarCode.Free; end; end; end; procedure THCFloatBarCodeItem.ToXml(const ANode: IHCXMLNode); begin inherited ToXml(ANode); ANode.Text := FText; end; end.
//----------------------------------------- // Maciej Czekański // maves90@gmail.com //----------------------------------------- unit Utility; //--------------------------------------------------------------- interface //--------------------------------------------------------------- uses Windows; // Zapisuje podaną wiadomość do pliku oraz na konsoli procedure Log(msg: string); // Zwraca aktualny czas w sekundach. function GetTime: Double; //--------------------------------------------------------------- implementation //--------------------------------------------------------------- VAR gLogFile : Text; gTimerFrequency : Double; // Inicjalizuje logger procedure InitLogger; begin Assign(gLogFile, 'log.txt'); Rewrite(gLogFile); WriteLn(gLogFile, 'Log file created'); end; // Inicjalizuje timer procedure InitTimer; VAR li: Int64; begin if QueryPerformanceFrequency(li) = false then begin Log('Cant init timer'); end else Log('Timer initialized'); gTimerFrequency := 1.0/li; end; function GetTime: Double; VAR li: Int64; begin QueryPerformanceCounter(li); GetTime:= li*gTimerFrequency; end; procedure Log(msg: string); begin Append(gLogFile); WriteLn(gLogFile, msg); Close(gLogFile); WriteLn(msg); end; begin InitLogger; InitTimer; end.
{******************************************} { TeeChart. TChart Component } { Copyright (c) 1995-2001 by David Berneda } { All Rights Reserved } {******************************************} unit ubitmap; interface { This example shows how to draw a custom Bitmap on a Panel Chart component } { Bitmap images (TBitmap component) can be painted in several styles: pbmStretch : Bitmap is stretched to fit Chart Panel Rectangle pbmTile : Bitmap is repeteadly painted without stretching. pbmCenter : Bitmap is painted centered without stretching. You use the PanelBitmapMode property: Chart1.PanelBitmapMode := pbmTile ; } uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Chart, Series, StdCtrls, Teengine, Buttons, TeeProcs; type TBitmapForm = class(TForm) Chart1: TChart; OpenDialog1: TOpenDialog; Panel1: TPanel; RadioGroup1: TRadioGroup; BitBtn1: TBitBtn; BitBtn3: TBitBtn; CheckBox1: TCheckBox; Series1: TBarSeries; Button1: TButton; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TBitmapForm.FormCreate(Sender: TObject); begin { This is to show something random in this example } Series1.FillSampleValues(10); end; procedure TBitmapForm.RadioGroup1Click(Sender: TObject); begin Chart1.BackImageMode:=TTeeBackImageMode(RadioGroup1.ItemIndex); end; procedure TBitmapForm.BitBtn1Click(Sender: TObject); begin if OpenDialog1.Execute then begin RadioGroup1.Enabled:=False; Chart1.BackImage.LoadFromFile(OpenDialog1.FileName); RadioGroup1.Enabled:=True; end; end; procedure TBitmapForm.CheckBox1Click(Sender: TObject); begin Chart1.BackImageInside:=CheckBox1.Checked; end; procedure TBitmapForm.Button1Click(Sender: TObject); begin Chart1.BackImage:=nil; end; end.
unit u_params; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.IniFiles, Winapi.TlHelp32, u_ext_info, u_obimp_const; const CONF_NAME = 'config.ini'; //filling plugin parameters ExtParams: TExtParamsPG = ( ListenTextMsgs: False; ); ExtInfo: TExtensionInfo = ( ExtType : EXT_TYPE_PLUGIN; ExtUUID : ($F8,$48,$D9,$CB,$54,$76,$42,$82,$82,$DB,$D0,$20,$3B,$35,$78,$FD); //MUST BE unique for every new extension/plugin ExtName : 'Uptime server info plugin'; ExtVer : '0.0.1'; ExtAuthor : 'alexey-m'; ExtInfoURL : 'https://alexey-m.ru'; ExtParams : @ExtParams; ExtTimer : True; ); FTP_SRV_NAME = 'BimFtSrv32.exe'; type TConfig = record token: String; url: String; path: String; pathLog: String; srvVer: String; updateTime: UInt; startTime: UInt; idTimer: UIntPtr; enable: Boolean; end; //helpful functions procedure OutDebugStr(s: string); procedure LogToFile(FileName: string; Data: string); procedure InitConfig(AEventsPG: IEventsPG); function CmpStr(Str1, Str2: String): Boolean; function getPIdBimFtSrv(): UInt; function getStartTimeProc(const procId: THandle): UInt; var config: TConfig; implementation {*****************************************************************} procedure OutDebugStr(s: string); begin OutputDebugString(PChar(s)); end; {*******************************************************************} procedure LogToFile(FileName: string; Data: string); var aFS: TFileStream; BOM: TBytes; begin aFS := nil; try if FileExists(FileName) then aFS := TFileStream.Create(FileName, fmOpenWrite or fmShareDenyWrite) else begin aFS := TFileStream.Create(FileName, fmCreate); if Assigned(aFS) then begin BOM := TEncoding.Unicode.GetPreamble; aFS.Position := 0; aFS.Write(BOM[0], Length(BOM)); end; end; except if Assigned(aFS) then aFS.Free; Exit; end; aFS.Position := aFS.Size; try Data := Data + #13#10; SetLength(Data, Length(Data)); aFS.Write(Data[1], Length(Data) * SizeOf(Char)); finally aFS.Free; end; end; function DateTimeToUnix(ConvDate: TDateTime): Longint; const // Sets UnixStartDate to TDateTime of 01/01/1970 UnixStartDate: TDateTime = 25569.0; begin Result := Round((ConvDate - UnixStartDate) * 86400); end; function WindowsTickToUnixSeconds(windowsTicks: UInt64): UInt; const WINDOWS_TICK = 10000000; SEC_TO_UNIX_EPOCH = 11644473600; begin Result:= windowsTicks div WINDOWS_TICK - SEC_TO_UNIX_EPOCH; end; procedure InitConfig(AEventsPG: IEventsPG); var cfgFile: String; buffer: array[0..MAX_PATH] of WideChar; srvInfo: TExtServerInfo; ini: TIniFile; begin config.startTime:= DateTimeToUnix(Now()); GetModuleFileName(HInstance, @buffer, sizeOf(buffer)); config.path:= ExtractFilePath(PChar(@buffer)); cfgFile:= config.path + CONF_NAME; config.enable:= False; AEventsPG.GetServerInfo(srvInfo); config.srvVer:= Format('%d.%d.%d.%d', [srvInfo.VerMajor, srvInfo.VerMinor, srvInfo.VerRelease, srvInfo.VerBuild]); config.pathLog:= srvInfo.PathLogFiles; if FileExists(cfgFile) then begin ini:= TIniFile.Create(cfgFile); try config.token:= ini.ReadString('main', 'token', ''); config.url:= ini.ReadString('main', 'url', 'http://localhost/uptime'); config.updateTime:= ini.ReadInteger('main', 'timeUpdate', 180); config.enable:= ini.ReadBool('main', 'enable', False); finally ini.Free; end; end; end; function getStartTimeProc(const procId: THandle): UInt; var hProcess: THandle; lpCreationTime, lpExitTime, lpKernelTime, lpUserTime: TFileTime; begin Result:= 0; hProcess:= OpenProcess(PROCESS_QUERY_INFORMATION, false, procId); if (hProcess <> 0) then try if GetProcessTimes(hProcess, lpCreationTime, lpExitTime, lpKernelTime, lpUserTime) then begin Result:= WindowsTickToUnixSeconds(PUInt64(@lpCreationTime)^); end; finally CloseHandle(hProcess); end; end; function getPIdBimFtSrv(): UInt; var hSnapShot: THandle; ProcInfo: TProcessEntry32; exeFile: String; begin Result:= 0; hSnapShot:= CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapShot <> INVALID_HANDLE_VALUE) then try ProcInfo.dwSize:= SizeOf(ProcInfo); if (Process32First(hSnapshot, ProcInfo)) then repeat exeFile:= ExtractFileName(ProcInfo.szExeFile); if CmpStr(FTP_SRV_NAME, exeFile) then begin Result:= getStartTimeProc(procInfo.th32ProcessID); Break; end; until not Process32Next(hSnapShot, ProcInfo); finally CloseHandle(hSnapShot); end; end; function CmpStr(Str1, Str2: String): Boolean; begin Result:= lstrcmpi(PChar(Str1), PChar(Str2)) = 0; end; end.
unit clsTClienteDTO; interface type TClienteDTO = class private FID: Integer; FLogin: String; FSenha: String; FEmail: String; FNome: String; published property ID: Integer read FID write FID; property Login: String read FLogin write FLogin; property Senha: String read FSenha write FSenha; property Email: String read FEmail write FEmail; property Nome: String read FNome write FNome; end; implementation end.
unit TMMsgs; { Aestan Tray Menu Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu for more information. This work is hereby released into the Public Domain. To view a copy of the public domain dedication, visit: http://creativecommons.org/licenses/publicdomain/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. This unit contains some constants for various 'compiler' messages etc. } interface resourcestring {***** PARSING *****} { Parameter parsing } SParsingParamHasNoValue = 'Specified parameter "%s" has no value'; SParsingParamQuoteError = 'Mismatched or misplaced quotes on parameter "%s"'; SParsingParamMissingClosingQuote = 'Missing closing quote on parameter "%s"'; SParsingParamDuplicated = 'Cannot have multiple "%s" parameters'; SParsingParamEmpty2 = 'Parameter "%s" is empty'; SParsingParamNoQuotes2 = 'Parameter "%s" cannot include quotes (")'; SParsingParamUnknownParam = 'Unrecognized parameter name "%s"'; SParsingParamInvalidBoolValue = 'Unrecognized boolean value "%s" (' + 'should be 1, 0, yes, no, on, off, true or false)'; SParsingParamInvalidIntValue = 'Integer expected on parameter "%s"'; SParsingUnknownVarType = 'Unknown variable type "%s"'; SParsingInvalidVarParam = 'The "%s" parameter is invalid in combination with ' + 'this type of variable'; SParsingInvalidRegRoot = 'Invalid registry root "%s"'; SParsingUnknownMenuItemType = 'Unknown menu item type "%s"'; SParsingInvalidMenuItemParam = 'The "%s" parameter is invalid in ' + 'combination with this type of menu item'; SParsingUnknownActionType = 'Unknown action type "%s"'; SParsingInvalidActionParam = 'The "%s" parameter is invalid in ' + 'combination with this type of action'; SParsingUnknownShowCmd = 'Unknown ShowCmd type "%s"'; SParsingParamUnknownService = 'Parameter "%s" specifies an unknown service'; SParsingServiceParamInvalid = 'The "Service" parameter is only valid in combination ' + 'with "ServiceSubMenu" items or "Service" actions'; SParsingInvalidServiceAction = 'Unknown service action "%s"'; SParsingParamExpected = 'Parameter "%s" expected'; SParsingCannotAssignActionFlagsYet = 'Please specify action flags after ' + 'specifying the action type'; SParsingAssignVarTypeFirst = 'You have to specify the variable''s type first'; { Flags } SParsingParamUnknownFlag2 = 'Parameter "%s" includes an unknown flag'; SParsingInvalidActionFlag = 'The "%s" flag is invalid in combination with ' + 'this type of action'; { Line parsing } SParsingSectionTagInvalid = 'Invalid section tag'; SParsingSectionBadEndTag = 'Not inside "%s" section, but an end tag for ' + 'it was encountered'; SParsingTextNotInSection = 'Text is not inside a section'; { Section directives } SParsingUnknownDirective = 'Unrecognized [%s] section directive "%s"'; SParsingEntryAlreadySpecified = '[%s] section directive "%s" already specified'; SParsingInvalidDirectiveValue = 'Invalid value "%s" on directive "%s"'; SParsingUnknownFontStyle = 'Unknown font style flag'; SParsingInvalidFontSpec = 'Invalid font specification'; SParsingInvalidColor = 'Invalid color specification on directive "%s"'; SParsingAmbiguousTrayIcon = 'You cannot specify both the TrayIcon*Running and ' + 'the TrayIcon directives in the [Config] section'; SParsingAmbiguousAboutText = 'You cannot specify both the AboutTextFile ' + 'directive and the [AboutText] section'; { Other } SParsingCouldNotLoadFile = 'Could not load the file "%s" specified ' + 'in the directive "%s"'; SParsingCouldNotOpenRegKey = 'Could not open registry key "%s\%s"'; SParsingCouldNotReadRegValue = 'Could not query registry value "%s\%s\%s"'; SParsingRegValueInvalidFormat = 'Registry value "%s\%s\%s" has an invalid format: %s'; SParsingValidatePropertiesFailed = 'Internal error: TTMConfigReader hasn''t been ' + 'initialized properly'; SParsingInvalidService = 'Invalid service "%s"'; SParsingCmdLineParameterNotFound = 'Command-line parameter "%s" not found'; {***** POST-PARSING VALIDATION *****} SValNoTrayIconAssigned = 'No tray icon was specified. Please assign a tray ' + 'icon by using one of the TrayIcon* directives in the [Config] section'; SValMustSpecifyThreeStateIcons = 'You have to specify all of the following ' + 'directives in the [Config] section: TrayIconAllRunning, TrayIconSomeRunning ' + 'and TrayIconNoneRunning'; {***** OTHER *****} SReaderHasntBeenInitializedYet = 'TTMConfigReader hasn''t been initialized properly yet'; SReaderSyntaxError = 'The configuration file contains a syntax error on line %d:'; SCannotSetPromptVarValue = 'Cannot set the value of a "Prompt" variable'; {***** DEFAULT MESSAGES *****} SDefAllRunningHint = 'All services running'; SDefSomeRunningHint = '%n of %t service(s) running'; SDefNoneRunningHint = 'None of %t service(s) running'; {*** MAIN PROGRAM ***} SMainCouldNotLoadConfig = 'Could not load configuration file'; SMainCouldNotExecuteMenuItem = 'Could not execute menu item (internal error)'; SMainBuiltInNotImplemented = 'Sorry, somehow you''ve come across a built-in action that hasn''t been implemented yet'; {*** HTML WINDOW ***} SHtmlUnknownAction = 'Unknown action "%s". You should declare actions ' + 'using the [Config]: HtmlActions directive before using them.'; implementation end.
unit sNIF.data; { ******************************************************* 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 uses System.SysUtils, ThreadUtils.SafeDataTypes; type { PROPOSITO: Datos de cada fichero candidato y resultado de su exploración } TsNIFData = class Ruta: string; Fichero: string; error: boolean; mensajeError: string; FechaUltimoAcceso: TDateTime; CuentaNIF: cardinal; constructor Create(const ARuta, AFichero: string; const AFechaUltimoAcceso: TDateTime); end; // -------------------------------------------------------------------------- TColaResultados = TThreadSafeQueue<TsNIFData>; TColaCandidatos = TColaResultados; // -------------------------------------------------------------------------- implementation constructor TsNIFData.Create(const ARuta, AFichero: string; const AFechaUltimoAcceso: TDateTime); begin Ruta := ARuta; Fichero := AFichero; FechaUltimoAcceso := AFechaUltimoAcceso; CuentaNIF := 0; error := false; mensajeError := ''; end; end.
unit uOutThread; interface uses Classes, SysUtils, FireDAC.Comp.Client, FireDAC.Stan.Option, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Stan.Async, FireDAC.Stan.Expr, FireDAC.Stan.Pool, IOUtils, Generics.Collections, Variants, DateUtils, uBaseThread, IniFiles, uTypes, uGlobal; type TOutThread = class(TBaseThread) private FConfig: TOraConfig; FConn: TFDConnection; FQuery: TFDQuery; FMaxValue: string; FLastTime: Double; function GetConn: TFDConnection; function QueryDataFromOracle: boolean; function GetRecord: string; procedure SaveMaxNO; protected procedure Prepare; override; procedure Perform; override; procedure AfterTerminate; override; public constructor Create(config: TOraConfig); overload; destructor Destroy; override; end; implementation { TOutThread } constructor TOutThread.Create(config: TOraConfig); begin FConfig := config; FConn := GetConn; inherited Create; end; destructor TOutThread.Destroy; begin FQuery.Free; FConn.Free; inherited; end; procedure TOutThread.Prepare; begin inherited; logger.Info(FConfig.Host + ' start' + FConfig.IntervalSecond.ToString); FMaxValue := FConfig.MaxOrderFieldValue; FLastTime := 0; end; procedure TOutThread.AfterTerminate; begin inherited; logger.Info(FConfig.Host + ' stoped'); end; procedure TOutThread.Perform; var lines: TStrings; filename: string; firstLine: boolean; begin inherited; if now - FLastTime < FConfig.IntervalSecond * OneSecond then exit; FLastTime := now; if QueryDataFromOracle then begin logger.Info('FQuery.RecordCount = ' + FQuery.RecordCount.ToString); if FQuery.RecordCount > 0 then begin lines := TStringList.Create; if FConfig.OrderField = '' then lines.Add('Delete ' + FConfig.TableName); lines.Add(FConfig.InsertSQL); firstLine := true; while not FQuery.Eof do begin if firstLine then begin lines.Add(GetRecord); firstLine := false; end else lines.Add(',' + GetRecord); if lines.Count >= 1000 then begin filename := FConfig.TargetFilePath + 'JJCSY_' + FConfig.TableName + FormatDateTime('yyyymmddhhmmsszzz', now); lines.SaveToFile(filename); logger.Info('SaveToFile: ' + filename); lines.Clear; lines.Add(FConfig.InsertSQL); firstLine := true; sleep(1); end; if FConfig.OrderField <> '' then FMaxValue := FQuery.FieldByName(FConfig.OrderField).AsString; FQuery.Next; end; if lines.Count > 1 then begin filename := FConfig.TargetFilePath + 'JJCSY_' + FormatDateTime('yyyymmddhhmmsszzz', now); lines.SaveToFile(filename); logger.Info('SaveToFile: ' + filename); end; lines.Free; if FConfig.OrderField <> '' then SaveMaxNo; end; FQuery.Close; end; end; function TOutThread.GetConn: TFDConnection; begin result := TFDConnection.Create(nil); result.FetchOptions.Mode := fmAll; result.Params.Add('DriverID=Ora'); result.Params.Add (Format('Database=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = %s)(PORT = %s)))' + '(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = %s)))', [FConfig.Host, FConfig.Port, FConfig.Sid])); result.Params.Add(Format('User_Name=%s', [FConfig.UserName])); result.Params.Add(Format('Password=%s', [FConfig.Password])); result.Params.Add('CharacterSet=UTF8'); // ·ñÔòÖÐÎÄÂÒÂë result.LoginPrompt := false; FQuery := TFDQuery.Create(nil); FQuery.DisableControls; FQuery.Connection := result; end; function TOutThread.QueryDataFromOracle: boolean; begin result := True; FQuery.Close; if FConfig.OrderField <> '' then FQuery.SQL.Text := Format(FConfig.SelectSQL, [FMaxValue]) else FQuery.SQL.Text := FConfig.SelectSQL; try FConn.Open; FQuery.Open; except on e: exception do begin result := false; logger.Error('QueryDataFromOracle:' + e.Message + FQuery.SQL.Text); end; end; end; procedure TOutThread.SaveMaxNO; var ini: TIniFile; begin ini:= TIniFile.Create(TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'Config.ini')); ini.WriteString(FConfig.TableName, 'MaxOrderFieldValue', FMaxValue); ini.Free; end; function TOutThread.GetRecord: string; var I: Integer; begin result := FQuery.Fields[0].AsString.QuotedString; for I := 1 to FQuery.FieldCount - 1 do begin result := result + ',' + FQuery.Fields[I].AsString.QuotedString; end; result := '(' + result + ')'; end; end.
unit PrtCtrl; interface uses Windows, Winspool, SysUtils, PMConst; type EPrtOpenErr = class(Exception); TPrinterCtrl = class(TObject) private FHandle: THandle; FName: string; public constructor Create; destructor Destroy; override; procedure Open(PrtName: string); function Close: Boolean; function StartDocPrinter(Level: Cardinal; pDocInfo: Pointer): DWORD; overload; function StartDocPrinter(DocName, OutputFile, DataType: string): DWORD; overload; function EndDocPrinter: BOOL; function Write(pBuf: Pointer; BufSize: DWORD): DWORD; published property Handle: THandle read FHandle; property Name: string read FName; end; implementation { TPrinterCtrl } function TPrinterCtrl.Close: Boolean; begin Result := False; if FHandle <> 0 then begin Result := ClosePrinter(FHandle); FHandle := 0; FName := ''; end; end; constructor TPrinterCtrl.Create; begin end; destructor TPrinterCtrl.Destroy; begin Close; inherited; end; function TPrinterCtrl.EndDocPrinter: BOOL; begin Result := Winspool.EndDocPrinter(FHandle); end; procedure TPrinterCtrl.Open(PrtName: string); var Res: BOOL; begin Res := OpenPrinter(PChar(PrtName), FHandle, nil); if Res then FName := PrtName else raise EPrtOpenErr.CreateFmt(ESTR_PrinterOpenError + ESTR_ErrorValue, [PrtName, GetLastError]); end; function TPrinterCtrl.StartDocPrinter(Level: Cardinal; pDocInfo: Pointer): DWORD; begin Result := Winspool.StartDocPrinter(FHandle, Level, pDocInfo); end; function TPrinterCtrl.StartDocPrinter(DocName, OutputFile, DataType: string): DWORD; var Doc: TDocInfo1; begin with Doc do begin pDocName := PChar(DocName); pOutputFile := PChar(OutputFile); pDatatype := PChar(DataType); end; Result := StartDocPrinter(1, @Doc); end; function TPrinterCtrl.Write(pBuf: Pointer; BufSize: DWORD): DWORD; var Written: DWORD; begin WritePrinter(FHandle, pBuf, BufSize, Written); Result := Written; end; end.
(******************************************************************************* Author: -> Jean-Pierre LESUEUR (@DarkCoderSc) https://github.com/DarkCoderSc https://gist.github.com/DarkCoderSc https://www.phrozen.io/ License: -> MIT *******************************************************************************) unit UntEnumDLLExport; interface uses Classes, Windows, Generics.Collections, SysUtils; type TExportEntry = class private FName : String; FForwarded : Boolean; FForwardName : String; FRelativeAddr : Cardinal; FAddress : Int64; FOrdinal : Word; {@M} function GetFormatedAddress() : String; function GetFormatedRelativeAddr() : String; public {@C} constructor Create(); {@G/S} property Name : String read FName write FName; property Forwarded : Boolean read FForwarded write FForwarded; property ForwardName : String read FForwardName write FForwardName; property Address : Int64 read FAddress write FAddress; property RelativeAddr : Cardinal read FRelativeAddr write FRelativeAddr; property Ordinal : Word read FOrdinal write FOrdinal; {@G} property FormatedAddress : String read GetFormatedAddress; property FormatedRelativeAddress : String read GetFormatedRelativeAddr; end; TEnumDLLExport = class private FItems : TObjectList<TExportEntry>; FFileName : String; {@M} public {@C} constructor Create(AFileName : String); destructor Destroy(); override; {@M} function Enum() : Integer; {@G} property Items : TObjectList<TExportEntry> read FItems; property FileName : String read FFileName; end; implementation {+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Local Functions +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} function IntToHexF(AValue : Int64; APad : Word = 0 {0=Auto}) : String; begin if (APad = 0) then begin if (AValue <= High(Word)) then APad := 2 else if (AValue <= High(DWORD)) and (AValue > High(Word)) then APad := 8 else if (AValue <= High(Int64)) and (AValue > High(DWORD)) then APad := 16; end; result := '0x' + IntToHex(AValue, APad); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TExportEntry +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} constructor TExportEntry.Create(); begin FName := ''; FForwarded := False; FForwardName := ''; FAddress := 0; FRelativeAddr := 0; FOrdinal := 0; end; function TExportEntry.GetFormatedAddress() : String; begin result := IntToHexF(FAddress {AUTO}); end; function TExportEntry.GetFormatedRelativeAddr() : String; begin result := IntToHexF(FRelativeAddr, (SizeOf(FRelativeAddr) * 2)); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TEnumPEExport +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} constructor TEnumDLLExport.Create(AFileName : String); begin FItems := TObjectList<TExportEntry>.Create(True); FFileName := AFileName; end; destructor TEnumDLLExport.Destroy(); begin if Assigned(FItems) then FreeAndNil(FItems); /// inherited Destroy(); end; { ERROR_CODES: ------------------------------------------------------------------------------ -99 : Unknown. -1 : Could not open file. -2 : Could not read image dos header. -3 : Invalid or corrupted PE File. -4 : Could not read nt header signature. -5 : Could not read image file header. -6 : Could not read optional header. -7 : Could not retrieve entry export address. -8 : Could not read export directory. -9 : No exported functions. } function TEnumDLLExport.Enum() : Integer; var hFile : THandle; dwBytesRead : Cardinal; AImageDosHeader : TImageDosHeader; AImageNtHeaderSignature : DWORD; x64Binary : Boolean; AImageFileHeader : TImageFileHeader; AImageOptionalHeader32 : TImageOptionalHeader32; AImageOptionalHeader64 : TImageOptionalHeader64; AExportAddr : TImageDataDirectory; AExportDir : TImageExportDirectory; I : Integer; ACanCatchSection : Boolean; AOffset : Cardinal; AExportName : AnsiString; ALen : Cardinal; AOrdinal : Word; AFuncAddress : Cardinal; AImageBase : UInt64; AExportEntry : TExportEntry; AForwarded : Boolean; AForwardName : AnsiString; AImportVirtualAddress : Cardinal; function RVAToFileOffset(ARVA : Cardinal) : Cardinal; var I : Integer; AImageSectionHeader : TImageSectionHeader; ASectionsOffset : Cardinal; begin result := 0; /// if (ARVA = 0) or (NOT ACanCatchSection) then Exit(); /// ASectionsOffset := ( AImageDosHeader._lfanew + SizeOf(DWORD) + SizeOf(TImageFileHeader) + AImageFileHeader.SizeOfOptionalHeader ); for I := 0 to (AImageFileHeader.NumberOfSections -1) do begin SetFilePointer(hFile, ASectionsOffset + (I * SizeOf(TImageSectionHeader)), nil, FILE_BEGIN); if NOT ReadFile(hFile, AImageSectionHeader, SizeOf(TImageSectionHeader), dwBytesRead, 0) then continue; if (ARVA >= AImageSectionHeader.VirtualAddress) and (ARVA < AImageSectionHeader.VirtualAddress + AImageSectionHeader.SizeOfRawData) then result := (ARVA - AImageSectionHeader.VirtualAddress + AImageSectionHeader.PointerToRawData); end; end; { Read file from a starting offset to a null character. } function GetStringLength(AStartAtPos : Cardinal) : Cardinal; var ADummy : Byte; begin result := 0; /// if (hFile = INVALID_HANDLE_VALUE) then Exit(); SetFilePointer(hFile, AStartAtPos, nil, FILE_BEGIN); while True do begin if NOT ReadFile(hFile, ADummy, SizeOf(Byte), dwBytesRead, nil) then break; /// if (ADummy = 0) then break; Inc(result); end; end; begin result := -99; // Failed /// if NOT Assigned(FItems) then Exit(); FItems.Clear(); ACanCatchSection := False; { Read PE Header to reach Export List } hFile := CreateFileW(PWideChar(FFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if hFile = INVALID_HANDLE_VALUE then Exit(-1); /// try if NOT ReadFile(hFile, AImageDosHeader, SizeOf(TImageDosHeader), dwBytesRead, 0) then Exit(-2); /// if (AImageDosHeader.e_magic <> IMAGE_DOS_SIGNATURE) then Exit(-3); // Not a valid PE File /// SetFilePointer(hFile, AImageDosHeader._lfanew, nil, FILE_BEGIN); if NOT ReadFile(hFile, AImageNtHeaderSignature, SizeOf(DWORD), dwBytesRead, 0) then Exit(-4); /// if (AImageNTHeaderSignature <> IMAGE_NT_SIGNATURE) then Exit(-3); /// SetFilePointer(hFile, (AImageDosHeader._lfanew + sizeOf(DWORD)), nil, FILE_BEGIN); if NOT ReadFile(hFile, AImageFileHeader, SizeOf(TImageFileHeader), dwBytesRead, 0) then Exit(-5); /// ACanCatchSection := True; x64Binary := (AImageFileHeader.Machine = IMAGE_FILE_MACHINE_AMD64); if x64Binary then begin if NOT ReadFile(hFile, AImageOptionalHeader64, AImageFileHeader.SizeOfOptionalHeader, dwBytesRead, 0) then Exit(-6); end else begin if NOT ReadFile(hFile, AImageOptionalHeader32, AImageFileHeader.SizeOfOptionalHeader, dwBytesRead, 0) then Exit(-6); end; /// AExportAddr.VirtualAddress := 0; AExportAddr.Size := 0; if x64Binary then begin AExportAddr := AImageOptionalHeader64.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; AImageBase := AImageOptionalHeader64.ImageBase; AImportVirtualAddress := AImageOptionalHeader64.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; end else begin AExportAddr := AImageOptionalHeader32.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; AImageBase := AImageOptionalHeader32.ImageBase; AImportVirtualAddress := AImageOptionalHeader32.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; end; AOffset := RVAToFileOffset(AExportAddr.VirtualAddress); if AOffset = 0 then Exit(-7); SetFilePointer(hFile, AOffset, nil, FILE_BEGIN); if NOT ReadFile(hFile, AExportDir, SizeOf(TImageExportDirectory), dwBytesRead, 0) then Exit(-8); /// if (AExportDir.NumberOfFunctions <= 0) then Exit(-9); /// { Enumerate Named Exported Functions } for I := 0 to AExportDir.NumberOfNames - 1 do begin { Get Exported Ordinal } AOffset := RVAToFileOffset(AExportDir.AddressOfNameOrdinals) + (I * SizeOf(Word)); SetFilePointer(hFile, AOffset, nil, FILE_BEGIN); if NOT ReadFile(hFile, AOrdinal, SizeOf(Word), dwBytesRead, 0) then continue; // Ignore this entry /// { Get Exported Function Address } AOffset := RVAToFileOffset(AExportDir.AddressOfFunctions) + (AOrdinal * SizeOf(Cardinal)); SetFilePointer(hFile, AOffset, nil, FILE_BEGIN); if NOT ReadFile(hFile, AFuncAddress, SizeOf(Cardinal), dwBytesRead, 0) then continue; // Ignore this entry { Get Exported Function Name } AOffset := RVAToFileOffset(AExportDir.AddressOfNames) + (I * SizeOf(Cardinal)); SetFilePointer(hFile, AOffset, nil, FILE_BEGIN); if NOT ReadFile(hFile, AOffset, SizeOf(Cardinal), dwBytesRead, 0) then continue; // Ignore this entry /// ALen := GetStringLength(RVAToFileOffset(AOffset)); SetLength(AExportName, ALen); SetFilePointer(hFile, RVAToFileOffset(AOffset), nil, FILE_BEGIN); if NOT ReadFile(hFile, AExportName[1], ALen, dwBytesRead, nil) then continue; // Ignore this entry { Is Function Forwarded ? If yes, we catch its name } AForwarded := (AFuncAddress > RVAToFileOffset(AExportAddr.VirtualAddress)) and (AFuncAddress <= AImportVirtualAddress); if AForwarded then begin ALen := GetStringLength(RVAToFileOffset(AFuncAddress)); SetFilePointer(hFile, RVAToFileOffset(AFuncAddress), nil, FILE_BEGIN); SetLength(AForwardName, ALen); if NOT ReadFile(hFile, AForwardName[1], ALen, dwBytesRead, nil) then continue; // Ignore this entry end; { Create and append a new export entry } AExportEntry := TExportEntry.Create(); AExportEntry.Name := AExportName; AExportEntry.Ordinal := (AOrdinal + AExportDir.Base); AExportEntry.RelativeAddr := AFuncAddress; AExportEntry.Address := (AImageBase + AFuncAddress); AExportEntry.Forwarded := AForwarded; AExportEntry.ForwardName := AForwardName; FItems.Add(AExportEntry); end; /// result := FItems.Count; finally CloseHandle(hFile); end; end; end.
{ Copyright (C) 1998-2003, written by Shkolnik Mike, Scalabium Software E-Mail: mshkolnik@scalabium.com WEB: http://www.scalabium.com tel: 380-/44/-552-10-29 This components allow to parse the SQL-script on parts (SQL-statement). TODO: - to skip comments (/* */ and all after ';' up to end of line) - to skip a Term within string values } unit SQLScript; interface uses Classes; const DefaultTermChar = ';'; type TSMSQLScript = class(TComponent) private FSQL: TStrings; FSeparators: TList; FTerm: Char; FParsed: Boolean; function GetSQL: TStrings; procedure SetSQL(Value: TStrings); protected procedure ParseSQL; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetStatementCount: Integer; function GetStatement(Index: Integer): string; published property SQL: TStrings read GetSQL write SetSQL; property Term: Char read FTerm write FTerm default DefaultTermChar; end; procedure Register; implementation procedure Register; begin RegisterComponents('SMComponents', [TSMSQLScript]); end; constructor TSMSQLScript.Create(AOwner: TComponent); begin inherited; FSQL := TStringList.Create; FSeparators := TList.Create; FTerm := DefaultTermChar; end; destructor TSMSQLScript.Destroy; begin FSeparators.Free; FSQL.Free; inherited; end; function TSMSQLScript.GetSQL: TStrings; begin Result := FSQL; end; procedure TSMSQLScript.SetSQL(Value: TStrings); begin FSQL.BeginUpdate; try FSQL.Assign(Value); FSeparators.Clear; FParsed := False; finally FSQL.EndUpdate; end; end; function TSMSQLScript.GetStatementCount: Integer; begin if not FParsed then ParseSQL; Result := FSeparators.Count end; function TSMSQLScript.GetStatement(Index: Integer): string; function RemoveCRLF(const Value: string): string; var intStart, intEnd, intLen: Integer; begin Result := ''; {remove chars in begining of string} intStart := 1; intLen := Length(Value); while (intStart < intLen) and (Value[intStart] in [#13, #10, ' ']) do Inc(intStart); {remove chars in end of string} intEnd := intLen; while (intEnd > 0) and (Value[intEnd] in [#13, #10, ' ']) do Dec(intEnd); Result := Copy(Value, intStart, intEnd-intStart+1); end; var intStart, intEnd: Integer; begin if not FParsed then ParseSQL; Result := ''; if (Index > -1) and (Index < FSeparators.Count) then begin intStart := LongInt(FSeparators[Index]); if (Index+1 < FSeparators.Count) then intEnd := LongInt(FSeparators[Index+1]) else intEnd := Length(SQL.Text); Result := Copy(SQL.Text, intStart, intEnd-intStart); Result := RemoveCRLF(Result); end; end; procedure TSMSQLScript.ParseSQL; var s: string; i: Integer; begin FSeparators.Clear; s := SQL.Text; if (s <> '') then begin FSeparators.Add(TObject(1)); for i := 1 to Length(s) do begin if (s[i] = Term) then FSeparators.Add(TObject(i+1)); end; end; FParsed := True end; end.
unit uRegExpr; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LConvEncoding, uConvEncoding, uRegExprA, uRegExprW, uRegExprU; type TRegExprType = (retAnsi, retUtf16le, retUtf8); type { TRegExprEx } TRegExprEx = class private FEncoding: String; FRegExpA: TRegExpr; FRegExpW: TRegExprW; FRegExpU: TRegExprU; FType: TRegExprType; procedure SetExpression(AValue: String); function GetMatchLen(Idx : Integer): PtrInt; function GetMatchPos(Idx : Integer): PtrInt; public constructor Create(const AEncoding: String = EncodingDefault); destructor Destroy; override; function Exec(AOffset: UIntPtr = 1): Boolean; procedure ChangeEncoding(const AEncoding: String); procedure SetInputString(AInputString : Pointer; ALength : UIntPtr); public property Expression : String write SetExpression; property MatchPos [Idx : Integer] : PtrInt read GetMatchPos; property MatchLen [Idx : Integer] : PtrInt read GetMatchLen; end; implementation uses LazUTF8; { TRegExprEx } procedure TRegExprEx.SetExpression(AValue: String); begin case FType of retUtf8: FRegExpU.Expression:= AValue; retUtf16le: FRegExpW.Expression:= UTF8ToUTF16(AValue); retAnsi: FRegExpA.Expression:= ConvertEncoding(AValue, EncodingUTF8, FEncoding); end; end; function TRegExprEx.GetMatchLen(Idx: integer): PtrInt; begin case FType of retAnsi: Result:= FRegExpA.MatchLen[Idx]; retUtf8: Result:= FRegExpU.MatchLen[Idx]; retUtf16le: Result:= FRegExpW.MatchLen[Idx] * SizeOf(WideChar); end; end; function TRegExprEx.GetMatchPos(Idx: integer): PtrInt; begin case FType of retAnsi: Result:= FRegExpA.MatchPos[Idx]; retUtf8: Result:= FRegExpU.MatchPos[Idx]; retUtf16le: Result:= FRegExpW.MatchPos[Idx] * SizeOf(WideChar); end; end; constructor TRegExprEx.Create(const AEncoding: String); begin FRegExpW:= TRegExprW.Create; FRegExpU:= TRegExprU.Create; FRegExpA:= TRegExpr.Create(AEncoding); end; destructor TRegExprEx.Destroy; begin FRegExpA.Free; FRegExpW.Free; FRegExpU.Free; inherited Destroy; end; function TRegExprEx.Exec(AOffset: UIntPtr): Boolean; begin case FType of retAnsi: Result:= FRegExpA.Exec(AOffset); retUtf8: Result:= FRegExpU.Exec(AOffset); retUtf16le: Result:= FRegExpW.Exec((AOffset + 1) div SizeOf(WideChar)); end; end; procedure TRegExprEx.ChangeEncoding(const AEncoding: String); begin FEncoding:= NormalizeEncoding(AEncoding); if FEncoding = EncodingUTF16LE then FType:= retUtf16le else if (FEncoding = EncodingUTF8) or (FEncoding = EncodingUTF8BOM) then FType:= retUtf8 else begin FType:= retAnsi; FRegExpA.ChangeEncoding(FEncoding); end; end; procedure TRegExprEx.SetInputString(AInputString: Pointer; ALength: UIntPtr); begin case FType of retAnsi: FRegExpA.SetInputString(AInputString, ALength); retUtf8: FRegExpU.SetInputString(AInputString, ALength); retUtf16le: FRegExpW.SetInputString(AInputString, ALength div SizeOf(WideChar)); end; end; end.
unit LCVectorClipboard; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Clipbrd, LCLType, LCVectorOriginal, BGRATransform; function CopyShapesToClipboard(AShapes: array of TVectorShape; const AMatrix: TAffineMatrix): boolean; procedure PasteShapesFromClipboard(ATargetContainer: TVectorOriginal; const ATargetMatrix: TAffineMatrix); function ClipboardHasShapes: boolean; implementation var vectorClipboardFormat : TClipboardFormat; function CopyShapesToClipboard(AShapes: array of TVectorShape; const AMatrix: TAffineMatrix): boolean; var tempContainer: TVectorOriginal; mem: TMemoryStream; i: Integer; s: TVectorShape; begin result:= false; if length(AShapes)=0 then exit; tempContainer := TVectorOriginal.Create; mem := TMemoryStream.Create; try for i := 0 to high(AShapes) do begin s := AShapes[i].Duplicate; s.Transform(AMatrix); tempContainer.AddShape(s); end; tempContainer.SaveToStream(mem); Clipboard.Clear; mem.Position:= 0; result := Clipboard.AddFormat(vectorClipboardFormat, mem); finally mem.Free; tempContainer.Free; end; end; procedure PasteShapesFromClipboard(ATargetContainer: TVectorOriginal; const ATargetMatrix: TAffineMatrix); var tempContainer: TVectorOriginal; mem: TMemoryStream; i: Integer; pastedShape: TVectorShape; invMatrix: TAffineMatrix; begin if not IsAffineMatrixInversible(ATargetMatrix) then exit; invMatrix := AffineMatrixInverse(ATargetMatrix); if Clipboard.HasFormat(vectorClipboardFormat) then begin mem := TMemoryStream.Create; tempContainer := TVectorOriginal.Create; try if Clipboard.GetFormat(vectorClipboardFormat, mem) then begin mem.Position:= 0; tempContainer.LoadFromStream(mem); for i := 0 to tempContainer.ShapeCount-1 do begin pastedShape := tempContainer.Shape[i].Duplicate; pastedShape.Transform(invMatrix); ATargetContainer.AddShape(pastedShape); if i = tempContainer.ShapeCount-1 then ATargetContainer.SelectShape(pastedShape); end; end; finally tempContainer.Free; mem.Free; end; end; end; function ClipboardHasShapes: boolean; begin result := Clipboard.HasFormat(vectorClipboardFormat); end; initialization vectorClipboardFormat := RegisterClipboardFormat('TVectorOriginal'); end.
unit IWCompListbox; {PUBDIST} interface uses {$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF} {$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF} Classes, IWLayoutMgr, IWHTMLTag, IWControl, IWScriptEvents; type TIWCustomListCombo = class(TIWControl) protected FItems: TStrings; FItemIndex: Integer; FItemsHaveValues: Boolean; FRequireSelection: Boolean; FNoSelectionText: string; FOnChange: TNotifyEvent; FUseSize: Boolean; // procedure DoChange; function GetSorted: boolean; function GetText: string; reintroduce; procedure HookEvents(AScriptEvents: TIWScriptEvents); override; procedure SetItems(AValue: TStrings); procedure SetItemIndex(AIndex: Integer); procedure SetRequireSelection(const AValue: Boolean); virtual; procedure SetSorted(AValue: boolean); procedure SetValue(const AValue: string); override; procedure SetUseSize(const AValue: Boolean); procedure SetItemsHaveValues(const Value: Boolean); // //@@ The items to appear in the control. // //SeeAlso: ItemIndex, Sorted, ItemsHaveValues property Items: TStrings read FItems write SetItems; //@@ Specifies the currently selected item. A value of -1 specifies that no item is currently // selected. // //SeeAlso: Items property ItemIndex: Integer read FItemIndex write SetItemIndex; // Do not publish sorted. DB controls use this and using it can interfere with their // functionality. Such as the lookuplist ones which rely on the sort order remaining the same // as fetched from the DB. // //The items in the TIWCustomListCombo are sorted. // // //@@ Description: Controls the sorting of items. Setting to True causes the items to be sorted // alphabetically. If the property is set to false, the items are presented as they are provided // in the Items property // //SeeAlso: Items property Sorted: Boolean read GetSorted write SetSorted; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ExtraTagParams; property Font; //@@ ItemsHaveValues if true expects that items is of the format: //Text=Value //The Value will be written out as the value portion of the HTML OPTION tag and only the text //portion will be displayed. IntraWeb does not use the value tag and has no use in a normal //IntraWeb application as this can be accomplished easier using Delphi code in the IntraWeb //application. This option is valuable however if you are using ScriptEvents. // //SeeAlso: Items property ItemsHaveValues: Boolean read FItemsHaveValues write SetItemsHaveValues; //@@ The HTML specification requires that listboxes and comboboxes have a selected item. Some //browsers allow for nonselection to occur, but will return the first item as selected. //Because of this when ItemIndex = -1 IntraWeb will dispaly -- No Selection -- and select //it. For customization and localization requirements you can use this property to change the //text that is dispalayed. property NoSelectionText: string read FNoSelectionText write FNoSelectionText; //@@ Specifies if a -- No Selection -- option appears. HTML does not allow for the user // to unselect a combo or list box by any other method. property RequireSelection: Boolean read FRequireSelection write SetRequireSelection; property ScriptEvents; property Text: string read GetText; //@@ OnChange is fired when the user makes a selection in the combobox. property OnChange: TNotifyEvent read FOnChange write FOnChange; //@@ Indicates whether to use the sizes defined at design-time or use the size assigned //on generation of the HTML property UseSize: Boolean read FUseSize write SetUseSize; end; TIWCustomComboBox = class(TIWCustomListCombo) protected procedure Submit(const AValue: string); override; public constructor Create(AOwner: TComponent); override; function RenderHTML: TIWHTMLTag; override; // Needed for PaintHandlers property Items; property ItemIndex; published property DoSubmitValidation; property Editable; property TabOrder; end; TIWComboBox = class(TIWCustomComboBox) published property ItemIndex; property Items; property Sorted; end; TIWCustomListbox = class(TIWCustomListCombo) protected FMultiSelect: Boolean; FSelectedList: TList; // function GetSelected(AIndex: integer): boolean; procedure SetSelected(AIndex: integer; const AValue: boolean); procedure SetMultiSelect(const AValue: Boolean); procedure SetValue(const AValue: string); override; procedure Submit(const AValue: string); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; // Needed for PaintHandlers property Items; property ItemIndex; //@@ Allows mutliple selection of items. // //Note: MultiSelect and RequireSelection are mutually exlusive property MultiSelect: boolean read FMultiSelect write SetMultiSelect; // //@@ This clears all listbox selections in the Selected property. // //SeeAlso: Selected procedure ResetSelection; // //@@ This property indicates if a specific item in a listbox is selected. This indexed property // is used in combination with the MultiSelect property to allow the user to select more than // one item at a time. // //SeeAlso: MultiSelect property Selected[AIndex: Integer]: Boolean read GetSelected write SetSelected; published property DoSubmitValidation; property Editable; property TabOrder; end; TIWListbox = class(TIWCustomListbox) protected procedure SetRequireSelection(const AValue: Boolean); override; published property ItemIndex; property Items; //@@ Allows mutliple selection of items. // //Note: MultiSelect and RequireSelection are mutually exlusive property MultiSelect: boolean read FMultiSelect write SetMultiSelect; property Sorted; end; implementation uses {$IFDEF Linux} QForms, Types, {$ELSE} Forms, Windows, {$ENDIF} IWApplication, IWServerControllerBase, IWAppForm, IWCompLabel, IWTypes, Math, SWStrings, SysUtils, SWSystem; { TIWCustomListCombo } constructor TIWCustomListCombo.Create(AOwner: TComponent); begin inherited; FNeedsFormTag := True; RequireSelection := True; FSupportsSubmit := True; FSupportsInput := True; FSupportedScriptEvents := 'OnBlur,OnChange,OnFocus'; FNoSelectionText := '-- No Selection --'; FItems := TStringList.Create; FItemIndex := -1; end; destructor TIWCustomListCombo.Destroy; begin FreeAndNil(FItems); inherited; end; function TIWCustomListCombo.GetSorted: boolean; begin Result := TStringList(FItems).Sorted; end; procedure TIWCustomListCombo.DoChange; begin if Assigned(OnChange) then begin OnChange(Self); end; end; procedure TIWCustomListCombo.HookEvents(AScriptEvents: TIWScriptEvents); begin inherited HookEvents(AScriptEvents); if Editable then begin AScriptEvents.HookEvent('OnChange', iif(Assigned(OnChange), SubmitHandler)); end; end; function TIWCustomComboBox.RenderHTML: TIWHTMLTag; var i: Integer; LText: string; LValue: string; begin Result := nil; if Editable then begin Result := TIWHTMLTag.CreateTag('SELECT'); try Result.AddStringParam('NAME', HTMLName); Result.AddIntegerParam('SIZE', 1); if FUseSize then begin Result.AddIntegerParam('WIDTH', Width); end; {Result.Add('STYLE', iif(WebApplication.Browser in [brIE, brNetscape6] , Font.FontToStringStyle(WebApplication.Browser)){ + 'width: ' + IntToStr(Width) + 'px;');} if FItems.Count > 0 then begin if ((FItemIndex = -1) or (RequireSelection = False)) then begin with Result.Contents.AddTag('OPTION') do begin Add('SELECTED'); AddIntegerParam('VALUE', -1); Contents.AddText(FNoSelectionText); end; end; for i := 0 to FItems.Count - 1 do begin LText := FItems[i]; LValue := ''; if ItemsHaveValues then begin LValue := LText; LText := Fetch(LValue, '='); end else begin LValue := IntToStr(i); end; with Result.Contents.AddTag('OPTION') do begin Add(iif(ItemIndex = i, 'SELECTED')); AddStringParam('VALUE', LValue); Contents.AddText(LText); end; end; end else begin Result.Contents.AddText(''); end; except FreeAndNil(Result); raise; end; end else begin with TIWLabel.Create(Self) do try Caption := ''; if (Self.Items.Count > 0) and (Self.ItemIndex > -1) then begin Caption := Self.Items[Self.ItemIndex]; end; Result := RenderHTML; finally Free; end; end; end; function TIWCustomListCombo.GetText: string; begin if ItemIndex > -1 then begin if ItemsHaveValues then begin Result := Items.Values[Items.Names[ItemIndex]]; end else begin Result := Items[ItemIndex]; end; end else begin Result := ''; end; end; procedure TIWCustomListCombo.SetItemIndex(AIndex: Integer); begin if csLoading in ComponentState then begin // Set no matter what, it might be set (and usually is) before the items are loaded FItemIndex := AIndex; end else if AIndex < Items.Count then begin FItemIndex := AIndex; Invalidate; end; end; procedure TIWCustomListCombo.SetItems(AValue: TStrings); begin FItems.Assign(AValue); Invalidate; end; procedure TIWCustomListCombo.SetRequireSelection(const AValue: Boolean); begin FRequireSelection := AValue; end; procedure TIWCustomListCombo.SetSorted(AValue: boolean); begin TStringList(FItems).Sorted := AValue; Invalidate; end; procedure TIWcustomListCombo.SetValue(const AValue: string); var s: string; i: integer; begin s := AValue; if ItemsHaveValues then begin for i := 0 to Items.Count - 1 do begin if S = Items.Values[Items.Names[i]] then begin ItemIndex := i; break; end; end; end else begin ItemIndex := StrToIntDef(Fetch(s, ','), -1); end; Invalidate; end; procedure TIWCustomListCombo.SetUseSize(const AValue: Boolean); begin FRenderSize := AValue; FUseSize := AValue; end; procedure TIWCustomListCombo.SetItemsHaveValues(const Value: Boolean); begin FItemsHaveValues := Value; Invalidate; end; { TIWCustomListbox } constructor TIWCustomListbox.Create(AOwner: TComponent); begin inherited; FSelectedList := TList.Create; Height := 121; Width := 121; end; destructor TIWCustomListbox.Destroy; begin FreeAndNil(FSelectedList); inherited; end; function TIWCustomListbox.GetSelected(AIndex: Integer): boolean; begin if FMultiSelect then begin Result := FSelectedList.IndexOf(TObject(AIndex)) > -1; end else begin Result := AIndex = ItemIndex; end; end; function TIWCustomListbox.RenderHTML: TIWHTMLTag; var i: Integer; LText: string; LValue: string; begin Result := nil; if Editable then begin Result := TIWHTMLTag.CreateTag('SELECT'); try Result.AddStringParam('NAME', HTMLName); Result.AddIntegerParam('SIZE', Height div 16); Result.Add(iif(FMultiSelect, 'MULTIPLE')); if FUseSize then begin Result.AddIntegerParam('WIDTH', Width); end; {Result.Add('STYLE', iif(WebApplication.Browser in [brIE, brNetscape6] , Font.FontToStringStyle(WebApplication.Browser)));} if FItems.Count > 0 then begin if ((FItemIndex = -1) or (RequireSelection = False)) and (FMultiSelect = False) then begin with Result.Contents.AddTag('OPTION') do begin Add('SELECTED'); AddIntegerParam('VALUE', -1); Contents.AddText(FNoSelectionText); end; end; for i := 0 to FItems.Count - 1 do begin LText := FItems[i]; LValue := ''; if ItemsHaveValues then begin LValue := LText; LText := Fetch(LValue, '='); end else begin LValue := IntToStr(i); end; with Result.Contents.AddTag('OPTION') do begin Add(iif(( (ItemIndex = i) and (FMultiSelect = False)) or (Selected[i] and FMultiSelect) , 'SELECTED')); AddStringParam('VALUE', LValue); Contents.AddText(LText); end; end; end else begin Result.Contents.AddText(''); end; except FreeAndNil(Result); raise; end; end else begin with TIWLabel.Create(Self) do try Name := Self.Name; Color := Self.Color; FFriendlyName := Self.FriendlyName; ExtraTagParams.Assign(Self.ExtraTagParams); Font.Assign(Self.Font); ScriptEvents.Assign(Self.ScriptEvents); Width := Self.Width; Height := Self.Height; Caption := ''; if Self.ItemIndex > -1 then begin Caption := Self.FItems[Self.ItemIndex]; end; Result := RenderHTML; finally Free; end; end; end; procedure TIWCustomListbox.ResetSelection; begin FSelectedList.Clear; Invalidate; end; procedure TIWCustomListbox.SetSelected(AIndex: integer; const AValue: boolean); begin if AValue then begin if not GetSelected(AIndex) then begin FSelectedList.Add(TObject(AIndex)); end; end else begin FSelectedList.Remove(TObject(AIndex)); end; Invalidate; end; procedure TIWCustomListbox.SetMultiSelect(const AValue: boolean); begin if AValue then begin FRequireSelection := False; end; FMultiSelect := AValue; end; procedure TIWCustomListbox.SetValue(const AValue: string); var LValue, s: string; i: Integer; begin LValue := AValue; s := Fetch(LValue, ','); if ItemsHaveValues then begin for i := 0 to Items.Count - 1 do begin if s = Items.Values[Items.Names[i]] then begin ItemIndex := i; break; end; end; end else begin ItemIndex := StrToIntDef(s, -1); end; // For multiselect, first one is ItemIndex. Will be repeated in selected list // ItemIndex := StrToIntDef(Fetch(LValue, ','), -1); if FMultiSelect then begin ResetSelection; Selected[ItemIndex] := true; while Length(LValue) > 0 do begin s := Fetch(LValue, ','); if ItemsHaveValues then begin for i := 0 to Items.Count - 1 do begin if s = Items.Values[Items.Names[i]] then break; end; end else begin i := StrToInt(s); end; Selected[i] := True; end; end; end; procedure TIWCustomListbox.Submit(const AValue: string); begin DoChange; end; { TIWCustomComboBox } constructor TIWCustomComboBox.Create(AOwner: TComponent); begin inherited; Height := 21; Width := 121; end; procedure TIWCustomComboBox.Submit(const AValue: string); begin DoChange; end; { TIWListbox } procedure TIWListbox.SetRequireSelection(const AValue: Boolean); begin if AValue then begin FMultiSelect := False; end; inherited; end; end.
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+} unit Levels; interface uses Global; procedure levelChange(var U : tUserRec; Lev : Char); procedure levelLoad(var Lev : tLevels); procedure levelLower(var U : tUserRec); procedure levelSave(var Lev : tLevels); procedure levelSet(var U : tUserRec; var L : tLevels; Lev : Char); procedure levelUpgrade(var U : tUserRec); implementation uses Files; procedure levelSet(var U : tUserRec; var L : tLevels; Lev : Char); begin U.SL := L[Lev].SL; U.DSL := L[Lev].DSL; U.filePts := L[Lev].filePts; U.PostCall := L[Lev].PostCall; U.limitDL := L[Lev].limitDL; U.limitDLkb := L[Lev].limitDLkb; U.UserNote := L[Lev].UserNote; U.timePerDay := L[Lev].timeLimit; U.timeToday := L[Lev].timeLimit; U.uldlRatio := L[Lev].uldlRatio; U.kbRatio := L[Lev].kbRatio; U.Level := Lev; end; procedure levelChange(var U : tUserRec; Lev : Char); var L : tLevels; begin levelLoad(L); if L[Lev].Desc <> '' then levelSet(U,L,Lev); end; procedure levelUpgrade(var U : tUserRec); var X : Char; L : tLevels; begin levelLoad(L); X := U.Level; if X = 'Z' then X := 'A' else Inc(X); while (L[X].Desc = '') and (X < 'Z') do Inc(X); if L[X].Desc = '' then Exit; levelChange(U,X); end; procedure levelLower(var U : tUserRec); var X : Char; L : tLevels; begin levelLoad(L); X := U.Level; if X = 'A' then X := 'Z' else Dec(X); while (L[X].Desc = '') and (X > 'A') do Dec(X); if L[X].Desc = '' then Exit; levelChange(U,X); end; procedure levelLoad(var Lev : tLevels); var F : file of tLevels; begin Assign(F,Cfg^.pathData+fileLevels); FillChar(Lev,SizeOf(Lev),0); {$I-} Reset(F); if ioResult <> 0 then begin Rewrite(F); Lev['A'].Desc := 'New user access level'; Lev['A'].SL := 25; Lev['A'].DSL := 25; Lev['A'].UserNote := 'New user access'; Lev['A'].timeLimit := 25; Lev['A'].filePts := 0; Lev['A'].postCall := 20; Lev['A'].limitDL := 5; Lev['A'].limitDLkb := 100; Lev['A'].uldlRatio := 1; Lev['A'].kbRatio := 10; Lev['B'].Desc := 'Normal user access level'; Lev['B'].SL := 50; Lev['B'].DSL := 50; Lev['B'].UserNote := 'Normal access'; Lev['B'].timeLimit := 60; Lev['B'].filePts := 50; Lev['B'].postCall := 20; Lev['B'].limitDL := 10; Lev['B'].limitDLkb := 600; Lev['B'].uldlRatio := 5; Lev['B'].kbRatio := 15; Lev['C'].Desc := 'Enhanced user access level'; Lev['C'].SL := 100; Lev['C'].DSL := 100; Lev['C'].UserNote := 'Enhanced access'; Lev['C'].timeLimit := 80; Lev['C'].filePts := 150; Lev['C'].postCall := 10; Lev['C'].limitDL := 15; Lev['C'].limitDLkb := 1500; Lev['C'].uldlRatio := 10; Lev['C'].kbRatio := 30; Lev['D'].Desc := 'Co-SysOp access level'; Lev['D'].SL := 250; Lev['D'].DSL := 250; Lev['D'].UserNote := 'Co-SysOp access'; Lev['D'].timeLimit := 120; Lev['D'].filePts := 200; Lev['D'].postCall := 0; Lev['D'].limitDL := 20; Lev['D'].limitDLkb := 5000; Lev['D'].uldlRatio := 30; Lev['D'].kbRatio := 100; Lev['E'].Desc := 'SysOp access level'; Lev['E'].SL := 255; Lev['E'].DSL := 255; Lev['E'].UserNote := 'SysOp access'; Lev['E'].timeLimit := 64000; Lev['E'].filePts := 64000; Lev['E'].postCall := 0; Lev['E'].limitDL := 64000; Lev['E'].limitDLkb := 64000; Lev['E'].uldlRatio := 64000; Lev['E'].kbRatio := 64000; Write(F,Lev); end else Read(F,Lev); Close(F); {$I+} end; procedure levelSave(var Lev : tLevels); var F : file of tLevels; begin Assign(F,Cfg^.pathData+fileLevels); {$I-} Rewrite(F); if ioResult <> 0 then Exit; Write(F,Lev); Close(F); {$I+} end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Spin, ActnList, Menus, ComCtrls, ToolWin, ImgList; type TLinker = class; TDataSet = class; TAttribute = class public Name: string; Linker: TLinker; DataSet: TDataSet; constructor Create(const aName: string; aDataSet: TDataSet); virtual; destructor Destroy; override; function Print: string; virtual; abstract; function Export: string; virtual; abstract; function StrSample: string; virtual; abstract; function Sample: extended; virtual; abstract; function FetchData(const x: integer): extended; function GetData(const Val: extended): string; virtual; abstract; procedure SaveToStream(S: TStream); virtual; procedure LoadFromStream(S: TStream); virtual; function ClassVal(const Ind: integer): string; virtual; abstract; // Comienza en 0 function DataClass(const Val: extended): string; virtual; abstract; end; TDistribution = class protected function Sample: extended; virtual; abstract; procedure SaveToStream(S: TStream); virtual; abstract; procedure LoadFromStream(S: TStream); virtual; abstract; end; TUniformDistribution = class(TDistribution) private fMinValue: extended; fMaxValue: extended; public constructor Create(const aMinVal, aMaxVal: extended); function Sample: extended; override; function IntSample: extended; procedure SaveToStream(S: TStream); override; procedure LoadFromStream(S: TStream); override; procedure setMinValue(const val: extended); procedure setMaxValue(const val: extended); property MinValue: extended read fMinValue; property MaxValue: extended read fMaxValue; end; TNormalDistribution = class(TDistribution) private fMean: extended; fStdDev: extended; public constructor Create(const aMean, aStdDev: extended); function Sample: extended; override; procedure setMean(const val: extended); procedure setStdDev(const val: extended); procedure SaveToStream(S: TStream); override; procedure LoadFromStream(S: TStream); override; property Mean: extended read fMean; property StdDev: extended read fStdDev; end; TNumericAttr = class(TAttribute) private fDistribution: TDistribution; fDiscretizationLevel: integer; protected fMinValue: extended; fMaxValue: extended; fMinSample: extended; fMaxSample: extended; public Interval: extended; function SetInterval: string; procedure SetVal(const V: extended); virtual; abstract; procedure SaveToStream(S: TStream); override; procedure LoadFromStream(S: TStream); override; procedure ComputeValues(); function ClassVal(const Ind: integer): string; override; function DataClass(const Val: extended): string; override; property Distribution: TDistribution read fDistribution write fDistribution; property MinValue: extended read fMinValue write fMinValue; property MaxValue: extended read fMaxValue write fMaxValue; property MinSample: extended read fMinSample write fMinSample; property MaxSample: extended read fMaxSample write fMaxSample; property DiscretizationLevel: integer read fDiscretizationLevel; end; TRealAttr = class(TNumericAttr) public constructor Create(const aName: string; aDataSet: TDataSet); override; function Print: string; override; function Export: string; override; function StrSample: string; override; function Sample: extended; override; procedure SetVal(const V: extended); override; function GetData(const Val: extended): string; override; end; TIntegerAttr = class(TNumericAttr) private function GetMaxValue: integer; function GetMinValue: integer; procedure SetMaxValue(const Value: integer); procedure SetMinValue(const Value: integer); function GetMaxSample: integer; function GetMinSample: integer; procedure SetMaxSample(const Value: integer); procedure SetMinSample(const Value: integer); public constructor Create(const aName: string; aDataSet: TDataSet); override; function Print: string; override; function Export: string; override; function StrSample: string; override; function Sample: extended; override; procedure SetVal(const V: extended); override; function GetData(const Val: extended): string; override; property MinValue: integer read GetMinValue write SetMinValue; property MaxValue: integer read GetMaxValue write SetMaxValue; property MinSample: integer read GetMinSample write SetMinSample; property MaxSample: integer read GetMaxSample write SetMaxSample; end; TSymbolicAttr = class(TAttribute) private FSymbols: TStringList; FNumberOfSymbols: integer; function GetNumberOfSymbols: integer; procedure SetNumberOfSymbols(const Value: integer); public constructor Create(const aName: string; aDataSet: TDataSet); override; destructor Destroy; override; procedure UseExplicitSymbols; function GetSymbol(const i: integer): string; // Comienza en 0 procedure AddSymbol(const S: string); function PosSymbol(const S: string): integer; function Print: string; override; function Export: string; override; function StrSample: string; override; function Sample: extended; override; function ClassVal(const Ind: integer): string; override; function DataClass(const Val: extended): string; override; function GetData(const Val: extended): string; override; function GetDataAt(const i: integer): string; procedure SaveToStream(S: TStream); override; procedure LoadFromStream(S: TStream); override; property NumberOfSymbols: integer read GetNumberOfSymbols write SetNumberOfSymbols; end; TWeights = array of integer; TLinker = class private fInputAttrs: TList; fOutputAttr: TAttribute; fNoise: integer; fWeights: TWeights; fNormWeights: array of extended; fSamples: array of extended; function NumToNum(AttrIn, AttrOut: TNumericAttr; const x: integer): extended; function SymToNum(AttrIn: TSymbolicAttr; AttrOut: TNumericAttr; const x: integer): extended; function NumToSym(AttrIn: TNumericAttr; AttrOut: TSymbolicAttr; const x: integer): extended; function SymToSym(AttrIn, AttrOut: TSymbolicAttr; const x: integer): extended; procedure Convert(const x: integer); function Average: extended; procedure RemoveWeight(const index: integer); procedure NormalizeWeights; function GetInputCount: integer; function GetInput(const i: integer): TAttribute; function GetWeight(const i: integer): string; function GetIndependent: boolean; function GetNoise: integer; procedure SetNoise(const Value: integer); public constructor Create(OutputAttr: TAttribute); destructor Destroy; override; function Cycle(Attr: TAttribute): boolean; procedure LinkAttr(Attr: TAttribute; const Value: integer); procedure UnlinkAttr(Attr: TAttribute); procedure RemoveLink(const index: integer); procedure SetWeight(Attr: TAttribute; const Value: integer); function ReadDependence(const x: integer): extended; function IsInput(Attr: TAttribute): boolean; procedure ClearInputs; function Print: string; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); property InputCount: integer read GetInputCount; property Input[const i: integer]: TAttribute read GetInput; property Weight[const i: integer]: string read GetWeight; property Independent: boolean read GetIndependent; property Noise: integer read GetNoise write SetNoise; end; TDataStore = array of array of extended; TIntArray = array of Integer; TDataSet = class private fDataStore: TDataStore; fInstanceNumber: integer; Insufflated: boolean; fAttributes: TList; AttrGenNumber: integer; FName: string; function IndexOfMax(const A: TIntArray): integer; procedure SetInstanceNumber(const Value: integer); function GetAttributesCount: integer; function GetAttribute(const Ai: integer): TAttribute; procedure FinalizeDataStore; function GetData(const Ai, Xi: integer): string; function GetClassAttribute: TAttribute; function GetClassCardinality: integer; function GetDataStore(const Ai, Xi: integer): extended; procedure SetDataStore(const Ai, Xi: integer; const Value: extended); procedure SetName(const Value: string); public constructor Create; destructor Destroy; override; procedure Insufflate; procedure UnknownValuesProcess; procedure BinarizationProcess; procedure GenerateAttr(Ai: integer); function NewAttrName: string; function AddRealAttribute: TRealAttr; function AddIntegerAttribute: TIntegerAttr; function AddSymbolicAttribute: TSymbolicAttr; procedure Delete(Attr: TAttribute); function DataClass(const Attr, Item: integer): string; function AttrCardinality(const Attr: integer): integer; function ClassValue(const Attr, Ind: integer): string; function FetchData(Attr: TAttribute; const x: integer): extended; function PosAttr(Attr: TAttribute): integer; function FindAttr(const AttrName: string): TAttribute; procedure SaveToStream(S: TStream); procedure LoadFromStream(S: TStream); function BinAttrNumber: integer; property InstanceNumber: integer read FInstanceNumber write SetInstanceNumber; property AttributesCount: integer read GetAttributesCount; property Attribute[const Ai: integer]: TAttribute read GetAttribute; //Basado en 0 property Data[const Ai, Xi: integer]: string read GetData; property ClassAttribute: TAttribute read GetClassAttribute; property ClassCardinality: integer read GetClassCardinality; property DataStore[const Ai, Xi: integer]: extended read GetDataStore write SetDataStore; property Name: string read FName write SetName; end; TParser = class private FDataSet: TDataSet; Line, Ind: integer; FToken: string; Text: TStrings; TextLine: string; EOF: boolean; LineBreak: boolean; procedure GoAhead; function NextToken: string; function ParseRelation: boolean; function ParseAttributes: boolean; function ParseData: boolean; function ParseArffData: boolean; function ParseInteger(var fval: extended): boolean; function ParseReal(var fval: extended): boolean; function ParseSymbolic(Attr: TSymbolicAttr; var fval: extended): boolean; function ParseIdent(var Ident: string): boolean; procedure ParseSymbolList(const AName: string); public constructor Create(Dataset: TDataSet); procedure Restart; procedure Init(aText: TStrings); function ParseStrings(aText: TStrings): boolean; function ParseXNames(aText: TStrings): boolean; function ParseXData(aText: TStrings): boolean; property Token: string read FToken; property DataSet: TDataSet read FDataSet; end; TDataSetDesigner = class(TForm) ActionList1: TActionList; NewReal: TAction; NewInt: TAction; NewSymbolic: TAction; EditAttr: TAction; Delete: TAction; PopupMenu1: TPopupMenu; Nuevo1: TMenuItem; Editar1: TMenuItem; Eliminar1: TMenuItem; Real1: TMenuItem; Entero1: TMenuItem; Simbolico1: TMenuItem; NewDB: TAction; Generate: TAction; Splitter1: TSplitter; PanelLeft: TPanel; HeaderLeft: TPanel; ListAttr: TListBox; PanelRight: TPanel; HeaderRight: TPanel; MemData: TMemo; ImageList1: TImageList; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; ToolButton10: TToolButton; ToolButton11: TToolButton; Panel1: TPanel; EditInstancesNumber: TSpinEdit; Label2: TLabel; SaveDialog1: TSaveDialog; AnalyzeAll: TAction; ToolButton12: TToolButton; MainMenu1: TMainMenu; Archivo1: TMenuItem; Edicin1: TMenuItem; Anlisis1: TMenuItem; Generar1: TMenuItem; NuevaBD1: TMenuItem; Abrir1: TMenuItem; Guardar1: TMenuItem; GuardarComo1: TMenuItem; Salir1: TMenuItem; N1: TMenuItem; ImportarBD1: TMenuItem; ExportarBD1: TMenuItem; N2: TMenuItem; NuevoReal1: TMenuItem; NuevoEntero1: TMenuItem; NuevoSimblico1: TMenuItem; N3: TMenuItem; EditarAtributo1: TMenuItem; Eliminar2: TMenuItem; GenerarBD1: TMenuItem; MedidasdeTeoradelaInformacin1: TMenuItem; MedidasdeConjuntosAproximados1: TMenuItem; MedidasEstadsticas1: TMenuItem; CaracteristicasBsicas1: TMenuItem; N4: TMenuItem; MostrarHojadeAnlisis1: TMenuItem; odaslasmedidas1: TMenuItem; BasicAnalysis: TAction; InformationTheoreticAnalysis: TAction; RoughSetsAnalysis: TAction; StatisticAnalysis: TAction; ViewAnalysisSheet: TAction; CleanAnalysisSheet: TAction; LimpiarHojadeAnlisis1: TMenuItem; Export: TAction; SaveAs: TAction; OpenDialog1: TOpenDialog; Open: TAction; Save: TAction; Import: TAction; Preprocesamiento: TAction; Preprocesamiento2: TMenuItem; ValoresDesconocidos1: TMenuItem; Binarizacin1: TMenuItem; UnknownVal: TAction; Binarization: TAction; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure GenerateExecute(Sender: TObject); procedure ListAttrMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); function GetFileName(const RawFileName: string): string; // Edición de BD procedure NewRealExecute(Sender: TObject); procedure NewIntExecute(Sender: TObject); procedure NewSymbolicExecute(Sender: TObject); procedure EditAttrExecute(Sender: TObject); procedure DeleteExecute(Sender: TObject); procedure EditInstancesNumberChange(Sender: TObject); // Manejo de archivos procedure NewDataBase; function CanProceed: boolean; //verifica que no se pierdan datos antes de proseguir procedure NewDBExecute(Sender: TObject); procedure SaveExecute(Sender: TObject); procedure SaveAsExecute(Sender: TObject); procedure OpenExecute(Sender: TObject); procedure ExportExecute(Sender: TObject); procedure ImportExecute(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); // Analisis de datos procedure BasicAnalysisExecute(Sender: TObject); procedure InformationTheoreticAnalysisExecute(Sender: TObject); procedure RoughSetsAnalysisExecute(Sender: TObject); procedure StatisticAnalysisExecute(Sender: TObject); procedure AnalyzeAllExecute(Sender: TObject); procedure ViewAnalysisSheetExecute(Sender: TObject); procedure CleanAnalysisSheetExecute(Sender: TObject); procedure UnknownValExecute(Sender: TObject); procedure BinarizationExecute(Sender: TObject); private DataSet: TDataSet; fFileName: string; fFileModified: boolean; fProceed: boolean; procedure UpdateDisplay; procedure ListAttributes(List: TStrings; Attr: TAttribute); procedure ListDependences(List: TStrings; Attr: TAttribute); procedure UpdateDependences(List: TStrings; Attr: TAttribute); procedure ImportXDataFile(Parser: TParser); public { Public declarations } procedure EditReal(Attr: TRealAttr); procedure EditInteger(Attr: TIntegerAttr); procedure EditSymbolic(Attr: TSymbolicAttr); procedure UpDateListAttr(const index: integer); procedure ExportDataSet(Media: TStrings); procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); end; var DataSetDesigner: TDataSetDesigner; procedure SetUnknown(var V: extended); function IsUnknown(const V: extended): boolean; implementation uses SymbolicAttr, NumericAttr, Analyzer, Math, cMatrix; type Int32 = -2147483648..2147483647; PInt32 = ^Int32; const SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz1234567890'; MainFormTitle = 'Dataset Designer'; DefaultInstancesNumber = 10; Comment = '%'; Separators = [' ', ',', Comment, #9, ':']; Operators = ['{', '}']; UNKNOWN = '?'; SAMPLESPERCELL = 10; {$R *.dfm} procedure SetUnknown(var V: extended); begin PInt32(@V)^ := $7FFFFFFF; end; function IsUnknown(const V: extended): boolean; begin Result := PInt32(@V)^ = $7FFFFFFF; end; { TDataSet } function TDataSet.AddIntegerAttribute: TIntegerAttr; begin Result := TIntegerAttr.Create(NewAttrName, self); fAttributes.Add(Result); Insufflated := false; end; function TDataSet.AddRealAttribute: TRealAttr; begin Result := TRealAttr.Create(NewAttrName, self); fAttributes.Add(Result); Insufflated := false; end; function TDataSet.AddSymbolicAttribute: TSymbolicAttr; begin Result := TSymbolicAttr.Create(NewAttrName, self); fAttributes.Add(Result); Insufflated := false; end; function TDataSet.AttrCardinality(const Attr: integer): integer; begin if Attribute[Attr] is TSymbolicAttr then Result := TSymbolicAttr(Attribute[Attr]).NumberOfSymbols else Result := TNumericAttr(Attribute[Attr]).DiscretizationLevel; // Revisar OJO end; procedure TDataSet.BinarizationProcess; var l: integer; // Variable de control de los atributos i: integer; // Variable de control de los datos iniciales j: integer; // Variable de control de nuevos atributos k: integer; // Variable de control de instancias NewAtNo: integer; FormerAttr, Attr: TSymbolicAttr; NewDataStore: TDataStore; begin // Preprocesamiento de atributos nominales con más de 2 valores l := 0; SetLength(NewDataStore, AttributesCount); for i := 0 to AttributesCount - 2 do // No se binariza la clase //while i < AttributesCount do begin if (Attribute[l] is TSymbolicAttr) and (TSymbolicAttr(Attribute[l]).NumberOfSymbols > 2) then begin FormerAttr := TSymbolicAttr(Attribute[l]); NewAtNo := FormerAttr.NumberOfSymbols - 1; // Insertar NewAtNo nuevos atributos binarios for j := pred(NewAtNo) downto 0 do begin Attr := TSymbolicAttr.Create(Attribute[l].Name + '_' + ClassValue(l, j), self); Attr.UseExplicitSymbols; Attr.AddSymbol('no'); Attr.AddSymbol('yes'); fAttributes.Insert(succ(l), Attr); end; // Inicializar las variables SetLength(NewDataStore, AttributesCount - 1); for j := 0 to pred(NewAtNo) do SetLength(NewDataStore[l + j], InstanceNumber); // Transcribir datos for k := 0 to pred(InstanceNumber) do if IsUnknown(fDataStore[i, k]) then for j := 0 to pred(NewAtNo) do SetUnknown(NewDataStore[l + j, k]) else if fDataStore[i, k] < NewAtNo then NewDataStore[l + Trunc(fDataStore[i, k]), k] := 1; // Eliminar Atributo fAttributes.Delete(l); Finalize(fDataStore[i]); inc(l, NewAtNo); end else begin NewDataStore[l] := fDataStore[i]; inc(l); end; end; NewDataStore[l] := fDataStore[High(fDataStore)]; // Copia los valores de clase Finalize(FDataStore); FDataStore := NewDataStore; end; function TDataSet.BinAttrNumber: integer; var i: integer; begin Result := 0; for i := 0 to fAttributes.Count - 2 do if AttrCardinality(i) = 2 then inc(Result); end; function TDataSet.ClassValue(const Attr, Ind: integer): string; begin Result := Attribute[Attr].ClassVal(Ind); { if Attribute[Attr] is TSymbolicAttr then Result := SYMBOLS[succ(Ind)] else Result := IntToStr(Ind); } end; constructor TDataSet.Create; begin fAttributes := TList.Create; Randomize; end; function TDataSet.DataClass(const Attr, Item: integer): string; { var C: integer;} begin Result := Attribute[Attr].DataClass(DataStore[Attr, Item]); { if Attribute[Attr] is TSymbolicAttr then Result := SYMBOLS[Trunc(DataStore[Attr, Item])] else begin C := Trunc((DataStore[Attr, Item] - TNumericAttr(Attribute[Attr]).fMinSample)) div TNumericAttr(Attribute[Attr]).Interval; Result := IntToStr(C); end } end; procedure TDataSet.Delete(Attr: TAttribute); begin fAttributes.Remove(Attr); Attr.Free; Insufflated := false; end; destructor TDataSet.Destroy; var i: integer; begin inherited; for i := 0 to pred(fAttributes.Count) do TAttribute(fAttributes[i]).free; fAttributes.Free; if Assigned(fDataStore) then FinalizeDataStore; end; function TDataSet.FetchData(Attr: TAttribute; const x: integer): extended; begin Result := DataStore[fAttributes.IndexOf(Attr), x]; end; procedure TDataSet.FinalizeDataStore; var i: integer; begin for i := 0 to High(fDataStore) do Finalize(fDataStore[i]); Finalize(fDataStore); end; function TDataSet.FindAttr(const AttrName: string): TAttribute; var i: integer; begin Result := nil; i := 0; while (i < fAttributes.Count) and (Attribute[i].Name <> AttrName) do inc(i); if i < fAttributes.Count then Result := Attribute[i]; end; procedure TDataSet.GenerateAttr(Ai: integer); var Xi: integer; begin if Attribute[Ai] is TNumericAttr then TNumericAttr(Attribute[Ai]).ComputeValues; SetLength(fDataStore[Ai], InstanceNumber); if Attribute[Ai].Linker.Independent then for Xi := 0 to pred(InstanceNumber) do fDataStore[Ai, Xi] := Attribute[Ai].Sample else for Xi := 0 to pred(InstanceNumber) do fDataStore[Ai, Xi] := Attribute[Ai].Linker.ReadDependence(Xi); if Attribute[Ai] is TNumericAttr then TNumericAttr(Attribute[Ai]).SetInterval; end; function TDataSet.GetAttribute(const Ai: integer): TAttribute; begin Result := fAttributes.Items[Ai]; end; function TDataSet.GetAttributesCount: integer; begin Result := fAttributes.Count; end; function TDataSet.GetClassAttribute: TAttribute; begin Result := Attribute[pred(AttributesCount)]; end; function TDataSet.GetClassCardinality: integer; begin Result := AttrCardinality(pred(AttributesCount)); end; function TDataSet.GetData(const Ai, Xi: integer): string; begin Result := Attribute[Ai].GetData(DataStore[Ai, Xi]); { if Attribute[Ai] is TSymbolicAttr then Result := SYMBOLS[Trunc(DataStore[Ai, Xi])] else if Attribute[Ai] is TIntegerAttr then Result := IntToStr(Trunc(DataStore[Ai, Xi])) else Result := FloatToStr(DataStore[Ai, Xi]) } end; function TDataSet.GetDataStore(const Ai, Xi: integer): extended; begin Result := fDataStore[Ai, Xi]; end; function TDataSet.IndexOfMax(const A: TIntArray): integer; var Max, i: integer; begin Max := 0; Result := 0; for i := 0 to High(A) do if A[i] > Max then begin Max := A[i]; Result := i; end; end; procedure TDataSet.Insufflate; var Ai: integer; begin SetLength(fDataStore, fAttributes.Count); for Ai := 0 to pred(fAttributes.Count) do if Attribute[Ai].Linker.Independent then GenerateAttr(Ai); for Ai := 0 to pred(fAttributes.Count) do if not Attribute[Ai].Linker.Independent then GenerateAttr(Ai); Insufflated := true; end; procedure TDataSet.LoadFromStream(S: TStream); var i: integer; ACount, NLength: integer; AClass: string; A: TAttribute; begin S.ReadBuffer(fInstanceNumber, SizeOf(fInstanceNumber)); S.ReadBuffer(AttrGenNumber, SizeOf(AttrGenNumber)); S.ReadBuffer(Insufflated, SizeOf(Insufflated)); S.ReadBuffer(ACount, SizeOf(ACount)); // Número de atributos for i := 0 to pred(ACount) do begin S.ReadBuffer(NLength, SizeOf(NLength)); // Longitud del nombre de la clase SetString(AClass, nil, NLength); S.ReadBuffer(Pointer(AClass)^, NLength); if AClass = 'TRealAttr' then A := TRealAttr.Create('', self) else if AClass = 'TIntegerAttr' then A := TIntegerAttr.Create('', self) else A := TSymbolicAttr.Create('', self); fAttributes.Add(A); A.LoadFromStream(S); end; // Load dependencies - TLink for i := 0 to pred(fAttributes.Count) do Attribute[i].Linker.LoadFromStream(S); if Insufflated then begin SetLength(fDataStore, ACount); for i := 0 to pred(ACount) do begin SetLength(fDataStore[i], fInstanceNumber); S.ReadBuffer(Pointer(fDataStore[i])^, fInstanceNumber * SizeOf(extended)); end //S.ReadBuffer(DataStore, fInstanceNumber * ACount * SizeOf(extended)); end; end; procedure TDataSet.SaveToStream(S: TStream); var i: integer; CN: string; L: integer; begin S.WriteBuffer(fInstanceNumber, SizeOf(fInstanceNumber)); S.WriteBuffer(AttrGenNumber, SizeOf(AttrGenNumber)); S.WriteBuffer(Insufflated, SizeOf(Insufflated)); S.WriteBuffer(fAttributes.Count, SizeOf(fAttributes.Count)); for i := 0 to pred(fAttributes.Count) do begin CN := Attribute[i].ClassName; L := Length(CN); S.WriteBuffer(L, SizeOf(L)); S.WriteBuffer(Pointer(CN)^, L); Attribute[i].SaveToStream(S); end; // Save dependencies - TLink for i := 0 to pred(fAttributes.Count) do Attribute[i].Linker.SaveToStream(S); if Insufflated then for i := 0 to pred(fAttributes.Count) do S.WriteBuffer(Pointer(fDataStore[i])^, fInstanceNumber * SizeOf(extended)); // S.WriteBuffer(Pointer(DataStore)^, fInstanceNumber * AttributesCount * SizeOf(extended)); end; function TDataSet.NewAttrName: string; begin Result := 'A' + IntToStr(AttrGenNumber); inc(AttrGenNumber); end; function TDataSet.PosAttr(Attr: TAttribute): integer; begin Result := fAttributes.IndexOf(Attr); end; procedure TDataSet.SetDataStore(const Ai, Xi: integer; const Value: extended); begin fDataStore[Ai, Xi] := Value; end; procedure TDataSet.SetInstanceNumber(const Value: integer); begin FInstanceNumber := Value; Insufflated := false; end; procedure TDataSet.SetName(const Value: string); begin FName := Value; end; procedure TDataSet.UnknownValuesProcess; var i, j, C: integer; M: extended; Moda: TIntArray; begin // Preprocesamiento de los valores desconocidos en los datos for i := 0 to pred(AttributesCount) do begin // Si Attribute[i] es numérico : Calcular la media de Attribute[i] if Attribute[i] is TNumericAttr then begin C := 0; M := 0; for j := 0 to pred(InstanceNumber) do if not IsUnknown(DataStore[i, j]) then begin M := M + DataStore[i, j]; inc(C); end; if C > 0 then begin M := M / C; if Attribute[i] is TIntegerAttr then M := Round(M); end else SetUnknown(M); end else // Si Attribute[i] es simbólico : Calcular la moda de Attribute[i] begin SetLength(Moda, TSymbolicAttr(Attribute[i]).NumberOfSymbols); for j := 0 to pred(InstanceNumber) do if not IsUnknown(DataStore[i, j]) then begin inc(Moda[trunc(DataStore[i, j])]); M := IndexOfMax(Moda); end; end; // recorrer fDataStore // Si Val es desconocido : sustituir por media o moda for j := 0 to pred(InstanceNumber) do if IsUnknown(DataStore[i, j]) then DataStore[i, j] := M; end; end; { TSymbolicAttr } procedure TSymbolicAttr.AddSymbol(const S: string); begin FSymbols.Add(S); FNumberOfSymbols := FSymbols.Count; end; function TSymbolicAttr.ClassVal(const Ind: integer): string; begin if Assigned(FSymbols) then Result := GetSymbol(Ind) else Result := SYMBOLS[succ(Ind)] end; constructor TSymbolicAttr.Create(const aName: string; aDataSet: TDataSet); begin inherited; NumberOfSymbols := 2; end; function TSymbolicAttr.DataClass(const Val: extended): string; begin Result := GetData(Val); end; destructor TSymbolicAttr.Destroy; begin if Assigned(FSymbols) then FSymbols.Free; inherited; end; function TSymbolicAttr.Export: string; var i: integer; begin Result := '@attribute ' + Name + ' {'; for i := 1 to pred(NumberOfSymbols) do Result := Result + GetDataAt(i) + ', '; Result := Result + GetDataAt(NumberOfSymbols) + '}'; end; function TSymbolicAttr.GetData(const Val: extended): string; begin if IsUnknown(Val) then Result := UNKNOWN else if Assigned(FSymbols) then Result := GetSymbol(Trunc(Val)) else Result := SYMBOLS[Trunc(Val)]; end; function TSymbolicAttr.GetDataAt(const i: integer): string; begin if Assigned(FSymbols) then Result := GetSymbol(pred(i)) else Result := SYMBOLS[i]; end; function TSymbolicAttr.GetNumberOfSymbols: integer; begin Result := FNumberOfSymbols; end; function TSymbolicAttr.GetSymbol(const i: integer): string; begin Result := FSymbols.Strings[i]; end; function TSymbolicAttr.PosSymbol(const S: string): integer; begin Result := FSymbols.IndexOf(S); end; function TSymbolicAttr.Print: string; var i: integer; begin Result := Name + ': Symbolic ( '; for i := 1 to pred(NumberOfSymbols) do Result := Result + GetDataAt(i) + ', '; Result := Result + GetDataAt(NumberOfSymbols) + ')'; Result := Result + Linker.Print; end; function TSymbolicAttr.StrSample: string; begin Result := GetSymbol(Trunc(Sample)); end; procedure TSymbolicAttr.LoadFromStream(S: TStream); begin inherited; S.ReadBuffer(FNumberOfSymbols, SizeOf(NumberOfSymbols)); end; procedure TSymbolicAttr.SaveToStream(S: TStream); begin inherited; S.WriteBuffer(FNumberOfSymbols, SizeOf(NumberOfSymbols)); end; procedure TSymbolicAttr.SetNumberOfSymbols(const Value: integer); begin FNumberOfSymbols := Value; end; procedure TSymbolicAttr.UseExplicitSymbols; begin FSymbols := TStringList.Create; end; function TSymbolicAttr.Sample: extended; begin Result := Random(NumberOfSymbols); if not Assigned(FSymbols) then Result := Result + 1; end; { TAttribute } constructor TAttribute.Create(const aName: string; aDataSet: TDataSet); begin Name := aName; Linker := TLinker.Create(self); DataSet := aDataSet; end; destructor TAttribute.Destroy; begin Linker.Free; inherited; end; function TAttribute.FetchData(const x: integer): extended; begin Result := DataSet.FetchData(Self, x); end; procedure TAttribute.LoadFromStream(S: TStream); var L: integer; begin S.ReadBuffer(L, SizeOf(L)); SetString(Name, nil, L); S.ReadBuffer(Pointer(Name)^, L); /// Linker.LoadFromStream(S); end; procedure TAttribute.SaveToStream(S: TStream); var L: integer; begin L := Length(Name); S.WriteBuffer(L, SizeOf(L)); S.WriteBuffer(Pointer(Name)^, L); /// Linker.SaveToStream(S); end; { TRealAttr } constructor TRealAttr.Create(const aName: string; aDataSet: TDataSet); begin inherited; MinSample := MaxValue; MaxSample := MinValue; end; function TRealAttr.Export: string; begin Result := '@attribute ' + Name + ' Real'; end; function TRealAttr.GetData(const Val: extended): string; begin if IsUnknown(Val) then Result := UNKNOWN else Result := FloatToStrF(Val, ffGeneral, 2, 2); end; function TRealAttr.Print: string; begin Result := Name + ': Real'; if Distribution is TNormalDistribution then begin Result := Result + ' N( ' + FloatToStr(TNormalDistribution(Distribution).Mean) + '; ' + FloatToStr(TNormalDistribution(Distribution).StdDev) + ' ) '; end else begin Result := Result + ' U( ' + FloatToStr(TUniformDistribution(Distribution).MinValue) + '; ' + FloatToStr(TUniformDistribution(Distribution).MaxValue) + ' ) '; end; Result := Result + Linker.Print; end; function TRealAttr.StrSample: string; begin Result := FloatToStr(Sample); end; procedure TRealAttr.SetVal(const V: extended); begin if not IsNAN(V) then begin if V < MinSample then MinSample := V; if V > MaxSample then MaxSample := V; end; end; function TRealAttr.Sample: extended; begin Result := fDistribution.Sample; SetVal(Result); end; { TIntegerAttr } constructor TIntegerAttr.Create(const aName: string; aDataSet: TDataSet); begin inherited; MinSample := MaxValue; MaxSample := MinValue; end; function TIntegerAttr.Export: string; begin Result := '@attribute ' + Name + ' Integer'; end; function TIntegerAttr.GetData(const Val: extended): string; begin if IsUnknown(Val) then Result := UNKNOWN else Result := IntToStr(Trunc(Val)); end; function TIntegerAttr.GetMaxSample: integer; begin Result := Trunc(fMaxSample); end; function TIntegerAttr.GetMaxValue: integer; begin Result := Trunc(fMaxValue); end; function TIntegerAttr.GetMinSample: integer; begin Result := Trunc(fMinSample); end; function TIntegerAttr.GetMinValue: integer; begin Result := Trunc(fMinValue); end; function TIntegerAttr.Print: string; begin Result := Name + ': Integer'; if Distribution is TNormalDistribution then begin Result := Result + ' N( ' + FloatToStr(TNormalDistribution(Distribution).Mean) + '; ' + FloatToStr(TNormalDistribution(Distribution).StdDev) + ' ) '; end else begin Result := Result + ' U( ' + FloatToStr(TUniformDistribution(Distribution).MinValue) + '; ' + FloatToStr(TUniformDistribution(Distribution).MaxValue) + ' ) '; end; Result := Result + Linker.Print; end; procedure TDataSetDesigner.FormCreate(Sender: TObject); begin DataSet := TDataSet.Create; DataSet.InstanceNumber := EditInstancesNumber.Value; DecimalSeparator := '.'; Application.UpdateFormatSettings := false; end; procedure TDataSetDesigner.FormDestroy(Sender: TObject); begin DataSet.Free; end; procedure TDataSetDesigner.EditReal(Attr: TRealAttr); begin with NumericForm do begin AttrName.Text := Attr.Name; if Attr.Distribution is TNormalDistribution then begin NormalDistButton.Checked := true; UniformDistButton.Checked := false; Mean.Text := FloatToStr(TNormalDistribution(Attr.Distribution).Mean); StdDev.Text := FloatToStr(TNormalDistribution(Attr.Distribution).StdDev); end else begin NormalDistButton.Checked := false; UniformDistButton.Checked := true; MinVal.Text := FloatToStr(TUniformDistribution(Attr.Distribution).MinValue); MaxVal.Text := FloatToStr(TUniformDistribution(Attr.Distribution).MaxValue); end; RuidoEdit.Value := Attr.Linker.Noise; ListAttributes(VarList.Items, Attr); ListDependences(DepenList.Items, Attr); Caption := 'Real Attribute ' + Attr.Name; if ShowModal = mrOK then begin Attr.Name := NumericForm.attrName.Text; if NumericForm.NormalDistButton.Checked then begin // Normal distribution if Attr.Distribution is TUniformDistribution then begin Attr.Distribution.Destroy; Attr.Distribution := TNormalDistribution.Create( StrToFloat(NumericForm.Mean.Text), StrToFloat(NumericForm.StdDev.Text)); end else begin TNormalDistribution(Attr.Distribution).setMean(StrToFloat(NumericForm.Mean.Text)); TNormalDistribution(Attr.Distribution).setStdDev(StrToFloat(NumericForm.StdDev.Text)); end; end else begin // Uniform distribution if Attr.Distribution is TNormalDistribution then begin Attr.Distribution.Destroy; Attr.Distribution := TUniformDistribution.Create( StrToFloat(NumericForm.MinVal.Text), StrToFloat(NumericForm.MaxVal.Text)); end else begin TUniformDistribution(Attr.Distribution).setMinValue(StrToFloat(NumericForm.MinVal.Text)); TUniformDistribution(Attr.Distribution).setMaxValue(StrToFloat(NumericForm.MaxVal.Text)); end; end; UpdateDependences(DepenList.Items, Attr); Attr.Linker.Noise := RuidoEdit.Value; DataSet.Insufflated := false; fFileModified := true; end; end; end; procedure TDataSetDesigner.UpDateListAttr(const index: integer); var Attr: TAttribute; begin Attr := TAttribute(ListAttr.Items.Objects[ListAttr.ItemIndex]); ListAttr.Items.Strings[index] := Attr.Print; end; procedure TDataSetDesigner.EditInteger(Attr: TIntegerAttr); begin with NumericForm do begin AttrName.Text := Attr.Name; if Attr.Distribution is TNormalDistribution then begin NormalDistButton.Checked := true; UniformDistButton.Checked := false; Mean.Text := FloatToStr(TNormalDistribution(Attr.Distribution).Mean); StdDev.Text := FloatToStr(TNormalDistribution(Attr.Distribution).StdDev); end else begin NormalDistButton.Checked := false; UniformDistButton.Checked := true; MinVal.Text := FloatToStr(TUniformDistribution(Attr.Distribution).MinValue); MaxVal.Text := FloatToStr(TUniformDistribution(Attr.Distribution).MaxValue); end; RuidoEdit.Value := Attr.Linker.Noise; ListAttributes(VarList.Items, Attr); ListDependences(DepenList.Items, Attr); Caption := 'Integer Attribute ' + Attr.Name; if ShowModal = mrOK then begin Attr.Name := NumericForm.attrName.Text; if NumericForm.NormalDistButton.Checked then begin // Normal distribution if Attr.Distribution is TUniformDistribution then begin Attr.Distribution.Destroy; Attr.Distribution := TNormalDistribution.Create( StrToFloat(NumericForm.Mean.Text), StrToFloat(NumericForm.StdDev.Text)); end else begin TNormalDistribution(Attr.Distribution).setMean(StrToFloat(NumericForm.Mean.Text)); TNormalDistribution(Attr.Distribution).setStdDev(StrToFloat(NumericForm.StdDev.Text)); end; end else begin // Uniform distribution if Attr.Distribution is TNormalDistribution then begin Attr.Distribution.Destroy; Attr.Distribution := TUniformDistribution.Create( StrToFloat(NumericForm.MinVal.Text), StrToFloat(NumericForm.MaxVal.Text)); end else begin TUniformDistribution(Attr.Distribution).setMinValue(StrToFloat(NumericForm.MinVal.Text)); TUniformDistribution(Attr.Distribution).setMaxValue(StrToFloat(NumericForm.MaxVal.Text)); end; end; UpdateDependences(DepenList.Items, Attr); Attr.Linker.Noise := RuidoEdit.Value; DataSet.Insufflated := false; fFileModified := true; end; end; end; procedure TDataSetDesigner.EditSymbolic(Attr: TSymbolicAttr); begin with SymbolicForm do begin attrName.Text := Attr.Name; EditSimbolico.Value :=Attr.NumberOfSymbols; RuidoEdit.Value := Attr.Linker.Noise; ListAttributes(VarList.Items, Attr); ListDependences(DepenList.Items, Attr); Caption := 'Symbolic Attribute ' + Attr.Name; if ShowModal = mrOK then begin Attr.NumberOfSymbols := EditSimbolico.Value; UpdateDependences(DepenList.Items, Attr); Attr.Linker.Noise := RuidoEdit.Value; DataSet.Insufflated := false; end; end; end; function TIntegerAttr.StrSample: string; begin Result := IntToStr(Trunc(Sample)); end; procedure TDataSetDesigner.EditInstancesNumberChange(Sender: TObject); begin if EditInstancesNumber.text <> '' then if EditInstancesNumber.Value >= 0 then begin DataSet.InstanceNumber := EditInstancesNumber.Value; fFileModified := true; end else EditInstancesNumber.Value := DataSet.InstanceNumber; end; procedure TDataSetDesigner.NewDBExecute(Sender: TObject); begin if CanProceed then NewDataBase; end; procedure TDataSetDesigner.GenerateExecute(Sender: TObject); begin DataSet.Insufflate; ExportDataSet(MemData.Lines); end; procedure TDataSetDesigner.NewRealExecute(Sender: TObject); var Dist: TDistribution; Attr: TRealAttr; begin ListAttributes(NumericForm.VarList.Items, nil); NumericForm.DepenList.Clear; NumericForm.AttrName.Text := ''; NumericForm.Caption := 'New Real Attribute'; if NumericForm.ShowModal = mrOK then begin Attr := DataSet.AddRealAttribute; Attr.Name := NumericForm.attrName.Text; if NumericForm.NormalDistButton.Checked then begin // Normal distribution Dist := TNormalDistribution.Create( StrToFloat(NumericForm.Mean.Text), StrToFloat(NumericForm.StdDev.Text)); end else begin // Uniform distribution Dist := TUniformDistribution.Create( StrToFloat(NumericForm.MinVal.Text), StrToFloat(NumericForm.MaxVal.Text)); end; Attr.Distribution := Dist; UpdateDependences(NumericForm.DepenList.Items, Attr); Attr.Linker.Noise := NumericForm.RuidoEdit.Value; DataSet.Insufflated := false; ListAttr.AddItem(Attr.Print, Attr); fFileModified := true; end; end; procedure TDataSetDesigner.NewIntExecute(Sender: TObject); var Dist: TDistribution; Attr: TIntegerAttr; begin ListAttributes(NumericForm.VarList.Items, nil); NumericForm.DepenList.Clear; NumericForm.AttrName.Text := ''; NumericForm.Caption := 'New Integer Attribute'; if NumericForm.ShowModal = mrOK then begin Attr := DataSet.AddIntegerAttribute; Attr.Name := NumericForm.attrName.Text; if NumericForm.NormalDistButton.Checked then begin // Normal distribution Dist := TNormalDistribution.Create( StrToFloat(NumericForm.Mean.Text), StrToFloat(NumericForm.StdDev.Text)); end else begin // Uniform distribution Dist := TUniformDistribution.Create( StrToFloat(NumericForm.MinVal.Text), StrToFloat(NumericForm.MaxVal.Text)); end; Attr.Distribution := Dist; UpdateDependences(NumericForm.DepenList.Items, Attr); Attr.Linker.Noise := NumericForm.RuidoEdit.Value; DataSet.Insufflated := false; ListAttr.AddItem(Attr.Print, Attr); fFileModified := true; end; end; procedure TDataSetDesigner.NewSymbolicExecute(Sender: TObject); var Attr: TSymbolicAttr; begin ListAttributes(SymbolicForm.VarList.Items, nil); NumericForm.DepenList.Clear; NumericForm.AttrName.Text := ''; with SymbolicForm do begin attrName.Text := ''; Caption := 'New Symbolic Attribute'; if SymbolicForm.ShowModal = mrOK then begin Attr := DataSet.AddSymbolicAttribute; Attr.Name := attrName.Text; Attr.NumberOfSymbols := EditSimbolico.Value; UpdateDependences(DepenList.Items, Attr); Attr.Linker.Noise := RuidoEdit.Value; DataSet.Insufflated := false; ListAttr.AddItem(Attr.Print, Attr); fFileModified := true; end; end; end; procedure TDataSetDesigner.EditAttrExecute(Sender: TObject); var Attr: TAttribute; begin if ListAttr.ItemIndex >= 0 then begin Attr := TAttribute(ListAttr.Items.Objects[ListAttr.ItemIndex]); if Attr is TRealAttr then EditReal(Attr as TRealAttr) else if Attr is TIntegerAttr then EditInteger(Attr as TIntegerAttr) else EditSymbolic(Attr as TSymbolicAttr); UpDateListAttr(ListAttr.ItemIndex); fFileModified := true; end; end; procedure TDataSetDesigner.ListAttrMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; begin P.X := X; P.Y := Y; ListAttr.ItemIndex := ListAttr.ItemAtPos(P, true); end; procedure TDataSetDesigner.ExportDataSet(Media: TStrings); var Ai, Xi: integer; Row: string; begin if DataSet.AttributesCount > 0 then begin Media.Clear; Media.Add('@relation ' + DataSet.Name); Media.Add(''); for Ai := 0 to pred(DataSet.AttributesCount) do Media.Add(DataSet.Attribute[Ai].Export); Media.Add(''); Media.Add('@data'); with DataSet do for Xi := 0 to pred(InstanceNumber) do begin Row := ''; for Ai := 0 to AttributesCount - 2 do Row := Row + Data[Ai, Xi] + ', '; Row := Row + Data[pred(AttributesCount), Xi]; Media.Add(Row); end; end; end; procedure TDataSetDesigner.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin if DataSet.Insufflated then MemData.Font.Color := clBlack else MemData.Font.Color := clRed; end; procedure TDataSetDesigner.DeleteExecute(Sender: TObject); var Attr: TAttribute; begin if ListAttr.ItemIndex >= 0 then begin Attr := TAttribute(ListAttr.Items.Objects[ListAttr.ItemIndex]); ListAttr.DeleteSelected; DataSet.Delete(Attr); fFileModified := true; end; end; procedure TDataSetDesigner.ExportExecute(Sender: TObject); begin SaveDialog1.Title := 'Exportar'; SaveDialog1.Filter := 'Weka File'; SaveDialog1.DefaultExt := 'arff'; if SaveDialog1.Execute then MemData.Lines.SaveToFile(SaveDialog1.FileName); end; procedure TDataSetDesigner.AnalyzeAllExecute(Sender: TObject); begin if DataSet.Insufflated then begin AnalyzerForm.Memo.Clear; AnalyzerForm.Execute(DataSet); AnalyzerForm.Show; end; end; procedure TIntegerAttr.SetMaxSample(const Value: integer); begin fMaxSample := Value; end; procedure TIntegerAttr.SetMaxValue(const Value: integer); begin fMaxValue := Value; end; procedure TIntegerAttr.SetMinSample(const Value: integer); begin fMinSample := Value; end; procedure TIntegerAttr.SetMinValue(const Value: integer); begin fMinValue := Value; end; procedure TIntegerAttr.SetVal(const V: extended); begin if not IsNAN(V) then begin if V < MinSample then MinSample := Trunc(V); if V > MaxSample then MaxSample := Trunc(V); end; end; function TIntegerAttr.Sample: extended; begin Result := fDistribution.Sample; SetVal(Result); end; { TNumericAttr } function TNumericAttr.ClassVal(const Ind: integer): string; begin Result := IntToStr(Ind); end; procedure TNumericAttr.ComputeValues; begin if Distribution is TUniformDistribution then begin fMinValue := TUniformDistribution(Distribution).MinValue; fMaxValue := TUniformDistribution(Distribution).MaxValue; end else begin fMinValue := TNormalDistribution(Distribution).Mean - 3 * TNormalDistribution(Distribution).StdDev; fMaxValue := TNormalDistribution(Distribution).Mean + 3 * TNormalDistribution(Distribution).StdDev; end; end; function TNumericAttr.DataClass(const Val: extended): string; var C: integer; begin if IsUnknown(Val) then Result := UNKNOWN else begin if Val = fMinSample then C := 0 else C := Pred(Ceil((Val - fMinSample) / Interval)); Result := IntToStr(C); end; end; procedure TNumericAttr.LoadFromStream(S: TStream); var N: string; L: integer; begin inherited; S.ReadBuffer(L, SizeOf(L)); // Longitud del nombre de la clase SetString(N, nil, L); S.ReadBuffer(Pointer(N)^, L); if N = 'TNormalDistribution' then begin fDistribution := TNormalDistribution.Create(0, 0); end else begin fDistribution := TUniformDistribution.Create(0, 0); end; fDistribution.LoadFromStream(S); S.ReadBuffer(fDiscretizationLevel, SizeOf(fDiscretizationLevel)); S.ReadBuffer(fMinValue, SizeOf(fMinValue)); S.ReadBuffer(fMaxValue, SizeOf(fMaxValue)); S.ReadBuffer(fMinSample, SizeOf(fMinSample)); S.ReadBuffer(fMaxSample, SizeOf(fMaxSample)); S.ReadBuffer(Interval, SizeOf(Interval)); end; procedure TNumericAttr.SaveToStream(S: TStream); var N: string; L: integer; begin inherited; N := fDistribution.ClassName; L := Length(N); S.WriteBuffer(L, SizeOf(L)); S.WriteBuffer(Pointer(N)^, L); fDistribution.SaveToStream(S); S.WriteBuffer(fDiscretizationLevel, SizeOf(fDiscretizationLevel)); S.WriteBuffer(fMinValue, SizeOf(fMinValue)); S.WriteBuffer(fMaxValue, SizeOf(fMaxValue)); S.WriteBuffer(fMinSample, SizeOf(fMinSample)); S.WriteBuffer(fMaxSample, SizeOf(fMaxSample)); S.WriteBuffer(Interval, SizeOf(Interval)); end; function TNumericAttr.SetInterval: string; var Range: extended; begin //SetRoundMode(rmUp); Range := fMaxSample - fMinSample; Interval := Range * SAMPLESPERCELL / DataSet.InstanceNumber; fDiscretizationLevel := Round(Range / Interval); //if Interval = 0 then Interval := 1; Result := FloatToStr(Interval); { if Range mod DataSet.InstanceNumber > 0 then inc(Interval); } end; { TLinker } function TLinker.Cycle(Attr: TAttribute): boolean; var i: integer; begin if Attr = fOutputAttr then Result := true else begin Result := false; if not Attr.Linker.Independent then begin i := 0; while (i < Attr.Linker.InputCount) and not Result do begin Result := Cycle(Attr.Linker.Input[i]); inc(i); end; end; end; end; constructor TLinker.Create(OutputAttr: TAttribute); begin fInputAttrs := TList.Create; fOutputAttr := OutputAttr; SetLength(fWeights, 1); fWeights[0] := 100; // Peso inicial del atributo por defecto: atributo de salida end; destructor TLinker.Destroy; begin fInputAttrs.Free; fWeights := nil; if Assigned(fNormWeights) then Finalize(fNormWeights); if Assigned(fSamples) then Finalize(fSamples); inherited; end; function TLinker.ReadDependence(const x: integer): extended; begin Convert(x); Result := Average; { if fOutputAttr is TRealAttr then Result := FloatToStr(Average) else if fOutputAttr is TIntegerAttr then Result := IntToStr(Round(Average)) else Result := SYMBOLS[Round(Average)]; } end; function TLinker.Average: extended; var i: integer; begin Result := 0; for i := 0 to High(fSamples) do Result := Result + fNormWeights[i] * fSamples[i]; if not (fOutputAttr is TRealAttr) then begin SetRoundMode(rmNearest); Result := Round(Result); end; end; procedure TLinker.SetWeight(Attr: TAttribute; const Value: integer); var i: integer; begin i := fInputAttrs.IndexOf(Attr); if i >= 0 then fWeights[succ(i)] := Value; NormalizeWeights; end; procedure TLinker.UnlinkAttr(Attr: TAttribute); begin RemoveLink(fInputAttrs.IndexOf(Attr)); end; procedure TLinker.LinkAttr(Attr: TAttribute; const Value: integer); begin fInputAttrs.Add(Attr); SetLength(fWeights, succ(Length(fWeights))); fWeights[High(fWeights)] := Value; NormalizeWeights; end; procedure TLinker.RemoveWeight(const index: integer); var w: TWeights; i: integer; begin if (Length(fWeights) > 0) and (index >= 0) and (index <= High(fWeights)) then begin w := Copy(fWeights, 0, index); SetLength(w, pred(Length(fWeights))); for i := succ(index) to High(fWeights) do w[pred(i)] := fWeights[i]; Finalize(fWeights); fWeights := w; end; end; procedure TLinker.Convert(const x: integer); var i: integer; Attr: TAttribute; begin SetLength(fSamples, succ(fInputAttrs.Count)); fSamples[0] := fOutputAttr.Sample; if fOutputAttr is TNumericAttr then for i := 1 to fInputAttrs.Count do begin Attr := fInputAttrs.Items[pred(i)]; if Attr is TNumericAttr then fSamples[i] := NumToNum(TNumericAttr(Attr), TNumericAttr(fOutputAttr), x) else fSamples[i] := SymToNum(TSymbolicAttr(Attr), TNumericAttr(fOutputAttr), x); end else // fOutputAttr is TSymbolicAttr for i := 1 to fInputAttrs.Count do begin Attr := fInputAttrs.Items[pred(i)]; if Attr is TNumericAttr then fSamples[i] := NumToSym(TNumericAttr(Attr), TSymbolicAttr(fOutputAttr), x) else fSamples[i] := SymToSym(TSymbolicAttr(Attr), TSymbolicAttr(fOutputAttr), x); end end; procedure TLinker.NormalizeWeights; var i: integer; TotalWeight: extended; begin SetLength(fNormWeights, Length(fWeights)); TotalWeight := 0; for i := 0 to High(fWeights) do TotalWeight := TotalWeight + fWeights[i]; // Si el atributo es independiente entonces la influencia de su muestreo // no puede ser nula sino completa if TotalWeight = 0 then begin fWeights[0] := 100; TotalWeight := 100; end; for i := 0 to High(fNormWeights) do fNormWeights[i] := fWeights[i] / TotalWeight; end; procedure TDataSetDesigner.ListAttributes(List: TStrings; Attr: TAttribute); var i: integer; A: TAttribute; begin List.Clear; for i := 0 to pred(DataSet.AttributesCount) do begin A := DataSet.Attribute[i]; if (Attr = nil) or ((A <> Attr) and not Attr.Linker.IsInput(A)) then List.AddObject(A.Name, A); end; end; procedure TDataSetDesigner.ListDependences(List: TStrings; Attr: TAttribute); var i: integer; A: TAttribute; begin List.Clear; if Assigned(Attr.Linker) then for i := 0 to pred(Attr.Linker.InputCount) do begin A := Attr.Linker.Input[i]; List.AddObject(Attr.Linker.Weight[i] + ' ' + A.Name, A); end; end; procedure TDataSetDesigner.UpdateDependences(List: TStrings; Attr: TAttribute); var i: integer; begin Attr.Linker.ClearInputs; for i := 0 to pred(List.Count) do if not Attr.Linker.IsInput(TAttribute(List.Objects[i])) then Attr.Linker.LinkAttr(TAttribute(List.Objects[i]), StrToInt(copy(List.Strings[i], 1, pred(pos(' ', List.Strings[i]))))); end; function TLinker.GetInputCount: integer; begin Result := fInputAttrs.Count; end; function TLinker.GetInput(const i: integer): TAttribute; begin Result := fInputAttrs[i]; end; function TLinker.GetWeight(const i: integer): string; begin Result := FloatToStr(fWeights[succ(i)]); end; function TLinker.IsInput(Attr: TAttribute): boolean; var i: integer; begin i := 0; while (i < fInputAttrs.Count) and (Attr <> fInputAttrs[i]) do inc(i); Result := i < fInputAttrs.Count; end; procedure TLinker.RemoveLink(const index: integer); begin fInputAttrs.Delete(index); RemoveWeight(index); NormalizeWeights; end; function TLinker.GetIndependent: boolean; begin Result := fInputAttrs.Count = 0; end; function TLinker.NumToNum(AttrIn, AttrOut: TNumericAttr; const x: integer): extended; begin Result := AttrOut.MinValue + (AttrIn.FetchData(x) - AttrIn.MinValue) * (AttrOut.MaxValue - AttrOut.MinValue) / (1 + (AttrIn.MaxValue - AttrIn.MinValue)); end; function TLinker.SymToNum(AttrIn: TSymbolicAttr; AttrOut: TNumericAttr; const x: integer): extended; begin Result := AttrOut.MinValue + (AttrIn.FetchData(x) - 1) * (AttrOut.MaxValue - AttrOut.MinValue) / (AttrIn.NumberOfSymbols); end; function TLinker.NumToSym(AttrIn: TNumericAttr; AttrOut: TSymbolicAttr; const x: integer): extended; begin Result := Trunc(1 + (AttrIn.FetchData(x) - AttrIn.MinValue) * (AttrOut.NumberOfSymbols) / (1 + abs(AttrIn.MaxValue - AttrIn.MinValue))); end; function TLinker.SymToSym(AttrIn, AttrOut: TSymbolicAttr; const x: integer): extended; begin Result := Trunc(1 + (AttrIn.FetchData(x) - 1) * (AttrOut.NumberOfSymbols) / (AttrIn.NumberOfSymbols)); end; function TLinker.GetNoise: integer; begin Result := fNoise; end; procedure TLinker.SetNoise(const Value: integer); begin fNoise := Value; fWeights[0] := 100 - fNoise; NormalizeWeights; end; procedure TLinker.ClearInputs; begin fInputAttrs.Clear; SetLength(fWeights, 1); end; function TLinker.Print: string; var i: integer; begin if InputCount = 0 then Result := '' else begin Result := ' Depend:'; for i := 0 to pred(InputCount) do Result := Result + ' ' + Weight[i] + '% ' + Input[i].Name; Result := Result + ' Noise: ' + IntToStr(fNoise) + '%'; end; end; procedure TDataSetDesigner.InformationTheoreticAnalysisExecute(Sender: TObject); begin if DataSet.Insufflated then begin AnalyzerForm.Memo.Clear; AnalyzerForm.InformationTheoryAnalysis(DataSet); AnalyzerForm.Show; end; end; procedure TDataSetDesigner.RoughSetsAnalysisExecute(Sender: TObject); begin if DataSet.Insufflated then begin AnalyzerForm.Memo.Clear; AnalyzerForm.RoughSetAnalysis(DataSet); AnalyzerForm.Show; end; end; procedure TDataSetDesigner.ViewAnalysisSheetExecute(Sender: TObject); begin ViewAnalysisSheet.Checked := not ViewAnalysisSheet.Checked; if ViewAnalysisSheet.Checked then begin AnalyzerForm.WindowState := wsMaximized; AnalyzerForm.Show; end else AnalyzerForm.Hide; end; procedure TDataSetDesigner.CleanAnalysisSheetExecute(Sender: TObject); begin AnalyzerForm.Memo.Clear; end; procedure TDataSetDesigner.SaveToFile(const FileName: string); var S: TFilestream; begin S := TFilestream.Create(FileName, fmCreate); DataSet.SaveToStream(S); S.Free; end; procedure TLinker.SaveToStream(S: TStream); var i, L: integer; N: string; begin S.WriteBuffer(fNoise, SizeOf(fNoise)); S.WriteBuffer(fInputAttrs.Count, SizeOf(fInputAttrs.Count)); for i := 0 to pred(fInputAttrs.Count) do begin N := TAttribute(fInputAttrs.Items[i]).Name; L := Length(N); S.WriteBuffer(L, SizeOf(L)); S.WriteBuffer(Pointer(N)^, L); end; S.WriteBuffer(Pointer(fWeights)^, Length(fWeights) * SizeOf(integer)); end; procedure TLinker.LoadFromStream(S: TStream); var C, i, L: integer; N: string; begin S.ReadBuffer(fNoise, SizeOf(fNoise)); S.ReadBuffer(C, SizeOf(C)); // fInputAttrs.Count for i := 0 to pred(C) do begin S.ReadBuffer(L, SizeOf(L)); SetString(N, nil, L); S.ReadBuffer(Pointer(N)^, L); fInputAttrs.Add(fOutputAttr.DataSet.FindAttr(N)); end; SetLength(fWeights, succ(C)); SetLength(fNormWeights, succ(C)); S.ReadBuffer(Pointer(fWeights)^, Length(fWeights) * SizeOf(integer)); NormalizeWeights; end; procedure TDataSetDesigner.LoadFromFile(const FileName: string); var S: TFilestream; begin NewDBExecute(Self); S := TFilestream.Create(FileName, fmOpenRead); DataSet.LoadFromStream(S); S.Free; UpdateDisplay; if DataSet.Insufflated then ExportDataSet(MemData.Lines); end; procedure TDataSetDesigner.SaveAsExecute(Sender: TObject); begin SaveDialog1.Title := 'Guardar como'; SaveDialog1.Filter := 'DataScultor File|*.dsf'; SaveDialog1.DefaultExt := 'dsf'; if SaveDialog1.Execute then begin SaveToFile(SaveDialog1.FileName); fFileName := SaveDialog1.FileName; Caption := MainFormTitle + ' - ' + GetFileName(fFileName); fFileModified := false; fProceed := true; end; end; procedure TDataSetDesigner.OpenExecute(Sender: TObject); begin OpenDialog1.Title := 'Abrir'; OpenDialog1.Filter := 'DataSculptor|*.dsf|Todos|*.*'; OpenDialog1.DefaultExt := 'dsf'; if OpenDialog1.Execute and CanProceed then begin NewDataBase; LoadFromFile(OpenDialog1.FileName); fFileModified := false; fFileName := OpenDialog1.FileName; Caption := MainFormTitle + ' - ' + GetFileName(fFileName); end; end; procedure TDataSetDesigner.UpdateDisplay; var i: integer; begin ListAttr.Clear; for i := 0 to pred(DataSet.AttributesCount) do ListAttr.AddItem(DataSet.Attribute[i].Print, DataSet.Attribute[i]); if DataSet.InstanceNumber = 0 then DataSet.InstanceNumber := DefaultInstancesNumber else begin EditInstancesNumber.OnChange := nil; EditInstancesNumber.Value := DataSet.InstanceNumber; EditInstancesNumber.OnChange := EditInstancesNumberChange; end; end; procedure TDataSetDesigner.SaveExecute(Sender: TObject); begin if fFileName = '' then SaveAsExecute(Self) else begin SaveToFile(fFileName); fFileModified := false; fProceed := true; end; end; function TDataSetDesigner.GetFileName(const RawFileName: string): string; var S: string; C: integer; begin S := ExtractFileName(RawFileName); C := LastDelimiter('.', S); if C = 0 then Result := S else Result := copy(S, 1, pred(C)); end; procedure TDataSetDesigner.NewDataBase; begin DataSet.Free; DataSet := TDataSet.Create; EditInstancesNumber.Value := DefaultInstancesNumber; DataSet.InstanceNumber := DefaultInstancesNumber; ListAttr.Clear; MemData.Clear; fFilename := ''; Caption := MainFormTitle; fFileModified := false; end; function TDataSetDesigner.CanProceed: boolean; var MR: word; begin // Si se ha comenzado un diseño, preguntar si no desea guardarlo fProceed := false; if fFileModified then MR := MessageDlg('¿Desea guardar la base de datos actual?', mtConfirmation, mbYesNoCancel, 0) else MR := mrNo; if MR = mrCancel then Result := false else if MR = mrYes then begin SaveExecute(Self); Result := fProceed; end else Result := true; end; procedure TDataSetDesigner.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if CanProceed then CanClose := true else CanClose := false; end; procedure TDataSetDesigner.BasicAnalysisExecute(Sender: TObject); begin if DataSet.Insufflated then begin AnalyzerForm.Memo.Clear; AnalyzerForm.BasicMeasures(DataSet); AnalyzerForm.Show; end; end; procedure TDataSetDesigner.StatisticAnalysisExecute(Sender: TObject); begin if DataSet.Insufflated then begin AnalyzerForm.Memo.Clear; AnalyzerForm.StatisticAnalysis(DataSet); AnalyzerForm.Show; end; end; procedure TDataSetDesigner.ImportExecute(Sender: TObject); var Parser: TParser; begin OpenDialog1.Title := 'Importar'; OpenDialog1.Filter := 'Weka File|*.arff|C4.5 File|*.names|Todos|*.*'; OpenDialog1.DefaultExt := 'arff'; if OpenDialog1.Execute and CanProceed then begin NewDataBase; MemData.Lines.LoadFromFile(OpenDialog1.FileName); fFileModified := false; fFileName := OpenDialog1.FileName; Caption := MainFormTitle + ' - ' + GetFileName(fFileName); Parser := TParser.Create(DataSet); if ExtractFileExt(fFileName) = '.arff' then Parser.ParseStrings(MemData.Lines) else ImportXDataFile(Parser); Parser.Free; UpdateDisplay; end; end; { TParser } constructor TParser.Create(Dataset: TDataSet); begin FDataSet := DataSet; Ind := 1; end; procedure TParser.GoAhead; begin if TextLine[Ind] = Comment then Ind := succ(Length(TextLine)) else inc(Ind); LineBreak := false; while (Ind > Length(TextLine)) and (Line < Text.Count) do begin Ind := 1; inc(Line); if Line < Text.count then TextLine := Trim(Text[Line]) else TextLine := ''; LineBreak := true; end; if Line = Text.count then EOF := true; end; procedure TParser.Init(aText: TStrings); begin Text := aText; TextLine := Trim(Text[Line]); end; function TParser.NextToken: string; begin while not EOF and (TextLine[Ind] in Separators) do GoAhead; Result := ''; if not EOF then if TextLine[Ind] in Operators then begin Result := TextLine[Ind]; GoAhead; end else repeat Result := Result + TextLine[Ind]; GoAhead; until EOF or LineBreak or ((TextLine[Ind] in (Separators + Operators))); FToken := Result; end; function TParser.ParseArffData: boolean; begin if Lowercase(Token) = '@data' then Result := ParseData else Result := false; end; function TParser.ParseAttributes: boolean; var AttrName: string; Attr: TAttribute; begin Result := false; while Lowercase(Token) = '@attribute' do begin NextToken; Result := ParseIdent(AttrName); if Result then if Lowercase(Token) = 'real' then begin Attr := FDataSet.AddRealAttribute; Attr.Name := AttrName; NextToken; end else if Lowercase(Token) = 'integer' then begin Attr := FDataSet.AddIntegerAttribute; Attr.Name := AttrName; NextToken; end else if Token = '{' then begin NextToken; Attr := FDataSet.AddSymbolicAttribute; Attr.Name := AttrName; TSymbolicAttr(Attr).UseExplicitSymbols; while Token <> '}' do begin TSymbolicAttr(Attr).AddSymbol(Token); NextToken; end; if TSymbolicAttr(Attr).NumberOfSymbols > 0 then NextToken else Result := false end else Result := false; end; end; function TParser.ParseData: boolean; var i, j: integer; val: extended; begin NextToken; j := 0; Result := true; SetLength(FDataSet.fDataStore, FDataSet.AttributesCount); while Result and not EOF do begin for i := 0 to pred(FDataSet.AttributesCount) do begin if FDataSet.Attribute[i] is TRealAttr then Result := ParseReal(val) else if FDataSet.Attribute[i] is TIntegerAttr then Result := ParseInteger(val) else if FDataSet.Attribute[i] is TSymbolicAttr then Result := ParseSymbolic(TSymbolicAttr(FDataSet.Attribute[i]), val); if Result then begin SetLength(FDataSet.fDataStore[i], succ(j)); FDataSet.fDataStore[i, j] := val; if FDataSet.Attribute[i] is TNumericAttr then TNumericAttr(FDataSet.Attribute[i]).SetVal(val); end; if not Result then exit; end; inc(j); end; if Result then with FDataSet do begin fInstanceNumber := j; for i := 0 to pred(AttributesCount) do if Attribute[i] is TNumericAttr then TNumericAttr(Attribute[i]).SetInterval; Insufflated := true; end; end; function TParser.ParseIdent(var Ident: string): boolean; begin if not EOF and not (Token[1] in Operators) then begin Ident := Token; NextToken; Result := true; end else Result := false; end; function TParser.ParseInteger(var fval: extended): boolean; begin if Token = '?' then begin SetUnknown(fval); Result := true; NextToken; end else try fval := StrToInt(Token); Result := true; NextToken; except Result := false; end; end; function TParser.ParseReal(var fval: extended): boolean; begin if Token = '?' then begin SetUnknown(fval); Result := true; NextToken; end else try fval := StrToFloat(Token); Result := true; NextToken; except Result := false; end; end; function TParser.ParseRelation: boolean; var RelName: string; begin if Lowercase(Token) = '@relation' then begin NextToken; Result := ParseIdent(RelName); DataSet.Name := RelName; end else Result := false; end; function TParser.ParseStrings(aText: TStrings): boolean; begin Init(aText); NextToken; Result := ParseRelation and ParseAttributes and ParseArffData; end; function TParser.ParseSymbolic(Attr: TSymbolicAttr; var fval: extended): boolean; begin if Token = '?' then begin SetUnknown(fval); Result := true; NextToken; end else begin fval := Attr.PosSymbol(Token); if fval = -1 then // Tal vez el símbolo esté codificado en decimal try fval := Attr.PosSymbol(IntToStr(Trunc(StrToFloat(Token)))) except fval := -1; end; if fval = -1 then Result := false else begin Result := true; NextToken; end; end; end; procedure TParser.ParseSymbolList(const AName: string); var Attr: TAttribute; begin Attr := FDataSet.AddSymbolicAttribute; Attr.Name := AName; TSymbolicAttr(Attr).UseExplicitSymbols; TSymbolicAttr(Attr).AddSymbol(Token); while not LineBreak do begin NextToken; TSymbolicAttr(Attr).AddSymbol(Token); end; end; function TParser.ParseXData(aText: TStrings): boolean; begin Text := aText; Restart; Result := ParseData; end; function TParser.ParseXNames(aText: TStrings): boolean; var AttrName: string; Attr: TAttribute; begin Init(aText); // Saltar la declaración de las clases repeat NextToken; until LineBreak; // Leer la declaración de los atributos Result := true; while Result and not EOF do begin NextToken; Result := ParseIdent(AttrName); if Result then if Token = 'continuous' then begin Attr := FDataSet.AddRealAttribute; Attr.Name := AttrName; end else ParseSymbolList(AttrName); end; // Regresar atrás para leer la declaración de las clases Restart; NextToken; ParseSymbolList('Class'); end; procedure TParser.Restart; begin Line := 0; Ind := 1; LineBreak := false; EOF := false; FToken := ''; TextLine := Trim(Text[Line]); end; procedure TDataSetDesigner.ImportXDataFile(Parser: TParser); var S: TStringList; fn: TFileName; begin Parser.ParseXNames(MemData.Lines); fn := ChangeFileExt(OpenDialog1.FileName, ''); S := TStringList.Create; try try S.LoadFromFile(fn); except fn := ChangeFileExt(OpenDialog1.FileName, '.data'); S.LoadFromFile(fn); end; Parser.ParseXData(S); MemData.Lines.Add(''); MemData.Lines.Add('- Data -'); MemData.Lines.Add(''); MemData.Lines.AddStrings(S); finally S.Free; end; end; procedure TDataSetDesigner.UnknownValExecute(Sender: TObject); begin if DataSet.Insufflated then begin DataSet.UnknownValuesProcess; ExportDataSet(MemData.Lines); end; end; procedure TDataSetDesigner.BinarizationExecute(Sender: TObject); begin if DataSet.Insufflated then begin DataSet.BinarizationProcess; ExportDataSet(MemData.Lines); UpdateDisplay; fFileModified := true; end; end; { TUniformDistribution } constructor TUniformDistribution.Create(const aMinVal, aMaxVal: extended); begin fMinValue := aMinVal; fMaxValue := aMaxVal; end; function TUniformDistribution.Sample: extended; var mean, sd: extended; s: extended; begin mean := (fMinValue + fMaxValue) / 2.0; sd := fMaxValue - fMinValue; s := RandG(mean, sd); if s > fMaxValue then s := mean + (Frac(abs(s)/(fMaxValue - mean)))*(fMaxValue - mean); if s < fMinValue then s := mean - (Frac(abs(s)/(mean - fMinValue)))*(mean - fMinValue); Result := s; end; function TUniformDistribution.IntSample: extended; begin Result := RandomRange(round(fMinValue), round(fMaxValue)); end; procedure TUniformDistribution.setMaxValue(const val: extended); begin fMaxValue := val; end; procedure TUniformDistribution.setMinValue(const val: extended); begin fMinValue := val; end; procedure TUniformDistribution.LoadFromStream(S: TStream); begin inherited; S.ReadBuffer(fMinValue, SizeOf(fMinValue)); S.ReadBuffer(fMaxValue, SizeOf(fMaxValue)); end; procedure TUniformDistribution.SaveToStream(S: TStream); begin inherited; S.WriteBuffer(fMinValue, SizeOf(fMinValue)); S.WriteBuffer(fMaxValue, SizeOf(fMaxValue)); end; { TNormalDistribution } constructor TNormalDistribution.Create(const aMean, aStdDev: extended); begin fMean := aMean; fStdDev := aStdDev; end; procedure TNormalDistribution.LoadFromStream(S: TStream); begin inherited; S.ReadBuffer(fMean, SizeOf(fMean)); S.ReadBuffer(fStdDev, SizeOf(fStdDev)); end; function TNormalDistribution.Sample: extended; begin Result := RandG(fMean, fStdDev); end; procedure TNormalDistribution.SaveToStream(S: TStream); begin inherited; S.WriteBuffer(fMean, SizeOf(fMean)); S.WriteBuffer(fStdDev, SizeOf(fStdDev)); end; procedure TNormalDistribution.setMean(const val: extended); begin fMean := val; end; procedure TNormalDistribution.setStdDev(const val: extended); begin fStdDev := val; end; end.
unit cImageBuffered; interface uses Vcl.Graphics; type TImageBuffered = class Protected FImageBuffered :TPicture; FName :String; Public property Name :String read FName write FName; property Image :TPicture read FImageBuffered write FImageBuffered; Constructor Create(N :String); end; implementation uses uClient,SysUtils,Forms,Dialogs; Constructor TImageBuffered.Create(N :String); begin FImageBuffered := TPicture.Create; FName:=N; FImageBuffered.LoadFromFile(ExtractFilePath(Application.ExeName)+'assets\Texture\'+FName+'.png'); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} {/* * (c) Copyright 1993, Silicon Graphics, Inc. * 1993-1995 Microsoft Corporation * * ALL RIGHTS RESERVED */} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls, Dialogs, SysUtils, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC : HDC; hrc : HGLRC; procedure DrawScene; procedure SetDCPixelFormat; protected {Обработка сообщения WM_PAINT - аналог события OnPaint} procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; implementation {$R *.DFM} uses DGLUT; // Initialize lighting and other values. procedure MyInit; const mat_ambient : Array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 ); mat_specular : Array[0..3] of GLfloat = ( 1.0, 1.0, 1.0, 1.0 ); light_position : Array[0..3] of GLfloat = ( 0.0, 0.0, 10.0, 1.0 ); lm_ambient : Array[0..3] of GLfloat = ( 0.2, 0.2, 0.2, 1.0 ); begin glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular); glMaterialf(GL_FRONT, GL_SHININESS, 50.0); glLightfv(GL_LIGHT0, GL_POSITION, @light_position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @lm_ambient); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); end; {======================================================================= Отрисовка картинки} procedure TfrmGL.DrawScene; const torus_diffuse: Array [0..3] of GLfloat = ( 0.7, 0.7, 0.0, 1.0 ); cube_diffuse: Array [0..3] of GLfloat = ( 0.0, 0.7, 0.7, 1.0 ); sphere_diffuse: Array [0..3] of GLfloat = ( 0.7, 0.0, 0.7, 1.0 ); octa_diffuse: Array [0..3] of GLfloat = ( 0.7, 0.4, 0.4, 1.0 ); begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glShadeModel (GL_FLAT); glPushMatrix; glRotatef (30.0, 1.0, 0.0, 0.0); glPushMatrix; glTranslatef (-0.80, 0.35, 0.0); glRotatef (100.0, 1.0, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_DIFFUSE, @torus_diffuse); glutSolidTorus (0.275, 0.85, 16, 16); glPopMatrix; glPushMatrix; glTranslatef (-0.75, -0.50, 0.0); glRotatef (45.0, 0.0, 0.0, 1.0); glRotatef (45.0, 1.0, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_DIFFUSE, @cube_diffuse); glutSolidCube (1.5); glPopMatrix; glPushMatrix; glTranslatef (0.75, 0.60, 0.0); glRotatef (30.0, 1.0, 0.0, 0.0); glMaterialfv(GL_FRONT, GL_DIFFUSE, @sphere_diffuse); glutSolidSphere (1.0, 16, 16); glPopMatrix; glPushMatrix; glTranslatef (0.70, -0.90, 0.25); glMaterialfv(GL_FRONT, GL_DIFFUSE, @octa_diffuse); glutSolidOctaheadron; glPopMatrix; glPopMatrix; SwapBuffers(DC); // конец работы end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); MyInit; end; {======================================================================= Установка формата пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity; if ClientWidth <= ClientHeight then glOrtho (-2.25, 2.25, -2.25*ClientHeight/ClientWidth, 2.25*ClientHeight/ClientWidth, -10.0, 10.0) else glOrtho (-2.25*ClientWidth/ClientHeight, 2.25*ClientWidth/ClientHeight, -2.25, 2.25, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); InvalidateRect(Handle, nil, False); end; {======================================================================= Обработка сообщения WM_PAINT, рисование окна} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); DrawScene; EndPaint(Handle, ps); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close end; end.
unit uFrameImageView; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Standard, UI.Base, UI.Frame; type TFrameImageView = class(TFrame) LinearLayout1: TLinearLayout; tvTitle: TTextView; ImageView1: TImageView; ButtonView1: TButtonView; ButtonView2: TButtonView; btnBack: TTextView; procedure ButtonView1Click(Sender: TObject); procedure ButtonView2Click(Sender: TObject); procedure btnBackClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.fmx} uses UI.Dialog, TypInfo; procedure TFrameImageView.btnBackClick(Sender: TObject); begin Finish; end; procedure TFrameImageView.ButtonView1Click(Sender: TObject); begin TDialogBuilder.Create(Self) .SetTitle('ScaleType') .SetItems(['None', 'Matrix', 'Center', 'CenterCrop', 'CenterInside', 'FitCenter', 'FitStart', 'FitEnd'], procedure (Dialog: IDialog; Which: Integer) begin ImageView1.ScaleType := TImageScaleType(Which); ButtonView1.Text := 'ScaleType: ' + GetEnumName(Typeinfo(TImageScaleType), Which); end ) .Show(); end; procedure TFrameImageView.ButtonView2Click(Sender: TObject); begin TDialogBuilder.Create(Self) .SetTitle('WrapMode') .SetItems(['Tile', 'TileOriginal', 'TileStretch'], procedure (Dialog: IDialog; Which: Integer) begin ImageView1.Image.ItemDefault.Bitmap.WrapMode := TWrapMode(Which); ButtonView2.Text := 'WrapMode: ' + GetEnumName(Typeinfo(TWrapMode), Which); end ) .Show(); end; end.
unit ejb_sidl_javax_ejb_c; {This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file sidl.idl. } {Delphi Pascal unit : ejb_sidl_javax_ejb_c } {derived from IDL module : ejb } interface uses CORBA, ejb_sidl_javax_ejb_i, ejb_sidl_java_lang_i; type ERemoveException = class; TEJBMetaDataHelper = class; TEJBMetaData = class; TEJBHomeHelper = class; TEJBHomeStub = class; TEJBObjectHelper = class; TEJBObjectStub = class; ECreateException = class; EFinderException = class; ERemoveException = class(UserException) private Fmessage : AnsiString; protected function _get_message : AnsiString; virtual; public property message : AnsiString read _get_message; constructor Create; overload; constructor Create(const message : AnsiString); overload; procedure Copy(const _Input : InputStream); override; procedure WriteExceptionInfo(var _Output : OutputStream); override; end; TEJBMetaDataHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBMetaData); class function Extract(const _A: CORBA.Any): ejb_sidl_javax_ejb_i.EJBMetaData; class function TypeCode : CORBA.TypeCode; class function RepositoryId: string; class function Read (const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBMetaData; class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBMetaData); end; TEJBMetaData = class (TInterfacedObject, ejb_sidl_javax_ejb_i.EJBMetaData) private home : ejb_sidl_javax_ejb_i.EJBHome; homeInterfaceClass : ejb_sidl_java_lang_i._Class; primaryKeyClass : ejb_sidl_java_lang_i._Class; remoteInterfaceClass : ejb_sidl_java_lang_i._Class; session : Boolean; statelessSession : Boolean; constructor Create; overload; public function _get_home : ejb_sidl_javax_ejb_i.EJBHome; virtual; procedure _set_home ( const _value : ejb_sidl_javax_ejb_i.EJBHome ); virtual; function _get_homeInterfaceClass : ejb_sidl_java_lang_i._Class; virtual; procedure _set_homeInterfaceClass ( const _value : ejb_sidl_java_lang_i._Class ); virtual; function _get_primaryKeyClass : ejb_sidl_java_lang_i._Class; virtual; procedure _set_primaryKeyClass ( const _value : ejb_sidl_java_lang_i._Class ); virtual; function _get_remoteInterfaceClass : ejb_sidl_java_lang_i._Class; virtual; procedure _set_remoteInterfaceClass ( const _value : ejb_sidl_java_lang_i._Class ); virtual; function _get_session : Boolean; virtual; procedure _set_session ( const _value : Boolean ); virtual; function _get_statelessSession : Boolean; virtual; procedure _set_statelessSession ( const _value : Boolean ); virtual; constructor Create (const home : ejb_sidl_javax_ejb_i.EJBHome; const homeInterfaceClass : ejb_sidl_java_lang_i._Class; const primaryKeyClass : ejb_sidl_java_lang_i._Class; const remoteInterfaceClass : ejb_sidl_java_lang_i._Class; const session : Boolean; const statelessSession : Boolean ); overload; end; TEJBHomeHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBHome); class function Extract(var _A: CORBA.Any) : ejb_sidl_javax_ejb_i.EJBHome; class function TypeCode : CORBA.TypeCode; class function RepositoryId : string; class function Read (const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBHome; class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBHome); class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : ejb_sidl_javax_ejb_i.EJBHome; class function Bind(const _InstanceName : string = ''; _HostName : string = '') : ejb_sidl_javax_ejb_i.EJBHome; overload; class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : ejb_sidl_javax_ejb_i.EJBHome; overload; end; TEJBHomeStub = class(CORBA.TCORBAObject, ejb_sidl_javax_ejb_i.EJBHome) public function getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData; virtual; procedure remove ( const primaryKey : ANY); virtual; function getSimplifiedIDL : AnsiString; virtual; end; TEJBObjectHelper = class class procedure Insert (var _A: CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBObject); class function Extract(var _A: CORBA.Any) : ejb_sidl_javax_ejb_i.EJBObject; class function TypeCode : CORBA.TypeCode; class function RepositoryId : string; class function Read (const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBObject; class procedure Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBObject); class function Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean = False) : ejb_sidl_javax_ejb_i.EJBObject; class function Bind(const _InstanceName : string = ''; _HostName : string = '') : ejb_sidl_javax_ejb_i.EJBObject; overload; class function Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName: string = '') : ejb_sidl_javax_ejb_i.EJBObject; overload; end; TEJBObjectStub = class(CORBA.TCORBAObject, ejb_sidl_javax_ejb_i.EJBObject) public function getEJBHome : ejb_sidl_javax_ejb_i.EJBHome; virtual; function getPrimaryKey : ANY; virtual; procedure remove ; virtual; end; ECreateException = class(UserException) private Fmessage : AnsiString; protected function _get_message : AnsiString; virtual; public property message : AnsiString read _get_message; constructor Create; overload; constructor Create(const message : AnsiString); overload; procedure Copy(const _Input : InputStream); override; procedure WriteExceptionInfo(var _Output : OutputStream); override; end; EFinderException = class(UserException) private Fmessage : AnsiString; protected function _get_message : AnsiString; virtual; public property message : AnsiString read _get_message; constructor Create; overload; constructor Create(const message : AnsiString); overload; procedure Copy(const _Input : InputStream); override; procedure WriteExceptionInfo(var _Output : OutputStream); override; end; implementation uses ejb_sidl_java_lang_c; var RemoveExceptionDesc : PExceptionDescription; CreateExceptionDesc : PExceptionDescription; FinderExceptionDesc : PExceptionDescription; function ERemoveException._get_message : AnsiString; begin Result := Fmessage; end; constructor ERemoveException.Create; begin inherited Create; end; constructor ERemoveException.Create(const message : AnsiString); begin inherited Create; Fmessage := message; end; procedure ERemoveException.Copy(const _Input: InputStream); begin _Input.ReadString(Fmessage); end; procedure ERemoveException.WriteExceptionInfo(var _Output : OutputStream); begin _Output.WriteString('IDL:borland.com/sidl/javax/ejb/RemoveException:1.0'); _Output.WriteString(Fmessage); end; function RemoveException_Factory: PExceptionProxy; cdecl; begin with ejb_sidl_javax_ejb_c.ERemoveException.Create() do Result := Proxy; end; class procedure TEJBMetaDataHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBMetaData); var _Output : CORBA.OutputStream; begin _Output := ORB.CreateOutputStream; TEJBMetaDataHelper.Write(_Output, _Value); ORB.PutAny(_A, TEJBMetaDataHelper.TypeCode, _Output); end; class function TEJBMetaDataHelper.Extract(const _A : CORBA.Any) : ejb_sidl_javax_ejb_i.EJBMetaData; var _Input : CORBA.InputStream; begin Orb.GetAny(_A, _Input); Result := TEJBMetaDataHelper.Read(_Input); end; class function TEJBMetaDataHelper.TypeCode : CORBA.TypeCode; var _Seq: StructMemberSeq; begin SetLength(_Seq, 6); _Seq[0].Name := 'home'; _Seq[0].TC := ejb_sidl_javax_ejb_c.TEJBHomeHelper.TypeCode; _Seq[1].Name := 'homeInterfaceClass'; _Seq[1].TC := ejb_sidl_java_lang_c.TClassHelper.TypeCode; _Seq[2].Name := 'primaryKeyClass'; _Seq[2].TC := ejb_sidl_java_lang_c.TClassHelper.TypeCode; _Seq[3].Name := 'remoteInterfaceClass'; _Seq[3].TC := ejb_sidl_java_lang_c.TClassHelper.TypeCode; _Seq[4].Name := 'session'; _Seq[4].TC := ORB.CreateTC(Integer(tk_boolean)); _Seq[5].Name := 'statelessSession'; _Seq[5].TC := ORB.CreateTC(Integer(tk_boolean)); Result := ORB.MakeStructureTypecode(RepositoryID, 'EJBMetaData', _Seq); end; class function TEJBMetaDataHelper.RepositoryId : string; begin Result := 'IDL:borland.com/sidl/javax/ejb/EJBMetaData:1.0'; end; class function TEJBMetaDataHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBMetaData; var _Value : ejb_sidl_javax_ejb_c.TEJBMetaData; begin _Value := ejb_sidl_javax_ejb_c.TEJBMetaData.Create; _Value.home := ejb_sidl_javax_ejb_c.TEJBHomeHelper.Read(_Input); _Value.homeInterfaceClass := ejb_sidl_java_lang_c.TClassHelper.Read(_Input); _Value.primaryKeyClass := ejb_sidl_java_lang_c.TClassHelper.Read(_Input); _Value.remoteInterfaceClass := ejb_sidl_java_lang_c.TClassHelper.Read(_Input); _Input.ReadBoolean(_Value.session); _Input.ReadBoolean(_Value.statelessSession); Result := _Value; end; class procedure TEJBMetaDataHelper.Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBMetaData); begin ejb_sidl_javax_ejb_c.TEJBHomeHelper.Write(_Output, _Value.home); ejb_sidl_java_lang_c.TClassHelper.Write(_Output, _Value.homeInterfaceClass); ejb_sidl_java_lang_c.TClassHelper.Write(_Output, _Value.primaryKeyClass); ejb_sidl_java_lang_c.TClassHelper.Write(_Output, _Value.remoteInterfaceClass); _Output.WriteBoolean(_Value.session); _Output.WriteBoolean(_Value.statelessSession); end; constructor TEJBMetaData.Create; begin inherited Create; end; constructor TEJBMetaData.Create(const home: ejb_sidl_javax_ejb_i.EJBHome; const homeInterfaceClass: ejb_sidl_java_lang_i._Class; const primaryKeyClass: ejb_sidl_java_lang_i._Class; const remoteInterfaceClass: ejb_sidl_java_lang_i._Class; const session: Boolean; const statelessSession: Boolean); begin Self.home := home; Self.homeInterfaceClass := homeInterfaceClass; Self.primaryKeyClass := primaryKeyClass; Self.remoteInterfaceClass := remoteInterfaceClass; Self.session := session; Self.statelessSession := statelessSession; end; function TEJBMetaData._get_home: ejb_sidl_javax_ejb_i.EJBHome; begin Result := home; end; procedure TEJBMetaData._set_home(const _Value : ejb_sidl_javax_ejb_i.EJBHome); begin home := _Value; end; function TEJBMetaData._get_homeInterfaceClass: ejb_sidl_java_lang_i._Class; begin Result := homeInterfaceClass; end; procedure TEJBMetaData._set_homeInterfaceClass(const _Value : ejb_sidl_java_lang_i._Class); begin homeInterfaceClass := _Value; end; function TEJBMetaData._get_primaryKeyClass: ejb_sidl_java_lang_i._Class; begin Result := primaryKeyClass; end; procedure TEJBMetaData._set_primaryKeyClass(const _Value : ejb_sidl_java_lang_i._Class); begin primaryKeyClass := _Value; end; function TEJBMetaData._get_remoteInterfaceClass: ejb_sidl_java_lang_i._Class; begin Result := remoteInterfaceClass; end; procedure TEJBMetaData._set_remoteInterfaceClass(const _Value : ejb_sidl_java_lang_i._Class); begin remoteInterfaceClass := _Value; end; function TEJBMetaData._get_session: Boolean; begin Result := session; end; procedure TEJBMetaData._set_session(const _Value : Boolean); begin session := _Value; end; function TEJBMetaData._get_statelessSession: Boolean; begin Result := statelessSession; end; procedure TEJBMetaData._set_statelessSession(const _Value : Boolean); begin statelessSession := _Value; end; class procedure TEJBHomeHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBHome); begin _A := Orb.MakeObjectRef( TEJBHomeHelper.TypeCode, _Value as CORBA.CORBAObject); end; class function TEJBHomeHelper.Extract(var _A : CORBA.Any): ejb_sidl_javax_ejb_i.EJBHome; var _obj : Corba.CorbaObject; begin _obj := Orb.GetObjectRef(_A); Result := TEJBHomeHelper.Narrow(_obj, True); end; class function TEJBHomeHelper.TypeCode : CORBA.TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'EJBHome'); end; class function TEJBHomeHelper.RepositoryId : string; begin Result := 'IDL:borland.com/sidl/javax/ejb/EJBHome:1.0'; end; class function TEJBHomeHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBHome; var _Obj : CORBA.CORBAObject; begin _Input.ReadObject(_Obj); Result := Narrow(_Obj, True) end; class procedure TEJBHomeHelper.Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBHome); begin _Output.WriteObject(_Value as CORBA.CORBAObject); end; class function TEJBHomeHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : ejb_sidl_javax_ejb_i.EJBHome; begin Result := nil; if (_Obj = nil) or (_Obj.QueryInterface(ejb_sidl_javax_ejb_i.EJBHome, Result) = 0) then exit; if _IsA and _Obj._IsA(RepositoryId) then Result := TEJBHomeStub.Create(_Obj); end; class function TEJBHomeHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : ejb_sidl_javax_ejb_i.EJBHome; begin Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True); end; class function TEJBHomeHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : ejb_sidl_javax_ejb_i.EJBHome; begin Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True); end; function TEJBHomeStub.getEJBMetaData : ejb_sidl_javax_ejb_i.EJBMetaData; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('getEJBMetaData',True, _Output); inherited _Invoke(_Output, _Input); Result := ejb_sidl_javax_ejb_c.TEJBMetaDataHelper.Read(_Input); end; procedure TEJBHomeStub.remove ( const primaryKey : ANY); var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('remove',True, _Output); _Output.WriteAny(primaryKey); inherited _Invoke(_Output, _Input); end; function TEJBHomeStub.getSimplifiedIDL : AnsiString; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('getSimplifiedIDL',True, _Output); inherited _Invoke(_Output, _Input); _Input.ReadString(Result); end; class procedure TEJBObjectHelper.Insert(var _A : CORBA.Any; const _Value : ejb_sidl_javax_ejb_i.EJBObject); begin _A := Orb.MakeObjectRef( TEJBObjectHelper.TypeCode, _Value as CORBA.CORBAObject); end; class function TEJBObjectHelper.Extract(var _A : CORBA.Any): ejb_sidl_javax_ejb_i.EJBObject; var _obj : Corba.CorbaObject; begin _obj := Orb.GetObjectRef(_A); Result := TEJBObjectHelper.Narrow(_obj, True); end; class function TEJBObjectHelper.TypeCode : CORBA.TypeCode; begin Result := ORB.CreateInterfaceTC(RepositoryId, 'EJBObject'); end; class function TEJBObjectHelper.RepositoryId : string; begin Result := 'IDL:borland.com/sidl/javax/ejb/EJBObject:1.0'; end; class function TEJBObjectHelper.Read(const _Input : CORBA.InputStream) : ejb_sidl_javax_ejb_i.EJBObject; var _Obj : CORBA.CORBAObject; begin _Input.ReadObject(_Obj); Result := Narrow(_Obj, True) end; class procedure TEJBObjectHelper.Write(const _Output : CORBA.OutputStream; const _Value : ejb_sidl_javax_ejb_i.EJBObject); begin _Output.WriteObject(_Value as CORBA.CORBAObject); end; class function TEJBObjectHelper.Narrow(const _Obj : CORBA.CORBAObject; _IsA : Boolean) : ejb_sidl_javax_ejb_i.EJBObject; begin Result := nil; if (_Obj = nil) or (_Obj.QueryInterface(ejb_sidl_javax_ejb_i.EJBObject, Result) = 0) then exit; if _IsA and _Obj._IsA(RepositoryId) then Result := TEJBObjectStub.Create(_Obj); end; class function TEJBObjectHelper.Bind(const _InstanceName : string = ''; _HostName: string = '') : ejb_sidl_javax_ejb_i.EJBObject; begin Result := Narrow(ORB.bind(RepositoryId, _InstanceName, _HostName), True); end; class function TEJBObjectHelper.Bind(_Options : BindOptions; const _InstanceName : string = ''; _HostName : string = '') : ejb_sidl_javax_ejb_i.EJBObject; begin Result := Narrow(ORB.bind(RepositoryId, _Options, _InstanceName, _HostName), True); end; function TEJBObjectStub.getEJBHome : ejb_sidl_javax_ejb_i.EJBHome; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('getEJBHome',True, _Output); inherited _Invoke(_Output, _Input); Result := ejb_sidl_javax_ejb_c.TEJBHomeHelper.Read(_Input); end; function TEJBObjectStub.getPrimaryKey : ANY; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('getPrimaryKey',True, _Output); inherited _Invoke(_Output, _Input); _Input.ReadAny(Result); end; procedure TEJBObjectStub.remove ; var _Output: CORBA.OutputStream; _Input : CORBA.InputStream; begin inherited _CreateRequest('remove',True, _Output); inherited _Invoke(_Output, _Input); end; function ECreateException._get_message : AnsiString; begin Result := Fmessage; end; constructor ECreateException.Create; begin inherited Create; end; constructor ECreateException.Create(const message : AnsiString); begin inherited Create; Fmessage := message; end; procedure ECreateException.Copy(const _Input: InputStream); begin _Input.ReadString(Fmessage); end; procedure ECreateException.WriteExceptionInfo(var _Output : OutputStream); begin _Output.WriteString('IDL:borland.com/sidl/javax/ejb/CreateException:1.0'); _Output.WriteString(Fmessage); end; function CreateException_Factory: PExceptionProxy; cdecl; begin with ejb_sidl_javax_ejb_c.ECreateException.Create() do Result := Proxy; end; function EFinderException._get_message : AnsiString; begin Result := Fmessage; end; constructor EFinderException.Create; begin inherited Create; end; constructor EFinderException.Create(const message : AnsiString); begin inherited Create; Fmessage := message; end; procedure EFinderException.Copy(const _Input: InputStream); begin _Input.ReadString(Fmessage); end; procedure EFinderException.WriteExceptionInfo(var _Output : OutputStream); begin _Output.WriteString('IDL:borland.com/sidl/javax/ejb/FinderException:1.0'); _Output.WriteString(Fmessage); end; function FinderException_Factory: PExceptionProxy; cdecl; begin with ejb_sidl_javax_ejb_c.EFinderException.Create() do Result := Proxy; end; initialization ejb_sidl_javax_ejb_c.RemoveExceptionDesc := RegisterUserException('RemoveException', 'IDL:borland.com/sidl/javax/ejb/RemoveException:1.0', @ejb_sidl_javax_ejb_c.RemoveException_Factory); ejb_sidl_javax_ejb_c.CreateExceptionDesc := RegisterUserException('CreateException', 'IDL:borland.com/sidl/javax/ejb/CreateException:1.0', @ejb_sidl_javax_ejb_c.CreateException_Factory); ejb_sidl_javax_ejb_c.FinderExceptionDesc := RegisterUserException('FinderException', 'IDL:borland.com/sidl/javax/ejb/FinderException:1.0', @ejb_sidl_javax_ejb_c.FinderException_Factory); finalization UnRegisterUserException(ejb_sidl_javax_ejb_c.RemoveExceptionDesc); UnRegisterUserException(ejb_sidl_javax_ejb_c.CreateExceptionDesc); UnRegisterUserException(ejb_sidl_javax_ejb_c.FinderExceptionDesc); end.
unit untEasyWorkFlowAlign; interface uses Windows, SysUtils, Classes, ActnList, atDiagram, Graphics; Type TEasyWorkFlowBlocksAlignment = (baLeft, baRight, baTop,baBottom, baHorzCenter, baVertCenter, baSameWidth, baSameHeight, baSameSize, baSameSpaceHorz, baSameSpaceVert, baIncHorzSpace, baIncrVertSpace, baDecHorzSpace, baDecVertSpace); TEasyWorkFlowDiagramAction = class(TAction) private FDiagram: TatDiagram; procedure SetDiagram(Value: TatDiagram); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property Diagram: TatDiagram read FDiagram write SetDiagram; end; TBlockList = class(TList) private function GetBlock(index: integer): TCustomDiagramBlock; function GetFirst: TCustomDiagramBlock; public property Blocks[index : integer] : TCustomDiagramBlock read GetBlock; default; property Champion : TCustomDiagramBlock read GetFirst; end; TBlockSort = (bsNone, bsByX, bsByY); {TEasyWorkFlowDiagramAlign class was first a contribution from David Nardella} TEasyWorkFlowDiagramAlign = class(TEasyWorkFlowDiagramAction) private FBlockAlignment: TEasyWorkFlowBlocksAlignment; FDefaultAlignment: TEasyWorkFlowDiagramAlign; FList : TBlockList; procedure GetSelection; procedure SortByX; procedure SortByY; procedure AlignLeft; procedure AlignRight; procedure AlignTop; procedure AlignBottom; procedure AlignHorzCenter; procedure AlignVertCenter; procedure SameWidth; procedure SameHeight; procedure SameSize; procedure SameSpaceHorz; procedure SameSpaceVert; procedure IncHorzSpace; procedure IncVertSpace; procedure DecHorzSpace; procedure DecVertSpace; procedure SetBlockAlignment(const Value: TEasyWorkFlowBlocksAlignment); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: boolean; override; function Update: boolean; override; published property DefaultAlignment : TEasyWorkFlowDiagramAlign read FDefaultAlignment write FDefaultAlignment; property BlockAlignment : TEasyWorkFlowBlocksAlignment read FBlockAlignment write SetBlockAlignment; end; procedure Register; implementation procedure Register; begin RegisterActions('EasyWorkFlowAlign', [TEasyWorkFlowDiagramAlign], TEasyWorkFlowDiagramAlign); end; resourcestring sAlignleftedges = '左对齐'; sAlignrightedges = '右对齐'; sAligntopedges = '上对齐'; sAlignbottomedges = '下对齐'; sAlignhorizontalcenters = '水平中心对齐'; sAlignverticalcenters = '垂直中心对齐'; sMakesamewidth = '等宽'; sMakesameheight = '等高'; sMakesamesize = '等尺寸'; sSpaceequallyhorizontally = '水平等分'; sSpaceequallyvertically = '垂直等分'; sIncrementhorizontalspace = '增加水平间距'; sIncrementverticalspace = '增加垂直间距'; sDecrementhorizontalspace = '减小水平间距'; sDecrementverticalspace = '减小垂直间距'; const AlignCaptions : Array[TEasyWorkFlowBlocksAlignment] of String = ( sAlignleftedges, sAlignrightedges, sAligntopedges, sAlignbottomedges, sAlignhorizontalcenters, sAlignverticalcenters, sMakesamewidth, sMakesameheight, sMakesamesize, sSpaceequallyhorizontally, sSpaceequallyvertically, sIncrementhorizontalspace, sIncrementverticalspace, sDecrementhorizontalspace, sDecrementverticalspace); AlignHints : Array[TEasyWorkFlowBlocksAlignment] of String = ( '左对齐', '右对齐', '上对齐', '下对齐', '水平中心对齐', '垂直中心对齐', '等宽', '等高', '等尺寸', '水平等分', '垂直等分', '增加水平间距', '增加垂直间距', '减小水平间距', '减小垂直间距'); { TEasyWorkFlowDiagramAction } procedure TEasyWorkFlowDiagramAction.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = Diagram) then Diagram := nil; end; procedure TEasyWorkFlowDiagramAction.SetDiagram(Value: TatDiagram); begin if Value <> FDiagram then begin FDiagram := Value; if Value <> nil then Value.FreeNotification(Self); end; end; { TBlockList } function TBlockList.GetBlock(index: integer): TCustomDiagramBlock; begin {$WARNINGS OFF} Result := TCustomDiagramBlock(Items[index]); {$WARNINGS ON} end; function TBlockList.GetFirst: TCustomDiagramBlock; begin Result:=Blocks[0]; end; { TEasyWorkFlowDiagramAlign } procedure TEasyWorkFlowDiagramAlign.AlignBottom; Var c,b : integer; begin b:=FList.Champion.Bottom; with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Top:=b-FList[c].Height; end; procedure TEasyWorkFlowDiagramAlign.AlignHorzCenter; Var c,hc : integer; begin with FList.Champion do hc:=Left+Width div 2; with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Left:=hc-(FList[c].Width div 2); end; procedure TEasyWorkFlowDiagramAlign.AlignVertCenter; Var c,vc : integer; begin with FList.Champion do vc:=Top+Height div 2; with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Top:=vc-(FList[c].Height div 2); end; procedure TEasyWorkFlowDiagramAlign.AlignLeft; Var c : integer; begin with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Left:=FList.Champion.Left; end; procedure TEasyWorkFlowDiagramAlign.AlignRight; Var c,r : integer; begin r:=FList.Champion.Right; with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Left:=r-FList[c].Width; end; procedure TEasyWorkFlowDiagramAlign.AlignTop; Var c : integer; begin with Diagram do for c := 0 to FList.Count - 1 do if not (crNoMove in FList[c].Restrictions) then FList[c].Top:=FList.Champion.Top; end; procedure TEasyWorkFlowDiagramAlign.SameWidth; Var c : integer; begin with Diagram do for c := 0 to FList.Count - 1 do if not (crNoResize in FList[c].Restrictions) and not (crKeepRatio in FList[c].Restrictions) then FList[c].Width:=FList.Champion.Width; end; procedure TEasyWorkFlowDiagramAlign.SameHeight; Var c : integer; begin with Diagram do for c := 0 to FList.Count - 1 do if not (crNoResize in FList[c].Restrictions) and not (crKeepRatio in FList[c].Restrictions) then FList[c].Height:=FList.Champion.Height; end; procedure TEasyWorkFlowDiagramAlign.SameSize; Var c : integer; begin with Diagram do for c := 0 to FList.Count - 1 do if not (crNoResize in FList[c].Restrictions) and not (crKeepRatio in FList[c].Restrictions) then begin FList[c].Width:=FList.Champion.Width; FList[c].Height:=FList.Champion.Height; end; end; procedure TEasyWorkFlowDiagramAlign.SameSpaceHorz; Var c, Gap : integer; TotW : integer; begin // User can select blocks randomly so we need to sort them SortByX; TotW:=0; for c := 0 to FList.Count - 1 do inc(TotW,FList[c].Width); with FList do Gap:= Round((Blocks[Count-1].Right - Blocks[0].Left - TotW) / (Count-1)); for c := 1 to FList.Count - 2 do FList[c].Left:=FList[c-1].Right+Gap; end; procedure TEasyWorkFlowDiagramAlign.SameSpaceVert; Var c, Gap : integer; TotH : integer; begin // User can select blocks randomly so we need to sort them SortByY; TotH:=0; for c := 0 to FList.Count - 1 do inc(TotH,FList[c].Height); with FList do Gap:= Round((Blocks[Count-1].Bottom - Blocks[0].Top - TotH) / (Count-1)); for c := 1 to FList.Count - 2 do FList[c].Top:=FList[c-1].Bottom+Gap; end; procedure TEasyWorkFlowDiagramAlign.IncHorzSpace; Var Step : integer; begin SortByX; Step:=Round(Diagram.SnapGrid.SizeX*Diagram.Zoom/100.0); with FList[FList.Count-1] do Left:=Left+Step; SameSpaceHorz; end; procedure TEasyWorkFlowDiagramAlign.IncVertSpace; Var Step : integer; begin SortByY; Step:=Round(Diagram.SnapGrid.SizeY*Diagram.Zoom/100.0); with FList[FList.Count-1] do Top:=Top+Step; SameSpaceVert; end; procedure TEasyWorkFlowDiagramAlign.DecHorzSpace; Var Step : integer; begin SortByX; Step:=Round(Diagram.SnapGrid.SizeX*Diagram.Zoom/100.0); with FList[FList.Count-1] do begin Left:=Left-Step; if Left<=FList.Champion.Left then AlignLeft else SameSpaceHorz; end; end; procedure TEasyWorkFlowDiagramAlign.DecVertSpace; Var Step : integer; begin SortByY; Step:=Round(Diagram.SnapGrid.SizeY*Diagram.Zoom/100.0); with FList[FList.Count-1] do begin Top:=Top-Step; if Top<=FList.Champion.Top then AlignTop else SameSpaceVert; end; end; function TEasyWorkFlowDiagramAlign.Execute: boolean; begin GetSelection; if FList.Count > 1 then begin Case FBlockAlignment of baLeft : AlignLeft; baRight : AlignRight; baTop : AlignTop; baBottom : AlignBottom; baHorzCenter : AlignHorzCenter; baVertCenter : AlignVertCenter; baSameWidth : SameWidth; baSameHeight : SameHeight; baSameSize : SameSize; baSameSpaceHorz : SameSpaceHorz; baSameSpaceVert : SameSpaceVert; baIncHorzSpace : IncHorzSpace; baIncrVertSpace : IncVertSpace; baDecHorzSpace : DecHorzSpace; baDecVertSpace : DecVertSpace; end; Diagram.PushUndoStack('Align'); if Assigned(FDefaultAlignment) and (FDefaultAlignment <> self) then begin // Properties reflection FDefaultAlignment.BlockAlignment:=FBlockAlignment; FDefaultAlignment.ImageIndex:=ImageIndex; FDefaultAlignment.Caption:=Caption; FDefaultAlignment.Hint:=Hint; end; end; result := True; end; function TEasyWorkFlowDiagramAlign.Update: boolean; begin if FBlockAlignment in [baSameSpaceHorz..baDecVertSpace] then Enabled := (Diagram <> nil) and (Diagram.SelectedBlockCount(cfIgnoreMembers) > 2) // we need at least 3 blocks else Enabled := (Diagram <> nil) and (Diagram.SelectedBlockCount(cfIgnoreMembers) > 1); result := true; end; procedure TEasyWorkFlowDiagramAlign.SetBlockAlignment(const Value: TEasyWorkFlowBlocksAlignment); begin if FBlockAlignment <> Value then begin FBlockAlignment := Value; Caption:=AlignCaptions[FBlockAlignment]; Hint:=AlignHints[FBlockAlignment]; end; end; procedure TEasyWorkFlowDiagramAlign.SortByX; function XSort : boolean; Var c : integer; begin Result:=true; for c := 0 to FList.Count - 2 do if Flist[c].Left>Flist[c+1].Left then begin Result:=false; FList.Exchange(C,C+1); end; end; begin Repeat Until XSort; end; procedure TEasyWorkFlowDiagramAlign.SortByY; function YSort : boolean; Var c : integer; begin Result:=true; for c := 0 to FList.Count - 2 do if Flist[c].Top>Flist[c+1].Top then begin Result:=false; FList.Exchange(C,C+1); end; end; begin Repeat Until YSort; end; constructor TEasyWorkFlowDiagramAlign.Create(AOwner: TComponent); begin inherited; FList:=TBlockList.Create; BlockAlignment:=baHorzCenter; end; destructor TEasyWorkFlowDiagramAlign.Destroy; begin FList.Free; inherited; end; procedure TEasyWorkFlowDiagramAlign.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FDefaultAlignment) then DefaultAlignment := nil; end; procedure TEasyWorkFlowDiagramAlign.GetSelection; Var c : integer; begin FList.Clear; for c := 0 to Diagram.SelectedCount - 1 do if not Diagram.Selecteds[c].IsMember then begin if Diagram.Selecteds[c].InheritsFrom(TCustomDiagramBlock) then FList.Add(Diagram.Selecteds[c]); end; end; end.
unit rtti_ordinal_1; interface implementation uses System, sys.rtti; var ti: TRTTIOrdinal; procedure Test_int8; begin ti := TypeInfo(Int8) as TRTTIOrdinal; Assert(ti.Name = 'Int8'); Assert(ti.TypeSize = 1); Assert(ti.Signed = True); Assert(ti.LoBound = MinInt8); Assert(ti.HiBound = MaxInt8); end; procedure Test_uint8; begin ti := TypeInfo(UInt8) as TRTTIOrdinal; Assert(ti.Name = 'UInt8'); Assert(ti.TypeSize = 1); Assert(ti.Signed = False); Assert(ti.LoBound = MinUInt8); Assert(ti.HiBound = MaxUInt8); end; procedure Test_int16; begin ti := TypeInfo(Int16) as TRTTIOrdinal; Assert(ti.Name = 'Int16'); Assert(ti.TypeSize = 2); Assert(ti.Signed = True); Assert(ti.LoBound = MinInt16); Assert(ti.HiBound = MaxInt16); end; procedure Test_uint16; begin ti := TypeInfo(UInt16) as TRTTIOrdinal; Assert(ti.Name = 'UInt16'); Assert(ti.TypeSize = 2); Assert(ti.Signed = False); Assert(ti.LoBound = MinUInt16); Assert(ti.HiBound = MaxUInt16); end; procedure Test_int32; begin ti := TypeInfo(Int32) as TRTTIOrdinal; Assert(ti.Name = 'Int32'); Assert(ti.TypeSize = 4); Assert(ti.Signed = True); Assert(ti.LoBound = MinInt32); Assert(ti.HiBound = MaxInt32); end; procedure Test_uint32; begin ti := TypeInfo(UInt32) as TRTTIOrdinal; Assert(ti.Name = 'UInt32'); Assert(ti.TypeSize = 4); Assert(ti.Signed = False); Assert(ti.LoBound = MinUInt32); Assert(ti.HiBound = MaxUInt32); end; initialization Test_int8(); Test_uint8(); Test_int16(); Test_uint16(); Test_int32(); Test_uint32(); finalization end.
unit NtUtils.Ldr; interface uses Winapi.WinNt, Ntapi.ntldr, NtUtils.Exceptions; const // Artificial limitation to prevent infinite loops MAX_MODULES = $800; type TModuleEntry = record DllBase: Pointer; EntryPoint: TLdrInitRoutine; SizeOfImage: Cardinal; FullDllName: String; BaseDllName: String; Flags: Cardinal; TimeDateStamp: Cardinal; ParentDllBase: Pointer; OriginalBase: NativeUInt; LoadTime: TLargeInteger; LoadReason: TLdrDllLoadReason; // Win 8+ // TODO: more fields end; { Delayed import } // Check if a function presents in ntdll function LdrxCheckNtDelayedImport(Name: AnsiString): TNtxStatus; // Check if a function presents in a dll. Loads the dll if necessary function LdrxCheckModuleDelayedImport(ModuleName: String; ProcedureName: AnsiString): TNtxStatus; { Other } // Get base address of a loaded dll function LdrxGetDllHandle(DllName: String; out DllHandle: HMODULE): TNtxStatus; // Get a function address function LdrxGetProcedureAddress(DllHandle: HMODULE; ProcedureName: AnsiString; out Status: TNtxStatus): Pointer; // Enumerate loaded modules function LdrxEnumerateModules: TArray<TModuleEntry>; implementation uses System.SysUtils, System.Generics.Collections, Ntapi.ntdef, Ntapi.ntpebteb, NtUtils.Version; var ImportCache: TDictionary<AnsiString, NTSTATUS>; OldFailureHook: TDelayedLoadHook; function LdrxCheckNtDelayedImport(Name: AnsiString): TNtxStatus; var ProcName: ANSI_STRING; ProcAddr: Pointer; begin if not Assigned(ImportCache) then ImportCache := TDictionary<AnsiString,NTSTATUS>.Create; Result.Location := 'LdrGetProcedureAddress("' + String(Name) + '")'; if ImportCache.TryGetValue(Name, Result.Status) then Exit; ProcName.FromString(Name); Result.Status := LdrGetProcedureAddress(hNtdll, ProcName, 0, ProcAddr); ImportCache.Add(Name, Result.Status); end; function LdrxCheckModuleDelayedImport(ModuleName: String; ProcedureName: AnsiString): TNtxStatus; var DllName: UNICODE_STRING; ProcName: ANSI_STRING; hDll: NativeUInt; ProcAddr: Pointer; begin DllName.FromString(ModuleName); Result.Location := 'LdrGetDllHandle'; Result.Status := LdrGetDllHandle(nil, nil, DllName, hDll); if not NT_SUCCESS(Result.Status) then begin // Try to load it Result.Location := 'LdrLoadDll'; Result.Status := LdrLoadDll(nil, nil, DllName, hDll); if not NT_SUCCESS(Result.Status) then Exit; end; ProcName.FromString(ProcedureName); Result.Location := 'LdrGetProcedureAddress'; Result.Status := LdrGetProcedureAddress(hDll, ProcName, 0, ProcAddr); end; function NtxpDelayedLoadHook(dliNotify: dliNotification; pdli: PDelayLoadInfo): Pointer; stdcall; const DELAY_MSG = 'Delayed load of '; begin // Report delayed load errors case dliNotify of dliFailLoadLibrary: ENtError.Report(NTSTATUS_FROM_WIN32(pdli.dwLastError), DELAY_MSG + pdli.szDll); dliFailGetProcAddress: ENtError.Report(NTSTATUS_FROM_WIN32(pdli.dwLastError), DELAY_MSG + pdli.dlp.szProcName); end; if Assigned(OldFailureHook) then OldFailureHook(dliNotify, pdli); Result := nil; end; function LdrxGetDllHandle(DllName: String; out DllHandle: HMODULE): TNtxStatus; var DllNameStr: UNICODE_STRING; begin DllNameStr.FromString(DllName); Result.Location := 'LdrGetDllHandle("' + DllName + '")'; Result.Status := LdrGetDllHandle(nil, nil, DllNameStr, DllHandle); end; function LdrxGetProcedureAddress(DllHandle: HMODULE; ProcedureName: AnsiString; out Status: TNtxStatus): Pointer; var ProcNameStr: ANSI_STRING; begin ProcNameStr.FromString(ProcedureName); Status.Location := 'LdrGetProcedureAddress("' + String(ProcedureName) + '")'; Status.Status := LdrGetProcedureAddress(DllHandle, ProcNameStr, 0, Result); end; function LdrxEnumerateModules: TArray<TModuleEntry>; var i: Integer; Start, Current: PLdrDataTableEntry; OsVersion: TKnownOsVersion; begin // Traverse the list i := 0; Start := PLdrDataTableEntry(@RtlGetCurrentPeb.Ldr.InLoadOrderModuleList); Current := PLdrDataTableEntry(RtlGetCurrentPeb.Ldr.InLoadOrderModuleList.Flink); OsVersion := RtlOsVersion; SetLength(Result, 0); while (Start <> Current) and (i <= MAX_MODULES) do begin // Save it SetLength(Result, Length(Result) + 1); with Result[High(Result)] do begin DllBase := Current.DllBase; EntryPoint := Current.EntryPoint; SizeOfImage := Current.SizeOfImage; FullDllName := Current.FullDllName.ToString; BaseDllName := Current.BaseDllName.ToString; Flags := Current.Flags; TimeDateStamp := Current.TimeDateStamp; LoadTime := Current.LoadTime; ParentDllBase := Current.ParentDllBase; OriginalBase := Current.OriginalBase; if OsVersion >= OsWin8 then LoadReason := Current.LoadReason; end; // Go to the next one Current := PLdrDataTableEntry(Current.InLoadOrderLinks.Flink); Inc(i); end; end; initialization OldFailureHook := SetDliFailureHook2(NtxpDelayedLoadHook); finalization ImportCache.Free; end.
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Ini management : Chargement des options de fichiers .INI // Permet d'exploiter les paramétres en fichier de configuration // et (a faire...) en overide ligne de commande // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= unit IniMangt; interface uses Classes, InternalTypes, Unities, ExtensionTypeManager, PathsAndGroupsManager, SpecificPaths, Specificpath, FileInfoSet, SysUtils, IniFiles; type TAppParams = class private IniF : TIniFile; fUnity : TUnityList; fSettingsSrc : WideString; fSettingsDepth :Integer; fSettingsKeepUDetails : Boolean; fSettingsDrillDown : Boolean; fSettingsListFile : string; fLimitDate : TDateTime; fSettingsCopyTreeDir : string; fSettingsCopyTarget : string; fLimitCopy : TdateTime; fSettingsExclFullDir : Boolean; // Sur les règles d'exclusion, continue-t-on de traverser le contenu du répertoire ? //fSpecificPaths : TStringList; fExtensionTypeManager : TExtensionTypeManager; fPathAndGroupManager : TPathsAndGroupsManager; fReportExtType : TStringList; fSourceSet : tFileInfoSet; fGroupSet : tFileInfoSet; fSpecificSet : tFileInfoSet; procedure InitializeIniFile(); procedure LoadExtensions(); procedure LoadUnities(); procedure LoadSettings(); procedure LoadSpecificPath(); procedure LoadSpecificGroup(); procedure LoadGroupOptions(GroupName : String); function GetSpecificPaths : TSpecificPaths; property ExtensionTypeManager: TExtensionTypeManager read FExtensionTypeManager write FExtensionTypeManager; property PathAndGroupManager: TPathsAndGroupsManager read FPathAndGroupManager write FPathAndGroupManager; function GetExceptIncludeRegExp(GName : string) : TExtensionTypeManager; public constructor Create(fName : String); destructor Destroy; override; procedure DumpExtensions; procedure DumpPaths; procedure DumpExtType(); function AddSizeExtension(key : string; info : TSearchRec; WithDetails: Boolean; GName : String): UInt64; function FindGroupByPath(S : String) : string; function FindSpecificByPath(S : String) : string; function GetExtensionType(fname : String; GName : string) : string; function GetLimitIndex(info : TSearchRec) : Integer; function SettingsGetJSON : AnsiString; function IsPathExcluded(Gname : string; Path : String) : boolean; function IsFileToTrace(info : TSearchRec) : boolean; function IsFileToCopy(info : TSearchRec) : boolean; property Unities: tUnityList read fUnity; property SettingsSrc: WideString read FSettingsSrc write FSettingsSrc; property SettingsDepth: Integer read FSettingsDepth write FSettingsDepth; property SettingsKeepUDetails: Boolean read FSettingsKeepUDetails write FSettingsKeepUDetails; property SettingsDrillDown: Boolean read fSettingsDrillDown write fSettingsDrillDown; property SpecificPaths: TSpecificPaths read GetSpecificPaths; property SourceSet : tFileInfoSet read fSourceSet; property GroupSet : tFileInfoSet read fGroupSet; property SpecificSet : tFileInfoSet read fSpecificSet; property SettingsListFile : String read fSettingsListFile write fSettingsListFile; property SettingsCopyTreeDir : String read fSettingsCopyTreeDir write fSettingsCopyTreeDir; property SettingsCopyTarget : String read fSettingsCopyTarget write fSettingsCopyTarget; property SettingsExclFullDir : boolean read fSettingsExclFullDir write fSettingsExclFullDir; property ExcludeIncludeRegExp [GName : String] : TExtensionTypeManager read GetExceptIncludeRegExp; end; implementation uses StrUtils, ExtensionTypes, DirectoryStat; Type tSections = (tsExtensions,tsDrives,tsSettings,tsSizes,tsSpecificPath,tsSpecificGroup,tsGroupOptions); Const cComment = ';'; Const cExclude = '-'; Const cInclude = '+'; Const cSections : array [low(tSections)..high(tSections)] of String = ( 'extensions', 'drives', 'settings', 'sizedetails', 'specificpath', 'specificgroup', 'group'); Const cDefaultExt : array [0..12] of String = ( 'Unknown/xxx', 'Video/mp4,mov', 'Image/jpg,jpeg', 'Pascal/pas', 'Executable/exe,com', 'Library/dll', 'Objet/obj,o', 'Pdf/pdf', 'Office Excel/xls,xlsx', 'Office Word/doc,docx', 'OpenOffice Calc/ods', 'OpenOffice Write/odt', 'Setup/cab,msi' ); constructor TAppParams.Create(fName : String); begin fUnity := TUnityList.Create(); IniF := TIniFile.create(fName,False); //fSpecificPaths := TStringList.create; //fSpecificPaths.OwnsObjects := True; fExtensionTypeManager := TExtensionTypeManager.Create(); fPathAndGroupManager := TPathsAndGroupsManager.create(); fReportExtType := TStringList.create(); fReportExtType.Duplicates := dupError; fReportExtType.OwnsObjects := True; fReportExtType.Sorted := True; fSourceSet := tFileInfoSet.create; fGroupSet := tFileInfoSet.create; fSpecificSet := tFileInfoSet.create; // pas nécessaire ou obligatoire (valeur par défaut) InitializeIniFile; LoadExtensions; LoadSettings; LoadUnities; LoadSpecificPath; LoadSpecificGroup; end; destructor TAppParams.Destroy; begin // writeln(funity.DelimitedText); fUnity.free; //writeln(fSpecificPaths.DelimitedText); //fSpecificPaths.free; IniF.free; fExtensionTypeManager.free; fPathAndGroupManager.free; fReportExtType.free; fGroupSet.free; fSourceSet.free; fSpecificSet.free; inherited Destroy; end; procedure TAppParams.InitializeIniFile(); var Counter : Integer; begin If not IniF.SectionExists(cSections[tsExtensions]) then begin for Counter := low(cDefaultExt) to high(cDefaultExt) do begin IniF.WriteString(cSections[tsExtensions], ExtractDelimited(1,cDefaultExt[Counter],['/']), ExtractDelimited(2,cDefaultExt[Counter],['/'])); end; end; end; procedure TAppParams.LoadExtensions(); var Sections : TStringList; Counter, SectionIndex : Integer; Values : TStringList; ExtValue : string; begin try Sections := TStringList.create(); IniF.ReadSectionValues(cSections[tsExtensions], Sections); ExtensionTypeManager.AddExtensionType('Unknown'); ExtensionTypeManager.AddExtension('.*','Unknown'); for Counter := 0 to Pred(Sections.count) do if Sections.Names[Counter][1]<>cComment then begin ExtValue := Sections.ValueFromIndex[Counter]; if RegularExpression(ExtValue) then else begin Values := TStringList.create(); Values.CommaText := Sections.ValueFromIndex[Counter]; ExtensionTypeManager.AddExtensionType(Sections.Names[Counter]); for SectionIndex := 0 to Pred(Values.count) do begin ExtensionTypeManager.AddExtension('.'+Values.ValueFromIndex[SectionIndex],Sections.Names[Counter]); end; end; end; Sections.free; except on e: EExtensionTypesNotUnique do begin writeln('ExtensionType en double ! Msg->' + e.message); raise; end; end; end; procedure TAppParams.LoadUnities(); var Sections : TStringList; Counter : Integer; begin Sections := TStringList.create(); IniF.ReadSectionValues(cSections[tsSizes], Sections); for Counter := 0 to Pred(Sections.count) do if Sections.Names[Counter][1]<>cComment then begin fUnity.AddUnity(Sections.Names[Counter],Sections.ValueFromIndex[Counter]); end; Sections.free; SizeLimit := fUnity.Count; end; procedure TAppParams.LoadSettings(); begin SettingsDepth := IniF.ReadInteger(cSections[tsSettings],'depth', 3); SettingsSrc := IniF.ReadString(cSections[tsSettings],'source', 'c'); SettingsKeepUDetails := IniF.ReadBool(cSections[tsSettings],'KeepUnknownDetails', False); SettingsExclFullDir := IniF.ReadBool(cSections[tsSettings],'ExcludeFullDir', False); SettingsDrillDown := IniF.ReadBool(cSections[tsSettings],'drilldown', False); SettingsListFile := IniF.ReadString(cSections[tsSettings],'ListFiles', ''); if SettingsListFile<>'' then if not ProcessOneFormula(SettingsListFile,fLimitDate) then SettingsListFile := ''; SettingsCopyTreeDir := IniF.ReadString(cSections[tsSettings],'CopyTreeDir', ''); if SettingsCopyTreeDir<>'' then if not ProcessOneFormula(SettingsCopyTreeDir,fLimitCopy) then SettingsCopyTreeDir := ''; SettingsCopyTarget := IniF.ReadString(cSections[tsSettings],'CopyTarget', ''); end; procedure TAppParams.LoadSpecificPath(); var Sections : TStringList; Counter,J : Integer; wPaths : TStringList; begin Sections := TStringList.create(); IniF.ReadSectionValues(cSections[tsSpecificPath], Sections); for Counter := 0 to Pred(Sections.count) do if Sections.Names[Counter][1]<>cComment then begin //fSpecificPaths.AddObject(Sections.Names[Counter],TSpecificPath.Create(Sections.Names[Counter],Sections.ValueFromIndex[Counter])); PathAndGroupManager.AddSpecificPathName(Sections.Names[Counter]); wPaths := TStringList.create(); try wPaths.Delimiter := ','; wPaths.StrictDelimiter := True; wPaths.Delimitedtext := Sections.ValueFromIndex[Counter]; // Important : Needed for Space in paths for J := 0 to Pred(wPaths.count) do PathAndGroupManager.AddPath(wPaths[J],Sections.Names[Counter]); finally wPaths.free; end; end; Sections.free; end; procedure TAppParams.LoadGroupOptions(GroupName : String); var Sections : TStringList; Counter,SectionIndex : Integer; wPaths : TStringList; ExtensionTypeMan : TExtensionTypeManager; Values : TStringList; ExtValue : String; begin Sections := TStringList.create(); ExtensionTypeMan := PathAndGroupManager.Groups.ExtensionTypeMan(GroupName); IniF.ReadSectionValues(GroupName+cSections[tsGroupOptions], Sections); for Counter := 0 to Pred(Sections.count) do if Sections.Names[Counter][1]<>cComment then begin ExtValue := Sections.ValueFromIndex[Counter]; // writeln('Group Option : ',ExtValue, ' Except, Include, ExtensionGroup Regular or not'); if Sections.Names[Counter][1] in [cInclude,cExclude] then begin // Group Options : Except, Include if RegularExpression(ExtValue) then ExtensionTypeMan.AddIncExclPathRegExp(Sections.Names[Counter],ExtValue) else writeln('GroupOption:',GroupName,'/',Sections.Names[Counter],' - Value not RegExp [',ExtValue,']'); end else if RegularExpression(ExtValue) then begin ExtensionTypeMan.AddExtensionType(Sections.Names[Counter]); ExtensionTypeMan.AddExtension(ExtValue,Sections.Names[Counter]); end else begin Values := TStringList.create(); Values.CommaText := Sections.ValueFromIndex[Counter]; ExtensionTypeMan.AddExtensionType(Sections.Names[Counter]); for SectionIndex := 0 to Pred(Values.count) do ExtensionTypeMan.AddExtension('.'+Values.ValueFromIndex[SectionIndex],Sections.Names[Counter]); end; end; Sections.free; end; procedure TAppParams.LoadSpecificGroup(); var Sections : TStringList; Counter,J : Integer; wPaths : TStringList; begin Sections := TStringList.create(); IniF.ReadSectionValues(cSections[tsSpecificGroup], Sections); for Counter := 0 to Pred(Sections.count) do if Sections.Names[Counter][1]<>cComment then begin PathAndGroupManager.AddSpecificGroup(Sections.Names[Counter]); wPaths := TStringList.create(); try wPaths.Delimiter := ','; wPaths.StrictDelimiter := True; wPaths.Delimitedtext := Sections.ValueFromIndex[Counter]; // Important : Needed for Space in paths for J := 0 to Pred(wPaths.count) do PathAndGroupManager.AddPathName(wPaths[J],Sections.Names[Counter]); LoadGroupOptions(Sections.Names[Counter]); finally wPaths.free; end; end; Sections.free; end; function TAppParams.AddSizeExtension(key : string; info : TSearchRec; WithDetails: Boolean; GName : String): UInt64; var ExtType : String; var Obj : TDirectoryStat; var i : integer; begin Result := 0; // Extensions.AddSizeExtension(key,size,WithDetails); // ExtType := PathAndGroupManager.GetExtensionType(Key,GName); ExtType := PathAndGroupManager.GetExtensionType(info.name,GName); if ExtType='' then ExtType := ExtensionTypeManager.GetExtensionType(info.name); if ExtType='' then ExtType := '*any*'; i := fReportExtType.indexOf(ExtType); if i=-1 then begin obj := TDirectoryStat.Create; fReportExtType.AddObject(ExtType,obj); end else obj := fReportExtType.Objects[i] as TDirectoryStat; Result := obj.Size.Add(info.Size); end; function TAppParams.FindGroupByPath(S : String) : string; begin Result := PathAndGroupManager.FindGroupByPath(S); end; function TAppParams.FindSpecificByPath(S : String) : string; begin Result := PathAndGroupManager.FindSpecificByPath(S); end; procedure TAppParams.DumpExtensions(); begin ExtensionTypeManager.DumpExtensions(); end; procedure TAppParams.DumpPaths(); begin PathAndGroupManager.DumpPathsAndGroups(); end; procedure TAppParams.DumpExtType(); var i : integer; begin writeln('Type extension':25,' = ','Taille':25); for i:= 0 to pred(fReportExtType.count) do with fReportExtType.Objects[i] as TDirectoryStat do writeln(fReportExtType[i]:25,' = ',Size.FromByteToHR:25); end; function TAppParams.GetSpecificPaths : TSpecificPaths; begin Result := PathAndGroupManager.Paths; end; function TAppParams.GetExtensionType(fName : String; GName : string) : string; begin Result := PathAndGroupManager.GetExtensionType(Fname,GName); if Result = '' then Result := ExtensionTypeManager.GetExtensionType(Fname); end; function TAppParams.GetExceptIncludeRegExp(GName : string) : TExtensionTypeManager; begin Result := PathAndGroupManager.GetExceptIncludeRegExp(GName); end; function TAppParams.GetLimitIndex(info : TSearchRec) : Integer; var i : integer; begin for i:= 0 to pred(fUnity.count) do if info.size <= funity.Values[i] then break; Result := i; end; function TAppParams.IsPathExcluded(Gname : string; Path : String) : boolean; begin Result := false; if GName<>'' then begin // writeln('On teste pour le groupe '+Gname+' si le Path '+Path+' est exclu ou inclus ?'); if Assigned(ExcludeIncludeRegExp[GName]) then Result := ExcludeIncludeRegExp[GName].IsPathExcluded(Gname,Path); end; end; function TAppParams.IsFileToTrace(info : TSearchRec) : boolean; begin Result := (SettingsListFile<>'') and (IsFileNewer(info,fLimitDate)); end; function TAppParams.IsFileToCopy(info : TSearchRec) : boolean; begin Result := (SettingsCopyTreeDir<>'') and (IsFileNewer(info,fLimitCopy)); end; function TAppParams.SettingsGetJSON : AnsiString; begin Result := '"DrillDown": "'+cTrueFalse[SettingsDrillDown]+'", '+ '"KeepUnknownDetails": "'+cTrueFalse[SettingsKeepUDetails]+'", '+ '"Depth": "'+IntToStr(SettingsDepth)+'", '+ '"Sources": "'+SettingsSrc+'",'+ '"ListFiles": "'+SettingsListFile+'"'; end; end.
unit Antlr.Runtime.Tools.Tests; { 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 SysUtils, TestFramework, Generics.Defaults, Generics.Collections, Antlr.Runtime.Tools; type // Test methods for class IANTLRString TestIANTLRString = class(TTestCase) strict private FIANTLRString: IANTLRString; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetValue; procedure TestSetValue; end; // Test methods for class TANTLRString TestTANTLRString = class(TTestCase) strict private FANTLRString: TANTLRString; public procedure SetUp; override; procedure TearDown; override; published procedure TestToString; end; // Test methods for class ICloneable TestICloneable = class(TTestCase) strict private FICloneable: ICloneable; public procedure SetUp; override; procedure TearDown; override; published procedure TestClone; end; // Test methods for class IList TestIList = class(TTestCase) strict private FIList: IList<Integer>; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetCapacity; procedure TestSetCapacity; procedure TestGetCount; procedure TestSetCount; procedure TestGetItem; procedure TestSetItem; procedure TestAdd; procedure TestAddRange; procedure TestInsert; procedure TestRemove; procedure TestDelete; procedure TestDeleteRange; procedure TestClear; procedure TestContains; procedure TestIndexOf; end; // Test methods for class IDictionary TestIDictionary = class(TTestCase) strict private FIDictionary: IDictionary<String, Integer>; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetItem; procedure TestSetItem; procedure TestGetCount; procedure TestAdd; procedure TestRemove; procedure TestTryGetValue; procedure TestContainsKey; procedure TestContainsValue; procedure TestEnumeration; end; // Test methods for record TLocalStorage TestTLocalStorage = class(TTestCase) published procedure TestLocalIntegerStorage; procedure TestLocalInterfaceStorage; end; implementation type IFoo = interface(IANTLRInterface) ['{48E3FC72-4E63-46D8-8450-A561ECF76995}'] function GetValue: String; procedure SetValue(const V: String); property Value: String read GetValue write SetValue; end; TFoo = class(TANTLRObject, ICloneable, IFoo) FValue: String; function GetValue: String; procedure SetValue(const V: String); function Clone: IANTLRInterface; end; function TFoo.GetValue: String; begin Result := FValue; end; procedure TFoo.SetValue(const V: String); begin FValue := V; end; function TFoo.Clone: IANTLRInterface; var Foo: IFoo; begin Foo := TFoo.Create; Foo.Value := FValue; Result := Foo; end; procedure TestIANTLRString.SetUp; begin FIANTLRString := TANTLRString.Create('foo'); end; procedure TestIANTLRString.TearDown; begin FIANTLRString := nil; end; procedure TestIANTLRString.TestGetValue; var ReturnValue: string; begin ReturnValue := FIANTLRString.GetValue; CheckEquals(ReturnValue,'foo'); end; procedure TestIANTLRString.TestSetValue; var Value: string; begin Value := 'bar'; FIANTLRString.SetValue(Value); CheckEquals(FIANTLRString.Value,'bar'); end; procedure TestTANTLRString.SetUp; begin FANTLRString := TANTLRString.Create('foo'); end; procedure TestTANTLRString.TearDown; begin FANTLRString.Free; FANTLRString := nil; end; procedure TestTANTLRString.TestToString; var ReturnValue: string; begin ReturnValue := FANTLRString.ToString; CheckEquals(ReturnValue,'foo'); end; procedure TestICloneable.SetUp; var Foo: IFoo; begin Foo := TFoo.Create; Foo.Value := 'original'; FICloneable := Foo as ICloneable; end; procedure TestICloneable.TearDown; begin FICloneable := nil; end; procedure TestICloneable.TestClone; var ReturnValue: IANTLRInterface; begin ReturnValue := FICloneable.Clone; Check(Supports(ReturnValue, IFoo)); CheckEquals((ReturnValue as IFoo).Value,(FICloneable as IFoo).Value); end; procedure TestIList.SetUp; begin FIList := TList<Integer>.Create; end; procedure TestIList.TearDown; begin FIList := nil; end; procedure TestIList.TestGetCapacity; var ReturnValue: Integer; begin FIList.Capacity := 100; ReturnValue := FIList.GetCapacity; CheckEquals(ReturnValue,100); end; procedure TestIList.TestSetCapacity; var Value: Integer; begin Value := 100; FIList.SetCapacity(Value); CheckEquals(FIList.Capacity,100); end; procedure TestIList.TestGetCount; var ReturnValue: Integer; begin FIList.Clear; FIList.Add(123); ReturnValue := FIList.GetCount; CheckEquals(ReturnValue,1); end; procedure TestIList.TestSetCount; var Value: Integer; begin Value := 4; FIList.SetCount(Value); CheckEquals(FIList.Count,4); end; procedure TestIList.TestGetItem; var ReturnValue: Integer; Index: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Index := 2; ReturnValue := FIList.GetItem(Index); CheckEquals(ReturnValue,300); end; procedure TestIList.TestSetItem; var Value: Integer; Index: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Index := 3; Value := 333; FIList.SetItem(Index, Value); CheckEquals(FIList.Items[3],333); end; procedure TestIList.TestAdd; var ReturnValue: Integer; Value: Integer; begin FIList.Clear; Value := 3; ReturnValue := FIList.Add(Value); CheckEquals(ReturnValue,0); end; procedure TestIList.TestAddRange; var Values: array [0..3] of Integer; begin FIList.Clear; Values[0] := 111; Values[1] := 222; Values[2] := 333; Values[3] := 444; FIList.AddRange(Values); CheckEquals(FIList[0],111); CheckEquals(FIList[1],222); CheckEquals(FIList[2],333); CheckEquals(FIList[3],444); end; procedure TestIList.TestInsert; var Value: Integer; Index: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Index := 2; Value := 250; FIList.Insert(Index, Value); CheckEquals(FIList[1],200); CheckEquals(FIList[2],250); CheckEquals(FIList[3],300); end; procedure TestIList.TestRemove; var ReturnValue: Integer; Value: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Value := 300; ReturnValue := FIList.Remove(Value); CheckEquals(ReturnValue,2); end; procedure TestIList.TestDelete; var Index: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Index := 2; FIList.Delete(Index); CheckEquals(FIList[2],400); end; procedure TestIList.TestDeleteRange; var ACount: Integer; AIndex: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); AIndex := 1; ACount := 2; FIList.DeleteRange(AIndex, ACount); CheckEquals(FIlist[0],100); CheckEquals(FIlist[1],400); end; procedure TestIList.TestClear; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); FIList.Clear; CheckEquals(FIList.Count,0); end; procedure TestIList.TestContains; var ReturnValue: Boolean; Value: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Value := 200; ReturnValue := FIList.Contains(Value); CheckTrue(ReturnValue); Value := 250; ReturnValue := FIList.Contains(Value); CheckFalse(ReturnValue); end; procedure TestIList.TestIndexOf; var ReturnValue: Integer; Value: Integer; begin FIList.Clear; FIList.Add(100); FIList.Add(200); FIList.Add(300); FIList.Add(400); Value := 300; ReturnValue := FIList.IndexOf(Value); CheckEquals(ReturnValue,2); Value := 301; ReturnValue := FIList.IndexOf(Value); CheckEquals(ReturnValue,-1); end; procedure TestIDictionary.SetUp; begin FIDictionary := TDictionary<String, Integer>.Create; FIDictionary.Add('Foo',1); FIDictionary.Add('Bar',3); FIDictionary.Add('Baz',7); FIDictionary.Add('Zip',7); end; procedure TestIDictionary.TearDown; begin FIDictionary := nil; end; procedure TestIDictionary.TestGetItem; var ReturnValue: Integer; Key: String; begin Key := 'Baz'; ReturnValue := FIDictionary.GetItem(Key); CheckEquals(ReturnValue,7); end; procedure TestIDictionary.TestSetItem; var Value: Integer; Key: String; begin Key := 'Bar'; Value := 20; FIDictionary.SetItem(Key, Value); CheckEquals(FIDictionary['Bar'],20); end; procedure TestIDictionary.TestGetCount; var ReturnValue: Integer; begin ReturnValue := FIDictionary.GetCount; CheckEquals(ReturnValue,4); end; procedure TestIDictionary.TestAdd; var Value: Integer; Key: String; begin Key := 'Key'; Value := -1; FIDictionary.Add(Key, Value); CheckEquals(FIDictionary['Key'],-1); end; procedure TestIDictionary.TestRemove; var Key: String; begin Key := 'Bar'; FIDictionary.Remove(Key); CheckEquals(FIDictionary.Count,3); end; procedure TestIDictionary.TestTryGetValue; var ReturnValue: Boolean; Value: Integer; Key: String; begin Key := 'Zip'; ReturnValue := FIDictionary.TryGetValue(Key, Value); CheckTrue(ReturnValue); CheckEquals(Value,7); Key := 'Oops'; ReturnValue := FIDictionary.TryGetValue(Key, Value); CheckFalse(ReturnValue); end; procedure TestIDictionary.TestContainsKey; var ReturnValue: Boolean; Key: String; begin Key := 'Foo'; ReturnValue := FIDictionary.ContainsKey(Key); CheckTrue(ReturnValue); Key := 'foo'; ReturnValue := FIDictionary.ContainsKey(Key); CheckFalse(ReturnValue); end; procedure TestIDictionary.TestContainsValue; var ReturnValue: Boolean; Value: Integer; begin Value := 3; ReturnValue := FIDictionary.ContainsValue(Value); CheckTrue(ReturnValue); Value := 2; ReturnValue := FIDictionary.ContainsValue(Value); CheckFalse(ReturnValue); end; procedure TestIDictionary.TestEnumeration; var Pair: TPair<String, Integer>; Foo, Bar, Baz, Zip: Boolean; begin Foo := False; Bar := False; Baz := False; Zip := False; for Pair in FIDictionary do begin if (Pair.Key = 'Foo') then begin Foo := True; CheckEquals(Pair.Value, 1); end else if (Pair.Key = 'Bar') then begin Bar := True; CheckEquals(Pair.Value, 3); end else if (Pair.Key = 'Baz') then begin Baz := True; CheckEquals(Pair.Value, 7); end else if (Pair.Key = 'Zip') then begin Zip := True; CheckEquals(Pair.Value, 7); end else Check(False, 'Unknown key in dictionary'); end; CheckTrue(Foo); CheckTrue(Bar); CheckTrue(Baz); CheckTrue(Zip); end; { TestTLocalStorage } procedure TestTLocalStorage.TestLocalIntegerStorage; var Locals: TLocalStorage; begin Locals.Initialize; try Locals.AsInteger['x'] := 2; Locals.AsInteger['X'] := 3; CheckEquals(2, Locals.AsInteger['x']); CheckEquals(3, Locals.AsInteger['X']); CheckEquals(0, Locals.AsInteger['y']); Locals.AsInteger['X'] := Locals.AsInteger['x'] * 2; CheckEquals(4, Locals.AsInteger['X']); CheckEquals(2, Locals.Count); finally Locals.Finalize; end; end; procedure TestTLocalStorage.TestLocalInterfaceStorage; var Locals: TLocalStorage; begin Locals.Initialize; try { Local variable Z is never accessed again. We add it to check that there will be no memory leak. } Locals['Z'] := TANTLRString.Create('Value Z'); Locals['x'] := TANTLRString.Create('Value x'); Locals['X'] := TANTLRString.Create('Value X'); CheckEquals('Value x', (Locals['x'] as IANTLRString).Value); CheckEquals('Value X', (Locals['X'] as IANTLRString).Value); Check(Locals['y'] = nil); Locals['X'] := TANTLRString.Create( (Locals['X'] as IANTLRString).Value + ' Update'); CheckEquals('Value X Update', (Locals['X'] as IANTLRString).Value); CheckEquals(3, Locals.Count); finally Locals.Finalize; end; end; initialization // Register any test cases with the test runner RegisterTest(TestIANTLRString.Suite); RegisterTest(TestTANTLRString.Suite); RegisterTest(TestICloneable.Suite); RegisterTest(TestIList.Suite); RegisterTest(TestIDictionary.Suite); RegisterTest(TestTLocalStorage.Suite); end.
unit Threads; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, System.Threading ; type TThreadProcessamento = class(TThread) private TempoMaximoEspera: integer; protected procedure Execute; override; public constructor Create(_TempoMaximoEspera:integer); end; TfThreads = class(TForm) edNThreads: TEdit; edTempoEspera: TEdit; btExecutar: TButton; ProgressBar: TProgressBar; Memo1: TMemo; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure edNThreadsKeyPress(Sender: TObject; var Key: Char); procedure btExecutarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fThreads: TfThreads; implementation {$R *.dfm} procedure TfThreads.btExecutarClick(Sender: TObject); var TempoMaximoEspera:Integer; begin if trim(edNThreads.text)='' then edNThreads.text:='1'; if trim(edTempoEspera.text)='' then edTempoEspera.text:='0'; ProgressBar.max:=101*strtoint(edNThreads.text)-1; ProgressBar.position:=0; if edNThreads.text='0' then begin ShowMessage('Não é possível processar com 0 Threads !'); exit; end; TempoMaximoEspera := strtoint(edTempoEspera.text); Memo1.Lines.Clear; TTask.Run( procedure begin TParallel.For(0,strtoint(edNThreads.text)-1, procedure (Index: Integer) begin TThreadProcessamento.Create(TempoMaximoEspera); end); end); end; procedure TfThreads.edNThreadsKeyPress(Sender: TObject; var Key: Char); begin if (not (CharInSet(Key,['0'..'9',#8])) and (word(key) <> vk_back)) then key := #0; end; { TThreadProcessamento } constructor TThreadProcessamento.Create(_TempoMaximoEspera:integer); begin inherited create(false); TempoMaximoEspera := _TempoMaximoEspera; FreeOnTerminate := true; end; procedure TThreadProcessamento.Execute; var i:integer; begin inherited; fThreads.Memo1.Lines.Add(IntToStr(TThreadProcessamento.CurrentThread.ThreadID)+' - Iniciando processamento'); for i := 0 to 100 do begin TThread.Sleep(Random(Self.TempoMaximoEspera)); TThread.Synchronize(TThread.CurrentThread, procedure begin fThreads.ProgressBar.position := fThreads.ProgressBar.position + 1; end); Application.ProcessMessages; end; fThreads.Memo1.Lines.Add(IntToStr(TThreadProcessamento.CurrentThread.ThreadID)+' - Processamento finalizado'); end; end.
unit DockDemo.Utilities; {******************************************************************************} { } { Cesar Romero <cesar@liws.com.br> } { All Rights Reserved } { } {******************************************************************************} { } { Version: MPL 1.1 } { } { The contents of this file are subject to the Mozilla Public License } { Version 1.1 (the "License"); you may not use this file except in compliance } { with the License. } { You may obtain a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, } { WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for } { the specific language governing rights and limitations under the License. } { } {******************************************************************************} { } { How to use this unit: } { } { 1) add to the project } { 2) in the base dock form, implement the event OnStartDock like this: } { } { procedure TBaseDockForm.FormStartDock(Sender: TObject; var DragObject: } { TDragDockObject); } { begin } { DragObject:= TTransparentDragDockObject.Create(Self); } { end; } { } {******************************************************************************} interface uses Classes, Windows, SysUtils, Graphics, Controls, ExtCtrls, Forms, DockTabSet; type TTransparentForm = class(TForm) protected procedure CreateParams(var Params: TCreateParams); override; end; TTransparentDragDockObject = class(TDragDockObjectEx) protected function GetEraseWhenMoving: Boolean; override; procedure DrawDragDockImage; override; procedure EraseDragDockImage; override; public constructor Create(AControl: TControl); override; end; implementation var TransparentForm: TTransparentForm; const CAlphaBlendValue: Integer = 128; { TTransparentForm } procedure TTransparentForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle:= Params.ExStyle or WS_EX_TRANSPARENT; end; { TTransparentDragDockObject } constructor TTransparentDragDockObject.Create(AControl: TControl); begin inherited; if TransparentForm = nil then begin TransparentForm := TTransparentForm.CreateNew(Application); with TransparentForm do begin AlphaBlend:= True; AlphaBlendValue := CAlphaBlendValue; BorderStyle := bsNone; Color := clHighlight; FormStyle := fsStayOnTop; end; end; end; procedure TTransparentDragDockObject.EraseDragDockImage; begin TransparentForm.Hide; end; procedure TTransparentDragDockObject.DrawDragDockImage; begin if TransparentForm <> nil then begin TransparentForm.BoundsRect := DockRect; if not TransparentForm.Visible then TransparentForm.Show; end; end; function TTransparentDragDockObject.GetEraseWhenMoving: Boolean; begin Result := False; end; end.
unit ncaFrmConfig_NFE; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseOpcao, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, cxDBEdit, cxLabel, Data.DB, kbmMemTable, cxCheckBox, dxGDIPlusClasses, Vcl.ExtCtrls, cxButtonEdit, ncaFrmNCMPesq, dxLayoutcxEditAdapters, dxLayoutContainer, dxLayoutControl, Vcl.Mask, Vcl.DBCtrls, cxSpinEdit, dxLayoutLookAndFeels, cxClasses, dxLayoutControlAdapters, dxBarBuiltInMenu, cxPC, ncaDocEdit, cxMemo, nxdb, ncClassesBase, LMDBaseControl, LMDBaseGraphicControl, LMDBaseLabel, LMDCustomLabel, LMDLabel, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; type TFrmConfig_NFE = class(TFrmBaseOpcao) panTopo: TLMDSimplePanel; edEmitirNFe: TcxDBCheckBox; MT: TkbmMemTable; MTEmitirNFE: TBooleanField; MTCRT: TByteField; MTModeloNFE: TStringField; MTSerieNFe: TStringField; MTInicioNFe: TLongWordField; MTRazaoSocial: TStringField; MTNomeFantasia: TStringField; MTCNPJ: TStringField; MTIE: TStringField; MTEnd_Logradouro: TStringField; MTEnd_Numero: TStringField; MTEnd_Bairro: TStringField; MTEnd_UF: TStringField; MTEnd_CEP: TStringField; MTEnd_Municipio: TStringField; MTEnd_CodMun: TStringField; MTEnd_CodUF: TByteField; MTTelefone: TStringField; DS: TDataSource; btnPremium: TcxButton; MTMostrarDadosNFE: TBooleanField; MTPedirEmail: TByteField; MTPedirCPF: TByteField; img: TImage; edSerieNFe: TcxDBTextEdit; lcSerieNFE: TdxLayoutItem; edInicioNFe: TcxDBSpinEdit; lcInicioNFE: TdxLayoutItem; edLogr: TcxDBTextEdit; LCItem1: TdxLayoutItem; edNumero: TcxDBTextEdit; LCItem3: TdxLayoutItem; edBairro: TcxDBTextEdit; LCItem4: TdxLayoutItem; edCEP: TcxDBTextEdit; LCItem6: TdxLayoutItem; edMun: TcxDBTextEdit; LCItem7: TdxLayoutItem; edTel: TcxDBTextEdit; LCItem10: TdxLayoutItem; edCodMun: TcxDBButtonEdit; lcCodMun: TdxLayoutItem; MTEnd_Complemento: TStringField; edComplemento: TcxDBTextEdit; LCItem2: TdxLayoutItem; dxLayoutLookAndFeelList1: TdxLayoutLookAndFeelList; llfUltraFlat: TdxLayoutCxLookAndFeel; MTCertificadoDig: TStringField; btnAvancadas: TcxButton; LCItem5: TdxLayoutItem; llfFlat: TdxLayoutCxLookAndFeel; Paginas: TcxPageControl; tsSefaz: TcxTabSheet; tsEndereco: TcxTabSheet; tsOpcoes: TcxTabSheet; panSefaz: TLMDSimplePanel; lc1: TdxLayoutControl; lc1Group_Root: TdxLayoutGroup; panEnd: TLMDSimplePanel; lc3: TdxLayoutControl; lc3Group_Root: TdxLayoutGroup; panOpcoes: TLMDSimplePanel; lc4: TdxLayoutControl; lc4Group_Root: TdxLayoutGroup; lc3Group2: TdxLayoutAutoCreatedGroup; lc3Group3: TdxLayoutAutoCreatedGroup; edPedirEmail: TcxDBCheckBox; lc4Item2: TdxLayoutItem; lcgr_avancado: TdxLayoutGroup; edHom: TcxDBCheckBox; lctpAmb: TdxLayoutItem; cxLabel1: TcxLabel; lc4Item4: TdxLayoutItem; MTTipoCert: TByteField; tsEmail: TcxTabSheet; lc5Group_Root: TdxLayoutGroup; lc5: TdxLayoutControl; edFromEmail: TcxDBTextEdit; lcFromEmail: TdxLayoutItem; MTFromEmail: TStringField; MTFromName: TStringField; edCorpoEmail: TcxDBMemo; lcCorpoEmail: TdxLayoutItem; edAssunto: TcxDBTextEdit; lcAssunto: TdxLayoutItem; MTAssuntoEmail: TStringField; cxLabel2: TcxLabel; lc5Item1: TdxLayoutItem; lcModEmailNFE: TdxLayoutItem; edModEmailNFE: TncDocEdit; MTCorpoEmail: TMemoField; btnInstalaDepend: TcxButton; lc4Item3: TdxLayoutItem; lc4Group3: TdxLayoutAutoCreatedGroup; MTPinCert: TStringField; Timer1: TTimer; tsCert: TcxTabSheet; lcCD: TdxLayoutControl; edCertificado: TcxDBComboBox; edTipoCert: TcxDBImageComboBox; edPin: TcxDBTextEdit; lcCDGroup_Root: TdxLayoutGroup; lcCertificado: TdxLayoutItem; lcTipoCert: TdxLayoutItem; lcPIN: TdxLayoutItem; MTCodigoAtivacao: TStringField; panEstado: TLMDSimplePanel; cxLabel4: TcxLabel; edEstado: TcxDBImageComboBox; dxLayoutItem3: TdxLayoutItem; edIE: TcxDBTextEdit; dxLayoutItem4: TdxLayoutItem; edCNPJ: TcxDBMaskEdit; dxLayoutItem5: TdxLayoutItem; edFantasia: TcxDBTextEdit; dxLayoutItem6: TdxLayoutItem; edRazao: TcxDBTextEdit; dxLayoutItem7: TdxLayoutItem; edCRT: TcxDBImageComboBox; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; OpenDlg: TOpenDialog; h: TIdHTTP; MTsat_modelo: TByteField; MTsat_config: TStringField; MTtpAmbNFe: TByteField; procedure edEmitirNFCePropertiesChange(Sender: TObject); procedure edMostrarNCMPropertiesChange(Sender: TObject); procedure edMostrarSitTribPropertiesChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edCRTPropertiesChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure edCodMunPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure edCodMunPropertiesChange(Sender: TObject); procedure btnAvancadasClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure PaginasDrawTabEx(AControl: TcxCustomTabControl; ATab: TcxTab; Font: TFont); procedure btnPremiumClick(Sender: TObject); procedure PaginasChange(Sender: TObject); procedure btnInstalaDependClick(Sender: TObject); procedure edTipoCertPropertiesChange(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure edEstadoPropertiesChange(Sender: TObject); procedure edsat_modeloPropertiesCloseUp(Sender: TObject); private FFrmNCM : TFrmNCMPesq; FEditModelo : Boolean; FDisableSetFocus : Boolean; FAtivar : Boolean; FCNPJ : String; FSignAC : String; FSignACCNPJ : String; { Private declarations } procedure Atualiza; procedure Valida; procedure EnableDisable; procedure SetEditModelo(const Value: Boolean); procedure wmAtualizaDireitosConfig(var Msg: TMessage); message wm_atualizadireitosconfig; public { Public declarations } procedure Ler; override; procedure Salvar; override; function Alterou: Boolean; override; procedure AtualizaMun; procedure Renumera; override; property Ativar: Boolean read FAtivar write FAtivar; class procedure Mostrar(aAtivar : Boolean); function NumItens: Integer; override; property EditModelo: Boolean read FEditModelo write SetEditModelo; end; var FrmConfig_NFE: TFrmConfig_NFE; implementation {$R *.dfm} uses ncaFrmPri, ncaDM, ncaFrmMunBr, ncEspecie, ncaFrmConfigEspecies, ncaFrmRecursoPremium, ncaFrmNFeDepend, ncaProgressoDepend, ncaFrmAlertaPIN, ufmImagens, md5, ncHttp; { TFrmConfigNFE } resourcestring rsNFCePremium = 'A emissão de NF é um recurso exclusivo para assinantes do plano PREMIUM.'; function Chave(aLoja, aCNPJ: string): string; begin aLoja := Trim(aLoja); aCNPJ := SoDig(aCNPJ); Result := getmd5str('piLKHerASD17IUywefd7kdsfTkjhasfdkxzxxx778213zxcnbv'+LowerCase(aLoja)+aCNPJ); // do not localize end; function TFrmConfig_NFE.Alterou: Boolean; begin Result := True; with Dados do begin if edEmitirNFe.Checked <> tNFConfigEmitirNFe.Value then Exit; if edEstado.EditValue <> tNFConfigEnd_UF.Value then Exit; if edCertificado.Text <> tNFConfigCertificadoDig.Value then Exit; if edCRT.EditValue <> tNFConfigCRT.Value then Exit; if edRazao.Text <> tNFConfigRazaoSocial.Value then Exit; if edFantasia.Text <> tNFConfigNomeFantasia.Value then Exit; if edCNPJ.Text <> tNFConfigCNPJ.Value then Exit; if edIE.Text <> tNFConfigIE.Value then Exit; if edLogr.Text <> tNFConfigEnd_Logradouro.Value then Exit; if edNumero.Text <> tNFConfigEnd_Numero.Value then Exit; if edComplemento.Text <> tNFConfigEnd_Complemento.Value then Exit; if edBairro.Text <> tNFConfigEnd_Bairro.Value then Exit; if edCEP.Text <> tNFConfigEnd_CEP.Value then Exit; if edTel.Text <> tNFConfigTelefone.Value then Exit; if edCodMun.Text <> tNFConfigEnd_CodMun.Value then Exit; if MTPedirCPF.Value <> tNFConfigPedirCPF.Value then Exit; if MTPedirEmail.Value <> tNFConfigPedirEmail.Value then Exit; if edSerieNFe.Text <> tNFConfigSerieNFe.Value then Exit; if edInicioNFe.Value <> tNFConfigInicioNFe.Value then Exit; if edHom.EditValue <> tNFConfigtpAmbNFe.Value then Exit; if edModEmailNFE.IDDoc <> tNFConfigModeloNFe_Email.Value then Exit; if edAssunto.Text <> TNFConfigAssuntoEmail.Value then Exit; if edFromEmail.Text <> tNFConfigFromEmail.Value then Exit; if edTipoCert.EditValue <> tNFConfigTipoCert.Value then Exit; if edPin.Text <> tNFConfigPinCert.Value then Exit; end; Result := False; end; procedure TFrmConfig_NFE.Atualiza; begin lcPIN.Visible := False; //(edTipoCert.ItemIndex=1); tsCert.TabVisible := True; lcSerieNFE.Visible := True; lcInicioNFE.Visible := True; lctpAmb.Visible := True; lcModEmailNFE.Visible := True; end; procedure TFrmConfig_NFE.AtualizaMun; begin with Dados do if tbMun.FindKey([edCodMun.Text]) then begin edMun.Text := tbMunNome.Value; MTEnd_Municipio.Value := tbMunNome.Value; MTEnd_CodUF.Value := StrToInt(Copy(edCodMun.Text, 1, 2)); end else begin edMun.Text := ''; MTEnd_Municipio.Value := ''; MTEnd_CodUF.Value := 0; end; end; procedure TFrmConfig_NFE.btnAvancadasClick(Sender: TObject); begin inherited; lcgr_Avancado.Visible := btnAvancadas.Down; end; procedure TFrmConfig_NFE.btnInstalaDependClick(Sender: TObject); begin inherited; NotifySucessoDepend := True; ncaDM.NotityErroDepend := True; if Assigned(panProgressoDepend) then ShowMessage('Já existe uma instalação em andamento') else Dados.CM.InstalaNFeDepend; end; procedure TFrmConfig_NFE.btnOkClick(Sender: TObject); begin if edEmitirNFe.Checked then begin Paginas.ActivePageIndex := 0; edRazao.SetFocus; edFantasia.SetFocus; end; if Alterou then Salvar; Close; end; procedure TFrmConfig_NFE.btnPremiumClick(Sender: TObject); begin inherited; TFrmRecursoPremium.Create(Self).Mostrar(rsNFCePremium, 'nfce'); end; procedure TFrmConfig_NFE.edCodMunPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var aUF, aCod: String; P : TFrmMunPesq; begin inherited; aUF := MTEnd_UF.Value; if aUF='' then begin Paginas.ActivePageIndex := 0; raise exception.Create('É necessário selecionar um estado'); end; aCod := edCodMun.Text; P := TFrmMunPesq.Create(self); try if P.Pesquisar(aUF, aCod) then begin edCodMun.Text := aCod; MTEnd_CodMun.Value := aCod; MTEnd_Municipio.Value := P.TabNome.Value; MTEnd_CodUF.Value := StrToInt(copy(aCod, 1, 2)); end; finally P.Free; end; end; procedure TFrmConfig_NFE.edCodMunPropertiesChange(Sender: TObject); begin inherited; AtualizaMun; end; procedure TFrmConfig_NFE.edCRTPropertiesChange(Sender: TObject); begin inherited; if edCRT.Focused and (edCRT.ItemIndex=2) then begin ShowMessage('O NEX ainda não está preparado para emitir NF-e para empresas que trabalham em Regime Normal'); edCRT.ItemIndex := 0; end; Atualiza; end; procedure TFrmConfig_NFE.edEmitirNFCePropertiesChange(Sender: TObject); begin inherited; Atualiza; EnableDisable; end; procedure TFrmConfig_NFE.edEstadoPropertiesChange(Sender: TObject); begin inherited; EnableDisable; Atualiza; end; procedure TFrmConfig_NFE.edMostrarNCMPropertiesChange(Sender: TObject); begin inherited; Atualiza; end; procedure TFrmConfig_NFE.edMostrarSitTribPropertiesChange(Sender: TObject); begin inherited; Atualiza; end; procedure TFrmConfig_NFE.edsat_modeloPropertiesCloseUp(Sender: TObject); begin inherited; Atualiza; end; procedure TFrmConfig_NFE.edTipoCertPropertiesChange(Sender: TObject); begin inherited; Atualiza; end; procedure TFrmConfig_NFE.EnableDisable; var aEnable: Boolean; begin lcPIN.Visible := False; //(edTipoCert.ItemIndex=1); btnPremium.Visible := not ((gConfig.IsPremium) and (not gConfig.Pro)); edEmitirNFe.Enabled := not btnPremium.Visible; aEnable := edEmitirNFe.Checked and edEmitirNFe.Enabled and (edEstado.ItemIndex>=0); lc1Group_Root.Enabled := aEnable; lcCDGroup_Root.Enabled := aEnable; lc3Group_Root.Enabled := aEnable; lc4Group_Root.Enabled := aEnable; lc5Group_Root.Enabled := aEnable; btnOk.Enabled := Dados.CM.UA.Admin and edEmitirNFe.Enabled; end; procedure TFrmConfig_NFE.FormCreate(Sender: TObject); begin inherited; FSignACCNPJ := ''; FDisableSetFocus := True; FAtivar := False; FFrmNCM := nil; FEditModelo := False; Paginas.ActivePageIndex := 0; btnInstalaDepend.Enabled := Dados.CM.UA.Admin; lctpAmb.Visible := (Dados.tNFConfigtpAmb.Value=1); end; procedure TFrmConfig_NFE.FormDestroy(Sender: TObject); begin inherited; if Assigned(FFrmNCM) then gNCMPesqList.ReleaseFrm(FFrmNCM); end; procedure TFrmConfig_NFE.FormShow(Sender: TObject); begin inherited; FDisableSetFocus := False; Dados.CM.ObtemCertificados(edCertificado.Properties.Items); EnableDisable; Timer1.Enabled := True; end; procedure TFrmConfig_NFE.Ler; begin inherited; MT.Active := False; MT.Active := True; MT.Append; TransfDados(Dados.tNFConfig, MT); FCNPJ := Dados.tNFConfigCNPJ.Value; FSignAC := Dados.tNFConfigSignACSat.Value; if FAtivar then MTEmitirNFe.Value := True; if Dados.tNFConfigModeloNFCe_Email.IsNull then edModEmailNFE.IDDoc := '' else edModEmailNFE.IDDoc := Dados.tNFConfigModeloNFe_Email.Value; Atualiza; end; class procedure TFrmConfig_NFE.Mostrar(aAtivar: Boolean); begin inherited; Dados.GravaFlag('acessou_config_nfe', '1'); if (not gConfig.IsPremium) or gConfig.Pro then TFrmRecursoPremium.Create(nil).ShowModal; if gConfig.IsPremium and (not gConfig.Pro) then with TFrmConfig_NFE.Create(nil) do begin Ativar := aAtivar; ShowModal; end; end; function TFrmConfig_NFE.NumItens: Integer; begin Result := 3; end; procedure TFrmConfig_NFE.PaginasChange(Sender: TObject); begin inherited; if lc1Group_Root.Enabled and (not FDisableSetFocus) then case Paginas.ActivePageIndex of 0 : edEstado.SetFocus; 1 : edCertificado.SetFocus; 2 : edLogr.SetFocus; 3 : edPedirEmail.SetFocus; 4 : edFromEmail.SetFocus; end; end; procedure TFrmConfig_NFE.PaginasDrawTabEx(AControl: TcxCustomTabControl; ATab: TcxTab; Font: TFont); begin inherited; if btnPremium.Visible then Font.Color := clSilver; end; procedure TFrmConfig_NFE.Renumera; begin // RenumCB(edEmitirNFCe, 0); // RenumLB(lbCRT, 2); end; procedure TFrmConfig_NFE.Salvar; var aEmissaoAntes : Boolean; aCNPJAnt, aRazaoAnt : String; begin inherited; Valida; with Dados do begin if tNFConfig.IsEmpty then tNFConfig.Append else tNFConfig.Edit; aEmissaoAntes := tNFConfigEmitirNFe.Value; aCNPJAnt := tNFConfigCNPJ.Value; aRazaoAnt := tNFConfigRazaoSocial.Value; TransfDados(MT, tNFConfig); tNFConfigPinCert.Value := Trim(edPin.Text); if edModEmailNFE.IDDoc='' then tNFConfigModeloNFe_Email.Clear else tNFConfigModeloNFe_Email.Value := edModEmailNFE.IDDoc; tNFConfig.Post; if tNFConfigEmitirNFe.Value and (not aEmissaoAntes) then begin Dados.GravaFlag('acessou_config_nfe', '1'); Dados.GravaFlag('ativou_nfe', '1'); if (not tNFConfigDependNFEOk.Value) then NotityErroDepend := True; Dados.EnviaEmailAtivacaoNF(True, '', ''); end else if tNFConfigEmitirNFe.Value then begin if (aCNPJAnt=tNFConfigCNPJ.Value) then aCNPJAnt := ''; if aRazaoAnt=tNFConfigRazaoSocial.Value then aRazaoAnt := ''; if (aRazaoAnt>'') or (aCNPJAnt>'') then Dados.EnviaEmailAtivacaoNF(True, aCNPJAnt, aRazaoAnt); end; end; end; procedure TFrmConfig_NFE.SetEditModelo(const Value: Boolean); begin Paginas.ActivePageIndex := 3; FEditModelo := Value; end; procedure TFrmConfig_NFE.Timer1Timer(Sender: TObject); begin inherited; Timer1.Enabled := False; if edEmitirNFe.Enabled and FEditModelo then begin Paginas.ActivePage := tsEmail; edModEmailNFE.SetFocus; end else if lc1Group_Root.Enabled then begin Paginas.ActivePageIndex := 0; edEstado.SetFocus; end; end; procedure TFrmConfig_NFE.Valida; begin if not edEmitirNFe.Checked then Exit; if edEstado.EditValue='' then begin Paginas.ActivePageIndex := 0; edEstado.SetFocus; raise exception.Create('É necessário infomar o estado'); end; if edMun.Text='' then begin Paginas.ActivePageIndex := 2; edCodMun.SetFocus; if Trim(edCodMun.Text)='' then raise exception.Create('É necessário informar o código do município') else raise Exception.Create('O código de municipio informado não existe'); end; { if lcPin.Visible and (Trim(edPin.Text)>'') then begin Paginas.ActivePageIndex := 0; edPin.SetFocus; raise Exception.Create('É necessário informar o PIN do certificado A3'); end; } with Dados do if tbMun.FindKey([MTEnd_CodMun.Value]) then if tbMunUF.Value <> MTEnd_UF.Value then raise exception.Create('O município informado no endereço não é do mesmo estado selecionado.'); if Trim(edCertificado.Text)='' then begin Paginas.ActivePageIndex := 1; edCertificado.SetFocus; raise Exception.Create('É necessário selecionar o certificado digital a ser usado'); end; if (Trim(edRazao.Text)='') then begin Paginas.ActivePageIndex := 0; edRazao.SetFocus; raise Exception.Create('A razão social deve ser informada'); end; if (Trim(edFantasia.Text)='') then begin Paginas.ActivePageIndex := 0; edFantasia.SetFocus; raise Exception.Create('O nome fantasia deve ser informado'); end; if (Trim(edCNPJ.Text)='') then begin Paginas.ActivePageIndex := 0; edCNPJ.SetFocus; raise Exception.Create('O CNPJ deve ser informado'); end; if not IsCNPJ(edCNPJ.Text) then begin Paginas.ActivePageIndex := 0; edCNPJ.SetFocus; raise Exception.Create('O CNPJ informado não é válido'); end; if Trim(edFantasia.Text)='' then begin Paginas.ActivePageIndex := 0; edIE.SetFocus; raise Exception.Create('A Inscrição Estadual deve ser informada'); end; if Trim(edLogr.Text)='' then begin Paginas.ActivePageIndex := 2; edLogr.SetFocus; raise Exception.Create('O endereço deve ser informado'); end; if Trim(edNumero.Text)='' then begin Paginas.ActivePageIndex := 2; edNumero.SetFocus; raise Exception.Create('O número do endereço deve ser informado'); end; if Trim(edBairro.Text)='' then begin Paginas.ActivePageIndex := 2; edBairro.SetFocus; raise Exception.Create('O bairro deve ser informado'); end; if Trim(edCEP.Text)='' then begin Paginas.ActivePageIndex := 2; edCEP.SetFocus; raise Exception.Create('O CEP deve ser informado'); end; if Length(SoDig(edCEP.Text))<8 then begin Paginas.ActivePageIndex := 2; edCEP.SetFocus; raise Exception.Create('O CEP deve ter 8 dígitos'); end; if Trim(edSerieNFe.Text)='' then begin btnAvancadas.Down := True; lcgr_Avancado.Visible := True; Paginas.ActivePageIndex := 3; edSerieNFe.SetFocus; raise Exception.Create('É necessário informar a série da NF-e'); end; if not gEspecies.TipoPagNFE_Ok then begin Beep; ShowMessage('Para cada Meio de Pagamento que você configurou no NEX para sua loja é necessário configurar o meio de pagamento correspondente na NF'); TFrmConfigEspecies.Create(Self).Mostrar(True, False); raise EAbort.Create(''); end; { if lcPin.Visible and (not TFrmAlertaPIN.Create(Self).Ciente((Trim(edPin.Text)=''))) then raise EAbort.Create('');} end; procedure TFrmConfig_NFE.wmAtualizaDireitosConfig(var Msg: TMessage); var I : Integer; B : Boolean; begin B := edEmitirNFe.Enabled; EnableDisable; if (not B) and edEmitirNFe.Enabled then begin I := Paginas.ActivePageIndex; Paginas.ActivePageIndex := 0; Paginas.ActivePageIndex := 1; Paginas.ActivePageIndex := I; end; end; end.
Unit ac_Strings; (* (C)opyright 1995-2002 George Birbilis / Agrinio Club *) (************************************************************************ History: ... - ... 28Feb1999 - added "startsWith" function - added "endsWith" function 4Aug1999 - fixed a wrong-result case bug in 'endsWith' function 6Aug1999 - added "RightPos" function 26Sep1999 - added "toEnd" function 14Mar2001 - added "lrTrim" procedure - added "removeChars" procedure 5Apr2002 - added "isBlankStr" procedure 11Apr2002 - added "tokenizeStr" function 4Jun2002 - fixed "tokenizeStr" to work correctly when missing separator or when input doesn't have a separator char as its last character - added "upTo" function - added "replaceStr" function 19Aug2002 - fixed "replaceStr", wound return an empty string instead of the input string if the string to be replaced wasn't found in the input string 1Nov2002 - added "trimBefore", "trimAfter", "skipFirst", "skipLast" functions 10Dec2002 - added "copyAfterChar" function *************************************************************************) interface uses SysUtils; type charSet=set of char; function NCharStr(c:char;count:integer):string; function extractnum(s:string;var start:integer{start=0};default:word):word; function CharPos(s:string;c:char;start:integer;RightDir:boolean):integer; function RightPos(c:char;s:string):integer; function Long2CommaStr(x:longint):string; function Int2Str(x:integer):string; function Long2Str(x:real):string; function Real2Str(x:real):string; function Str2Int(s:string):integer; function Str2Long(s:string):longint; function Str2Real(s:string):real; function integer2BinStr(b:integer):string; function ReverseStr(s:string):string; function upStr(s:string):string; procedure upString(var s:string); procedure lTrim(var s:string;c:char); procedure rTrim(var s:string;c:char); procedure lrTrim(var s:string;c:char); procedure InsertNChars(c:char;n:integer;var S:String;Index:integer); procedure removeChars(var s:string;chrset:charSet); procedure convertChars(var s:string;FromChars,ToChars:string); function _convertChars(s:string;FromChars,ToChars:string):string; function compareStr(s,match:string):boolean; function FindChars(s,matchChars:string;start:integer):integer; //find the first char from the left that is one of... function FindNonChars(s,notWantedChars:string;start:integer):integer; //find the first char from the left that isn't one of... function containsOnly(chrset:charSet;s:string):boolean; function startsWith(const substr:string;const s:string):boolean; function endsWith(const substr:string;const s:string):boolean; function part(s:string;first,last:integer):string; function copyTillBeforeLastChar(c:char;s:string):string; function copyAfterChar(c:char;s:string):string; function toEnd(s:string;first:integer):string; function upTo(s:string;last:integer):string; function isBlankStr(s:string):boolean; type strArray=array of string; function tokenizeStr(s:string;separator:string):strArray; function replaceStr(s, fromS, toS:String):string; function trimBefore(substr:string;s:string):string; function trimAfter(substr:string;s:string):string; function skipFirst(s:string;count:integer):string; function skipLast(s:string;count:integer):string; (************************************************************************) implementation {$B-} function startsWith; begin result:=(pos(substr,s)=1); end; function endsWith; //4Aug1999: fixed to handle a case where pos returned -1 (not found) and endsWith returned "true" //not: strange comment I have here, Delphi's pos function returns 0 if the searched substring is not found var position:integer; begin position:=pos(substr,s); result:=(position>0) and (position=(length(s)-length(substr)+1)); end; function extractnum; var s1:string; code:integer; const numdigits=['0'..'9']; begin {ignore a sequence of spaces and/or tabs at s[start]} while (start<length(s)) and (s[start] in [' ',#9]) do inc(start); {go on} s1:=''; inc(start); while (start<=length(s)) and (s[start] in numdigits+['$']) do begin s1:=s1+s[start]; inc(start); end; if s1<>'' then val(s1,default,code); extractnum:=default; end; function CharPos(s:string;c:char;start:integer;RightDir:boolean):integer; var i:integer; begin result:=0; if (start=0) or (start>length(s)) then exit; if rightDir then begin for i:=start to length(s) do if s[i]=c then begin result:=i; exit; end; end else for i:=start downto 1 do if s[i]=c then begin result:=i; exit; end; end; function Long2CommaStr; var s:string; counter,len,i:integer; begin str(x,s); len:=length(s); counter:=Trunc(len/3); if Frac(len/3)=0 then counter:=counter-1; for i:=1 to counter do insert(',',s,len-3*i+1); Long2CommaStr:=s; end; function int2str; var s:string; begin str(x,s); int2str:=s; end; function long2str; var s:string; begin str(x,s); long2str:=s; end; function real2str; var s:string; begin str(x,s); real2str:=s; end; function str2int; var i,err:integer; begin val(s,i,err); str2int:=i; end; function str2long; var err:integer; i:longint; begin val(s,i,err); str2long:=i; end; function str2real; var err:integer; i:real; begin val(s,i,err); str2real:=i; end; procedure InsertNChars; var i:integer; begin for i:=1 to n do insert(c,s,index); end; procedure upString; var i:integer; begin for i:=1 to length(s) do s[i]:=upcase(s[i]); end; function upStr; begin upString(s); upStr:=s; end; function integer2BinStr; var i:integer; s:string; begin s:=''; for i:=1 to 8 do begin if odd(b) then s:='1'+s else s:='0'+s; b:=b shr 1; end; integer2BinStr:=s; end; function NCharStr; var s:string; begin setLength(s,count); fillchar(s[1],count,c); NCharStr:=s; end; procedure lTrim; var i:integer; begin i:=1; while (i<=length(s)) and (s[i]=c) do inc(i); //i<=length must precede the s[i]=c check, in case i=0 at first loop s:=copy(s,i,length(s)-i+1); end; procedure rTrim; var i:integer; begin i:=length(s); while (i>0) and (s[i]=c) do dec(i); //i>0 check must precede the s[i]=c check, in case i=0 at first loop s:=copy(s,1,i); end; procedure lrTrim; begin lTrim(s,c); rTrim(s,c); end; procedure removeChars; var i:integer; ss:string; begin ss:=''; for i:=1 to length(s) do if not (s[i] in chrset) then ss:=ss+s[i]; s:=ss; end; function rightPos; var i:integer; begin for i:=length(s) downto 1 do if s[i]=c then begin result:=i; exit; end; result:=0; end; function containsOnly; var i:integer; begin containsonly:=FALSE; for i:=1 to length(s) do if not (s[i] in chrset) then exit; containsonly:=TRUE; end; function compareStr; const wildcards:set of char=['*','?']; var i:integer; {$B-} begin if (s=match) then compareStr:=TRUE else begin compareStr:=FALSE; {!} for i:=1 to length(match) do if s[i]='*' then begin compareStr:=TRUE; exit; end else if (i>length(s)) then break else if (s[i]<>match[i]) and (s[i]<>'?') then exit; {FALSE} {length(s)>length(match)} if containsOnly(wildcards,copy(s,length(match)+1,length(s)-length(match))) then compareStr:=TRUE; {! else compareStr:=FALSE !} end; end; procedure convertChars; var i,p,ToCharsLen:integer; result:string; begin result:=''; ToCharsLen:=Length(ToChars); for i:=1 to length(s) do begin p:=pos(s[i],FromChars); if p=0 then result:=result+s[i] else if ToCharsLen=0 then continue {if ToChars='' the FromChars are striped} else begin if p>ToCharsLen then p:=length(ToChars); {else are changed by same pos} result:=result+ToChars[p]; {char at ToChars or the last char of ToChars} end; end; s:=result; end; function _convertChars; begin convertChars(s,FromChars,ToChars); _convertChars:=s; end; function FindChars; var i:integer; begin if start>0 then for i:=start to length(s) do if pos(s[i],matchChars)<>0 then begin FindChars:=i; exit; end; FindChars:=0; end; function FindNonChars; var i:integer; begin if start>0 then for i:=start to length(s) do if pos(s[i],notWantedChars)=0 then begin FindNonChars:=i; exit; end; FindNonChars:=0; end; function part; begin part:=copy(s,first,last-first+1); end; function ReverseStr; var i:integer; begin result:=''; for i:=length(s) downto 1 do result:=result+s[i]; end; function copyTillBeforeLastChar; var i:integer; begin i:=rightPos(c,s); if (i>0) then result:=copy(s,1,i-1) else result:=s; end; function copyAfterChar(c:char;s:string):string; begin result:=toEnd(s,pos(c,s)+1); end; function toEnd; begin result:=part(s,first,length(s)); end; function upTo; begin result:=copy(s,1,last); end; function isBlankStr; begin result:=length(trim(s))=0; end; function tokenizeStr; var i,c,sepLength:integer; begin setLength(result,0); c:=0; sepLength:=length(separator); i:=pos(separator,s); while i<>0 do begin setLength(result,c+1); result[c]:=part(s,1,i-1); //zero-based array inc(c); s:=toEnd(s,i+sepLength); i:=pos(separator,s); end; if s<>'' then begin setLength(result,c+1); result[c]:=s; end; end; function replaceStr; var i,length_fromS:integer; begin length_fromS:=length(fromS); result:=''; i:=pos(fromS,s); while i>0 do begin result:=result + upTo(s,i-1) + toS; s:=toEnd(s,i+length_fromS); i:=pos(fromS,s); end; if i=0 then result:=result+s; //keep out of the while loop (else will fail end; //@version: 1Nov2002 function trimBefore(substr:string;s:string):string; begin result:=toEnd(s,pos(substr,s)-1); end; //@version: 1Nov2002 function trimAfter(substr:string;s:string):string; begin result:=upTo(s,pos(substr,s)+length(substr)); end; //@version: 1Nov2002 function skipFirst(s:string;count:integer):string; begin result:=toEnd(s,count+1); end; //@version: 1Nov2002 function skipLast(s:string;count:integer):string; begin result:=upTo(s,length(s)-count); end; end.
unit uCapturaExcecoes; interface uses System.SysUtils; type TCapturaExcecoes = class public function GetUsuario: string; function GetVersaoWindows: string; procedure GravarImagemTela(const NomeArquivo: string); public procedure CapturarExcecao(Sender: TObject; E: Exception); end; implementation uses Winapi.Windows,System.Win.Registry, System.UITypes, Vcl.Forms, Vcl.Dialogs, Vcl.Graphics, Vcl.Imaging.jpeg, Vcl.ClipBrd, Vcl.ComCtrls; { TCapturaExcecoes } procedure TCapturaExcecoes.CapturarExcecao(Sender: TObject; E: Exception); var CaminhoArquivoLog: string; ArquivoLog: TextFile; //StringBuilder: TStringBuilder; DataHora: string; begin CaminhoArquivoLog := GetCurrentDir + '\LogExcecoes.txt'; AssignFile(ArquivoLog, CaminhoArquivoLog); // Se o arquivo existir, abre para edição, // Caso contrário, cria o arquivo if FileExists(CaminhoArquivoLog) then Append(ArquivoLog) else ReWrite(ArquivoLog); DataHora := FormatDateTime('dd-mm-yyyy_hh-nn-ss', Now); WriteLn(ArquivoLog, 'Data/Hora.......: ' + DateTimeToStr(Now)); WriteLn(ArquivoLog, 'Mensagem........: ' + E.Message); WriteLn(ArquivoLog, 'Classe Exceção..: ' + E.ClassName); WriteLn(ArquivoLog, 'Formulário......: ' + Screen.ActiveForm.Name); WriteLn(ArquivoLog, 'Unit............: ' + Sender.UnitName); WriteLn(ArquivoLog, 'Controle Visual.: ' + Screen.ActiveControl.Name); WriteLn(ArquivoLog, 'Usuario.........: ' + GetUsuario); WriteLn(ArquivoLog, 'Versão Windows..: ' + GetVersaoWindows); WriteLn(ArquivoLog, StringOfChar('-', 70)); // Fecha o arquivo CloseFile(ArquivoLog); GravarImagemTela(DataHora); { * Descomente esse código para que a exceção seja exibida para o usuário * StringBuilder := TStringBuilder.Create; try // Exibe a mensagem para o usuário StringBuilder.AppendLine('Ocorreu um erro na aplicação.') .AppendLine('O problema será analisado pelos desenvolvedores.') .AppendLine(EmptyStr) .AppendLine('Descrição técnica:') .AppendLine(E.Message); MessageDlg(StringBuilder.ToString, mtWarning, [mbOK], 0); finally StringBuilder.Free; end;} end; procedure TCapturaExcecoes.GravarImagemTela(const NomeArquivo: string); var DesktopDC: HDC; Bitmap: TBitmap; JPEG: TJpegImage; begin DesktopDC := GetWindowDC(GetDesktopWindow); Bitmap := TBitmap.Create; JPEG := TJpegImage.Create; try Bitmap.PixelFormat := pf24bit; Bitmap.Height := Screen.Height; Bitmap.Width := Screen.Width; BitBlt(Bitmap.Canvas.Handle, 0, 0, Bitmap.Width, Bitmap.Height, DesktopDC, 0, 0, SRCCOPY); JPEG.Assign(Bitmap); JPEG.SaveToFile(Format('%s\%s.jpg', [GetCurrentDir, NomeArquivo])); finally JPEG.Free; Bitmap.Free; ReleaseDC(GetDesktopWindow, DesktopDC); end; end; function TCapturaExcecoes.GetUsuario: string; var Size: DWord; begin // retorna o login do usuário do sistema operacional Size := 1024; SetLength(result, Size); GetUserName(PChar(result), Size); SetLength(result, Size - 1); end; function TCapturaExcecoes.GetVersaoWindows: string; begin case Win32MajorVersion of 5: case Win32MinorVersion of 0: result := 'Windows 2000'; 1: result := 'Windows XP'; 2: Result := 'Windows XP 64-Bit Edition / Windows Server 2003 / Windows Server 2003 R2'; end; 6: case Win32MinorVersion of 0: result := 'Windows Vista / Windows Server 2008'; 1: result := 'Windows 7 / Windows Server 2008 R2'; 2: result := 'Windows 8 / Windows Server 2012'; 3: result := 'Windows 8.1 / Windows Server 2012 R2'; end; 10: case Win32MinorVersion of 0: result := 'Windows 10 / Windows Server 2016'; end; end; end; end.
unit FIToolkit.Config.Storage; interface uses System.Classes, System.SysUtils, System.IniFiles; type TConfigFile = class sealed strict private FConfig : TMemIniFile; FConfigFile : TFileStream; private function GetFileName : TFileName; function GetHasFile : Boolean; public procedure AfterConstruction; override; public constructor Create(const FileName : TFileName; Writable : Boolean); destructor Destroy; override; function Load : Boolean; function Save : Boolean; property Config : TMemIniFile read FConfig; property FileName : TFileName read GetFileName; property HasFile : Boolean read GetHasFile; end; implementation uses System.IOUtils, FIToolkit.Commons.Utils; type TMemIniFileHelper = class helper for TMemIniFile public procedure LoadFromStream(Stream : TStream); procedure SaveToStream(Stream : TStream); end; { TMemIniFileHelper } procedure TMemIniFileHelper.LoadFromStream(Stream : TStream); var L : TStringList; begin L := TStringList.Create; try Stream.Position := 0; L.LoadFromStream(Stream, Encoding); SetStrings(L); finally L.Free; end; end; procedure TMemIniFileHelper.SaveToStream(Stream : TStream); var L : TStringList; begin L := TStringList.Create; try GetStrings(L); Stream.Position := 0; Stream.Size := 0; L.SaveToStream(Stream, Encoding); finally L.Free; end; end; { TConfigFile } procedure TConfigFile.AfterConstruction; begin inherited AfterConstruction; if HasFile then Load; end; constructor TConfigFile.Create(const FileName : TFileName; Writable : Boolean); begin inherited Create; if TFile.Exists(FileName) or Writable then FConfigFile := TFile.Open(FileName, Iff.Get<TFileMode>(Writable, TFileMode.fmOpenOrCreate, TFileMode.fmOpen), Iff.Get<TFileAccess>(Writable, TFileAccess.faReadWrite, TFileAccess.faRead), TFileShare.fsRead); FConfig := TMemIniFile.Create(String.Empty, TEncoding.UTF8); end; destructor TConfigFile.Destroy; begin FreeAndNil(FConfig); FreeAndNil(FConfigFile); inherited Destroy; end; function TConfigFile.GetFileName : TFileName; begin if Assigned(FConfigFile) then Result := TPath.GetFullPath(FConfigFile.FileName) else Result := String.Empty; end; function TConfigFile.GetHasFile : Boolean; begin Result := Assigned(FConfigFile); end; function TConfigFile.Load : Boolean; begin Result := HasFile; if Result then FConfig.LoadFromStream(FConfigFile); end; function TConfigFile.Save : Boolean; begin Result := HasFile; if Result then FConfig.SaveToStream(FConfigFile); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; procedure Init; procedure SetDCPixelFormat; procedure PrepareImage(bmap: string); protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; const Earth = 1; Moon = 2; var frmGL: TfrmGL; Angle : GLfloat = 0; time : LongInt; implementation {$R *.DFM} {====================================================================== Подготовка текстуры} procedure TfrmGL.PrepareImage(bmap: string); type PPixelArray = ^TPixelArray; TPixelArray = array [0..0] of Byte; var Bitmap : TBitmap; Data : PPixelArray; BMInfo : TBitmapInfo; I, ImageSize : Integer; Temp : Byte; MemDC : HDC; begin Bitmap := TBitmap.Create; Bitmap.LoadFromFile (bmap); with BMinfo.bmiHeader do begin FillChar (BMInfo, SizeOf(BMInfo), 0); biSize := sizeof (TBitmapInfoHeader); biBitCount := 24; biWidth := Bitmap.Width; biHeight := Bitmap.Height; ImageSize := biWidth * biHeight; biPlanes := 1; biCompression := BI_RGB; MemDC := CreateCompatibleDC (0); GetMem (Data, ImageSize * 3); try GetDIBits (MemDC, Bitmap.Handle, 0, biHeight, Data, BMInfo, DIB_RGB_COLORS); For I := 0 to ImageSize - 1 do begin Temp := Data [I * 3]; Data [I * 3] := Data [I * 3 + 2]; Data [I * 3 + 2] := Temp; end; glTexImage2d(GL_TEXTURE_2D, 0, 3, biWidth, biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, Data); finally FreeMem (Data); DeleteDC (MemDC); Bitmap.Free; end; end; end; {======================================================================= Инициализация} procedure TfrmGL.Init; const LightPos : Array [0..3] of GLFloat = (10.0, 10.0, 0.0, 1.0); var Quadric : GLUquadricObj; begin glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, @LightPos); Quadric := gluNewQuadric; gluQuadricTexture (Quadric, TRUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glEnable(GL_TEXTURE_2D); glNewList (Earth, GL_COMPILE); prepareImage ('..\earth.bmp'); gluSphere (Quadric, 1.0, 24, 24); glEndList; glNewList (Moon, GL_COMPILE); prepareImage ('..\moon.bmp'); glPushMatrix; glTranslatef (1.3, 1.3, 0.3); gluSphere (Quadric, 0.2, 24, 24); glPopMatrix; glEndList; gluDeleteQuadric (Quadric); glEnable(GL_DEPTH_TEST); end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glPushMatrix; glRotatef (-10, 0.0, 1.0, 0.0); glRotatef (Angle, 0.0, 0.0, 1.0); glCallList(Earth); glPopMatrix; glPushMatrix; glRotatef (-Angle, 0.0, 0.0, 1.0); glCallList(Moon); glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000; If Angle >= 360.0 then Angle := 0.0; time := GetTickCount; InvalidateRect(Handle, nil, False); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); Init; time := GetTickCount; end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight ); glMatrixMode( GL_PROJECTION ); glLoadIdentity; glFrustum( -1.0, 1.0, -1.0, 1.0, 5.0, 1500.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity; glTranslatef( 0.0, 0.0, -12.0 ); glRotatef(-90.0, 1.0, 0.0, 0.0); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin glDeleteLists (Earth, 2); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x59; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation Uses SysUtils; (* Type $59 - Current sensors Buffer[0] = packetlength = $0D; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = count Buffer[7] = ch1_high Buffer[8] = ch1_low Buffer[9] = ch2_high Buffer[10] = ch2_low Buffer[11] = ch3_high Buffer[12] = ch3_low Buffer[13] = battery_level:4/rssi:4 Test strings : 0D59010F860004001D0000000049 xPL Schema sensor.basic { device=elec1_1 0x<hex sensor id> type=current current=<ampere> } sensor.basic { device=elec1_2 0x<hex sensor id> type=current current=<ampere> } sensor.basic { device=elec1_3 0x<hex sensor id> type=current current=<ampere> } sensor.basic { device=elec1 0x<hex sensor id> type=battery current=0-100 } *) const // Type CURRENT = $59; // Subtype ELEC1 = $01; var SubtypeArray : array[1..1] of TRFXSubTypeRec = ((SubType : ELEC1; SubTypeString : 'elec1')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID, DeviceID1, DeviceID2, DeviceID3 : String; SubType : Byte; Ampere1, Ampere2, Ampere3 : Extended; BatteryLevel : Integer; xPLMessage : TxPLMessage; begin SubType := Buffer[2]; DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); DeviceID1 := GetSubTypeString(SubType,SubTypeArray)+'_1'+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); DeviceID2 := GetSubTypeString(SubType,SubTypeArray)+'_2'+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); DeviceID3 := GetSubTypeString(SubType,SubTypeArray)+'_3'+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); Ampere1 := ((Buffer[7] shl 8) + Buffer[8]) / 10; Ampere2 := ((Buffer[9] shl 8) + Buffer[10]) / 10; Ampere3 := ((Buffer[11] shl 8) + Buffer[12]) / 10; if (Buffer[13] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic messages xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID1); xPLMessage.Body.AddKeyValue('current='+FloatToStr(Ampere1)); xPLMessage.Body.AddKeyValue('type=current'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID2); xPLMessage.Body.AddKeyValue('current='+FloatToStr(Ampere2)); xPLMessage.Body.AddKeyValue('type=current'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID3); xPLMessage.Body.AddKeyValue('current='+FloatToStr(Ampere3)); xPLMessage.Body.AddKeyValue('type=current'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
unit ARCH_REG_Pacientes; interface uses FUNC_REG_Pacientes; const Directorio_Paciente = '.\Datos\Datos Pacientes.dat'; type ARCHIVO_Pacientes = File Of REG_Persona; procedure Abrir_archivo_pacientes_para_lectura_escritura(VAR ARCH_Pacientes: ARCHIVO_Pacientes); procedure Guarda_Registro_Persona(VAR ARCH_Pacientes: ARCHIVO_Pacientes; R_Persona : REG_Persona); procedure Sobre_escribir_un_elemento_en_archivo_paciente(VAR ARCH_Pacientes: ARCHIVO_Pacientes; R_Persona : REG_Persona; pos: LongInt); procedure cargar_un_elemento_del_archivo_pacientes_una_posicion_especifica(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR R_Persona : REG_Persona; pos: LongInt); function Verificar_Existencia_del_DNI(VAR ARCH_Pacientes: ARCHIVO_Pacientes; DNI: LongWord): Boolean; implementation uses Funciones_Buscar; function Verificar_Existencia_del_DNI(VAR ARCH_Pacientes: ARCHIVO_Pacientes; DNI: LongWord): Boolean; VAR pos: LongInt; begin BBIN_DNI(ARCH_Pacientes, DNI, pos); if pos = -1 then Verificar_Existencia_del_DNI:= False else Verificar_Existencia_del_DNI:= True end; procedure Abrir_archivo_pacientes_para_lectura_escritura(VAR ARCH_Pacientes: ARCHIVO_Pacientes); const Directorio = Directorio_Paciente; begin assign(ARCH_Pacientes, Directorio); {$I-} reset(ARCH_Pacientes); {$I+} end; procedure Sobre_escribir_un_elemento_en_archivo_paciente(VAR ARCH_Pacientes: ARCHIVO_Pacientes; R_Persona : REG_Persona; pos: LongInt); begin seek(ARCH_Pacientes, pos); write(ARCH_Pacientes, R_Persona); end; procedure cargar_un_elemento_del_archivo_pacientes_una_posicion_especifica(VAR ARCH_Pacientes: ARCHIVO_Pacientes; VAR R_Persona : REG_Persona; pos: LongInt); begin Seek(ARCH_Pacientes, pos); Read(ARCH_Pacientes, R_Persona); end; procedure Guarda_Registro_Persona(VAR ARCH_Pacientes: ARCHIVO_Pacientes; R_Persona : REG_Persona); begin Abrir_archivo_pacientes_para_lectura_escritura(ARCH_Pacientes); if ioresult <> 0 then begin rewrite(ARCH_Pacientes); Sobre_escribir_un_elemento_en_archivo_paciente(ARCH_Pacientes, R_Persona, 0); end else begin Sobre_escribir_un_elemento_en_archivo_paciente(ARCH_Pacientes, R_Persona, filesize(ARCH_Pacientes)); end; close(ARCH_Pacientes); end; end.
unit BillContentQuerySimple; 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, DSWrap, BaseEventsQuery; type TBillContentSimpleW = class(TDSWrap) private FBillID: TFieldWrap; FID: TFieldWrap; FSaleCount: TFieldWrap; FCalcPriceR: TFieldWrap; FRetail: TFieldWrap; FWholeSale: TFieldWrap; FStoreHouseProductID: TFieldWrap; FMarkup: TFieldWrap; public constructor Create(AOwner: TComponent); override; procedure AddContent(ABillID, AStoreHouseProductID, ASaleCount: Integer; ACalcPriceR, ARetail, AWholeSale, AMarkup: Double); property BillID: TFieldWrap read FBillID; property ID: TFieldWrap read FID; property SaleCount: TFieldWrap read FSaleCount; property CalcPriceR: TFieldWrap read FCalcPriceR; property Retail: TFieldWrap read FRetail; property WholeSale: TFieldWrap read FWholeSale; property StoreHouseProductID: TFieldWrap read FStoreHouseProductID; property Markup: TFieldWrap read FMarkup; end; TQueryBillContentSimple = class(TQueryBaseEvents) private FW: TBillContentSimpleW; { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; function SearchByID(AID: Integer): Integer; property W: TBillContentSimpleW read FW; { Public declarations } end; implementation uses BaseQuery; {$R *.dfm} constructor TQueryBillContentSimple.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TBillContentSimpleW; end; function TQueryBillContentSimple.CreateDSWrap: TDSWrap; begin Result := TBillContentSimpleW.Create(FDQuery); end; function TQueryBillContentSimple.SearchByID(AID: Integer): Integer; begin Assert(AID > 0); Result := SearchEx([TParamRec.Create(W.ID.FullName, AID)]); end; constructor TBillContentSimpleW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FBillID := TFieldWrap.Create(Self, 'BillID'); FSaleCount := TFieldWrap.Create(Self, 'SaleCount'); FCalcPriceR := TFieldWrap.Create(Self, 'CalcPriceR'); FRetail := TFieldWrap.Create(Self, 'Retail'); FWholeSale := TFieldWrap.Create(Self, 'WholeSale'); FMarkup := TFieldWrap.Create(Self, 'Markup'); FStoreHouseProductID := TFieldWrap.Create(Self, 'StoreHouseProductID'); end; procedure TBillContentSimpleW.AddContent(ABillID, AStoreHouseProductID, ASaleCount: Integer; ACalcPriceR, ARetail, AWholeSale, AMarkup: Double); begin Assert(ABillID > 0); Assert(AStoreHouseProductID > 0); Assert(ASaleCount > 0); TryAppend; try BillID.F.AsInteger := ABillID; StoreHouseProductID.F.AsInteger := AStoreHouseProductID; SaleCount.F.Value := ASaleCount; CalcPriceR.F.Value := ACalcPriceR; Retail.F.Value := ARetail; WholeSale.F.Value := AWholeSale; Markup.F.Value := AMarkup; TryPost; except TryCancel; raise; end; end; end.
{=============================================================================== TCP客户端通讯基类 ===============================================================================} unit xTCPClientBase; interface uses xCommBase, System.Types, xTypes, System.Classes, xFunction, system.SysUtils, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdGlobal, Dialogs; type TCheckRevDataProc = reference to procedure(Sender: TObject); type TRevDataThread = class(TThread) private FCheckRevDataProce : TCheckRevDataProc; protected procedure Execute; override; procedure FormDo; public constructor Create(CreateSuspended: Boolean; ACheckRevDataProce : TCheckRevDataProc); virtual; destructor Destroy; override; end; type TTCPClientBase = class(TCommBase) private FServerPort: Integer; FServerIP: string; FRevThread : TRevDataThread; FOnConnected: TNotifyEvent; FOnDisconnect: TNotifyEvent; FConnected: Boolean; procedure RevData(Sender: TObject); procedure TCPConnect(Sender: TObject); procedure TCPDisconnect(Sender: TObject); procedure SetConnected(const Value: Boolean); protected /// <summary> ///真实发送 串口或以太网发送 /// </summary> function RealSend(APacks: TArray<Byte>; sParam1: string = ''; sParam2 : string=''): Boolean; override; /// <summary> /// 真实连接 /// </summary> function RealConnect : Boolean; override; /// <summary> /// 真实断开连接 /// </summary> procedure RealDisconnect; override; public FTCPClient: TIdTCPClient; constructor Create; override; destructor Destroy; override; /// <summary> /// 服务器IP /// </summary> property ServerIP : string read FServerIP write FServerIP; /// <summary> /// 服务器端口 /// </summary> property ServerPort : Integer read FServerPort write FServerPort; /// <summary> /// /// </summary> property Connected : Boolean read FConnected write SetConnected; public /// <summary> /// 连接事件 /// </summary> property OnConnected : TNotifyEvent read FOnConnected write FOnConnected; /// <summary> /// 断开连接事件 /// </summary> property OnDisconnect : TNotifyEvent read FOnDisconnect write FOnDisconnect; end; implementation { TTCPClientBase } constructor TTCPClientBase.Create; begin inherited; FRevThread := TRevDataThread.Create(False, RevData); FTCPClient:= TIdTCPClient.Create; FTCPClient.ConnectTimeout := 1000; FTCPClient.ReadTimeout := 1000; // FTCPClient.OnConnected := TCPConnect; // FTCPClient.OnDisconnected := TCPDisconnect; FServerIP := '127.0.0.1'; FServerPort := 10000; end; destructor TTCPClientBase.Destroy; begin FTCPClient.Free; FRevThread.Free; inherited; end; function TTCPClientBase.RealConnect: Boolean; var s : string; begin FTCPClient.Host := FServerIP; FTCPClient.Port := FServerPort; try FTCPClient.Connect; except end; Result := FTCPClient.Connected; if Result then s := '成功' else s := '失败'; Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 连接服务器'+FServerIP + ':' + IntToStr(FServerPort)+s); end; procedure TTCPClientBase.RealDisconnect; begin inherited; FTCPClient.Disconnect; Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 断开连接'+FServerIP + ':' + IntToStr(FServerPort)); end; function TTCPClientBase.RealSend(APacks: TArray<Byte>; sParam1,sParam2 : string): Boolean; var ABuffer : TIdBytes; i : Integer; begin Result := False; if FTCPClient.Connected then begin try SetLength(ABuffer, Length(APacks)); for i := 0 to Length(APacks) - 1 do begin ABuffer[i] := APacks[i]; end; // FTCPClient.IOHandler.Write(PacksToStr(APacks)); FTCPClient.IOHandler.Write(ABuffer); Result := True; except end; end; end; procedure TTCPClientBase.RevData(Sender: TObject); var nLen : Integer; aBuf : TIdBytes; i : Integer; s : string; begin try Connected := FTCPClient.Connected; except Disconnect; Connected := False; end; try if Assigned(FTCPClient) and FTCPClient.Connected then begin FTCPClient.IOHandler.CheckForDataOnSource; nLen := FTCPClient.IOHandler.InputBuffer.Size; if nLen > 0 then begin try FTCPClient.Socket.ReadBytes(aBuf, nLen, False); except Connected := FTCPClient.Connected; end; s := ''; for i := 0 to Length(aBuf) - 1 do s := s + Char(aBuf[i]); if s <> '' then begin RevStrData(s); RevPacksData(StrToPacks(s)) end; end; end; except end; end; procedure TTCPClientBase.SetConnected(const Value: Boolean); begin if Value <> FConnected then begin FConnected := Value; if Value then begin TCPConnect(Self); end else begin TCPDisconnect(Self); Disconnect; end; end; end; procedure TTCPClientBase.TCPConnect(Sender: TObject); begin if Assigned(FOnConnected) then begin FOnConnected(Self); end; end; procedure TTCPClientBase.TCPDisconnect(Sender: TObject); begin if Assigned(FOnDisconnect) then begin FOnDisconnect(Self); end; end; { TRevDataThread } constructor TRevDataThread.Create(CreateSuspended: Boolean; ACheckRevDataProce: TCheckRevDataProc); begin inherited Create(CreateSuspended); FCheckRevDataProce := ACheckRevDataProce; end; destructor TRevDataThread.Destroy; begin inherited; end; procedure TRevDataThread.Execute; begin inherited; while not Terminated do begin Synchronize( FormDo); Sleep(5); end; end; procedure TRevDataThread.FormDo; begin if Assigned(FCheckRevDataProce) then FCheckRevDataProce(Self); end; end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x5D; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation Uses SysUtils; (* Type $5D - Weighting scale Buffer[0] = packetlength = $08; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = weighthigh Buffer[7] = weightlow Buffer[8] = battery_level:4/rssi:4 xPL Schema sensor.basic { device=weight1|weight2 0x<hex sensor id> type=weight current=<kg> units=kg } sensor.basic { device=weight1|weight2 0x<hex sensor id> type=battery current=0-100 } *) const // Type WEIGHTING = $5B; // Subtype WEIGHT1 = $01; WEIGHT2 = $02; var SubTypeArray : array[1..2] of TRFXSubTypeRec = ((SubType : WEIGHT1; SubTypeString : 'weight1'), (SubType : WEIGHT2; SubTypeString : 'weight2')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID : String; SubType : byte; Weight : Extended; BatteryLevel : Integer; xPLMessage : TxPLMessage; begin SubType := Buffer[2]; DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); Weight := ((Buffer[6] shl 8) + Buffer[7]) / 10; if (Buffer[8] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic messages xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+FloatToStr(Weight)); xPLMessage.Body.AddKeyValue('type=weight'); xPLMessage.Body.AddKeyValue('units=kg'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
var // establishing variables x:integer; // integer variable used for for loop of main function // function for calculating factorial numbers function fact(n:real):real; // the return type is a real because pascal will display begin // error if integer is used(arithmetric overflow error). Same for all functions if n = 0 then begin fact:= 1; end else begin fact:= n*fact(n-1); end; end; // function for binomial coefficient function binCo(n:integer; k:integer):real; begin binCo:= fact(n)/(fact(k)*fact(n-k)); end; // function for catalan numbers function cataNum(n:integer):real; begin if n = 0 then begin cataNum:= binCo(2*n,n); end else begin cataNum:= binCo(2*n,n)-binCo(2*n, n-1); end; end; begin // beginning of main program for x:=0 to 9 do begin writeln(cataNum(x)); end; end. // end of program
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000, 2001 Borland Software Corporation } { } { *************************************************************************** } unit QImgList; {$T-,H+,X+} interface uses Classes, Types, Qt, QGraphics; type { TChangeLink } TCustomImageList = class; TChangeLink = class(TObject) private FSender: TCustomImageList; FOnChange: TNotifyEvent; public destructor Destroy; override; procedure Change; dynamic; property OnChange: TNotifyEvent read FOnChange write FOnChange; property Sender: TCustomImageList read FSender write FSender; end; { TCustomImageList } TImageType = (itImage, itMask); TImageIndex = type Integer; TCustomImageList = class(TComponent) private FOnChange: TNotifyEvent; FClients: TList; FChanged: Boolean; FHeight: Integer; FWidth: Integer; FUpdateCount: Integer; FMasked: Boolean; FBkColor: TColor; FPixmapList: TList; FTempMask: QBitmapH; FMaskColor: TColor; procedure BeginUpdate; procedure EndUpdate; procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); procedure CheckImage(Image: TGraphic); procedure CopyImages(Value: TCustomImageList); function GetImageHandle(AImage: TBitmap): QPixmapH; function GetMaskHandle(AImage: TBitmap): QBitmapH; function Equal(IL: TCustomImageList): Boolean; procedure DefaultMask(AImage: QPixmapH); function AddImage(AImage: QPixmapH; AMask: QBitmapH): Integer; procedure ReplaceImage(Index: Integer; AImage: QPixmapH; AMask: QBitmapH); procedure InsertImage(Index: Integer; AImage: QPixmapH; AMask: QBitmapH); procedure DoDelete(Index: Integer); procedure DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer; AImage: TImageType; Enabled: Boolean); virtual; procedure HandleMultipleImages(AImage: QPixmapH; AIndex: Integer); function GetCount: Integer; procedure FillImageList(FullImage, FullMask: TBitmap; CX, CY, MaskOffset, Count: Integer); procedure ReadD2Stream(Stream: TStream); procedure ReadD3Stream(Stream: TStream); procedure ReadClxStream(Stream: TStream); protected procedure Change; dynamic; procedure DefineProperties(Filer: TFiler); override; procedure Initialize(const AWidth, AHeight: Integer); virtual; property Masked: Boolean read FMasked write FMasked default True; property OnChange: TNotifyEvent read FOnChange write FOnChange; public constructor Create(AOwner: TComponent); override; constructor CreateSize(AWidth, AHeight: Integer); destructor Destroy; override; procedure Assign(Source: TPersistent); override; function Add(AImage, AMask: TBitmap): Integer; procedure AddImages(Value: TCustomImageList); function AddMasked(AImage: TBitmap; MaskColor: TColor): Integer; procedure Clear; procedure Delete(Index: Integer); procedure Draw(Canvas: TCanvas; X, Y, Index: Integer; AImageType: TImageType = itImage; Enabled: Boolean = True); procedure GetBitmap(Index: Integer; Image: TBitmap); function GetPixmap(Index: Integer): QPixmapH; function GetMask(Index: Integer): QBitmapH; procedure Insert(Index: Integer; Image, Mask: TBitmap); procedure InsertMasked(Index: Integer; Image: TBitmap; MaskColor: TColor); procedure Move(CurIndex, NewIndex: Integer); virtual; procedure ReadData(Stream: TStream); virtual; procedure RegisterChanges(Value: TChangeLink); procedure Replace(Index: Integer; AImage, AMask: TBitmap); procedure ReplaceMasked(Index: Integer; NewImage: TBitmap; MaskColor: TColor); procedure UnRegisterChanges(Value: TChangeLink); procedure WriteData(Stream: TStream); virtual; property BkColor: TColor read FBkColor write FBkColor default clNone; property Count: Integer read GetCount; property Height: Integer read FHeight write SetHeight default 16; property Width: Integer read FWidth write SetWidth default 16; end; TImageList = class(TCustomImageList) published property BkColor; property Height; property Masked; property Width; property OnChange; end; implementation uses SysUtils, QConsts; function Min(A, B: Integer): Integer; begin if A < B then Result := A else Result := B; end; { TCustomImageList } procedure TCustomImageList.AddImages(Value: TCustomImageList); begin if Assigned(Value) then CopyImages(Value); end; function TCustomImageList.AddMasked(AImage: TBitmap; MaskColor: TColor): Integer; var Image: TBitmap; begin CheckImage(AImage); Image := TBitmap.Create; try FMaskColor := MaskColor; try if Masked and (FMaskColor <> clNone) then with Image do begin Assign(AImage); Mask(FMaskColor); Result := Add(AImage, Image); end else Result := Add(AImage, nil); finally FMaskColor := clNone; end; finally Image.Free; end; end; procedure TCustomImageList.Assign(Source: TPersistent); var ImageList: TCustomImageList; begin if Source is TCustomImageList then begin if not Equal(TCustomImageList(Source)) then begin Clear; ImageList := TCustomImageList(Source); Masked := ImageList.Masked; Width := ImageList.Width; Height := ImageList.Height; BkColor := ImageList.BkColor; AddImages(ImageList); end; end else inherited Assign(Source); end; procedure TCustomImageList.Clear; begin Delete(-1); end; constructor TCustomImageList.Create(AOwner: TComponent); begin inherited Create(AOwner); Initialize(16, 16); end; constructor TCustomImageList.CreateSize(AWidth, AHeight: Integer); begin inherited Create(nil); Initialize(AWidth, AHeight); end; destructor TCustomImageList.Destroy; begin while FClients.Count > 0 do UnRegisterChanges(TChangeLink(FClients.Last)); FClients.Free; FClients := nil; if Assigned(FTempMask) then QBitmap_destroy(FTempMask); inherited Destroy; end; procedure TCustomImageList.Delete(Index: Integer); begin DoDelete(Index); end; procedure TCustomImageList.Draw(Canvas: TCanvas; X, Y, Index: Integer; AImageType: TImageType; Enabled: Boolean); begin DoDraw(Index, Canvas, X, Y, AImageType, Enabled); end; procedure TCustomImageList.Insert(Index: Integer; Image, Mask: TBitmap); begin CheckImage(Image); CheckImage(Mask); InsertImage(Index, GetImageHandle(Image), GetMaskHandle(Mask)); end; procedure TCustomImageList.InsertMasked(Index: Integer; Image: TBitmap; MaskColor: TColor); var Mask: TBitmap; begin CheckImage(Image); Mask := TBitmap.Create; try try FMaskColor := MaskColor; if Masked and (FMaskColor <> clNone) then begin Mask.Assign(Image); Mask.Mask(FMaskColor); InsertImage(Index, GetImageHandle(Image), GetMaskHandle(Mask)); end else InsertImage(Index, GetImageHandle(Image), nil); finally FMaskColor := clNone; end; finally Mask.Free; end; end; procedure TCustomImageList.Move(CurIndex, NewIndex: Integer); begin FPixmapList.Move(CurIndex, NewIndex); Change; end; procedure TCustomImageList.RegisterChanges(Value: TChangeLink); begin if not Assigned(Value) then Exit; Value.Sender := Self; if Assigned(FClients) then FClients.Add(Value); end; procedure TCustomImageList.Replace(Index: Integer; AImage, AMask: TBitmap); begin CheckImage(AImage); CheckImage(AMask); ReplaceImage(Index, GetImageHandle(AImage), GetMaskHandle(AMask)); end; procedure TCustomImageList.ReplaceMasked(Index: Integer; NewImage: TBitmap; MaskColor: TColor); var Image: TBitmap; begin CheckImage(NewImage); Image := TBitmap.Create; try FMaskColor := MaskColor; try if Masked and (FMaskColor <> clNone) and Assigned(NewImage) then begin Image.Assign(NewImage); Image.Mask(FMaskColor); end; ReplaceImage(Index, GetImageHandle(NewImage), GetMaskHandle(NewImage)); finally FMaskColor := clNone; end; finally Image.Free; end; end; procedure TCustomImageList.UnRegisterChanges(Value: TChangeLink); var I: Integer; begin if Assigned(FClients) then for I := 0 to FClients.Count - 1 do if FClients[I] = Value then begin Value.Sender := nil; FClients.Delete(I); Break; end; end; procedure TCustomImageList.Change; var I: Integer; begin FChanged := True; if FUpdateCount > 0 then Exit; if Assigned(FClients) then for I := 0 to FClients.Count - 1 do TChangeLink(FClients[I]).Change; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomImageList.CheckImage(Image: TGraphic); begin if Image = nil then Exit; with Image do if (Height < FHeight) or (Width < FWidth) then raise EInvalidOperation.Create(SInvalidImageSize); end; procedure TCustomImageList.CopyImages(Value: TCustomImageList); var I: Integer; begin if Assigned(Value) and (Value.Count > 0) then begin if (FWidth <> Value.FWidth) or (FHeight <> Value.FHeight) then raise EInvalidOperation.CreateRes(@SInvalidImageDimensions); BeginUpdate; try for I := 0 to Value.Count-1 do AddImage(Value.GetPixmap(I), Value.GetMask(I)); finally EndUpdate; end; end; end; procedure TCustomImageList.Initialize(const AWidth, AHeight: Integer); begin FClients := TList.Create; FWidth := AWidth; FHeight := AHeight; BkColor := clNone; FMasked := True; FMaskColor := clNone; if (Height < 1) or (Width < 1) then raise EInvalidOperation.Create(SInvalidImageSize); if not Assigned(FPixmapList) then FPixmapList := TList.Create; end; function TCustomImageList.GetImageHandle(AImage: TBitmap): QPixmapH; begin Result := nil; if Assigned(AImage) then Result := AImage.Handle; end; function TCustomImageList.Add(AImage, AMask: TBitmap): Integer; begin CheckImage(AImage); CheckImage(AMask); Result := AddImage(GetImageHandle(AImage), GetMaskHandle(AMask)); end; function TCustomImageList.Equal(IL: TCustomImageList): Boolean; function StreamsEqual(S1, S2: TMemoryStream): Boolean; begin Result := (S1.Size = S2.Size) and CompareMem(S1.Memory, S2.Memory, S1.Size); end; var MyImage, OtherImage: TMemoryStream; begin if not Assigned(IL) or (Count <> IL.Count) then begin Result := False; Exit; end; if (Count = 0) and (IL.Count = 0) then begin Result := True; Exit; end; MyImage := TMemoryStream.Create; try WriteData(MyImage); OtherImage := TMemoryStream.Create; try IL.WriteData(OtherImage); Result := StreamsEqual(MyImage, OtherImage); finally OtherImage.Free; end; finally MyImage.Free; end; end; procedure TCustomImageList.DefaultMask(AImage: QPixmapH); var Bitmap: TBitmap; begin if Assigned(QPixmap_mask(AImage)) or (QPixmap_depth(AImage) = 1) then Exit; Bitmap := TBitmap.Create; try Bitmap.Handle := AImage; Bitmap.Transparent := True; Bitmap.ReleasePixmap; finally Bitmap.Free; end; end; procedure TCustomImageList.BeginUpdate; begin Inc(FUpdateCount); end; procedure TCustomImageList.EndUpdate; begin if FUpdateCount > 0 then Dec(FUpdateCount); if FChanged then begin FChanged := False; Change; end; end; function TCustomImageList.GetMaskHandle(AImage: TBitmap): QBitmapH; var Bitmap: TBitmap; begin Result := nil; if Assigned(AImage) then if QPixmap_isQBitmap(AImage.Handle) then Result := QBitmapH(AImage.Handle) else begin Result := QPixmap_mask(AImage.Handle); if AImage.PixelFormat <> pf1bit then if Result = nil then begin if Assigned(FTempMask) then QBitmap_destroy(FTempMask); Bitmap := TBitmap.Create; try Bitmap.Assign(AImage); Bitmap.Mask(FMaskColor); FTempMask := QBitmap_create(QPixmap_mask(Bitmap.Handle)); Result := FTempMask; finally Bitmap.Free; end; end; end; end; procedure TCustomImageList.GetBitmap(Index: Integer; Image: TBitmap); begin if Assigned(Image) then with Image do begin Height := FHeight; Width := FWidth; Draw(Canvas, 0, 0, Index); end; end; function TCustomImageList.GetMask(Index: Integer): QBitmapH; begin if (Index > -1) and (Index < Count) then Result := QPixmap_mask(QPixmapH(FPixmapList[Index])) else Result := nil; end; function TCustomImageList.GetPixmap(Index: Integer): QPixmapH; begin if (Index > -1) and (Index < Count) then Result := QPixmapH(FPixmapList[Index]) else Result := nil; end; procedure TCustomImageList.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin if Filer.Ancestor <> nil then Result := not (Filer.Ancestor is TCustomImageList) or not Equal(TCustomImageList(Filer.Ancestor)) else Result := Count > 0; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Bitmap', ReadData, WriteData, DoWrite); end; { TChangeLink } procedure TChangeLink.Change; begin if Assigned(OnChange) then OnChange(Sender); end; destructor TChangeLink.Destroy; begin if Assigned(Sender) then Sender.UnRegisterChanges(Self); inherited Destroy; end; function TCustomImageList.AddImage(AImage: QPixmapH; AMask: QBitmapH): Integer; var Pixmap: QPixmapH; begin if not Assigned(AImage) then begin Pixmap := QPixmap_create; QPixmap_resize(Pixmap, Width, Height); end else Pixmap := QPixmap_create(AImage); Result := FPixmapList.Add(Pixmap); HandleMultipleImages(Pixmap, Count); if Masked then begin if Assigned(AMask) then QPixmap_setMask(Pixmap, AMask) else DefaultMask(Pixmap); end; QPixmap_resize(Pixmap, Min(FWidth, QPixmap_width(Pixmap)), Min(FHeight, QPixmap_height(Pixmap))); Change; end; procedure TCustomImageList.DoDelete(Index: Integer); begin if Index = -1 then begin while FPixmapList.Count > 0 do QPixmap_destroy(QPixmapH(FPixmapList.Extract(FPixmapList[0]))); end else begin if Index >= Count then raise EInvalidOperation.Create(SImageIndexError); QPixmap_destroy(QPixmapH(FPixmapList.Extract(FPixmapList[Index]))); end; if not (csDestroying in ComponentState) then Change; end; type TCanvasAccessor = class(TCanvas); procedure TCustomImageList.DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer; AImage: TImageType; Enabled: Boolean); var PixH: QPixmapH; DisabledPixH: QPixmapH; IconSet: QIconSetH; begin if (Index <= -1) or (Index >= Count) then Exit; TCanvasAccessor(Canvas).Changing; Canvas.Start; try if BkColor <> clNone then begin Canvas.Brush.Color := BkColor; Canvas.FillRect(Rect(X, Y, X + Width, Y + Height)); end; if AImage = itImage then PixH := QPixmapH(FPixmapList[Index]) else PixH := QPixmap_mask(QPixmapH(FPixmapList[Index])); TCanvasAccessor(Canvas).RequiredState([csHandleValid, csPenValid]); if Enabled then begin if Assigned(PixH) then QPainter_drawPixmap(Canvas.Handle, X, Y, PixH, 0, 0, Width, Height); end else begin IconSet := QIconSet_create(PixH, QIconSetSize_Small); try DisabledPixH := QPixmap_create; try QIconSet_pixmap(IconSet, DisabledPixH, QIconSetSize_Small, False); QPainter_drawPixmap(Canvas.Handle, X, Y, DisabledPixH, 0, 0, Width, Height); finally QPixmap_destroy(DisabledPixH); end; finally QIconSet_destroy(IconSet); end; end; finally Canvas.Stop; end; TCanvasAccessor(Canvas).Changed; end; function TCustomImageList.GetCount: Integer; begin Result := FPixmapList.Count; end; procedure TCustomImageList.HandleMultipleImages(AImage: QPixmapH; AIndex: Integer); var I: Integer; J: Integer; Bitmap: TBitmap; WidthLoop: Integer; HeightLoop: Integer; Pixmap: QPixmapH; begin if (QPixmap_width(AImage) > FWidth) or (QPixmap_height(AImage) > FHeight) then begin BeginUpdate; try Bitmap := TBitmap.Create; Bitmap.Width := FWidth; Bitmap.Height := FHeight; try WidthLoop := (QPixmap_width(AImage) div FWidth) - 1; for J := 1 to WidthLoop do begin Bitmap.Canvas.Start; TCanvasAccessor(Bitmap.Canvas).RequiredState([csHandleValid, csPenValid]); try QPainter_drawPixmap(Bitmap.Canvas.Handle, 0, 0, AImage, J * FWidth, 0, FWidth, FHeight); finally Bitmap.Canvas.Stop; end; if Masked and (FMaskColor <> clNone) then DefaultMask(Bitmap.Handle); Pixmap := QPixmap_create(Bitmap.Handle); QPixmap_resize(Pixmap, Min(FWidth, QPixmap_width(Pixmap)), Min(FHeight, QPixmap_height(Pixmap))); FPixmapList.Insert(AIndex, Pixmap); Inc(AIndex); end; HeightLoop := (QPixmap_height(AImage) div FHeight) - 1; for I := 1 to HeightLoop do for J := 0 to WidthLoop do begin Bitmap.Canvas.Start; TCanvasAccessor(Bitmap.Canvas).RequiredState([csHandleValid, csPenValid]); try QPainter_drawPixmap(Bitmap.Canvas.Handle, 0, 0, AImage, J * FWidth, I * FHeight, FWidth, FHeight); finally Bitmap.Canvas.Stop; end; if Masked and (FMaskColor <> clNone) then DefaultMask(Bitmap.Handle); Pixmap := QPixmap_create(Bitmap.Handle); QPixmap_resize(Pixmap, Min(FWidth, QPixmap_width(Pixmap)), Min(FHeight, QPixmap_height(Pixmap))); FPixmapList.Insert(AIndex, Pixmap); Inc(AIndex); end; finally Bitmap.Free; end; finally EndUpdate; end; end; end; procedure TCustomImageList.InsertImage(Index: Integer; AImage: QPixmapH; AMask: QBitmapH); var Pixmap: QPixmapH; begin if not Assigned(AImage) then begin Pixmap := QPixmap_create; QPixmap_resize(Pixmap, Width, Height); end else Pixmap := QPixmap_create(AImage); FPixmapList.Insert(Index, Pixmap); Inc(Index); HandleMultipleImages(Pixmap, Index); if Masked and (FMaskColor <> clNone) then if Assigned(AMask) then QPixmap_setMask(Pixmap, AMask) else DefaultMask(Pixmap); QPixmap_resize(Pixmap, Min(FWidth, QPixmap_width(Pixmap)), Min(FHeight, QPixmap_height(Pixmap))); Change; end; procedure TCustomImageList.ReplaceImage(Index: Integer; AImage: QPixmapH; AMask: QBitmapH); var Pixmap: QPixmapH; begin if (Index >= 0) and (Index < Count) then begin QPixmap_destroy(QPixmapH(FPixmapList[Index])); Pixmap := QPixmap_create(AImage); FPixmapList[Index] := Pixmap; if Masked and (FMaskColor <> clNone) then if Assigned(AMask) then QPixmap_setMask(Pixmap, QBitmap_create(AMask)) else DefaultMask(Pixmap); QPixmap_resize(Pixmap, Min(FWidth, QPixmap_width(Pixmap)), Min(FHeight, QPixmap_height(Pixmap))); Change; end; end; procedure TCustomImageList.SetHeight(const Value: Integer); begin if FHeight <> Value then begin if (Value <= 0) then raise EInvalidOperation.CreateRes(@SInvalidImageDimension); FHeight := Value; Clear; Change; end; end; procedure TCustomImageList.SetWidth(const Value: Integer); begin if FWidth <> Value then begin if (Value <= 0) then raise EInvalidOperation.CreateRes(@SInvalidImageDimension); FWidth := Value; Clear; Change; end; end; const ILMagic = Word(Ord('L') shl 8 + Ord('I')); ILVersion = Word($0101); ILC_MASK = $0001; Magic = Integer(Ord('L') shl 24 + Ord('G') shl 16 + Ord('M') shl 8 + Ord('I')); OldVersion = $00010000; Version = $00010001; type TILHeader = packed record usMagic: Word; usVersion: Word; cCurImage: Word; cMaxImage: Word; cGrow: Word; cx: Word; cy: Word; bkcolor: Longint; flags: Word; ovls: array[0..3] of Smallint; end; TOldBMPHeader = packed record Width: Integer; Height: Integer; Count: Integer; end; TBMPHeader = packed record Magic: Integer; Version: Integer; Width: Integer; Height: Integer; Count: Integer; end; procedure TCustomImageList.FillImageList(FullImage, FullMask: TBitmap; CX, CY, MaskOffset, Count: Integer); var AImage: TBitmap; AMask: TBitmap; I, J: Integer; begin AImage := TBitmap.Create; try if FullMask <> nil then AMask := TBitmap.Create else AMask := nil; try AImage.Width := FullImage.Width div CX; AImage.Height := FullImage.Height div CY; try if Assigned(AMask) then begin AMask.Width := FullMask.Width div CX; AMask.Height := FullMask.Height div CY; end; Masked := AMask <> nil; BeginUpdate; for J := 0 to CY - 1 do begin if Count = 0 then Break; for I := 0 to CX - 1 do begin if Count = 0 then Break; AImage.Canvas.Start; try TCanvasAccessor(AImage.Canvas).RequiredState([csHandleValid, csPenValid]); QPainter_drawPixmap(AImage.Canvas.Handle, 0, 0, FullImage.Handle, I * Width, J * Height, Width, Height); finally AImage.Canvas.Stop; end; if Assigned(FullMask) and Assigned(AMask) then begin AMask.Canvas.Start; try TCanvasAccessor(AMask.Canvas).RequiredState([csHandleValid, csPenValid]); QPainter_drawPixmap(AMask.Canvas.Handle, 0, 0, FullMask.Handle, I * Width, J * Height + MaskOffset, Width, Height); AMask.PixelFormat := pf1bit; finally AMask.Canvas.Stop; end; end; Add(AImage, AMask); Dec(Count); end; end; finally EndUpdate; end; finally AMask.Free; end; finally AImage.Free; end; end; procedure TCustomImageList.ReadD2Stream(Stream: TStream); var FullImage, FullMask: TBitmap; Size, Count: Integer; Pos: Int64; begin Stream.ReadBuffer(Size, SizeOf(Size)); Stream.ReadBuffer(Count, SizeOf(Count)); FullImage := TBitmap.Create; try Pos := Stream.Position; FullImage.LoadFromStream(Stream); Stream.Position := Pos + Size; FullMask := TBitmap.Create; try FullMask.LoadFromStream(Stream); FillImageList(FullImage, FullMask, FullImage.Width div Width, FullImage.Height div Height, 0, Count); finally FullMask.Free; end; finally FullImage.Free; end; end; procedure TCustomImageList.ReadD3Stream(Stream: TStream); var ILHeader: TILHeader; Colors, Mask: TBitmap; begin Stream.Read(ILHeader, SizeOf(TILHeader)); if (ILHeader.usMagic <> ILMagic) or (ILHeader.usVersion <> ILVersion) then Exit; Mask := nil; Colors := TBitmap.Create; try Colors.LoadFromStream(Stream); if ILHeader.flags and ILC_MASK <> 0 then begin Mask := TBitmap.Create; Mask.LoadFromStream(Stream); end; FillImageList(Colors, Mask, Colors.Width div ILHeader.cx, Colors.Height div ILHeader.cy, 0, ILHeader.cCurImage); finally Colors.Free; Mask.Free; end; end; procedure TCustomImageList.ReadClxStream(Stream: TStream); var StreamPos: Int64; procedure ReadOldImages(AWidth, AHeight, Count: Integer); var Bitmap: TBitmap; begin Bitmap := TBitmap.Create; try Width := AWidth; Height := AHeight; Masked := True; Bitmap.LoadFromStream(Stream); FillImageList(Bitmap, Bitmap, Bitmap.Width div Width, Bitmap.Height div Height, Height, Count); finally Bitmap.Free; end; end; procedure ReadImages(AWidth, AHeight, Count: Integer); var Colors, Mask: TBitmap; begin Colors := TBitmap.Create; try Width := AWidth; Height := AHeight; Masked := True; Colors.LoadFromStream(Stream); Mask := TBitmap.Create; try Mask.LoadFromStream(Stream); FillImageList(Colors, Mask, Colors.Width div Width, Colors.Height div Height, 0, Count); finally Mask.Free; end; finally Colors.Free; end; end; function TryClxStream: Boolean; var Header: TBMPHeader; begin Result := False; Stream.Position := StreamPos; Stream.Read(Header, SizeOf(Header)); if Header.Magic <> Magic then Exit; if Header.Version = OldVersion then ReadOldImages(Header.Width, Header.Height, Header.Count) else if Header.Version = Version then ReadImages(Header.Width, Header.Height, Header.Count) else Exit; Result := True; end; procedure ReadFtStream; var Header: TOldBMPHeader; begin Stream.Position := StreamPos; Stream.Read(Header, SizeOf(Header)); ReadOldImages(Header.Width, Header.Height, Header.Count); end; begin StreamPos := Stream.Position; if not TryClxStream then ReadFtStream; end; procedure TCustomImageList.ReadData(Stream: TStream); var CheckInt1, CheckInt2, CheckInt3: Integer; CheckByte1, CheckByte2, CheckByte3, CheckByte4: Byte; StreamPos: Int64; begin if Stream.Size = 0 then Exit; StreamPos := Stream.Position; // check stream signature to Stream.Read(CheckInt1, SizeOf(CheckInt1)); // determine a Delphi 2 or Delphi Stream.Read(CheckInt2, SizeOf(CheckInt2)); // 3 imagelist stream. Delphi 2 CheckByte1 := CheckInt1 and $000000ff; // streams can be read, but only CheckByte2 := (CheckInt1 and $0000ff00) shr 8; // Delphi 3 streams will be written Stream.Read(CheckInt3, SizeOf(CheckInt3)); CheckByte3 := CheckInt3 and $000000ff; CheckByte4 := (CheckInt3 and $0000ff00) shr 8; Stream.Position := StreamPos; if (CheckInt1 <> CheckInt2) and (CheckByte1 = $49) and (CheckByte2 = $4C) then ReadD3Stream(Stream) else if (CheckByte3 = $42) and (CheckByte4 = $4D) then ReadD2Stream(Stream) else ReadClxStream(Stream); end; procedure TCustomImageList.WriteData(Stream: TStream); var Colors, Mask: TBitmap; Header: TBMPHeader; I, J, C: Integer; BWidth, BHeight: Integer; procedure CalcDimensions(var AWidth, AHeight: Integer); var X: Double; begin X := Sqrt(Count); AWidth := Trunc(X); if Frac(X) > 0 then Inc(AWidth); X := Count / AWidth; AHeight := Trunc(X); if Frac(X) > 0 then Inc(AHeight); end; begin if Count = 0 then Exit; Colors := TBitmap.Create; try Mask := TBitmap.Create; try Header.Magic := Magic; Header.Version := Version; Header.Width := FWidth; Header.Height := FHeight; Header.Count := Count; Stream.Write(Header, SizeOf(TBMPHeader)); CalcDimensions(BWidth, BHeight); Colors.Width := BWidth * FWidth; Colors.Height := BHeight * FHeight; Mask.Width := Colors.Width; Mask.Height := Colors.Height; Mask.PixelFormat := pf1Bit; C := 0; for I := 0 to BHeight - 1 do begin if C >= Count then Break; for J := 0 to BWidth - 1 do begin if C >= Count then Break; Draw(Colors.Canvas, J * FWidth, I * FHeight, C); Draw(Mask.Canvas, J * FWidth, I * FHeight, C, itMask); Inc(C); end; end; Colors.SaveToStream(Stream); Mask.SaveToStream(Stream); finally Mask.Free; end; finally Colors.Free; end; end; end.
unit MainCrypt; {$mode objfpc}{$H+} interface uses Classes, Controls, CustomCrypt, Dialogs, ExtCtrls, FileUtil, Forms, Graphics, md5, Menus, SQLiteWrap, SysUtils; const // Названия столбцов таблиц SQL_COL_ID_USER = 'ID_USER'; SQL_COL_ID_FRIEND = 'ID_FRIEND'; SQL_COL_AUTH = 'AUTH'; SQL_COL_UUID = 'UUID'; SQL_COL_NICK_NAME = 'NNAME'; SQL_COL_EMAIL = 'EMAIL'; SQL_COL_AVATAR = 'ADATA'; SQL_COL_RESP_DATE = 'RDATE'; SQL_COL_RESP_TIME = 'TDATE'; SQL_COL_XID = 'XID'; SQL_COL_IS_MYMSG = 'ISMY'; SQL_COL_OPEN_KEY = 'OPEN'; SQL_COL_SECRET_KEY = 'SECRET'; SQL_COL_BF_KEY = 'BF'; SQL_COL_ZIP_DATA = 'ZDATA'; SQL_COL_HASH = 'HASH'; SQL_COL_MESSAGE = 'MESSAGE'; // Таблицы SQL_TBL_USERS = 'USERS'; SQL_TBL_FRIENDS = 'FRIENDS'; SQL_TBL_MESSAGES = 'MESSAGES'; // Сообщения о ошибках ERROR_SQL_LOGIN = 'Ошибка аутентификации =('; type TUserEntry = record // Первичные Ключи ID_USER :integer; // Ник, Имя, Фамилия, Эл. почта, Хэш SHA1 от пароля и Ава NickName, Email, HashPwd :string; Avatar :TPicture; end; TFriendEntry = record // Первичные Ключи ID_USER, ID_FRIEND :integer; Auth :boolean; // У каждого друга свой UUID UUID, // Ник, Имя, Фамилия, Эл. почта и Ава NickName, Email :string; Avatar :TPicture; end; TMessageEntry = record // Первичные Ключи ID_USER, ID_FRIEND :integer; // Время отправки / получения Date :TDate; Time :TTime; // Порядковый номер сообщения XID :integer; // True если отправляли мы IsMyMsg :boolean; // Криптографические Ключи OpenKey, SecretKey, BFKey, // Сообщение Message, // Файлы Files :string; end; type { TMainCrypt } TMainCrypt = class(TCustomCrypt) {* Графический компонент + Вход в систему (шифровка\расшифровка полей БД при верном пароле) + Аутентификация (Запрос аутентификация и отлов подтверждения) + Отправка и чтение сообщений + Нужно замутить что-то вроде *} private fLogin :boolean; // Залогинились или не? fUser :TUserEntry; // Информация о себе fPathDb :string; //* ======================================================================== *// SQLDataBase :TSqliteDatabase; SQLTable :TSqliteTable; procedure CreateDataBaseTables; //* ======================================================================== *// function GetFriendEntry(Index :integer) :TFriendEntry; function GetUserEntry(Index: Integer): TUserEntry; procedure SetFriendEntry(Index :integer; AFriend :TFriendEntry); public function TextReadFile(FileName :string) :string; function Base64ReadFile(FileName :string) :string; procedure CreateAndWrite(FilePath, AData :string); public constructor Create (AOwner :TComponent); override; destructor Destroy; override; //* ======================================================================== *// function OpenDB(FileName :string) :boolean; // Создание базы данных function WriteDB(ASQL :string) :boolean; // Запись в базу данных function GetDBFilePath :string; function AssignDB :boolean; //* ======================================================================== *// function GetUserInfo :TUserEntry; // Получение данных пользователя function AddUser(AUser :TUserEntry) :boolean; // Добавление нового пользователя function GetCountUsers :integer; // Количество пользователей function ExistUser (AEMail :string) :boolean; // Проверка на наличие function LoginUser(AUser :TUserEntry) :boolean; overload; virtual; function LoginUser(AEMail, APassword:string) :boolean; overload; virtual; function UpdateUser(AUser :TUserEntry) :boolean; procedure SetUserImage(AUser :integer; AFileName: String); function GetUserImage(AUser :integer; AFileName: String): Boolean; property Users[Index :integer]:TUserEntry read GetUserEntry; //* ======================================================================== *// function AddFriend (AFriend:TFriendEntry) :boolean; virtual; function GetCountFriend :integer; function ExistFriend(AEMail :string) :boolean; function DeleteFriend(Index :integer) :boolean; function UpdateFriend(AFriend :TFriendEntry) :boolean; procedure SetFriendImage(AFriendID: integer; AFileName: String); function GetFriendImage(AFriendID: integer; AFileName: String): Boolean; property Friend[Index :integer]:TFriendEntry read GetFriendEntry write SetFriendEntry; default; //* ======================================================================== *// function AddMessage(AMsg:TMessageEntry) :boolean; function GetCountMessage(AFriendID :integer) :integer; function GetMaxXid(AFriendID :integer) :integer; function GetMessageEntry(Index, AFriendID :integer) :TMessageEntry; // Найти последний открытый ключ товарища function GetLastOpenKey(AFriendID :integer) :string; // Найти свой последний закрытый ключ function GetLastPrivateKey(AFriendID :integer) :string; //* ======================================================================== *// { TODO : Нужно будет перенести функции из MainCrypt в MailCrypt, а именно MakeFirstMail, ReadFirstMail, MakeMail, ReadMail } function MakeFirstMail(AFolder: String; AFriendID :integer): Boolean; function ReadFirstMail(AFolder: String; AFriendID :integer): Boolean; function MakeMail(AFolder, AText, AFiles :string; AFriendID :integer) :boolean; function ReadMail(AFolder:string; AFriendID :integer) :boolean; published property isUserLogin :boolean read fLogin; end; implementation { TMainCrypt } procedure TMainCrypt.CreateAndWrite(FilePath, AData :string); var hFile :TextFile; szBuf: String; ch: Char; begin AssignFile(hFile, FilePath); Rewrite(hFile); szBuf:= ''; for ch in AData do begin if ch = #13 then szBuf+= #10 else szBuf+= ch; end; Write(hFile, szBuf); CloseFile(hFile); end; function TMainCrypt.Base64ReadFile(FileName :string) :string; var hFile :TextFile; Buf :string; begin Result:= ''; Base64Encode(FileName, FileName+'.b64'); AssignFile(hFile, FileName+'.b64'); Reset(hFile); while not EOF(hFile) do begin ReadLn(hFile, Buf); Result:= Result + Buf + #10; end; CloseFile(hFile); DeleteFile(FileName+'.b64'); Result:= trim(Result); end; function TMainCrypt.TextReadFile(FileName :string) :string; var hFile :TextFile; Buf :string; begin Result:= ''; AssignFile(hFile, FileName); Reset(hFile); while not EOF(hFile) do begin ReadLn(hFile, Buf); Result:= Result + Buf + #10; end; CloseFile(hFile); Result:= trim(Result); end; constructor TMainCrypt.Create(AOwner :TComponent); begin inherited Create(AOwner); fPathDb:= ''; fLogin := False; end; function TMainCrypt.OpenDB(FileName :string) :boolean; begin Result:= True; if Assigned(SQLDataBase) then SQLDataBase.Free; try SQLDataBase := TSqliteDatabase.Create (FileName); fPathDb:= FileName; fLogin:= False; CreateDataBaseTables; except Result:= False; end; end; function TMainCrypt.WriteDB(ASQL :string) :boolean; begin Result:= True; try SQLDataBase.ExecSQL(ASQL); except Result:= False; end; end; function TMainCrypt.GetDBFilePath :string; begin Result:= fPathDb; end; function TMainCrypt.AssignDB :boolean; begin Result:= (fPathDb <> ''); end; function TMainCrypt.GetUserInfo :TUserEntry; begin Result:= fUser; end; function TMainCrypt.ExistUser (AEMail :string) :boolean; begin Result := False; try SQLTable := SQLDataBase.GetTable ('SELECT EMAIL FROM USERS'); try while not SQLTable.EOF do begin if AEMail = SQLTable.FieldAsString (SQLTable.FieldIndex['EMAIL']) then Result := True; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.GetUserEntry(Index: Integer): TUserEntry; begin Result.ID_USER:= -1; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_USERS); try while not SQLTable.EOF do begin if (int64(Index)+1) = SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]) then begin Result.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.NickName := SQLTable.FieldAsString (SQLTable.FieldIndex[SQL_COL_NICK_NAME]); Result.Email := SQLTable.FieldAsString (SQLTable.FieldIndex[SQL_COL_EMAIL]); Result.HashPwd := SQLTable.FieldAsString (SQLTable.FieldIndex[SQL_COL_HASH]); end; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.LoginUser(AUser :TUserEntry) :boolean; begin Result := False; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_USERS); try while not SQLTable.EOF do begin if (AUser.Email = SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_EMAIL])) and (MD5Print (MD5String (AUser.HashPwd)) = SQLTable.FieldAsString (SQLTable.FieldIndex[SQL_COL_HASH])) then begin fUser.ID_USER := SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_ID_USER]); fUser.NickName := SQLTable.FieldAsString (SQLTable.FieldIndex[SQL_COL_NICK_NAME]); fUser.Email := AUser.Email; fUser.HashPwd := AUser.HashPwd; Result := True; fLogin := True; end; SQLTable.Next; end; finally SQLTable.Free; end; finally end; end; function TMainCrypt.LoginUser(AEMail, APassword :string) :boolean; var TmpUser :TUserEntry; begin TmpUser.Email:= AEMail; TmpUser.HashPwd:= APassword; Result:= LoginUser(TmpUser); end; function TMainCrypt.UpdateUser(AUser :TUserEntry) :boolean; begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; Result:= False; try SQLTable := SQLDataBase.GetTable ('UPDATE '+SQL_TBL_USERS+' SET ' + SQL_COL_EMAIL + ' = "' + AUser.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AUser.NickName + '"' + ' WHERE ' + SQL_COL_ID_USER+' = '+IntToStr(fUser.ID_USER)); SQLTable.Free; if LoginUser(AUser.Email, fUser.HashPwd) then Result:= True; except raise Exception.Create ('Не могу найти пользователя...'); end; end; procedure TMainCrypt.SetUserImage(AUser: integer; AFileName: String); begin WriteDB('UPDATE '+SQL_TBL_USERS+' SET '+SQL_COL_AVATAR+' = "'+Base64ReadFile(AFileName)+ '" WHERE '+SQL_COL_ID_USER+' = "'+IntToStr(AUser+1)+'";'); end; function TMainCrypt.GetUserImage(AUser: integer; AFileName: String): Boolean; var hFile: TextFile; ch: Char; szBuf, szBase: String; begin try szBase:= ''; Result:= True; SQLTable := SQLDataBase.GetTable ('SELECT * FROM ' + SQL_TBL_USERS + ' WHERE '+SQL_COL_ID_USER+' = "'+IntToStr(AUser+1)+'";'); try AssignFile(hFile, AFileName+'.cr'); ReWrite(hFile); szBase:= SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_AVATAR]); if szBase = '' then begin Result:= False; exit; end; szBuf:= ''; for ch in szBase do begin if ch = #13 then szBuf+= #10 else szBuf+= ch; end; Write(hFile, szBuf); Close(hFile); Base64Decode(AFileName+'.cr', AFileName); finally SQLTable.Free; end; finally DeleteFile(AFileName+'.cr'); end; end; procedure TMainCrypt.SetFriendImage(AFriendID: integer; AFileName: String); begin WriteDB('UPDATE '+SQL_TBL_FRIENDS+' SET '+SQL_COL_AVATAR+' = "'+Base64ReadFile(AFileName)+ '" WHERE '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND+' = "'+IntToStr(AFriendID+1)+'";'); end; function TMainCrypt.GetFriendImage(AFriendID: integer; AFileName: String): Boolean; var hFile: TextFile; ch: Char; szBuf, szBase: String; begin try szBase:= ''; Result:= True; SQLTable := SQLDataBase.GetTable ('SELECT * FROM ' + SQL_TBL_FRIENDS + ' WHERE '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND+' = "'+IntToStr(AFriendID+1)+'";'); try AssignFile(hFile, AFileName+'.cr'); ReWrite(hFile); szBase:= SQLTable.FieldAsString(SQLTable.FieldIndex[SQL_COL_AVATAR]); if szBase = '' then begin Result:= False; exit; end; szBuf:= ''; for ch in szBase do begin if ch = #13 then szBuf+= #10 else szBuf+= ch; end; Write(hFile, szBuf); Close(hFile); Base64Decode(AFileName+'.cr', AFileName); finally SQLTable.Free; end; finally DeleteFile(AFileName+'.cr'); end; end; function TMainCrypt.AddFriend(AFriend :TFriendEntry) :boolean; var FCount :integer; Res :HResult; Uid :TGuid; begin // INSERT INTO FRIENDS VALUES (1, 2, "86AE072A-941F-408A-BD99-4C2E4845C291", "ANNA", "ANNA", "SINICYANA", "ANNA@MAIL.RU", ""); Result:= True; Res := CreateGUID (Uid); if Res = S_OK then begin FCount := GetCountFriend()+1; WriteDB('INSERT INTO ' + SQL_TBL_FRIENDS+'('+ SQL_COL_ID_FRIEND+', '+ SQL_COL_ID_USER+', '+ SQL_COL_UUID+', '+ SQL_COL_NICK_NAME+', '+ SQL_COL_EMAIL+') VALUES("' + IntToStr (FCount) + '", "' + IntToStr (GetUserInfo.ID_USER) + '", ' + '"' + GUIDToString (Uid) + '", ' + '"' + AFriend.NickName + '", ' + '"' + AFriend.EMail + '");'); end else Result:= False; end; function TMainCrypt.GetCountFriend :integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_FRIENDS + ' WHERE '+ SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER)+'";'); try while not SQLTable.EOF do begin Inc (Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create ('Не могу узнать количество Ваших контактов...'); end; end; function TMainCrypt.ExistFriend(AEMail :string) :boolean; var i :integer; begin Result:= False; for i:= 0 to GetCountFriend - 1 do if GetFriendEntry(i).Email = AEMail then Result:= True; end; function TMainCrypt.DeleteFriend(Index :integer) :boolean; var FCount, i :integer; begin Result := False; try FCount:= GetCountFriend; if Index > FCount-1 then exit; if Index < 0 then Exit; // 1. Удалить друга и сообщения WriteDB('DELETE FROM '+SQL_TBL_MESSAGES+' WHERE '+ SQL_COL_ID_FRIEND+' = "'+IntToStr(Index+1) + '" AND '+ SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); WriteDB('DELETE FROM '+SQL_TBL_FRIENDS+' WHERE '+ SQL_COL_ID_FRIEND+' = "'+IntToStr(Index+1) + '" AND '+ SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); // 2. Скорректировать индексы for I:= Index+2 to FCount do begin //WriteDB('UPDATE '+SQL_TBL_MESSAGES+' WHERE '+SQL_COL_ID_FRIEND+' = '+IntToStr(I-1)); WriteDB('UPDATE '+SQL_TBL_FRIENDS+' SET '+SQL_COL_ID_FRIEND+' = '+IntToStr(I-1)+ ' WHERE '+SQL_COL_ID_FRIEND+' = "'+IntToStr(I)+'";'); // Надо проверить на сообщениях WriteDB('UPDATE '+SQL_TBL_MESSAGES+' SET '+SQL_COL_ID_FRIEND+' = '+IntToStr(I-1)+ ' WHERE '+SQL_COL_ID_FRIEND+' = "'+IntToStr(I)+'";'); end; Result := True; except Result := False; end; end; function TMainCrypt.UpdateFriend(AFriend :TFriendEntry) :boolean; begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; // ID Friend меньше на единицу чем в таблице, таким образом от 0 до count - 1 Result:= False; try SQLTable := SQLDataBase.GetTable ('UPDATE '+SQL_TBL_FRIENDS+' SET ' + SQL_COL_EMAIL + ' = "' + AFriend.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AFriend.NickName + '"' + ' WHERE ' + SQL_COL_ID_USER + ' = "' + IntToStr(GetUserInfo.ID_USER) + '" AND ' + SQL_COL_ID_FRIEND + ' = "' + IntToStr(AFriend.ID_FRIEND+1)+'";'); SQLTable.Free; Result:= True; except raise Exception.Create ('Не могу изменить информацию о друге...'); end; end; function TMainCrypt.AddMessage(AMsg :TMessageEntry) :boolean; var szIsMy :string; begin Result:= True; try if AMsg.IsMyMsg then szIsMy:= 'TRUE' else szIsMy:= 'FALSE'; WriteDB('INSERT INTO ' + SQL_TBL_MESSAGES+' VALUES("' + IntToStr (AMsg.ID_FRIEND) + '", "' + IntToStr (GetUserInfo.ID_USER) + '", ' + '"' + DateToStr(AMsg.Date) + '", ' + '"' + TimeToStr(AMsg.Time) + '", ' + '"' + IntToStr(AMsg.XID) + '", ' + '"' + szIsMy + '", ' + '"' + AMsg.OpenKey +'", ' + '"' + AMsg.SecretKey +'", ' + '"' + AMsg.BFKey + '", ' + '"' + AMsg.Message + '", ' + '"' + AMsg.Files + '");'); except Result:= False; end; end; function TMainCrypt.GetCountMessage(AFriendID :integer) :integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_MESSAGES + ' WHERE '+SQL_COL_ID_FRIEND+' = "'+ IntToStr(AFriendID+1) + '" AND '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); try while not SQLTable.EOF do begin Inc (Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create ('Не могу узнать количество сообщений...'); end; end; function TMainCrypt.GetMaxXid(AFriendID :integer) :integer; var aMax :integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_MESSAGES + ' WHERE '+SQL_COL_ID_FRIEND+' = "'+ IntToStr(AFriendID+1) + '" AND '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); try while not SQLTable.EOF do begin aMax:= SQLTable.FieldAsInteger(SQLTable.FieldIndex[SQL_COL_XID]); if aMax > Result then Result:= aMax; SQLTable.Next; end; finally SQLTable.Free; Result:= aMax; end; except raise Exception.Create ('Не могу узнать XID сообщений...'); end; end; function TMainCrypt.AddUser(AUser :TUserEntry) :boolean; var Count :integer; begin if fPathDb = '' then begin Result:= False; Exit; end; Result := True; try Count := GetCountUsers () + 1; if not ExistUser (AUser.Email) then begin WriteDB('INSERT INTO '+SQL_TBL_USERS+' VALUES ("'+IntToStr(Count)+'", "'+ AUser.NickName+'", "'+ AUser.EMail+'", "' + MD5Print(MD5String (AUser.HashPwd)) + '", "");'); end else Result:= False; except Result := False; end; end; function TMainCrypt.GetCountUsers :integer; begin Result := 0; try SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_USERS); try while not SQLTable.EOF do begin Inc (Result, 1); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create ('Не могу узнать количество пользователей программы...'); end; end; procedure TMainCrypt.CreateDataBaseTables; begin // Таблица users SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS '+SQL_TBL_USERS+'('+ SQL_COL_ID_USER+' INTEGER, '+SQL_COL_NICK_NAME+', '+ SQL_COL_EMAIL+', '+SQL_COL_HASH+ ' TEXT, '+SQL_COL_AVATAR+' BLOB, PRIMARY KEY('+SQL_COL_ID_USER+'));'); // Таблица friends SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS '+SQL_TBL_FRIENDS+ '('+SQL_COL_ID_FRIEND+', '+ SQL_COL_ID_USER+' INTEGER, '+SQL_COL_UUID+', ' + SQL_COL_NICK_NAME + ', '+SQL_COL_EMAIL+' TEXT, '+SQL_COL_AVATAR+' BLOB, PRIMARY KEY('+ SQL_COL_ID_FRIEND+'), FOREIGN KEY (' + SQL_COL_ID_USER+ ') REFERENCES '+SQL_TBL_USERS+'('+SQL_COL_ID_USER+'));'); // Таблица messages SQLDataBase.ExecSQL ('CREATE TABLE IF NOT EXISTS ' + SQL_TBL_MESSAGES + '('+SQL_COL_ID_FRIEND+' INTEGER,' + SQL_COL_ID_USER+' INTEGER, '+ SQL_COL_RESP_DATE +', '+SQL_COL_RESP_TIME+' TEXT, '+SQL_COL_XID+' INTEGER, '+ SQL_COL_IS_MYMSG+', '+SQL_COL_OPEN_KEY+', '+SQL_COL_SECRET_KEY+ ','+SQL_COL_BF_KEY+',' + SQL_COL_MESSAGE+', '+SQL_COL_ZIP_DATA+ ' TEXT, FOREIGN KEY ('+SQL_COL_ID_FRIEND+ ') REFERENCES FRIENDS('+SQL_COL_ID_FRIEND+'));'); end; function TMainCrypt.GetMessageEntry(Index, AFriendID :integer) :TMessageEntry; var szIsMy :string; CurrInd :integer; begin Result.ID_FRIEND:= -1; try if (Index < 0) or (Index > GetCountMessage(AFriendID)) then exit; if (AFriendID < 0) or (AFriendID > GetCountFriend) then exit; SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_MESSAGES+ ' WHERE '+SQL_COL_ID_FRIEND+' = "'+ IntToStr(AFriendID+1) + '" AND '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); try CurrInd:= -1; while not SQLTable.EOF do begin Inc(CurrInd, 1); if CurrInd = Index then begin Result.ID_FRIEND:= SQLTable.FieldAsInteger( SQLTable.FieldIndex[SQL_COL_ID_FRIEND]); Result.ID_USER := SQLTable.FieldAsInteger( SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.Date := StrToDate(SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_RESP_DATE])); Result.Time := StrToTime(SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_RESP_TIME])); Result.XID := SQLTable.FieldAsInteger ( SQLTable.FieldIndex[SQL_COL_XID]); szIsMy := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_IS_MYMSG]); Result.IsMyMsg := (szIsMy = 'TRUE'); Result.Message := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_MESSAGE]); Result.Files := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_ZIP_DATA]); Result.OpenKey := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_OPEN_KEY]); Result.SecretKey:= SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_SECRET_KEY]); Result.BFKey := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_BF_KEY]); end; SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create ('Не могу найти сообщение...'); end; end; function TMainCrypt.GetLastOpenKey(AFriendID :integer) :string; var i, Count :integer; Msg :TMessageEntry; begin Result:= ''; Count := GetCountMessage(AFriendID); for i:= Count downto 0 do begin Msg:= GetMessageEntry(i, AFriendID); if not Msg.IsMyMsg then Result:= trim(Msg.OpenKey); end; end; function TMainCrypt.GetLastPrivateKey(AFriendID :integer) :string; var i, Count :integer; Msg :TMessageEntry; begin Result:= ''; Count := GetCountMessage(AFriendID); for i:= Count downto 0 do begin Msg:= GetMessageEntry(i, AFriendID); if Msg.IsMyMsg then Result:= trim(Msg.SecretKey); end; end; function TMainCrypt.MakeFirstMail(AFolder: String; AFriendID :integer): Boolean; var AMsg :TMessageEntry; begin Result:= False; try // Создаём ключи GenRsaKeys(AFolder+'Priv.key', AFolder+'Pub.key', 2048); GenBfPassword(AFolder+'BFKEY.TXT'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND:= AFriendID+1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.Time := Now; AMsg.IsMyMsg := True; AMsg.XID := 1; AMsg.Message := ''; AMsg.OpenKey := TextReadFile(AFolder+'Pub.key'); AMsg.SecretKey:= Base64ReadFile(AFolder+'Priv.key'); AMsg.BFKey := TextReadFile(AFolder+'BFKEY.TXT'); AMsg.Files := ''; AddMessage(AMsg); if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOk, mbCancel], 0) = mrOK then begin DeleteFile(AFolder+'Pub.key'); DeleteFile(AFolder+'Priv.key'); DeleteFile(AFolder+'Priv.key.b64'); DeleteFile(AFolder+'BFKEY.TXT'); end; finally Result:= True; end; end; function TMainCrypt.ReadFirstMail(AFolder: String; AFriendID: integer): Boolean; var AMsg :TMessageEntry; begin Result:= False; try // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND:= AFriendID+1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.Time := Now; AMsg.IsMyMsg := FALSE; AMsg.XID := 1; AMsg.Message := ''; AMsg.OpenKey := TextReadFile(AFolder+'Pub.key'); AMsg.SecretKey:= ''; AMsg.BFKey := TextReadFile(AFolder+'BFKEY.TXT'); AMsg.Files := ''; AddMessage(AMsg); if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOk, mbCancel], 0) = mrOK then begin DeleteFile(AFolder+'Pub.key'); DeleteFile(AFolder+'BFKEY.TXT'); end; finally Result:= True; end; end; function TMainCrypt.MakeMail(AFolder, AText, AFiles :string;AFriendID :integer) :boolean; var StringList :TStringList; i :integer; AMsg :TMessageEntry; begin Result:= False; try // Создаём ключи GenRsaKeys(AFolder+'Priv.key', AFolder+'Pub.key', 2048); GenBfPassword(AFolder+'BFKEY.TXT'); CreateAndWrite(AFolder+'friend.pem', GetLastOpenKey(AFriendID)); // Подготавливаем файлы CreateAndWrite(AFolder+'MSG.TXT', AText); StringList := TStringList.Create; StringList.Text:= AFiles; for i:= 0 to StringList.Count - 1 do begin MakeBz2(StringList[i], AFolder+'FILES.bz2'); //ShowMessage('StringList: ' + StringList[i]); //ShowMessage('Path to BZ: ' + AFolder+'FILES.bz2'); end; // Шифруем все файлы BlowFish, в том числе и свой новый публичный ключ EncryptFileBf(AFolder+'BFKEY.TXT', AFolder+'FILES.bz2', AFolder+'FILES.enc'); EncryptFileBf(AFolder+'BFKEY.TXT', AFolder+'MSG.TXT', AFolder+'MSG.enc'); EncryptFileBf(AFolder+'BFKEY.TXT', AFolder+'Pub.key', AFolder+'Pub.enc'); // Нужно получить последний открытый ключ от друга // из истории переписки и им зашифровать ключ BlowFish EncryptFile(AFolder+'friend.pem', AFolder+'BFKEY.TXT', AFolder+'BFKEY.enc'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND:= AFriendID+1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.Time := Now; AMsg.IsMyMsg := True; AMsg.XID := GetMaxXid(AFriendID) + 1; AMsg.Message := TextReadFile(AFolder+'MSG.TXT'); AMsg.OpenKey := TextReadFile(AFolder+'Pub.key'); AMsg.SecretKey:= Base64ReadFile(AFolder+'Priv.key'); AMsg.BFKey := TextReadFile(AFolder+'BFKEY.TXT'); AMsg.Files := Base64ReadFile(AFolder+'FILES.bz2'); AddMessage(AMsg); // Чистим за собой //ShowMessage('Сча всё удалю'); StringList.Free; if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOk, mbCancel], 0) = mrOK then begin DeleteFile(AFolder+'FILES.bz2.b64'); DeleteFile(AFolder+'MSG.TXT.b64'); DeleteFile(AFolder+'Pub.key.b64'); DeleteFile(AFolder+'Priv.key.b64'); DeleteFile(AFolder+'FILES.bz2'); DeleteFile(AFolder+'MSG.TXT'); DeleteFile(AFolder+'Pub.key'); DeleteFile(AFolder+'Priv.key'); DeleteFile(AFolder+'friend.pem'); DeleteFile(AFolder+'BFKEY.TXT'); end; finally Result:= True; end; end; function TMainCrypt.ReadMail(AFolder :string; AFriendID :integer) :boolean; var AMsg :TMessageEntry; begin Result:= False; try // Создаём ключи CreateAndWrite(AFolder+'MyPrivate.KEY', GetLastPrivateKey(AFriendID)); Base64Decode(AFolder+'MyPrivate.KEY', AFolder+'Private.KEY'); DecryptFile(AFolder+'Private.KEY', AFolder+'BFKEY.enc', AFolder+'BFKEY.TXT'); DecryptFileBf(AFolder+'BFKEY.TXT', AFolder+'FILES.enc', AFolder+'FILES.bz2'); DecryptFileBf(AFolder+'BFKEY.TXT', AFolder+'MSG.enc', AFolder+'MSG.TXT'); DecryptFileBf(AFolder+'BFKEY.TXT', AFolder+'Pub.enc', AFolder+'Pub.key'); // Так то ещё нужно в БД добавить и отправить почтой =( AMsg.ID_FRIEND:= AFriendID+1; AMsg.ID_USER := GetUserInfo.ID_USER; AMsg.Date := Now; AMsg.Time := Now; AMsg.IsMyMsg := False; AMsg.XID := GetMaxXid(AFriendID); AMsg.Message := TextReadFile(AFolder+'MSG.TXT'); AMsg.OpenKey := TextReadFile(AFolder+'Pub.key'); AMsg.SecretKey:= ''; AMsg.BFKey := TextReadFile(AFolder+'BFKEY.TXT'); AMsg.Files := Base64ReadFile(AFolder+'FILES.bz2'); AddMessage(AMsg); // Чистим за собой //ShowMessage('Сча всё удалю'); if MessageDlg('Вопрос', 'Удалить файлы?', mtConfirmation, [mbOk, mbCancel], 0) = mrOK then begin DeleteFile(AFolder+'FILES.bz2.b64'); DeleteFile(AFolder+'MSG.TXT.b64'); DeleteFile(AFolder+'Pub.key.b64'); DeleteFile(AFolder+'Priv.key.b64'); DeleteFile(AFolder+'FILES.bz2'); DeleteFile(AFolder+'MSG.TXT'); DeleteFile(AFolder+'Pub.key'); DeleteFile(AFolder+'Priv.key'); DeleteFile(AFolder+'FriendPub.KEY'); DeleteFile(AFolder+'BFKEY.TXT'); end; finally //Exception.Create('Чтение файлов - не завершено'); Result:= True; end; end; function TMainCrypt.GetFriendEntry(Index :integer) :TFriendEntry; begin Result.ID_FRIEND:= -1; try if (Index < 0) or (Index > GetCountFriend) then exit; SQLTable := SQLDataBase.GetTable ('SELECT * FROM '+SQL_TBL_FRIENDS+ ' WHERE '+SQL_COL_ID_FRIEND+' = "'+ IntToStr(Index+1) + '" AND '+SQL_COL_ID_USER+' = "'+IntToStr(GetUserInfo.ID_USER)+'";'); try while not SQLTable.EOF do begin Result.ID_USER := SQLTable.FieldAsInteger( SQLTable.FieldIndex[SQL_COL_ID_USER]); Result.ID_FRIEND:= SQLTable.FieldAsInteger( SQLTable.FieldIndex[SQL_COL_ID_FRIEND]); Result.Email := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_EMAIL] ); Result.NickName := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_NICK_NAME]); Result.UUID := SQLTable.FieldAsString ( SQLTable.FieldIndex[SQL_COL_UUID] ); SQLTable.Next; end; finally SQLTable.Free; end; except raise Exception.Create ('Не могу найти пользователя...'); end; end; procedure TMainCrypt.SetFriendEntry(Index :integer; AFriend :TFriendEntry); begin // UPDATE USERS SET NNAME = "RCode", FNAME = "Anton" WHERE ID_USER = 2; try SQLTable := SQLDataBase.GetTable ('UPDATE '+SQL_TBL_FRIENDS+' SET ' + SQL_COL_EMAIL + ' = "' + AFriend.Email + '", ' + SQL_COL_NICK_NAME + ' = "' + AFriend.NickName + '", ' + ' WHERE '+SQL_COL_ID_FRIEND+' = "'+ IntToStr(Index+1) + '" AND '+SQL_COL_ID_USER+' = "'+IntToStr(fUser.ID_USER)+'";'); SQLTable.Free; except raise Exception.Create ('Не могу найти пользователя...'); end; end; destructor TMainCrypt.Destroy; begin inherited Destroy; end; end.
unit PeekingChromium; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, uCEFChromium, uCEFResponseFilter, uCEFRequest, uCEFInterfaces, uCEFTypes; type TMyResponseFilter=class; TOnFilterComplete=procedure(AFilter:TMyResponseFilter; aStream:TMemoryStream)of object; { TMyResponseFilter } TMyResponseFilter=class private FFilteredUrl: String; //FComplete: Boolean; fFilter:TCustomResponseFilter; FInit: Boolean; FmimeType: String; FonFilterComplete: TOnFilterComplete; FResourceSize: Integer; procedure DoFilter(Sender: TObject; data_in: Pointer; data_in_size: NativeUInt; var data_in_read: NativeUInt; data_out: Pointer; data_out_size: NativeUInt; var data_out_written: NativeUInt; var aResult: TCefResponseFilterStatus); procedure SetComplete(AValue: Boolean); procedure SetFilteredUrl(AValue: String); procedure SetInit(AValue: Boolean); procedure SetmimeType(AValue: String); procedure SetonFilterComplete(AValue: TOnFilterComplete); procedure SetResourceSize(AValue: Integer); protected FStream:TMemoryStream; //FFilterUri:String; //FRequest:tcefreq FComplete:Boolean; function InitFilter: Boolean; function Filter(data_in: Pointer; data_in_size: NativeUInt; var data_in_read: NativeUInt; data_out: Pointer; data_out_size: NativeUInt; var data_out_written: NativeUInt ): TCefResponseFilterStatus; procedure doFilterComplete(); public constructor Create; destructor Destroy; override; procedure Execute(); property ResourceSize:Integer read FResourceSize write SetResourceSize; property Init:Boolean read FInit write SetInit; property Complete:Boolean read FComplete write SetComplete; property onFilterComplete:TOnFilterComplete read FonFilterComplete write SetonFilterComplete; property FilteredUrl:String read FFilteredUrl write SetFilteredUrl; property mimeType:String read FmimeType write SetmimeType; property ResponseFilter:TCustomResponseFilter read fFilter; end; { TPeekingChromium } TPeekingChromium = class(TChromium) private FonFilterCompleted: TOnFilterComplete; //fFilter:TCustomResponseFilter; //fStream:TMemoryStream; FResponseFilterList:TList; procedure SetonFilterCompleted(AValue: TOnFilterComplete); procedure checkResponse(aResponse:ICefResponse; aFilter:TMyResponseFilter); protected function GetMyResponseFilter(aURL:String):TMyResponseFilter; function doOnBeforeResourceLoad(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback ): TCefReturnValue; override; function doOnResourceResponse(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean; override; procedure doOnResourceLoadComplete(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64); override; public constructor Create(AOwner: TComponent); override; function AddFilter(aUrl:String):Integer; procedure GetResourceResponseFilter(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var aResponseFilter: ICefResponseFilter); published property onFilterCompleted:TOnFilterComplete read FonFilterCompleted write SetonFilterCompleted; end; procedure Register; implementation uses uregexpr, Math, uCEFStringMultimap; procedure Register; begin {$I peekingchromium_icon.lrs} RegisterComponents('HKScrappingComponent',[TPeekingChromium]); end; { TMyResponseFilter } procedure TMyResponseFilter.SetResourceSize(AValue: Integer); begin if FResourceSize=AValue then Exit; FResourceSize:=AValue; end; procedure TMyResponseFilter.SetComplete(AValue: Boolean); begin if FComplete=AValue then Exit; FComplete:=AValue; end; procedure TMyResponseFilter.DoFilter(Sender: TObject; data_in: Pointer; data_in_size: NativeUInt; var data_in_read: NativeUInt; data_out: Pointer; data_out_size: NativeUInt; var data_out_written: NativeUInt; var aResult: TCefResponseFilterStatus); begin Filter(data_in, data_in_size, data_in_read, data_out, data_out_size, data_out_written); end; procedure TMyResponseFilter.SetFilteredUrl(AValue: String); begin if FFilteredUrl=AValue then Exit; FFilteredUrl:=AValue; end; procedure TMyResponseFilter.SetInit(AValue: Boolean); begin if FInit=AValue then Exit; FInit:=AValue; end; procedure TMyResponseFilter.SetmimeType(AValue: String); begin if FmimeType=AValue then Exit; FmimeType:=AValue; end; procedure TMyResponseFilter.SetonFilterComplete(AValue: TOnFilterComplete); begin if FonFilterComplete=AValue then Exit; FonFilterComplete:=AValue; end; function TMyResponseFilter.InitFilter: Boolean; begin //Result:=inherited InitFilter; Result:=True;//fFilter.InitFilter; end; function TMyResponseFilter.Filter(data_in: Pointer; data_in_size: NativeUInt; var data_in_read: NativeUInt; data_out: Pointer; data_out_size: NativeUInt; var data_out_written: NativeUInt): TCefResponseFilterStatus; begin try if FInit then begin if data_in=nil then begin data_in_read := 0; data_out_written := 0; Result := RESPONSE_FILTER_DONE; if (not FComplete) and (FStream.Size>0) and (FStream.Size=FResourceSize) then begin doFilterComplete(); end; end else begin if data_out<>nil then begin data_out_written := min(data_in_size, data_out_size); if (data_out_written > 0) then Move(data_in^, data_out^, data_out_written); end; if (data_in_size > 0) then data_in_read := FStream.Write(data_in^, data_in_size); if not(Complete) and (FResourceSize <> -1) and (FResourceSize = FStream.Size) then begin //FRscCompleted := PostMessage(Handle, STREAM_COPY_COMPLETE, 0, 0); FComplete:=True; doFilterComplete(); Result := RESPONSE_FILTER_DONE; end else Result := RESPONSE_FILTER_NEED_MORE_DATA; end; end; except on e : exception do begin Result := RESPONSE_FILTER_ERROR; end; end; end; procedure TMyResponseFilter.doFilterComplete(); begin if Assigned(onFilterComplete) then onFilterComplete(Self, FStream); end; constructor TMyResponseFilter.Create; begin //inherited Create; FStream:=TMemoryStream.Create; end; destructor TMyResponseFilter.Destroy; begin FStream.Free; inherited Destroy; end; procedure TMyResponseFilter.Execute(); begin Init:=True; Complete:=False; FStream.Clear; fFilter:=TCustomResponseFilter.Create; fFilter.OnFilter:=@DoFilter; end; { TPeekingChromium } procedure TPeekingChromium.SetonFilterCompleted(AValue: TOnFilterComplete); begin if FonFilterCompleted=AValue then Exit; FonFilterCompleted:=AValue; end; procedure TPeekingChromium.checkResponse(aResponse: ICefResponse; aFilter: TMyResponseFilter); var TempContentLength, TempContentEncoding : string; TempLen : integer; begin TempContentEncoding := trim(lowercase(aResponse.GetHeaderByName('Content-Encoding'))); aFilter.mimeType:=aResponse.MimeType; if (length(TempContentEncoding) > 0) and (TempContentEncoding <> 'identity') then begin // We can't use this information because Content-Length has the // compressed length but the OnFilter event has uncompressed data. aFilter.ResourceSize:=-1; end else begin TempContentLength := trim(aResponse.GetHeaderByName('Content-Length')); if (length(TempContentLength) > 0) and TryStrToInt(TempContentLength, TempLen) and (TempLen > 0) then begin aFilter.ResourceSize:=-1; end end; end; function TPeekingChromium.GetMyResponseFilter(aURL: String): TMyResponseFilter; var aaa, ct: Integer; temp: TMyResponseFilter; reg:TRegExpr; fltUrl: String; begin reg:=TRegExpr.Create; reg.ModifierG:=True; reg.ModifierI:=True; Result:=Nil; ct:=FResponseFilterList.Count; try for aaa:=0 to ct-1 do begin temp:=TMyResponseFilter(FResponseFilterList[aaa]); fltUrl:=temp.FilteredUrl; if fltUrl='' then Continue; reg.Expression:=fltUrl; if reg.Exec(aURL)then begin Result:=temp; Break; end; end; finally reg.Free; end; end; procedure TPeekingChromium.GetResourceResponseFilter( const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var aResponseFilter: ICefResponseFilter); var temp: TMyResponseFilter; uri: string; //tempLn: ustring; begin uri:=request.Url; temp:=GetMyResponseFilter(uri); if temp<>nil then begin checkResponse(response, temp); temp.Execute(); aResponseFilter:=temp.ResponseFilter; end; end; function TPeekingChromium.doOnBeforeResourceLoad(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue; var TempOldMap, TempNewMap : ICefStringMultimap; i : NativeUInt; TempReplaced : boolean; begin Result:=inherited doOnBeforeResourceLoad(aBrowser, frame, request, callback); try // We replace the Accept-Encoding HTTP header to request uncompressed resources. // If the server sends uncompressed resources it should be easier to handle the // end of the resource reception because we may know its length. TempNewMap := TCefStringMultimapOwn.Create; TempOldMap := TCefStringMultimapOwn.Create; request.GetHeaderMap(TempOldMap); TempReplaced := False; i := 0; while (i < TempOldMap.Size) do begin if (CompareText(TempOldMap.Key[i], 'Accept-Encoding') = 0) then begin TempNewMap.Append('Accept-Encoding', 'identity'); TempReplaced := True; end else TempNewMap.Append(TempOldMap.Key[i], TempOldMap.Value[i]); inc(i); end; if not(TempReplaced) then TempNewMap.Append('Accept-Encoding', 'identity'); request.SetHeaderMap(TempNewMap); finally TempNewMap := nil; TempOldMap := nil; end; end; function TPeekingChromium.doOnResourceResponse(const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean; var temp: TMyResponseFilter; uri: string; begin uri:=request.Url; temp:=GetMyResponseFilter(uri); if temp<>nil then begin checkResponse(response, temp); temp.mimeType:=response.MimeType; end; Result:=inherited doOnResourceResponse(browser, frame, request, response); end; procedure TPeekingChromium.doOnResourceLoadComplete( const aBrowser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64); var temp: TMyResponseFilter; uri: ustring; begin uri:=request.Url; temp:=GetMyResponseFilter(uri); if temp<>nil then begin //checkResponse(response, temp); if not temp.Complete then begin temp.Complete:=true; temp.doFilterComplete(); end; end; inherited doOnResourceLoadComplete(browser, frame, request, response, status, receivedContentLength); end; constructor TPeekingChromium.Create(AOwner: TComponent); begin inherited Create(AOwner); FResponseFilterList:=TList.Create; end; function TPeekingChromium.AddFilter(aUrl: String): Integer; var aaa:Integer; Found: Boolean; temp: TMyResponseFilter; begin Result:=-1; if aUrl='' then Exit; Found:=false; for aaa:=0 to FResponseFilterList.Count-1 do begin if TMyResponseFilter(FResponseFilterList[aaa]).FilteredUrl=aUrl then begin Found:=True; break; end; end; if NOT Found then begin temp:=TMyResponseFilter.Create; temp.FilteredUrl:=aUrl; temp.onFilterComplete:=onFilterCompleted; FResponseFilterList.Add(temp); end; end; end.
unit dynamic_array_functions; interface uses SysUtils, DateUtils; const N1 = 1024; N2 = 2048; N3 = 4096; type TIArray = array of integer; TIMatrix = array of array of integer; function BubbleSort(var A: TIArray): TIArray; function BubbleSortReverse(var A: TIArray): TIArray; function GetRandomArray(const n: integer): TIArray; procedure OutputArray(A: TIArray); procedure Test(const j: integer); function TestT(const lengths: TIArray): TIMatrix; function DeltaTime(var A: TIArray): Integer; // function TestRandomSorted(arr: TIArray): TIArray; // function TestSorted(arr: TIArray): TIArray; implementation function BubbleSort(var A: TIArray): TIArray; var i, j, n, t : Integer; begin n := High(A); for i := 0 to n-1 do for j := 0 to n-i-1 do if A[j] > A[j+1] then begin t := A[j]; A[j] := A[j+1]; A[j+1] := t; end; BubbleSort := A; end; function BubbleSortReverse(var A: TIArray): TIArray; var i, j, n, t : Integer; begin n := High(A); for i := 0 to n-1 do for j := 0 to n-i-1 do if A[j] < A[j+1] then begin t := A[j]; A[j] := A[j+1]; A[j+1] := t; end; BubbleSortReverse := A; end; function GetRandomArray(const n: integer): TIArray; var i: Integer; A: TIArray; begin randomize; SetLength(A, n); for i := 0 to n-1 do A[i] := Random(1000); GetRandomArray := A; end; procedure OutputArray(A: TIArray); var i, n: Integer; begin n := High(A); for i := 0 to n do Write(A[i], ' '); Writeln; end; function DeltaTime(var A: TIArray): Integer; var start: TDateTime; dt: integer; begin start := Time; BubbleSort(A); dt := MilliSecondsBetween(start, Time); DeltaTime := dt; end; function TestT(const lengths: TIArray): TIMatrix; var results: TIMatrix; res: TIArray; arr: TIArray; i, l: integer; begin SetLength(res, 3); SetLength(results, 3); for i := 0 to High(results) do SetLength(results[i], 3); Writeln(Length(results)); for i := 0 to Length(lengths)-1 do Writeln('i: ', i); l := lengths[i]; arr := GetRandomArray(l); arr := BubbleSort(arr); res[0] := DeltaTime(arr); arr := GetRandomArray(l); arr := BubbleSortReverse(arr); res[2] := DeltaTime(arr); results[i] := res; Writeln('Length: ', Length(res)); OutputArray(res); TestT := results; end; procedure Test(const j: integer); var arrMin, arrAv, arrMax: TIArray; start, dt: TDateTime; begin arrMin := getRandomArray(N1); arrAv := getRandomArray(N2); arrMax := getRandomArray(N3); arrMax := BubbleSort(arrMax); arrAv := BubbleSort(arrAv); arrMin := BubbleSort(arrMin); write(' ', j, ' | '); start := Time; BubbleSort(arrMin); dt := Time; write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrAv); dt := Time; write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrMax); dt := Time; write(MilliSecondsBetween(start,dt), ' | '); arrMax := BubbleSortReverse(arrMax); arrAv := BubbleSortReverse(arrAv); arrMin := BubbleSortReverse(arrMin); start := Time; BubbleSort(arrMin); dt := Time; write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrAv); dt := Time; if MilliSecondsBetween(start,dt) < 10 then write(MilliSecondsBetween(start,dt), ' ') else write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrMax); dt := Time; write(MilliSecondsBetween(start,dt), ' | '); arrMin := getRandomArray(N1); arrAv := getRandomArray(N2); arrMax := getRandomArray(N3); start := Time; BubbleSort(arrMin); dt := Time; write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrAv); dt := Time; if MilliSecondsBetween(start,dt) < 10 then write(MilliSecondsBetween(start,dt), ' ') else write(MilliSecondsBetween(start,dt), ' '); start := Time; BubbleSort(arrMax); dt := Time; write(MilliSecondsBetween(start,dt), ' '); writeln; end; // function TestRandomSorted(arr: TIArray): TIArray; // var // time: Integer; // begin // time := DeltaTime(arr); // TestRandomSorted := time; // end; // function TestSorted(arr: TIArray): TIArray; // var // time: Integer; // begin // arr := BubbleSort(arr); // time := DeltaTime(arr); // TestSorted := time; // end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileTGA<p> Graphic engine friendly loading of TGA image. <b>History : </b><font size=-1><ul> <li>04/04/11 - Yar - Creation </ul><p> } unit GLFileTGA; interface {.$I GLScene.inc} uses System.Classes, System.SysUtils, GLCrossPlatform, OpenGLTokens, GLContext, GLGraphics, GLTextureFormat, GLApplicationFileIO; type // TGLTGAImage // TGLTGAImage = class(TGLBaseImage) public { Public Declarations } procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; class function Capabilities: TDataFileCapabilities; override; procedure AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: boolean; const intFormat: TGLInternalFormat); reintroduce; end; implementation type // TTGAHeader // TTGAFileHeader = packed record IDLength: Byte; ColorMapType: Byte; ImageType: Byte; ColorMapOrigin: Word; ColorMapLength: Word; ColorMapEntrySize: Byte; XOrigin: Word; YOrigin: Word; Width: Word; Height: Word; PixelSize: Byte; ImageDescriptor: Byte; end; // ReadAndUnPackRLETGA24 // procedure ReadAndUnPackRLETGA24(stream: TStream; destBuf: PAnsiChar; totalSize: Integer); type TRGB24 = packed record r, g, b: Byte; end; PRGB24 = ^TRGB24; var n: Integer; color: TRGB24; bufEnd: PAnsiChar; b: Byte; begin bufEnd := @destBuf[totalSize]; while destBuf < bufEnd do begin stream.Read(b, 1); if b >= 128 then begin // repetition packet stream.Read(color, 3); b := (b and 127) + 1; while b > 0 do begin PRGB24(destBuf)^ := color; Inc(destBuf, 3); Dec(b); end; end else begin n := ((b and 127) + 1) * 3; stream.Read(destBuf^, n); Inc(destBuf, n); end; end; end; // ReadAndUnPackRLETGA32 // procedure ReadAndUnPackRLETGA32(stream: TStream; destBuf: PAnsiChar; totalSize: Integer); type TRGB32 = packed record r, g, b, a: Byte; end; PRGB32 = ^TRGB32; var n: Integer; color: TRGB32; bufEnd: PAnsiChar; b: Byte; begin bufEnd := @destBuf[totalSize]; while destBuf < bufEnd do begin stream.Read(b, 1); if b >= 128 then begin // repetition packet stream.Read(color, 4); b := (b and 127) + 1; while b > 0 do begin PRGB32(destBuf)^ := color; Inc(destBuf, 4); Dec(b); end; end else begin n := ((b and 127) + 1) * 4; stream.Read(destBuf^, n); Inc(destBuf, n); end; end; end; // LoadFromFile // procedure TGLTGAImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(fileName) then begin fs := CreateFileStream(fileName, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; // SaveToFile // procedure TGLTGAImage.SaveToFile(const filename: string); var fs: TStream; begin fs := CreateFileStream(fileName, fmOpenWrite or fmCreate); try SaveToStream(fs); finally fs.Free; end; ResourceName := filename; end; // LoadFromStream // procedure TGLTGAImage.LoadFromStream(stream: TStream); var LHeader: TTGAFileHeader; y, rowSize, bufSize: Integer; verticalFlip: Boolean; unpackBuf: PAnsiChar; Ptr: PByte; begin stream.Read(LHeader, Sizeof(TTGAFileHeader)); if LHeader.ColorMapType <> 0 then raise EInvalidRasterFile.Create('ColorMapped TGA unsupported'); UnMipmap; FLOD[0].Width := LHeader.Width; FLOD[0].Height := LHeader.Height; FLOD[0].Depth := 0; case LHeader.PixelSize of 24: begin FColorFormat := GL_BGR; FInternalFormat := tfRGB8; FElementSize := 3; end; 32: begin FColorFormat := GL_RGBA; FInternalFormat := tfRGBA8; FElementSize := 4; end; else raise EInvalidRasterFile.Create('Unsupported TGA ImageType'); end; FDataType := GL_UNSIGNED_BYTE; FCubeMap := False; FTextureArray := False; ReallocMem(FData, DataSize); rowSize := GetWidth * FElementSize; verticalFlip := ((LHeader.ImageDescriptor and $20) <> 1); if LHeader.IDLength > 0 then stream.Seek(LHeader.IDLength, soFromCurrent); case LHeader.ImageType of 2: begin // uncompressed RGB/RGBA if verticalFlip then begin Ptr := PByte(FData); Inc(Ptr, rowSize * (GetHeight - 1)); for y := 0 to GetHeight - 1 do begin stream.Read(Ptr^, rowSize); Dec(Ptr, rowSize); end; end else stream.Read(FData^, rowSize * GetHeight); end; 10: begin // RLE encoded RGB/RGBA bufSize := GetHeight * rowSize; GetMem(unpackBuf, bufSize); try // read & unpack everything if LHeader.PixelSize = 24 then ReadAndUnPackRLETGA24(stream, unpackBuf, bufSize) else ReadAndUnPackRLETGA32(stream, unpackBuf, bufSize); // fillup bitmap if verticalFlip then begin Ptr := PByte(FData); Inc(Ptr, rowSize * (GetHeight - 1)); for y := 0 to GetHeight - 1 do begin Move(unPackBuf[y * rowSize], Ptr^, rowSize); Dec(Ptr, rowSize); end; end else Move(unPackBuf[rowSize * GetHeight], FData^, rowSize * GetHeight); finally FreeMem(unpackBuf); end; end; else raise EInvalidRasterFile.CreateFmt('Unsupported TGA ImageType %d', [LHeader.ImageType]); end; end; // SaveToStream // procedure TGLTGAImage.SaveToStream(stream: TStream); begin {$MESSAGE Hint 'TGLTGAImage.SaveToStream not yet implemented' } end; // AssignFromTexture // procedure TGLTGAImage.AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: boolean; const intFormat: TGLInternalFormat); begin {$MESSAGE Hint 'TGLTGAImage.AssignFromTexture not yet implemented' } end; class function TGLTGAImage.Capabilities: TDataFileCapabilities; begin Result := [dfcRead {, dfcWrite}]; end; initialization { Register this Fileformat-Handler with GLScene } RegisterRasterFormat('tga', 'TARGA Image File', TGLTGAImage); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Tether.TCPProtocol; interface {$SCOPEDENUMS ON} uses System.Classes, System.SysUtils, System.Generics.Collections, System.Tether.Manager, System.Tether.Comm; type TTetheringTCPProtocol = class(TTetheringProtocol) private type TConnectionPair = TPair<string, TTetheringCustomComm>; public const ProtocolID = 'TCP'; // do not localize private const ReadTimeout = 200; private FTCPClient: TTetheringCustomComm; [Weak] FTCPResponseClient: TTetheringCustomComm; FTCPServer: TTetheringCustomServerComm; FImplementationID: string; FActiveTarget: string; FAsClient: Boolean; procedure DoOnExecute(const AConnection: TTetheringCustomComm); procedure DoOnConnect(const AConnection: TTetheringCustomComm); procedure DoOnDisconnect(const AConnection: TTetheringCustomComm); procedure StartServerSide; protected function GetProtocolType: TTetheringProtocolType; override; function GetIsConnected: Boolean; override; procedure DoSendData(const AData: TBytes); override; function DoReceiveData: TBytes; override; /// <summary>Function to Receive a stream.</summary> function DoReceiveStream(const AStream: TStream): Boolean; override; /// <summary>Function to Send a stream.</summary> function DoSendStream(const AStream: TStream): Boolean; override; public constructor Create(const AnAdapter: TTetheringAdapter; AsClient: Boolean = False); override; destructor Destroy; override; procedure StopCommunication; override; procedure StartCommunication; override; function Connect(const AProfile: TTetheringConnection): Boolean; override; procedure Disconnect; override; function GetConnectionString(const ManagerConnectionString: string): string; override; class function CreateInstance(const AnAdapter: TTetheringAdapter; AsClient: Boolean): TTetheringProtocol; override; end; implementation uses System.Tether.Consts; type TFakeProfile = class(TTetheringProfile); TFakeAdapter = class(TTetheringAdapter); { TTetheringTCPProtocol } function TTetheringTCPProtocol.Connect(const AProfile: TTetheringConnection): Boolean; const OkResponse = 'Ok'; // do not localize var SepPos: Integer; ClientToken: string; ManagerID: string; RandomString: string; ServerToken: string; begin SepPos := AProfile.ConnectionString.IndexOf(TetheringConnectionSeparator); if SepPos > 0 then begin Result := FTCPClient.Connect(AProfile.ConnectionString); if Result then begin RandomString := ReceiveStringData; if RandomString <> OkResponse then begin ManagerID := FAdapter.Manager.Identifier; SendData(ManagerID); ManagerID := ReceiveStringData; ClientToken := GenerateToken(ManagerID, RandomString); SendData(TEncoding.UTF8.GetBytes(ClientToken)); ServerToken := ReceiveStringData; if ServerToken <> OkResponse then begin FTCPClient.Disconnect; Result := False; end; end; end; end else Result := False; end; procedure TTetheringTCPProtocol.StopCommunication; begin try if (FTCPClient <> nil) and FTCPClient.Connected then FTCPClient.Disconnect; except end; if not FAsClient then begin if (FTCPServer <> nil) then begin try FTCPServer.StopServer; except end; FreeAndNil(FTCPServer); end; end; end; procedure TTetheringTCPProtocol.StartCommunication; begin if FTCPClient = nil then begin FTCPClient := FAdapter.GetClientPeer(ProtocolID); FTCPClient.OnAfterReceiveData := OnAfterReceiveData; FTCPClient.OnBeforeSendData := OnBeforeSendData; FTCPClient.OnAfterReceiveStream := OnAfterReceiveStream; FTCPClient.OnBeforeSendStream := OnBeforeSendStream; FTCPResponseClient := FTCPClient; end; if not FAsClient then begin if (FTCPServer = nil) or ((FTCPServer <> nil) and not FTCPServer.Active) then StartServerSide; end; end; constructor TTetheringTCPProtocol.Create(const AnAdapter: TTetheringAdapter; AsClient: Boolean = False); begin inherited; FAdapter := AnAdapter; FImplementationID := ''; FAsClient := AsClient; end; class function TTetheringTCPProtocol.CreateInstance(const AnAdapter: TTetheringAdapter; AsClient: Boolean): TTetheringProtocol; begin Result := TTetheringTCPProtocol.Create(AnAdapter, AsClient); end; destructor TTetheringTCPProtocol.Destroy; begin FTCPResponseClient := nil; try if (FTCPClient <> nil) and FTCPClient.Connected then FTCPClient.Disconnect; except end; FTCPCLient.Free; if (not FAsClient) and (FTCPServer <> nil) then begin try FTCPServer.StopServer; except end; FTCPServer.Free; end; inherited; end; procedure TTetheringTCPProtocol.Disconnect; begin FTCPClient.Disconnect; end; procedure TTetheringTCPProtocol.DoOnConnect(const AConnection: TTetheringCustomComm); const OkResponse = 'Ok'; // do not localize ErrorResponse = 'Error'; // do not localize var ServerToken, ClientToken: string; RandomString: string; ClientManagerID: string; ServerManagerID: string; function InternalReadData: string; begin Result := TEncoding.UTF8.GetString(AConnection.ReadData); end; procedure InternalSendData(const StrData: string); begin AConnection.WriteData(TEncoding.UTF8.GetBytes(StrData)); end; begin if FAdapter.Manager.Password = '' then InternalSendData(OkResponse) else begin RandomString := GetRandomString; InternalSendData(RandomString); ClientManagerID := InternalReadData; ServerToken := GenerateToken(ClientManagerID, RandomString); ServerManagerID := FAdapter.Manager.Identifier; InternalSendData(ServerManagerID); ClientToken := InternalReadData; if (ServerToken <> ClientToken) or (ClientToken = '') then begin InternalSendData(ErrorResponse); AConnection.Disconnect; end else InternalSendData(OkResponse); end; end; procedure TTetheringTCPProtocol.DoOnDisconnect(const AConnection: TTetheringCustomComm); begin // Do nothing... end; procedure TTetheringTCPProtocol.DoOnExecute(const AConnection: TTetheringCustomComm); var Buffer: TBytes; begin Buffer := AConnection.ReadData; if Length(Buffer) > 0 then begin if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Protocol) then TFakeAdapter.Log('Protocol Received: <' + TEncoding.UTF8.GetString(Buffer) + '>'); FTCPResponseClient := AConnection; TFakeProfile(FProfile).DoOnIncomingData(Self, Buffer); FTCPResponseClient := FTCPClient; end; end; procedure TTetheringTCPProtocol.DoSendData(const AData: TBytes); begin if FTCPResponseClient <> nil then try FTCPResponseClient.WriteData(AData); except if FTCPResponseClient.ReConnect then FTCPResponseClient.WriteData(AData); end; if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Protocol) then TFakeAdapter.Log('Protocol Sent: <' + TEncoding.UTF8.GetString(AData) + '>'); end; function TTetheringTCPProtocol.DoSendStream(const AStream: TStream): Boolean; var LOldPos: Int64; TmpStream: TMemoryStream; begin Result := True; try TmpStream := TMemoryStream.Create; try TMonitor.Enter(AStream); LOldPos := AStream.Position; try AStream.Position := 0; TmpStream.CopyFrom(AStream, AStream.Size); finally AStream.Position := LOldPos; TMonitor.Exit(AStream); end; TmpStream.Position := 0; FTCPResponseClient.WriteStream(TmpStream); finally TmpStream.Free; end; except Result := False; end; end; function TTetheringTCPProtocol.GetConnectionString(const ManagerConnectionString: string): string; begin Result := ManagerConnectionString.Substring(0, ManagerConnectionString.IndexOf(TetheringConnectionSeparator)) + TetheringConnectionSeparator + FActiveTarget; end; function TTetheringTCPProtocol.GetProtocolType: TTetheringProtocolType; begin Result := ProtocolID; end; function TTetheringTCPProtocol.GetIsConnected: Boolean; begin Result := (FTCPClient <> nil) and FTCPClient.Connected; end; function TTetheringTCPProtocol.DoReceiveStream(const AStream: TStream): Boolean; begin Result := True; try FTCPResponseClient.ReadStream(AStream); AStream.Position := 0; except Result := False; end; end; function TTetheringTCPProtocol.DoReceiveData: TBytes; begin Result := FTCPResponseClient.ReadData; end; procedure TTetheringTCPProtocol.StartServerSide; var I: Integer; begin if FTCPServer = nil then begin FTCPServer := FAdapter.GetServerPeer(ProtocolID); FTCPServer.OnExecute := DoOnExecute; FTCPServer.OnConnect := DoOnConnect; FTCPServer.OnDisconnect := DoOnDisconnect; FTCPServer.OnAfterReceiveData := OnAfterReceiveData; FTCPServer.OnBeforeSendData := OnBeforeSendData; FTCPServer.OnAfterReceiveStream := OnAfterReceiveStream; FTCPServer.OnBeforeSendStream := OnBeforeSendStream; end else try FTCPServer.StopServer; except end; for I := 0 to FAdapter.MaxConnections - 1 do begin FTCPServer.Target := FAdapter.GetTargetConnection(I, 0); FActiveTarget := FTCPServer.Target; if FTCPServer.StartServer then Break; end; if not FTCPServer.Active then raise ETetheringException.CreateFmt(SProtocolCreation, [TTetheringTCPProtocol.ProtocolID]); end; initialization TTetheringProtocols.RegisterProtocol(TTetheringTCPProtocol, TTetheringTCPProtocol.ProtocolID); finalization TTetheringProtocols.UnRegisterProtocol(TTetheringTCPProtocol.ProtocolID); end.
unit World; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseTypes, Voxel, Economy, GL, GLext, Entities, Character; type spatial = longword; { tWorld } tWorld = class Voxels: tVoxelContainer; //RootVoxel: tVoxel; //absolute Voxels.RootVoxel; Hubs: array of tEconomicHub; Vicinity: tCharContainer; Vertices: array of rVec3; Indices: array of GLUInt; //IndexCount: array of GLsizei; //for multidraw // IndexOffset: array of pointer; Counter: longword; VertexBuffer, IndexBuffer: GLUInt; VoxelCount: longword; Extent: single; WorldSeed: longword; Wireframe: boolean; Camera: tCamera; UI3DListID, WireFrameListID: longword; private procedure GenerateHubs; public constructor Load(FileName: string); constructor LoadHM(FileName: string); constructor CreateNew(Seed: longword); function GetVoxel(x, y, z: single; c1, c2: longword; MaxOrder: longword = 0): tVoxel; function Generate(Voxel: tVoxel): longint; procedure ListVoxel(Voxel: tVoxel; cx, cy, cz: single); procedure PassVoxels; procedure Render; procedure Save(FileName: string); destructor Destroy; override; end; implementation uses math, Utility; const HubVoxelOrder = 3; HubCount = 2; { tWorld } procedure tWorld.GenerateHubs; var i, j: integer; cv: tVoxel; begin for i:= 1 to HubCount do begin cv:= Voxels.RootVoxel; while cv.Order <> HubVoxelOrder do begin cv:= cv.Children[eVoxelPos(srand(integer(high(eVoxelPos)), WorldSeed + Counter))]; if cv = nil then cv:= Voxels.RootVoxel; inc(Counter); end; setlength(Hubs, length(Hubs) + 1); Hubs[high(Hubs)]:= tEconomicHub.Create(cv); end; end; constructor tWorld.Load(FileName: string); var Result: integer; begin Voxels:= tVoxelContainer.Create; Result:= Voxels.Load(FileName, lWhole); if Result <> 0 then WriteLog(emNoF); {with Voxels do begin RootVoxel:= LoadBlock(0, DefaultBlockDepth); end; } end; constructor tWorld.LoadHM(FileName: string); var fs: tFileStream; i, j, k, l: longword; hm: array of array of single; d: single; begin Voxels:= tVoxelContainer.Create; VoxelFidelity:= 10; Extent:= MinVoxelDim * power(2, VoxelFidelity); l:= round(power(2, VoxelFidelity)); VoxelCount:= l * l; setlength(hm, l, l); setlength(Vertices, l * l); setlength(Indices, (l - 1) * (l - 1) * 6); {setlength(IndexCount, l); setlength(IndexOffset, l); for i:= 0 to high(IndexCount) do begin IndexCount[i]:= l; IndexOffset[i]:= nil; end; } Voxels.RootVoxel:= tVoxel.Create(nil); //writelog(strf(RootVoxel.InstanceSize)); d:= power(2, VoxelFidelity - Voxels.RootVoxel.Order) / 2; FileName+= '.hm'; fs:= TFileStream.Create(FileName, fmOpenRead); for i:= 0 to l - 1 do for j:= 0 to l - 1 do begin fs.Read(hm[i,j], sizeof(hm[i,j])); hm[i,j]/= 128; //GetVoxel((i - d) * MinVoxelDim, hm[i,j], (j - d) * MinVoxelDim); //do in 1 loop end; fs.free; // glPolygonMode(GL_FRONT, GL_FILL); k:= 0; for j:= 0 to l - 2 do begin for i:= 0 to l - 1 do begin GetVoxel((i - d) * MinVoxelDim, hm[i,j], (j - d) * MinVoxelDim, i + (j * l), k); inc(k); GetVoxel((i - d) * MinVoxelDim, hm[i,j + 1], (j + 1 - d) * MinVoxelDim, i + (j+1) * l, k); inc(k); end; end; WriteLog('Voxels loaded: ' + strf(VoxelCount)); GenerateHubs; Camera:= tCamera.Create; end; constructor tWorld.CreateNew(Seed: longword); var l: longword; begin WorldSeed:= Seed; VoxelFidelity:= 6; l:= round(power(2, VoxelFidelity)); setlength(Vertices, l * l * l); setlength(Indices, l * l * l); Extent:= MinVoxelDim * power(2, VoxelFidelity); Voxels:= tVoxelContainer.Create; Voxels.RootVoxel:= tVoxel.Create(nil); Voxels.RootVoxel.Order:= 0; VoxelCount:= 0; Counter:= 0; Generate(Voxels.RootVoxel); WriteLog('Voxels generated: ' + strf(VoxelCount)); Camera:= tCamera.Create; end; function tWorld.GetVoxel(x, y, z: single; c1, c2: longword; MaxOrder: longword = 0): tVoxel; var Next: eVoxelPos; d, cx, cy, cz: single; i: integer; begin Result:= Voxels.RootVoxel; cx:= 0; //center of current voxel cy:= 0; cz:= 0; with Result do for i:= 0 to VoxelFidelity - 1 do begin d:= MinVoxelDim * power(2, VoxelFidelity - Order - 2) {/ 4}; if z < cz then begin cz-= d; if x < cx then begin cx-= d; if y < cy then begin Next:= BNW; cy-= d; end else begin Next:= TNW; cy+= d; end; end else begin cx+= d; if y < cy then begin Next:= BNE; cy-= d; end else begin Next:= TNE; cy+= d; end; end; end else begin cz+= d; if x < cx then begin cx-= d; if y < cy then begin Next:= BSW; cy-= d; end else begin Next:= TSW; cy+= d; end; end else begin cx+= d; if y < cy then begin Next:= BSE; cy-= d; end else begin Next:= TSE; cy+= d; end; end; end; if Children[Next] = nil then Children[Next]:= tVoxel.Create(Result); Result:= Children[Next]; end; Vertices[c1].x:= x; //excess Vertices[c1].y:= y; Vertices[c1].z:= z; Indices[c2]:= c1; //writelog('i' + strf(Child[Next].Index)); end; function tWorld.Generate(Voxel: tVoxel): longint; var //ChildHeight: spatial; i: eVoxelPos; begin inc(VoxelCount);//writeln('gen'); with Voxel do begin //WriteLog('Order ' + strf(Order)); if Order = VoxelFidelity then begin { for i:= low(eVoxelPos) to high(eVoxelPos) do writelog(strf(longword(pointer(Children[i])))); } Result:= 0; exit; end; Result:= 0; for i:= low(eVoxelPos) to TSW do //change to iterative begin if srand(3, WorldSeed + Counter) = 0 then begin Children[i]:= tVoxel.Create(Voxel); {Result+=} Generate(Children[i]); end else begin Children[eVoxelPos(integer(i) + 4)]:= tVoxel.Create(Voxel); {Result+=} Generate(Children[eVoxelPos(integer(i) + 4)]); end; inc(Counter); end; end; {Result+= Counter; } end; procedure tWorld.ListVoxel(Voxel: tVoxel; cx, cy, cz: single); //center of voxel var i: eVoxelPos; d: single; //убрать рекурсию - self сравнить с адресами родителя x, y, z: single; begin with Voxel do begin d:= MinVoxelDim * power(2, VoxelFidelity - Order) / 2; for i:= BNW to TSE do begin x:= cx; y:= cy; z:= cz; if Children[i] <> nil then begin with Children[i] do begin case i of BNW: begin x+= 0; y+= 0; z+= 0; // Counter:= integer(i); end; BNE: begin x+= d; // Counter:= integer(i); end; BSE: begin x+= d; z+= d; // Counter:= integer(i); end; BSW: begin z+= d; // Counter:= integer(i); end; TNW: begin y+= d; // Counter:= integer(i); end; TNE: begin x+= d; y+= d; // Counter:= integer(i); end; TSE: begin x+= d; y+= d; z+= d; // Counter:= integer(i); end; TSW: begin y+= d; z+= d; // Counter:= integer(i); end; end; //inc(Counter); if Order = VoxelFidelity then begin Vertices[counter].x:= x; //excess Vertices[counter].y:= y; Vertices[counter].z:= z; Indices[counter]:= counter; inc(counter); end; {//if ListID = 0 then ListID:= Counter; //glNewList(ListID, GL_COMPILE_and_execute); {if Order < VoxelFidelity then begin} {glPolygonMode(GL_FRONT, GL_LINE) else glPolygonMode(GL_FRONT, GL_FILL); } //glBegin(GL_quads{_STRIP}); glColor3f(Order * 1 / VoxelFidelity, random, Counter / VoxelCount); glVertex3f(x - d, y - d, z - d); //n glVertex3f(x - d, y, z - d); glVertex3f(x, y, z - d); glVertex3f(x, y - d, z - d); glVertex3f(x, y - d, z - d); //e glVertex3f(x, y, z - d); glVertex3f(x, y, z ); glVertex3f(x, y - d, z ); {glVertex3f(x, y - d, z ); //s glVertex3f(x, y, z ); glVertex3f(x - d, y, z ); glVertex3f(x - d, y - d, z ); } {glVertex3f(x - d, y - d, z ); //w glVertex3f(x - d, y, z ); glVertex3f(x - d, y, z - d); glVertex3f(x - d, y - d, z - d); } glVertex3f(x - d, y - d, z - d); //b glVertex3f(x, y - d, z - d); glVertex3f(x , y - d, z ); glVertex3f(x - d, y - d, z ); { glVertex3f(x - d, y, z - d); //t glVertex3f(x - d, y, z ); glVertex3f(x , y, z ); glVertex3f(x , y, z - d); } //glEnd; //glEndList; {end;} } end; ListVoxel(Children[i], x - d / 2, y - d / 2, z - d / 2); end; end; end; end; procedure tWorld.PassVoxels; begin {UI3DListID:= glGenLists(1); glNewList(UI3DListID, GL_COMPILE); glBegin(GL_LINES); glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,1); glVertex3f(0.005,0,0); glVertex3f(0.005,0,1); glVertex3f(-0.005,0,0); glVertex3f(-0.005,0,1); glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(1,0,0); glVertex3f(0,0.005,0); glVertex3f(1,0.005,0); glVertex3f(0,-0.005,0); glVertex3f(1,-0.005,0); glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,1,0); glVertex3f(0,0,0.005); glVertex3f(0,1,0.005); glVertex3f(0,0,-0.005); glVertex3f(0,1,-0.005); glEnd; glEndList; d:= MinVoxelDim * power(2, VoxelFidelity); x:= d/2; //tse corner y:= d/2; z:= d/2; {RootVoxel.ListID:= glGenLists(1); glNewList(RootVoxel.ListID, GL_COMPILE); } WireFrameListID:= glGenLists(1); glNewList(WireFrameListID, GL_COMPILE); glPolygonMode(GL_FRONT, GL_fill); glBegin(GL_QUADS{_STRIP}); glShadeModel(gl_Smooth); glColor3f(1, 1, 1); glVertex3f(x - d, y - d, z - d); //n glVertex3f(x - d, y, z - d); glVertex3f(x, y, z - d); glVertex3f(x, y - d, z - d); glVertex3f(x, y - d, z - d); //e glVertex3f(x, y, z - d); glVertex3f(x, y, z ); glVertex3f(x, y - d, z ); glVertex3f(x, y - d, z ); //s glVertex3f(x, y, z ); glVertex3f(x - d, y, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y - d, z ); //w glVertex3f(x - d, y, z ); glVertex3f(x - d, y, z - d); glVertex3f(x - d, y - d, z - d); glVertex3f(x - d, y - d, z - d); //b glVertex3f(x, y - d, z - d); glVertex3f(x , y - d, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y, z - d); //t glVertex3f(x - d, y, z ); glVertex3f(x , y, z ); glVertex3f(x , y, z - d); Counter:= 1; ListVoxel(Voxels.RootVoxel, 0, 0, 0); glEnd; glEndList; } {glBegin(gl_quads); glEnd; } //glEnableClientState(GL_VERTEX_ARRAY); Counter:= 0; ListVoxel(Voxels.RootVoxel, 0, 0, 0); glGenBuffers(1, @VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer); glBufferData(GL_ARRAY_BUFFER, length(Vertices) * sizeof(rVec3), PGLVoid(Vertices), GL_STATIC_DRAW); glGenBuffers(1, @IndexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, length(Indices) * sizeof(GLuint), PGLVoid(Indices), GL_STATIC_DRAW); glEnableClientState(GL_VERTEX_ARRAY); //glDisableClientState(GL_VERTEX_ARRAY); end; procedure tWorld.Render; var p: rVec3; //move on cam vec begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); //glLoadIdentity; glPopMatrix; glPushMatrix; //to separate proc with Camera.o do begin glRotatef(x,1,0,0); glRotatef(y,0,1,0); glRotatef(z,0,0,1); end; with Camera.c do glTranslatef(x, y, z); //glEnableClientState(GL_VERTEX_ARRAY); //glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer); glVertexPointer(3, GL_FLOAT, 0, nil); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBuffer); glDrawElements(GL_TRIANGLE_STRIP, length(Indices), GL_UNSIGNED_INT, nil); // glMultiDrawElements(GL_TRIANGLE_STRIP, PGLSizei(IndexCount), GL_UNSIGNED_INT, PGLVoid(IndexOffset), length(Indexcount)*length(Indexcount)*sizeof(gluint)); //glDisableClientState(GL_VERTEX_ARRAY); {glMatrixMode(GL_Projection); glLoadIdentity; } //glCallList(UI3DListID); //if WireFrame then glCallList(WireFrameListID); //glFlush; end; procedure tWorld.Save(FileName: string); begin {if FileExists(FileName) then begin Filestream:= TFileStream.Create(FileName, fmOpenReadWrite); BlockCount:= FileStream.ReadDWord; setlength(BlockSizes, BlockCount); FirstBlock:= sizeof(BlockCount) + BlockCount * sizeof(BlockSizes[0]); FileStream.ReadBuffer(BlockSizes, BlockCount); RootVoxel:= LoadBlock(0); end else begin Filestream:= TFileStream.Create(FileName, fmCreate); //Gen new end;} end; destructor tWorld.Destroy; var i: integer; begin WriteLog('Freeing world'); Voxels.Destroy; for i:= 0 to high(Hubs) do Hubs[i].Destroy; Camera.Destroy; end; end.
{******************************************************************************} { } { Delphi HangulParser } { } { Copyright (C) TeakHyun Kang } { } { https://github.com/kth920517 } { https://developist.tistory.com/ } { } {******************************************************************************} unit HangulParser; interface uses System.Classes, System.SysUtils, Winapi.Windows; const HANGUL_START_UNICODE = $AC00; HANGUL_END_UNICODE = $D7A3; //초성 ARRAY_SET_CHOSUNG : array[0..18] of string = ( 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'); //중성 ARRAY_SET_JUNGSUNG : array[0..20] of string = ( 'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'); //종성 ARRAY_SET_JONGSUNG : array[0..27] of string = ( '', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'); function HangulParse(AWord: string; ADelimiter: Char = #0): string; implementation function HangulParse(AWord: string; ADelimiter: Char): string; var I: Integer; nLength : Integer; lstResult : TStringList; sTemp : WideChar; nUniCode : Integer; nCho : Integer; nJung : Integer; nJong : Integer; begin Result := ''; if AWord = '' then Exit; try lstResult := TStringList.Create; lstResult.LineBreak := ''; lstResult.Delimiter := ADelimiter; lstResult.StrictDelimiter := True; try nLength := Length(AWord); for I := 1 to nLength do begin sTemp := AWord[I]; nUniCode := Integer(sTemp); if (HANGUL_START_UNICODE <= nUniCode) and (nUniCode <= HANGUL_END_UNICODE) then begin nUniCode := nUniCode - HANGUL_START_UNICODE; nJong := nUniCode mod 28; nJung := (nUniCode - nJong) div 28 mod 21; nCho := Integer((nUniCode - nJong) div 28 div 21); lstResult.Add(ARRAY_SET_CHOSUNG[nCho]); lstResult.Add(ARRAY_SET_JUNGSUNG[nJung]); if nJong > 0 then lstResult.Add(ARRAY_SET_JONGSUNG[nJong]); end else lstResult.Add(sTemp); end; if ADelimiter = '' then Result := lstResult.Text else Result := lstResult.DelimitedText; finally lstResult.Free; end; except on E: Exception do raise Exception.Create('Hangul Parse Failed! - ' + E.Message); end; end; end.
unit IdSNTP; interface uses Classes, IdGlobal, IdUDPClient; const NTPMaxInt = 4294967297.0; type // NTP Datagram format TNTPGram = packed record Head1: byte; Head2: byte; Head3: byte; Head4: byte; RootDelay: longint; RootDispersion: longint; RefID: longint; Ref1: longint; Ref2: longint; Org1: longint; Org2: longint; Rcv1: longint; Rcv2: longint; Xmit1: longint; Xmit2: longint; end; TLr = packed record L1: byte; L2: byte; L3: byte; L4: byte; end; TIdSNTP = class(TIdUDPClient) protected FDestinationTimestamp: TDateTime; FLocalClockOffset: TDateTime; FOriginateTimestamp: TDateTime; FReceiveTimestamp: TDateTime; FRoundTripDelay: TDateTime; FTransmitTimestamp: TDateTime; function Disregard(NTPMessage: TNTPGram): Boolean; function GetAdjustmentTime: TDateTime; function GetDateTime: TDateTime; public constructor Create(AOwner: TComponent); override; function SyncTime: Boolean; property AdjustmentTime: TDateTime read GetAdjustmentTime; property DateTime: TDateTime read GetDateTime; property RoundTripDelay: TDateTime read FRoundTripDelay; property Port default IdPORT_SNTP; end; implementation uses SysUtils; function Flip(var Number: longint): longint; var Number1, Number2: TLr; begin Number1 := TLr(Number); Number2.L1 := Number1.L4; Number2.L2 := Number1.L3; Number2.L3 := Number1.L2; Number1.L4 := Number1.L1; Result := longint(Number2); end; procedure DateTimeToNTP(ADateTime: TDateTime; var Second, Fraction: longint); var Value1, Value2: Double; begin Value1 := ADateTime + TimeZoneBias - 2; Value1 := Value1 * 86400; Value2 := Value1; if Value2 > NTPMaxInt then Value2 := Value2 - NTPMaxInt; Second := Trunc(Value2); Value2 := ((Frac(Value1) * 1000) / 1000) * NTPMaxInt; if Value2 > NTPMaxInt then Value2 := Value2 - NTPMaxInt; Fraction := Trunc(Value2); end; function NTPToDateTime(Second, Fraction: longint): TDateTime; var Value1, Value2: Double; begin Value1 := Second; if Value1 < 0 then begin Value1 := NTPMaxInt + Value1 - 1; end; Value2 := Fraction; if Value2 < 0 then begin Value2 := NTPMaxInt + Value2 - 1; end; Value2 := Value2 / NTPMaxInt; Value2 := Trunc(Value2 * 1000) / 1000; Result := ((Value1 + Value2) / 86400); Result := Result - TimeZoneBias + 2; end; constructor TIdSNTP.Create(AOwner: TComponent); begin inherited; Port := IdPORT_SNTP; end; function TIdSNTP.Disregard(NTPMessage: TNTPGram): Boolean; var Stratum, LeapIndicator: Integer; begin LeapIndicator := (NTPMessage.Head1 and 192) shr 6; Stratum := NTPMessage.Head2; Result := (LeapIndicator = 3) or (Stratum > 15) or (Stratum = 0) or (((Int(FTransmitTimestamp)) = 0.0) and (Frac(FTransmitTimestamp) = 0.0)); end; function TIdSNTP.GetAdjustmentTime: TDateTime; begin Result := FLocalClockOffset; end; function TIdSNTP.GetDateTime: TDateTime; var NTPDataGram: TNTPGram; ResultString: string; begin FillChar(NTPDataGram, SizeOf(NTPDataGram), 0); NTPDataGram.Head1 := $1B; DateTimeToNTP(Now, NTPDataGram.Xmit1, NTPDataGram.Xmit2); NTPDataGram.Xmit1 := Flip(NTPDataGram.Xmit1); NTPDataGram.Xmit2 := Flip(NTPDataGram.Xmit2); SetLength(ResultString, SizeOf(NTPDataGram)); Move(NTPDataGram, ResultString[1], SizeOf(NTPDataGram)); BufferSize := SizeOf(NTPDataGram); Send(ResultString); ResultString := ReceiveString; if Length(ResultString) > 0 then begin FDestinationTimeStamp := Now; Result := NTPToDateTime(Flip(NTPDataGram.Xmit1), Flip(NTPDataGram.Xmit2)); FOriginateTimeStamp := NTPToDateTime(Flip(NTPDataGram.Org1), Flip(NTPDataGram.Org2)); FReceiveTimestamp := NTPToDateTime(Flip(NTPDataGram.Rcv1), Flip(NTPDataGram.Rcv2)); FTransmitTimestamp := NTPToDateTime(Flip(NTPDataGram.Xmit1), Flip(NTPDataGram.Xmit2)); FRoundTripDelay := (FDestinationTimestamp - FOriginateTimestamp) - (FReceiveTimestamp - FTransmitTimestamp); FLocalClockOffset := ((FReceiveTimestamp - FOriginateTimestamp) + (FTransmitTimestamp - FDestinationTimestamp)) / 2; if Disregard(NTPDataGram) then begin Result := 0.0; end; end else begin Result := 0.0; end; end; function TIdSNTP.SyncTime: Boolean; begin Result := DateTime <> 0; if Result then begin result := SetLocalTime(FOriginateTimestamp + FLocalClockOffset + FRoundTripDelay); end; end; end.
unit Ths.Erp.Database.Table.OlcuBirimi; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TOlcuBirimi = class(TTable) private FBirim: TFieldDB; FEFaturaBirim: TFieldDB; FBirimAciklama: TFieldDB; FIsFloatTip: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property Birim: TFieldDB read FBirim write FBirim; Property EFaturaBirim: TFieldDB read FEFaturaBirim write FEFaturaBirim; Property BirimAciklama: TFieldDB read FBirimAciklama write FBirimAciklama; Property IsFloatTip: TFieldDB read FIsFloatTip write FIsFloatTip; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TOlcuBirimi.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'olcu_birimi'; SourceCode := '1000'; FBirim := TFieldDB.Create('birim', ftString, '', 0, False, False); FEFaturaBirim := TFieldDB.Create('efatura_birim', ftString, '', 0, False, False); FBirimAciklama := TFieldDB.Create('birim_aciklama', ftString, '', 0, False, True); FIsFloatTip := TFieldDB.Create('is_float_tip', ftBoolean, False, 0, False, False); end; procedure TOlcuBirimi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, getRawDataByLang(TableName, FBirim.FieldName), TableName + '.' + FEFaturaBirim.FieldName, TableName + '.' + FBirimAciklama.FieldName, TableName + '.' + FIsFloatTip.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FBirim.FieldName).DisplayLabel := 'Birim'; Self.DataSource.DataSet.FindField(FEFaturaBirim.FieldName).DisplayLabel := 'E-Fatura Birim'; Self.DataSource.DataSet.FindField(FBirimAciklama.FieldName).DisplayLabel := 'Birim Açıklama'; Self.DataSource.DataSet.FindField(FIsFloatTip.FieldName).DisplayLabel := 'Float Tip?'; end; end; end; procedure TOlcuBirimi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, getRawDataByLang(TableName, FBirim.FieldName), TableName + '.' + FEFaturaBirim.FieldName, TableName + '.' + FBirimAciklama.FieldName, TableName + '.' + FIsFloatTip.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FBirim.Value := FormatedVariantVal(FieldByName(FBirim.FieldName).DataType, FieldByName(FBirim.FieldName).Value); FEFaturaBirim.Value := FormatedVariantVal(FieldByName(FEFaturaBirim.FieldName).DataType, FieldByName(FEFaturaBirim.FieldName).Value); FBirimAciklama.Value := FormatedVariantVal(FieldByName(FBirimAciklama.FieldName).DataType, FieldByName(FBirimAciklama.FieldName).Value); FIsFloatTip.Value := FormatedVariantVal(FieldByName(FIsFloatTip.FieldName).DataType, FieldByName(FIsFloatTip.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; end; end; end; procedure TOlcuBirimi.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FBirim.FieldName, FEFaturaBirim.FieldName, FBirimAciklama.FieldName, FIsFloatTip.FieldName ]); NewParamForQuery(QueryOfInsert, FBirim); NewParamForQuery(QueryOfInsert, FEFaturaBirim); NewParamForQuery(QueryOfInsert, FBirimAciklama); NewParamForQuery(QueryOfInsert, FIsFloatTip); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TOlcuBirimi.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FBirim.FieldName, FEFaturaBirim.FieldName, FBirimAciklama.FieldName, FIsFloatTip.FieldName ]); NewParamForQuery(QueryOfUpdate, FBirim); NewParamForQuery(QueryOfUpdate, FEFaturaBirim); NewParamForQuery(QueryOfUpdate, FBirimAciklama); NewParamForQuery(QueryOfUpdate, FIsFloatTip); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TOlcuBirimi.Clone():TTable; begin Result := TOlcuBirimi.Create(Database); Self.Id.Clone(TOlcuBirimi(Result).Id); FBirim.Clone(TOlcuBirimi(Result).FBirim); FEFaturaBirim.Clone(TOlcuBirimi(Result).FEFaturaBirim); FBirimAciklama.Clone(TOlcuBirimi(Result).FBirimAciklama); FIsFloatTip.Clone(TOlcuBirimi(Result).FIsFloatTip); end; end.
unit SharedUnit; interface uses DelphiTwain, Twain; function CheckCap(ret: TCapabilityRet; Name: String = ''): Boolean; function ItemToStr(Item: integer; ItemType: string): string; function StrToItem(Item: string; ItemType: string): integer; function CapUnitToStr(Item: TTwainUnit): string; function StrToCapUnit(Item: string): TTwainUnit; var sPreview: string = 'Предпросмотр'; // Measure units sInches: string = 'Дюймы'; sCentimeters: string = 'Сантиметры'; sPicas: string = 'Picas'; sPoints: string = 'Точки'; sTwips: string = 'Twips'; sPixels: string = 'Пиксели'; sMillimeters: string = 'Миллиметры'; sUnknown: string = 'Неизвестно'; // Image file formats sTIFF: string = 'TIFF'; // Used for document imaging sPICT: string = 'PICT'; // Native Macintosh format sBMP: string = 'BMP'; // Native Microsoft format sXBM: string = 'XBM'; // Used for document imaging sJFIF: string = 'JFIF'; // Wrapper for JPEG images sFPX: string = 'FPX'; // FlashPix, used with digital cameras sTIFFMULTI: string = 'TIFF Multi'; // Multi-page TIFF files sPNG: string = 'PNG'; // An image format standard intended for use on the web, replaces GIF sSPIFF: string = 'SPIFF'; // A standard from JPEG, intended to replace JFIF, also supports JBIG sEXIF: string = 'EXIF'; // File format for use with digital cameras sPDF: string = 'PDF'; // A file format from Adobe sJP2: string = 'JP2'; // A file format from the Joint Photographic Experts Group sDEJAVU: string = 'DEJAVU'; // A file format from LizardTech sPDFA: string = 'PDFA'; // A file format from Adobe // Extra transfer formats sTransferMemory: string = 'Memory'; sTransferNative: string = 'Native'; // Pixel types sBW: string = 'Ч/Б'; sGray: string = 'Градации серого'; sRGB: string = 'Цвет (RGB)'; sPalette: string = 'Цвет (палитра)'; sCMY: string = 'Цвет (CMY)'; sCMYK: string = 'Цвет (CMYK)'; sYUV: string = 'Цвет (YUV)'; sYUVK: string = 'Цвет (YUVK)'; sCIEXYZ: string = 'Цвет (CIEXYZ)'; sLAB: string = 'Цвет (LAB)'; sSRGB: string = 'Цвет (SRGB)'; sErrSrcBusy: string = 'Current source busy'; sErrSrcNotFound: string = 'Source not found'; sErrSrcNotEnabled: string = 'Source can''t be enabled'; sErrAcquireCancelled: string = 'Image acquire cancelled'; sErrAcquireError: string = 'Image acquire error'; sErrColorModeNotFound: string = 'Requested color mode not found'; sInfScanerListLoaded: string = 'Scanner list loaded..'; sInfScanStarted: string = 'Scan started..'; sInfScanning: string = 'Scanning.. '; sInfTransferingImage: string = 'Transfering image..'; sInfTransferingImageFile: string = 'Transfering image file..'; implementation //============================================ function CheckCap(ret: TCapabilityRet; Name: String = ''): Boolean; var sr: string; begin Result := False; case ret of crSuccess: result:=True; crUnsupported: sr:='Capability not supported by the source'; crBadOperation: sr:='Bad combination of values from the parameters.'; crDependencyError: sr:='Capability depends on another capability which is not properly set'; crLowMemory: sr:='The system is short on memory'; crInvalidState: sr:='The source or the source manager are not ready to set this capability or do the requested operation'; crInvalidContainer:sr:='The container used is invalid'; else sr:='Uncnown error'; end; if Result then Exit; //ShowMessage(Name+': '+sr); //memoDebug.Lines.Add(Name+': '+sr); end; function ItemToStr(Item: integer; ItemType: string): string; begin Result:=''; if ItemType='units' then begin if Item=TWUN_INCHES then Result:=sInches else if Item=TWUN_CENTIMETERS then Result:=sCentimeters else if Item=TWUN_PICAS then Result:=sPicas else if Item=TWUN_POINTS then Result:=sPoints else if Item=TWUN_TWIPS then Result:=sTwips else if Item=TWUN_PIXELS then Result:=sPixels else if Item=TWUN_MILLIMETERS then Result:=sMillimeters; end else if ItemType='img_formats' then begin if Item=TWFF_TIFF then Result:=sTIFF else if Item=TWFF_PICT then Result:=sPICT else if Item=TWFF_BMP then Result:=sBMP else if Item=TWFF_XBM then Result:=sXBM else if Item=TWFF_JFIF then Result:=sFPX else if Item=TWFF_TIFFMULTI then Result:=sTIFFMULTI else if Item=TWFF_PNG then Result:=sPNG else if Item=TWFF_SPIFF then Result:=sSPIFF else if Item=TWFF_EXIF then Result:=sEXIF else if Item=TWFF_PDF then Result:=sPDF else if Item=TWFF_DEJAVU then Result:=sDEJAVU; end else if ItemType='pixel_types' then begin if Item=TWPT_BW then Result:=sBW else if Item=TWPT_GRAY then Result:=sGray else if Item=TWPT_RGB then Result:=sRGB else if Item=TWPT_PALETTE then Result:=sPalette else if Item=TWPT_CMY then Result:=sCMY else if Item=TWPT_CMYK then Result:=sCMYK else if Item=TWPT_YUV then Result:=sYUV else if Item=TWPT_YUVK then Result:=sYUVK else if Item=TWPT_CIEXYZ then Result:=sCIEXYZ else if Item=TWPT_LAB then Result:=sLAB else if Item=TWPT_SRGB then Result:=sSRGB; end; end; function StrToItem(Item: string; ItemType: string): integer; begin Result:=-1; if ItemType='units' then begin if Item=sInches then Result:=TWUN_INCHES else if Item=sCentimeters then Result:=TWUN_CENTIMETERS else if Item=sPicas then Result:=TWUN_PICAS else if Item=sPoints then Result:=TWUN_POINTS else if Item=sTwips then Result:=TWUN_TWIPS else if Item=sPixels then Result:=TWUN_PIXELS else if Item=sMillimeters then Result:=TWUN_MILLIMETERS; end else if ItemType='img_formats' then begin if Item=sTIFF then Result:=TWFF_TIFF else if Item=sPICT then Result:=TWFF_PICT else if Item=sBMP then Result:=TWFF_BMP else if Item=sXBM then Result:=TWFF_XBM else if Item=sFPX then Result:=TWFF_JFIF else if Item=sTIFFMULTI then Result:=TWFF_TIFFMULTI else if Item=sPNG then Result:=TWFF_PNG else if Item=sSPIFF then Result:=TWFF_SPIFF else if Item=sEXIF then Result:=TWFF_EXIF else if Item=sPDF then Result:=TWFF_PDF else if Item=sDEJAVU then Result:=TWFF_DEJAVU; end else if ItemType='pixel_types' then begin if Item=sBW then Result:=TWPT_BW else if Item=sGray then Result:=TWPT_GRAY else if Item=sRGB then Result:=TWPT_RGB else if Item=sPalette then Result:=TWPT_PALETTE else if Item=sCMY then Result:=TWPT_CMY else if Item=sCMYK then Result:=TWPT_CMYK else if Item=sYUV then Result:=TWPT_YUV else if Item=sYUVK then Result:=TWPT_YUVK else if Item=sCIEXYZ then Result:=TWPT_CIEXYZ else if Item=sLAB then Result:=TWPT_LAB else if Item=sSRGB then Result:=TWPT_SRGB; end; end; function CapUnitToStr(Item: TTwainUnit): string; begin if Item=tuInches then Result:=sInches else if Item=tuCentimeters then Result:=sCentimeters else if Item=tuPicas then Result:=sPicas else if Item=tuPoints then Result:=sPoints else if Item=tuTwips then Result:=sTwips else if Item=tuPixels then Result:=sPixels else if Item=tuUnknown then Result:=sUnknown else Result:=''; end; function StrToCapUnit(Item: string): TTwainUnit; begin if Item=sInches then Result:=tuInches else if Item=sCentimeters then Result:=tuCentimeters else if Item=sPicas then Result:=tuPicas else if Item=sPoints then Result:=tuPoints else if Item=sTwips then Result:=tuTwips else if Item=sPixels then Result:=tuPixels else if Item=sUnknown then Result:=tuUnknown else Result:=tuUnknown; end; end.
unit U_DIAGRAM_TYPE; interface uses SysUtils; type /// <summary> 接线图类型 </summary> TDiagramType = ( dt3CTClear, //三相三线CT简化 dt3M, //三相三线多功能 dt3L4, //三相三线四线制 dt4M_NoPT, //三相四线多功能无PT dt4Direct, //三相四线直通 dt4_NoPT_L6, //三相四线无PT六线制 dt4M_PT, //三相四线多功能有PT dt4_PT_CT_CLear, //三相四线经PT,CT简化 dt4_PT_L6 //三相四线经PT,六线制 ); function DiagramTypeToStr(ADiagramType: TDiagramType): string; function DiagramStrToType(sDiagramStr: string): TDiagramType; implementation function DiagramTypeToStr(ADiagramType: TDiagramType): string; begin case ADiagramType of dt3CTClear: Result := '三相三线CT简化'; dt3M: Result := '三相三线多功能'; dt3L4: Result := '三相三线四线制'; dt4M_NoPT: Result := '三相四线多功能无PT'; dt4M_PT: Result := '三相四线多功能有PT'; dt4_PT_CT_CLear: Result := '三相四线经PT,CT简化'; dt4_PT_L6: Result := '三相四线经PT六线制'; dt4_NoPT_L6: Result := '三相四线无PT六线制'; dt4Direct: Result := '三相四线直通'; else raise Exception.Create('Unrecognized'); end; end; function DiagramStrToType(sDiagramStr: string): TDiagramType; begin if sDiagramStr = '三相三线CT简化' then Result := dt3CTClear else if sDiagramStr = '三相三线多功能' then Result := dt3M else if sDiagramStr = '三相三线四线制' then Result := dt3L4 else if sDiagramStr = '三相四线多功能无PT' then Result := dt4M_NoPT else if sDiagramStr = '三相四线多功能有PT' then Result := dt4M_PT else if sDiagramStr = '三相四线经PT,CT简化' then Result := dt4_PT_CT_CLear else if sDiagramStr = '三相四线经PT六线制' then Result := dt4_PT_L6 else if sDiagramStr = '三相四线无PT六线制' then Result := dt4_NoPT_L6 else if sDiagramStr = '三相四线直通' then Result := dt4Direct else Result := dt3L4; end; end.
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info) unit SMARTSupport.Mtron; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TMtronSMARTSupport = class(TSMARTSupport) private const EntryID = $BB; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported(const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; function InnerIsErrorAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsCautionAvailable(const SMARTList: TSMARTValueList): Boolean; override; function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; function InnerIsCaution(const SMARTList: TSMARTValueList): TSMARTErrorResult; override; end; implementation { TMtronSMARTSupport } function TMtronSMARTSupport.GetTypeName: String; begin result := 'SmartMtron'; end; function TMtronSMARTSupport.IsInsufficientSMART: Boolean; begin result := true; end; function TMtronSMARTSupport.IsSSD: Boolean; begin result := true; end; function TMtronSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := (FindAtFirst('MTRON', IdentifyDevice.Model)) and (SMARTList.Count = 1) and (SMARTList[0].ID = $BB); end; function TMtronSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID($BB)].Current; end; function TMtronSMARTSupport.InnerIsErrorAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := true; end; function TMtronSMARTSupport.InnerIsCautionAvailable( const SMARTList: TSMARTValueList): Boolean; begin result := IsEntryAvailable(EntryID, SMARTList); end; function TMtronSMARTSupport.InnerIsError( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result.Override := false; result.Status := InnerCommonIsError(EntryID, SMARTList).Status; end; function TMtronSMARTSupport.InnerIsCaution( const SMARTList: TSMARTValueList): TSMARTErrorResult; begin result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold); end; function TMtronSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; begin result := false; end; function TMtronSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; begin FillChar(result, SizeOf(result), 0); end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, WinApi.Winsock2, Vcl.Menus, Vcl.Samples.Spin, superobject, sfLog, org.utilities, org.tcpip.tcp, org.tcpip.tcp.client, org.algorithms.time; type TForm2 = class(TForm) Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Edit1: TEdit; Label1: TLabel; Edit2: TEdit; Label2: TLabel; Memo1: TMemo; btnEcho: TButton; btnStart: TButton; btnStop: TButton; MainMenu1: TMainMenu; N1: TMenuItem; llFatal1: TMenuItem; llError1: TMenuItem; llWarnning1: TMenuItem; llNormal1: TMenuItem; llDebug1: TMenuItem; btnUploadFile: TButton; Edit4: TEdit; Edit3: TEdit; SpinEdit1: TSpinEdit; GroupBox1: TGroupBox; Label3: TLabel; Label4: TLabel; SpinEdit2: TSpinEdit; SpinEdit3: TSpinEdit; btnDownload: TButton; Edit5: TEdit; procedure btnEchoClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure llDebug1Click(Sender: TObject); procedure llNormal1Click(Sender: TObject); procedure btnUploadFileClick(Sender: TObject); procedure Edit4Change(Sender: TObject); procedure SpinEdit2Change(Sender: TObject); procedure SpinEdit3Change(Sender: TObject); procedure llFatal1Click(Sender: TObject); procedure llError1Click(Sender: TObject); procedure llWarnning1Click(Sender: TObject); procedure btnDownloadClick(Sender: TObject); private FLog: TsfLog; FMaxPreIOContextCount: Integer; FMultiIOBufferCount: Integer; FLogLevel: TLogLevel; FTCPClient: TTCPClient; FTimeWheel: TTimeWheel<TForm2>; procedure DoTestEcho(AForm: TForm2); procedure DoTestUploadFile(AForm: TForm2); procedure OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); procedure OnConnected(Sender: TObject; Context: TTCPIOContext); procedure WriteToScreen(const Value: string); { Private declarations } protected procedure WndProc(var MsgRec: TMessage); override; public { Public declarations } procedure StartService; procedure StopService; end; var Form2: TForm2; const WM_WRITE_LOG_TO_SCREEN = WM_USER + 1; implementation uses dm.tcpip.tcp.client; {$R *.dfm} procedure TForm2.btnDownloadClick(Sender: TObject); var bRet: Boolean; ErrDesc: string; Parameters: TTCPRequestParameters; FileName: string; FilePath: string; Body: TMemoryStream; Length: Integer; JO: ISuperObject; begin btnDownload.Enabled := False; FilePath := Edit5.Text; // FileName := ExtractFileName(FilePath); Parameters.RemoteIP := Edit1.Text; Parameters.RemotePort := StrToInt(Edit2.Text); JO := TSuperObject.Create(); JO.S['Cmd'] := 'DownloadFile'; JO.S['SrcLocation'] := FilePath; {$IfDef DEBUG} ErrDesc := Format('[%d]<%s.SendRequest> [DownloadFile] Body=%s, FilePath=%s', [ GetCurrentThreadId(), ClassName, JO.AsJSon(), FilePath]); OnLog(nil, llDebug, ErrDesc); {$Endif} Body := TMemoryStream.Create(); Length := JO.SaveTo(Body); // bRet := FTCPClient.SendRequest(@Parameters, Body, Length, FilePath, IO_OPTION_NOTIFY_BODYEX_PROGRESS); bRet := FTCPClient.SendRequest(@Parameters, Body, Length, IO_OPTION_EMPTY); if not bRet then begin ErrDesc := Format('[%d]<%s.SendRequest> failed', [ GetCurrentThreadId(), ClassName]); OnLog(nil, llNormal, ErrDesc); end; end; procedure TForm2.btnEchoClick(Sender: TObject); var bRet: Boolean; ErrDesc: string; Parameters: TTCPRequestParameters; buf: TMemoryStream; Msg: string; JO: ISuperObject; Len: Integer; I, nCount: Integer; begin Parameters.RemoteIP := Edit1.Text; Parameters.RemotePort := StrToInt(Edit2.Text); nCount := SpinEdit1.Value; if nCount = 0 then nCount := 10; for I := 0 to nCount - 1 do begin Msg := FormatDateTime('YYYY-MM-DD hh:mm:ss.zzz', Now); JO := TSuperObject.Create(); JO.S['Cmd'] := 'Echo'; JO.S['Time'] := Msg; JO.S['Msg'] := Edit3.Text; {$IfDef DEBUG} ErrDesc := Format('[µ÷ÊÔ][][%d]<%s.SendRequest> Request=%s', [ GetCurrentThreadId(), ClassName, JO.AsJSon()]); OnLog(nil, llDebug, ErrDesc); {$Endif} buf := TMemoryStream.Create(); Len := JO.SaveTo(buf); bRet := FTCPClient.SendRequest(@Parameters, buf, Len, IO_OPTION_EMPTY); if not bRet then begin ErrDesc := Format('[´íÎó][][%d]<%s.SendRequest> failed', [ GetCurrentThreadId(), ClassName]); OnLog(nil, llError, ErrDesc); end; end; end; procedure TForm2.btnStartClick(Sender: TObject); begin StartService(); end; procedure TForm2.btnStopClick(Sender: TObject); begin StopService(); end; procedure TForm2.btnUploadFileClick(Sender: TObject); var bRet: Boolean; ErrDesc: string; Parameters: TTCPRequestParameters; FileName: string; FilePath: string; Body: TMemoryStream; Length: Integer; JO: ISuperObject; begin btnUploadFile.Enabled := False; FilePath := Edit4.Text; FileName := ExtractFileName(FilePath); Parameters.RemoteIP := Edit1.Text; Parameters.RemotePort := StrToInt(Edit2.Text); JO := TSuperObject.Create(); JO.S['Cmd'] := 'UploadFile'; JO.S['DstLocation'] := FileName; {$IfDef DEBUG} ErrDesc := Format('[%d]<%s.SendRequest> [UploadFile] Body=%s, FilePath=%s', [ GetCurrentThreadId(), ClassName, JO.AsJSon(), FilePath]); OnLog(nil, llDebug, ErrDesc); {$Endif} Body := TMemoryStream.Create(); Length := JO.SaveTo(Body); bRet := FTCPClient.SendRequest(@Parameters, Body, Length, FilePath, IO_OPTION_NOTIFY_BODYEX_PROGRESS); if not bRet then begin ErrDesc := Format('[%d]<%s.SendRequest> failed', [ GetCurrentThreadId(), ClassName]); OnLog(nil, llNormal, ErrDesc); end; end; procedure TForm2.DoTestEcho(AForm: TForm2); begin AForm.btnEchoClick(nil); FTimeWheel.StartTimer(Self, 5 * 60 * 1000, DoTestEcho); end; procedure TForm2.DoTestUploadFile(AForm: TForm2); begin AForm.btnUploadFileClick(nil); FTimeWheel.StartTimer(Self, 5 * 60 * 1000, DoTestUploadFile); end; procedure TForm2.Edit4Change(Sender: TObject); begin btnUploadFile.Enabled := True; end; procedure TForm2.FormCreate(Sender: TObject); var CurDir: string; LogFile: string; begin CurDir := ExtractFilePath(ParamStr(0)); ForceDirectories(CurDir + 'Log\'); LogFile := CurDir + 'Log\Log_' + FormatDateTime('YYYYMMDD', Now()) + '.txt'; FLog := TsfLog.Create(LogFile); FLog.AutoLogFileName := True; FLog.LogFilePrefix := 'Log_'; FLogLevel := llNormal; FTCPClient := TTCPClient.Create(); FTCPClient.HeadSize := Sizeof(TTCPSocketProtocolHead); FTimeWheel := TTimeWheel<TForm2>.Create(); end; procedure TForm2.llDebug1Click(Sender: TObject); begin FLogLevel := llDebug; FTCPClient.LogLevel := llDebug; end; procedure TForm2.llError1Click(Sender: TObject); begin FLogLevel := llError; FTCPClient.LogLevel := llError; end; procedure TForm2.llFatal1Click(Sender: TObject); begin FLogLevel := llFatal; FTCPClient.LogLevel := llFatal; end; procedure TForm2.llNormal1Click(Sender: TObject); begin FLogLevel := llNormal; FTCPClient.LogLevel := llNormal; end; procedure TForm2.llWarnning1Click(Sender: TObject); begin FLogLevel := llWarning; FTCPClient.LogLevel := llWarning; end; procedure TForm2.OnConnected(Sender: TObject; Context: TTCPIOContext); var Msg: string; begin {$IfDef DEBUG} Msg := Format('[µ÷ÊÔ][%d][%d]<OnConnected> [%s:%d]', [ Context.Socket, GetCurrentThreadId(), Context.RemoteIP, Context.RemotePort]); OnLog(nil, llDebug, Msg); {$Endif} end; procedure TForm2.OnLog(Sender: TObject; LogLevel: TLogLevel; LogContent: string); begin if LogLevel <= FLogLevel then WriteToScreen(LogContent); FLog.WriteLog(LogContent); end; procedure TForm2.SpinEdit2Change(Sender: TObject); begin FMaxPreIOContextCount := SpinEdit2.Value; end; procedure TForm2.SpinEdit3Change(Sender: TObject); begin FMultiIOBufferCount := SpinEdit3.Value; end; procedure TForm2.StartService; var Msg: string; CurDir: string; begin CurDir := ExtractFilePath(ParamStr(0)); FMaxPreIOContextCount := SpinEdit2.Value; FMultiIOBufferCount := SpinEdit3.Value; FTCPClient.LogLevel := FLogLevel; FTCPClient.MaxPreIOContextCount := FMaxPreIOContextCount; FTCPClient.MultiIOBufferCount := FMultiIOBufferCount; FTCPClient.TempDirectory := CurDir + 'Temp\'; ForceDirectories(FTCPClient.TempDirectory); FTCPClient.OnLog := OnLog; FTCPClient.OnConnected := OnConnected; FTCPClient.RegisterIOContextClass($20000000, TDMTCPClientSocket); //\\ FTCPClient.Start(); SpinEdit2.Enabled := False; SpinEdit3.Enabled := False; Msg := Format('»ù±¾ÅäÖÃ:'#13#10'MaxPreIOContextCount: %d'#13#10'MultiIOBufferCount: %d'#13#10'BufferSize: %d', [ FMaxPreIOContextCount, FMultiIOBufferCount, FTCPClient.BufferSize]); Memo1.Lines.Add(Msg); FTimeWheel.Start(); // FTimeWheel.StartTimer(Self, 10 * 1000, DoTestEcho); // FTimeWheel.StartTimer(Self, 10 * 1000, DoTestUploadFile); end; procedure TForm2.StopService; begin end; procedure TForm2.WndProc(var MsgRec: TMessage); var Msg: string; begin if MsgRec.Msg = WM_WRITE_LOG_TO_SCREEN then begin Msg := FormatDateTime('YYYY-MM-DD hh:mm:ss.zzz',Now) + ':' + string(MsgRec.WParam); Memo1.Lines.Add(Msg); end else inherited; end; procedure TForm2.WriteToScreen(const Value: string); begin SendMessage(Application.MainForm.Handle, WM_WRITE_LOG_TO_SCREEN, WPARAM(Value), 0); end; end.
unit ncgDesliga; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; function Desliga(Flags: Cardinal): Boolean; { EWX_FORCE Forces processes to terminate. When this flag is set, Windows does not send the messages WM_QUERYENDSESSION and WM_ENDSESSION to the applications currently running in the system. This can cause the applications to lose data. Therefore, you should only use this flag in an emergency. EWX_LOGOFF Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off. EWX_POWEROFF Shuts down the system and turns off the power. The system must support the power-off feature. EWX_REBOOT Shuts down the system and then restarts the system. EWX_SHUTDOWN Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped. } implementation function Desliga(Flags: Cardinal): Boolean; var buffer: DWord; tkp, tpko: TTokenPrivileges; hToken: THandle; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_NT then begin if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin exit; end; LookupPrivilegeValue(nil, 'SeShutdownPrivilege', tkp.Privileges[0].Luid); tkp.PrivilegeCount := 1; tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; if not Windows.AdjustTokenPrivileges(hToken, FALSE, tkp, sizeof(tkp), tpko, buffer) then begin exit; end; end; Result := ExitWindowsEx(Flags, 0); if Win32Platform = VER_PLATFORM_WIN32_NT then begin Windows.AdjustTokenPrivileges(hToken, FALSE,tpko, sizeOf(tpko), tkp, Buffer); Windows.CloseHandle(hToken); end; end; end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { } { Copyright (c) 1995, 2001 Borland Software Corporation } { } { *************************************************************************** } unit MaskUtils; {$R-,T-,H+,X+} interface const DefaultBlank: Char = '_'; MaskFieldSeparator: Char = ';'; MaskNoSave: Char = '0'; mDirReverse = '!'; { removes leading blanks if true, else trailing blanks} mDirUpperCase = '>'; { all chars that follow to upper case } mDirLowerCase = '<'; { all chars that follow to lower case } { '<>' means remove casing directive } mDirLiteral = '\'; { char that immediately follows is a literal } mMskAlpha = 'L'; { in US = A-Z,a-z } mMskAlphaOpt = 'l'; mMskAlphaNum = 'A'; { in US = A-Z,a-z,0-9 } mMskAlphaNumOpt = 'a'; mMskAscii = 'C'; { any character} mMskAsciiOpt = 'c'; mMskNumeric = '0'; { 0-9, no plus or minus } mMskNumericOpt = '9'; mMskNumSymOpt = '#'; { 0-9, plus and minus } { intl literals } mMskTimeSeparator = ':'; mMskDateSeparator = '/'; type TMaskCharType = (mcNone, mcLiteral, mcIntlLiteral, mcDirective, mcMask, mcMaskOpt, mcFieldSeparator, mcField); TMaskDirectives = set of (mdReverseDir, mdUpperCase, mdLowerCase, mdLiteralChar); TMaskedText = type string; TEditMask = type string; function FormatMaskText(const EditMask: string; const Value: string): string; function MaskGetMaskSave(const EditMask: string): Boolean; function MaskGetMaskBlank(const EditMask: string): Char; function MaskGetFldSeparator(const EditMask: string): Integer; function PadInputLiterals(const EditMask: String; const Value: string; Blank: Char): string; function MaskOffsetToOffset(const EditMask: String; MaskOffset: Integer): Integer; function MaskOffsetToWideOffset(const EditMask: String; MaskOffset: Integer): Integer; function IsLiteralChar(const EditMask: string; Offset: Integer): Boolean; function MaskGetCharType(const EditMask: string; MaskOffset: Integer): TMaskCharType; function MaskGetCurrentDirectives(const EditMask: string; MaskOffset: Integer): TMaskDirectives; function MaskIntlLiteralToChar(IChar: Char): Char; function OffsetToMaskOffset(const EditMask: string; Offset: Integer): Integer; function MaskDoFormatText(const EditMask: string; const Value: string; Blank: Char): string; implementation uses SysUtils; { Mask utility routines } function MaskGetCharType(const EditMask: string; MaskOffset: Integer): TMaskCharType; var MaskChar: Char; begin Result := mcLiteral; MaskChar := #0; if MaskOffset <= Length(EditMask) then MaskChar := EditMask[MaskOffset]; if MaskOffset > Length(EditMask) then Result := mcNone else if ByteType(EditMask, MaskOffset) <> mbSingleByte then Result := mcLiteral else if (MaskOffset > 1) and (EditMask[MaskOffset - 1] = mDirLiteral) and (ByteType(EditMask, MaskOffset - 1) = mbSingleByte) and not ((MaskOffset > 2) and (EditMask[MaskOffset - 2] = mDirLiteral) and (ByteType(EditMask, MaskOffset - 2) = mbSingleByte)) then Result := mcLiteral else if (MaskChar = MaskFieldSeparator) and (Length(EditMask) >= 4) and (MaskOffset > Length(EditMask) - 4) then Result := mcFieldSeparator else if (Length(EditMask) >= 4) and (MaskOffset > (Length(EditMask) - 4)) and (EditMask[MaskOffset - 1] = MaskFieldSeparator) and not ((MaskOffset > 2) and (EditMask[MaskOffset - 2] = mDirLiteral) and (ByteType(EditMask, MaskOffset - 2) <> mbTrailByte)) then Result := mcField else if MaskChar in [mMskTimeSeparator, mMskDateSeparator] then Result := mcIntlLiteral else if MaskChar in [mDirReverse, mDirUpperCase, mDirLowerCase, mDirLiteral] then Result := mcDirective else if MaskChar in [mMskAlphaOpt, mMskAlphaNumOpt, mMskAsciiOpt, mMskNumSymOpt, mMskNumericOpt] then Result := mcMaskOpt else if MaskChar in [mMskAlpha, mMskAlphaNum, mMskAscii, mMskNumeric] then Result := mcMask; end; function MaskGetCurrentDirectives(const EditMask: string; MaskOffset: Integer): TMaskDirectives; var I: Integer; MaskChar: Char; begin Result := []; for I := 1 to Length(EditMask) do begin MaskChar := EditMask[I]; if (MaskChar = mDirReverse) then Include(Result, mdReverseDir) else if (MaskChar = mDirUpperCase) and (I < MaskOffset) then begin Exclude(Result, mdLowerCase); if not ((I > 1) and (EditMask[I-1] = mDirLowerCase)) then Include(Result, mdUpperCase); end else if (MaskChar = mDirLowerCase) and (I < MaskOffset) then begin Exclude(Result, mdUpperCase); Include(Result, mdLowerCase); end; end; if MaskGetCharType(EditMask, MaskOffset) = mcLiteral then Include(Result, mdLiteralChar); end; function MaskIntlLiteralToChar(IChar: Char): Char; begin Result := IChar; case IChar of mMskTimeSeparator: Result := TimeSeparator; mMskDateSeparator: Result := DateSeparator; end; end; function MaskDoFormatText(const EditMask: string; const Value: string; Blank: Char): string; var I: Integer; Offset, MaskOffset: Integer; CType: TMaskCharType; Dir: TMaskDirectives; begin Result := Value; Dir := MaskGetCurrentDirectives(EditMask, 1); if not (mdReverseDir in Dir) then begin { starting at the beginning, insert literal chars in the string and add spaces on the end } Offset := 1; for MaskOffset := 1 to Length(EditMask) do begin CType := MaskGetCharType(EditMask, MaskOffset); if CType in [mcLiteral, mcIntlLiteral] then begin Result := Copy(Result, 1, Offset - 1) + MaskIntlLiteralToChar(EditMask[MaskOffset]) + Copy(Result, Offset, Length(Result) - Offset + 1); Inc(Offset); end else if CType in [mcMask, mcMaskOpt] then begin if Offset > Length(Result) then Result := Result + Blank; Inc(Offset); end; end; end else begin { starting at the end, insert literal chars in the string and add spaces at the beginning } Offset := Length(Result); for I := 0 to(Length(EditMask) - 1) do begin MaskOffset := Length(EditMask) - I; CType := MaskGetCharType(EditMask, MaskOffset); if CType in [mcLiteral, mcIntlLiteral] then begin Result := Copy(Result, 1, Offset) + MaskIntlLiteralToChar(EditMask[MaskOffset]) + Copy(Result, Offset + 1, Length(Result) - Offset); end else if CType in [mcMask, mcMaskOpt] then begin if Offset < 1 then Result := Blank + Result else Dec(Offset); end; end; end; end; function MaskGetMaskSave(const EditMask: string): Boolean; var I: Integer; Sep1, Sep2: Integer; begin Result := True; if Length(EditMask) >= 4 then begin Sep1 := -1; Sep2 := -1; I := Length(EditMask); while Sep2 < 0 do begin if (MaskGetCharType(EditMask, I) = mcFieldSeparator) then begin if Sep1 < 0 then Sep1 := I else Sep2 := I; end; Dec(I); if (I <= 0) or(I < Length(EditMask) - 4) then Break; end; if Sep2 < 0 then Sep2 := Sep1; if (Sep2 > 0) and (Sep2 <> Length(EditMask)) then Result := not (EditMask [Sep2 + 1] = MaskNoSave); end; end; function MaskGetMaskBlank(const EditMask: string): Char; begin Result := DefaultBlank; if Length(EditMask) >= 4 then begin if (MaskGetCharType(EditMask, Length(EditMask) - 1) = mcFieldSeparator) then begin {in order for blank specifier to be valid, there must also be a save specifier } if (MaskGetCharType(EditMask, Length(EditMask) - 2) = mcFieldSeparator) or (MaskGetCharType(EditMask, Length(EditMask) - 3) = mcFieldSeparator) then begin Result := EditMask [Length(EditMask)]; end; end; end; end; function MaskGetFldSeparator(const EditMask: String): Integer; var I: Integer; begin Result := -1; if Length(EditMask) >= 4 then begin for I := (Length(EditMask) - 4) to Length(EditMask) do begin if (MaskGetCharType(EditMask, I) = mcFieldSeparator) then begin Result := I; Exit; end; end; end; end; function MaskOffsetToString(const EditMask: String; MaskOffset: Integer): string; var I: Integer; CType: TMaskCharType; begin Result := ''; for I := 1 to MaskOffset do begin CType := MaskGetCharType(EditMask, I); if not (CType in [mcDirective, mcField, mcFieldSeparator]) then Result := Result + EditMask[I]; end; end; function MaskOffsetToOffset(const EditMask: String; MaskOffset: Integer): Integer; begin Result := length(MaskOffsetToString(Editmask, MaskOffset)); end; function MaskOffsetToWideOffset(const EditMask: String; MaskOffset: Integer): Integer; begin Result := length( WideString(MaskOffsetToString(Editmask, MaskOffset))); end; function OffsetToMaskOffset(const EditMask: string; Offset: Integer): Integer; var I: Integer; Count: Integer; MaxChars: Integer; begin MaxChars := MaskOffsetToOffset(EditMask, Length(EditMask)); if Offset > MaxChars then begin Result := -1; Exit; end; Result := 0; Count := Offset; for I := 1 to Length(EditMask) do begin Inc(Result); if not (mcDirective = MaskGetCharType(EditMask, I)) then begin Dec(Count); if Count < 0 then Exit; end; end; end; function IsLiteralChar(const EditMask: string; Offset: Integer): Boolean; var MaskOffset: Integer; CType: TMaskCharType; begin Result := False; MaskOffset := OffsetToMaskOffset(EditMask, Offset); if MaskOffset >= 0 then begin CType := MaskGetCharType(EditMask, MaskOffset); Result := CType in [mcLiteral, mcIntlLiteral]; end; end; function PadSubField(const EditMask: String; const Value: string; StartFld, StopFld, Len: Integer; Blank: Char): string; var Dir: TMaskDirectives; StartPad: Integer; K: Integer; begin if (StopFld - StartFld) < Len then begin { found literal at position J, now pad it } Dir := MaskGetCurrentDirectives(EditMask, 1); StartPad := StopFld - 1; if mdReverseDir in Dir then StartPad := StartFld - 1; Result := Copy(Value, 1, StartPad); for K := 1 to (Len - (StopFld - StartFld)) do Result := Result + Blank; Result := Result + Copy(Value, StartPad + 1, Length(Value)); end else if (StopFld - StartFld) > Len then begin Dir := MaskGetCurrentDirectives(EditMask, 1); if mdReverseDir in Dir then Result := Copy(Value, 1, StartFld - 1) + Copy(Value, StopFld - Len, Length(Value)) else Result := Copy(Value, 1, StartFld + Len - 1) + Copy(Value, StopFld, Length(Value)); end else Result := Value; end; function PadInputLiterals(const EditMask: String; const Value: string; Blank: Char): string; var J: Integer; LastLiteral, EndSubFld: Integer; Offset, MaskOffset: Integer; CType: TMaskCharType; MaxChars: Integer; begin LastLiteral := 0; Result := Value; for MaskOffset := 1 to Length(EditMask) do begin CType := MaskGetCharType(EditMask, MaskOffset); if CType in [mcLiteral, mcIntlLiteral] then begin Offset := MaskOffsetToOffset(EditMask, MaskOffset); EndSubFld := Length(Result) + 1; for J := LastLiteral + 1 to Length(Result) do begin if Result[J] = MaskIntlLiteralToChar(EditMask[MaskOffset]) then begin EndSubFld := J; Break; end; end; { we have found a subfield, ensure that it complies } if EndSubFld > Length(Result) then Result := Result + MaskIntlLiteralToChar(EditMask[MaskOffset]); Result := PadSubField(EditMask, Result, LastLiteral + 1, EndSubFld, Offset - (LastLiteral + 1), Blank); LastLiteral := Offset; end; end; {ensure that the remainder complies, too } MaxChars := MaskOffsetToOffset(EditMask, Length(EditMask)); if Length (Result) <> MaxChars then Result := PadSubField(EditMask, Result, LastLiteral + 1, Length (Result) + 1, MaxChars - LastLiteral, Blank); { replace non-literal blanks with blank char } for Offset := 1 to Length (Result) do begin if Result[Offset] = ' ' then begin if not IsLiteralChar(EditMask, Offset - 1) then Result[Offset] := Blank; end; end; end; function FormatMaskText(const EditMask: string; const Value: string ): string; begin if MaskGetMaskSave(EditMask) then Result := PadInputLiterals(EditMask, Value, ' ') else Result := MaskDoFormatText(EditMask, Value, ' '); end; end.
unit uClient; interface uses uSharedMemoryPoint; type TSharedMemoryClient = class(TSharedMemoryPoint) private FileName_: String; Terminated_: Boolean; protected procedure Start(Callback: TSharedMemoryClient.TProcessCallBack); override; public constructor Create(); destructor Destroy(); override; procedure Terminated(); override; procedure Send(const FileName: String; Callback: TSharedMemoryClient.TProcessCallBack); property FileName: String read FileName_; end; implementation uses Vcl.Forms, Winapi.Windows, System.SysUtils, System.Classes, System.IniFiles, System.Math, uCommon; constructor TSharedMemoryClient.Create(); procedure LoadSettings(); var Settings: TIniFile; AppDirName: String; begin AppDirName := ExtractFilePath(Application.ExeName); try Settings := TIniFile.Create(Format('%s\client.ini', [AppDirName])); try FileName_ := Settings.ReadString('Client', 'FileName', ''); finally FreeAndNil(Settings); end; except end; end; begin try LoadSettings(); inherited Create(False); except on E: EGetSharedMemoryName do raise Exception.Create('Не удалось подключиться к COM-серверу!'); on E: EExistSharedMemoryPoint do raise Exception.Create(Format('Клиент для объекта "%s" уже запущен!', [SharedMemoryName])); on E: EOpenSharedMemoryMapped do raise Exception.Create('Не удалось подключиться к серверу!'); on E: Exception do raise Exception.Create(Format('Не удалось запустить клиент: "%s"!', [E.Message])); end; end; destructor TSharedMemoryClient.Destroy(); procedure SaveSettings(); var Settings: TIniFile; AppDirName: String; begin AppDirName := ExtractFilePath(Application.ExeName); try Settings := TIniFile.Create(Format('%s\client.ini', [AppDirName])); try Settings.WriteString('Client', 'FileName', FileName_); finally FreeAndNil(Settings); end; except end; end; begin SaveSettings(); inherited Destroy(); end; procedure TSharedMemoryClient.Terminated(); begin Terminated_ := True; end; procedure TSharedMemoryClient.Send(const FileName: String; Callback: TSharedMemoryClient.TProcessCallBack); begin if FileName = '' then raise Exception.Create('Не указан файл для передачи!') else if not FileExists(FileName) then raise Exception.Create('Указанный файл не найден!') else begin FileName_ := FileName; Terminated_ := False; Start(Callback); end; end; procedure TSharedMemoryClient.Start(Callback: TSharedMemoryClient.TProcessCallBack); procedure WriteMetaData(DataPointer: Pointer; Stream: TStream); var Memory: TMemoryStream; StreamSize: Int64; FileName: WideString; FileNameLength: Integer; begin Memory := TMemoryStream.Create(); try StreamSize := Stream.Size; FileName := ExtractFileName(FileName_); FileNameLength := Length(FileName); Memory.WriteBuffer(StreamSize, SizeOf(StreamSize)); Memory.WriteBuffer(FileNameLength, SizeOf(FileNameLength)); Memory.WriteBuffer(FileName[1], FileNameLength*SizeOf(WideChar)); Memory.Position := 0; Memory.ReadBuffer(DataPointer^, Memory.Size); finally FreeAndNil(Memory); end; end; procedure WriteData(DataPointer: Pointer; Stream: TStream; var TransferSize: Int64); var Memory: TMemoryStream; DataSize: Integer; begin Memory := TMemoryStream.Create(); try DataSize := Min(POINT_DATA_SIZE - SizeOf(DataSize), Stream.Size - TransferSize); Memory.WriteBuffer(DataSize, SizeOf(DataSize)); Memory.CopyFrom(Stream, DataSize); Memory.Position := 0; Memory.ReadBuffer(DataPointer^, Memory.Size); Inc(TransferSize, DataSize) finally FreeAndNil(Memory); end; end; var hRead, hWrite: THandle; Msg: String; PrevPercents, Percents, Attempts: Integer; IsTransfer: Boolean; TransferSize: Int64; Stream: TFileStream; begin if Assigned(Callback) then begin hRead := 0; hWrite := 0; PrevPercents := 0; Percents := 0; Attempts := 0; IsTransfer := False; TransferSize := 0; Stream := NIL; try try hRead := OpenEvent(EVENT_ALL_ACCESS, False, PChar(Format('%s.read', [SharedMemoryName]))); hWrite := OpenEvent(EVENT_ALL_ACCESS, False, PChar(Format('%s.write', [SharedMemoryName]))); if (hRead = 0) or (hWrite = 0) then raise Exception.Create('Сервер не доступен!'); Stream := TFileStream.Create(FileName_, fmOpenRead or fmShareDenyNone); while not Terminated_ and ((TransferSize < Stream.Size) or (Stream.Size = 0)) do begin case WaitForSingleObject(hWrite, POINT_WAIT_TIMEOUT) of WAIT_TIMEOUT: begin if IsTransfer then begin Inc(Attempts); if Attempts >= POINT_ATTEPMTS_COUNT then raise Exception.Create('Сервер не доступен!'); end; end; WAIT_OBJECT_0: begin if not IsTransfer then begin WriteMetaData(DataPointer, Stream); if Stream.Size = 0 then begin Terminated_ := True; Msg := Format('Передан файл "%s" нулевого размера', [FileName_]) end else begin IsTransfer := True; Msg := Format('Начата передача файла' + ' (Файл: "%s", Размер: %s)', [FileName_, FileSizeToStr(Stream.Size)]); end; end else begin Attempts := 0; WriteData(DataPointer, Stream, TransferSize); if TransferSize = Stream.Size then begin Terminated_ := True; TransferSize := 0; Msg := Format('Завершена передача файла "%s"', [FileName_]); end; end; SetEvent(hRead); end else raise Exception.Create(SysErrorMessage(GetLastError())); end; if Stream.Size <> 0 then Percents := Floor(100*TransferSize/Stream.Size); if (Msg <> '') or (Percents <> PrevPercents) then begin Callback(Msg, Percents, False); PrevPercents := Percents; Msg := ''; end; end; except on E: Exception do Callback(E.Message, Percents, True) end; finally if Assigned(Stream) then FreeAndNil(Stream); if hWrite <> 0 then CloseHandle(hWrite); if hRead <> 0 then CloseHandle(hRead); end; end; end; end.
unit AAlterarSenha; { Autor: Sergio Luiz Censi Data Criação: 01/04/1999; Função: Altera a senha do usuário Data Alteração: 01/04/1999; Alterado por: Rafael Budag Motivo alteração: - Adicionado os comentários e o blocos nas rotinas, e realizado um teste - 01/04/199 / rafael Budag } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Db, DBTables, constMsg, constantes, formularios, FunValida, LabelCorMove, Componentes1, PainelGradiente, DBClient, Tabela; type TFAlteraSenha = class(TFormularioPermissao) Usuarios: TSQL; UsuariosI_COD_USU: TFMTBCDField; UsuariosC_NOM_USU: TWideStringField; UsuariosC_NOM_LOG: TWideStringField; UsuariosC_SEN_USU: TWideStringField; UsuariosC_USU_ATI: TWideStringField; PainelGradiente1: TPainelGradiente; UsuariosI_EMP_FIL: TFMTBCDField; PanelColor1: TPanelColor; Label2: TLabel; SenhaAtual: TEditColor; Label1: TLabel; NovaSenha: TEditColor; Label3: TLabel; ConfSenha: TEditColor; AbeCancela: TBitBtn; OK: TBitBtn; UsuariosD_DAT_MOV: TSQLTimeStampField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SenhaAtualExit(Sender: TObject); procedure AbeCancelaClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var FAlteraSenha: TFAlteraSenha; implementation uses APrincipal, funSql; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFAlteraSenha.FormCreate(Sender: TObject); begin Usuarios.open; end; { ******************* Quando o formulario e fechado ************************** } procedure TFAlteraSenha.FormClose(Sender: TObject; var Action: TCloseAction); begin Usuarios.close; Action := cafree; end; { ****************** Altera a Senha do Usuário ******************************* } procedure TFAlteraSenha.OKClick(Sender: TObject); begin if (varia.Senha = Criptografa(SenhaAtual.text)) then begin if NovaSenha.Text <> ConfSenha.Text Then Messagedlg(CT_ConfirmaSenha,mtWarning,[mbok],0) else if NovaSenha.Text = '' then aviso('NOVA SENHA EM BRANCO!!!'#13'É necessário digitar uma nova senha') else if NovaSenha.text <> ConfSenha.Text then aviso('CONFIRMAÇÃO DA SENHA INVÁLIDA!!!'#13'A confirmação da senha é diferente da nova senha. Digite novamente.') else begin AdicionaSqlAbreTabela(Usuarios,'Select * from CADUSUARIOS '+ ' Where I_COD_USU = '+inttoStr(varia.CodigoUsuario)); Usuarios.Edit; UsuariosC_SEN_USU.Value := Criptografa(NovaSenha.text); Usuarios.Post; beep; Messagedlg(CT_SenhaAlterada,mtConfirmation,[mbok],0); FAlteraSenha.Close; end; end else begin beep; Messagedlg(CT_SenhaInvalida,mtWarning,[mbok],0); SenhaAtual.SetFocus; end; end; { ******** Habilita Ok quando todas os edit estiverem diferente de vazio ***** } procedure TFAlteraSenha.SenhaAtualExit(Sender: TObject); begin end; { *************** fecha o formulário ***************************************** } procedure TFAlteraSenha.AbeCancelaClick(Sender: TObject); begin FAlteraSenha.Close; end; { *************** Registra a classe para evitar duplicidade ****************** } procedure TFAlteraSenha.FormShow(Sender: TObject); begin self.Color := FPrincipal.CorForm.ACorPainel; end; Initialization RegisterClasses([TFAlteraSenha]); end.
unit FC.Trade.Brokers.BrokerBase; interface uses Classes, BaseUtils, SysUtils, Graphics, FC.Definitions,StockChart.Definitions; type TStockBrokerBase = class (TInterfacedObject) private FEventHandlers: array of IStockBrokerEventHandler; FMessages : TInterfaceList; //of IStockBrokerMessage function GetEventHandler(index: integer): IStockBrokerEventHandler; function GetMessage(index: integer): IStockBrokerMessage; protected procedure RaiseOnStartEvent; procedure RaiseOnNewDataEvent(const aSymbol: string); procedure RaiseOnNewOrderEvent(const aOrder: IStockOrder); procedure RaiseOnModifyOrderEvent(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); function EventHandlerCount: integer; property EventHandlers[index:integer]: IStockBrokerEventHandler read GetEventHandler; function MessageCount: integer; property Messages[index:integer]: IStockBrokerMessage read GetMessage; public //from IStockBroker procedure AddEventHandler(const aHandler: IStockBrokerEventHandler); procedure RemoveEventHandler(const aHandler: IStockBrokerEventHandler); //Добавить произволный комментарий. Время установи комментария берется текущее function AddMessage(const aMessage: string; aColor: TColor=clDefault): IStockBrokerMessage; overload; //Добавить произволный комментарий. Время установи комментария берется текущее function AddMessage(const aOrder:IStockOrder; const aMessage: string; aColor: TColor=clDefault): IStockBrokerMessage; overload; //Кол-во точек после запятой function GetPricePrecision(const aSymbol: string) : integer; virtual; abstract; //Коэффициент трансформации из точки в цену, для EURUSD=10000, для USDJPY=100 function GetPricesInPoint(const aSymbol: string): integer; virtual; abstract; //Округление цены до PricePrecision function RoundPrice(const aSymbol: string; const aPrice: TSCRealNumber) : TSCRealNumber; virtual; //Перевод цены в пункты (умножение на PricesInPoint) function PriceToPoint(const aSymbol: string; const aPrice: TSCRealNumber) : integer; virtual; //Перевод пунктов в цену (деление на PricesInPoint) function PointToPrice(const aSymbol: string; const aPoint: integer) : TSCRealNumber; virtual; //Перевод цены в деньги с учетом указанного кол-ва лотов function PriceToMoney(const aSymbol: string; const aPrice: TSCRealNumber; const aLots: TStockOrderLots): TStockRealNumber; virtual; constructor Create; destructor Destroy; override; end; TStockBrokerMessage=class(TInterfacedObject,IStockBrokerMessage) private FText: string; FColor: TColor; public function Text: string; function Color: TColor; constructor Create(const aText: string; aColor:TColor=clDefault); end; implementation uses Math; { TStockBrokerBase } procedure TStockBrokerBase.AddEventHandler(const aHandler: IStockBrokerEventHandler); begin SetLength(FEventHandlers,Length(FEventHandlers)+1); FEventHandlers[High(FEventHandlers)]:=aHandler; end; procedure TStockBrokerBase.RaiseOnNewDataEvent(const aSymbol: string); var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; for i:=0 to EventHandlerCount-1 do FEventHandlers[i].OnNewData(aStockBroker,aSymbol); end; procedure TStockBrokerBase.RaiseOnStartEvent; var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; for i:=0 to EventHandlerCount-1 do FEventHandlers[i].OnStart(aStockBroker); end; procedure TStockBrokerBase.RaiseOnNewOrderEvent(const aOrder: IStockOrder); var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; for i:=0 to EventHandlerCount-1 do FEventHandlers[i].OnNewOrder(aStockBroker,aOrder); end; procedure TStockBrokerBase.RaiseOnModifyOrderEvent(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; for i:=0 to EventHandlerCount-1 do FEventHandlers[i].OnModifyOrder(aStockBroker,aOrder,aModifyEventArgs); end; procedure TStockBrokerBase.RemoveEventHandler(const aHandler: IStockBrokerEventHandler); var i,j: integer; begin for i := 0 to High(FEventHandlers) do begin if FEventHandlers[i]=aHandler then begin //Сдвигаем то, что сзади на место образовавшегося проема for j:=i to High(FEventHandlers)-1 do FEventHandlers[j]:=FEventHandlers[j+1]; SetLength(FEventHandlers,Length(FEventHandlers)-1); break; end; end; end; function TStockBrokerBase.AddMessage(const aMessage: string; aColor: TColor=clDefault):IStockBrokerMessage; var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; result:=TStockBrokerMessage.Create(aMessage,aColor); FMessages.Add(Result); for i:=0 to EventHandlerCount-1 do EventHandlers[i].OnNewMessage(aStockBroker,result); end; function TStockBrokerBase.AddMessage(const aOrder:IStockOrder; const aMessage: string; aColor: TColor=clDefault):IStockBrokerMessage; var i: integer; aStockBroker: IStockBroker; begin aStockBroker:=self as IStockBroker; result:=TStockBrokerMessage.Create(aMessage,aColor); FMessages.Add(Result); for i:=0 to EventHandlerCount-1 do EventHandlers[i].OnNewMessage(aStockBroker,aOrder,result); end; constructor TStockBrokerBase.Create; begin FMessages:=TInterfaceList.Create; end; destructor TStockBrokerBase.Destroy; begin Finalize(FEventHandlers); FreeAndNil(FMessages); inherited; end; function TStockBrokerBase.EventHandlerCount: integer; begin result:=Length(FEventHandlers); end; function TStockBrokerBase.GetEventHandler(index: integer): IStockBrokerEventHandler; begin result:= FEventHandlers[index]; end; function TStockBrokerBase.GetMessage(index: integer): IStockBrokerMessage; begin result:=FMessages[index] as IStockBrokerMessage; end; function TStockBrokerBase.MessageCount: integer; begin result:=FMessages.Count; end; function TStockBrokerBase.RoundPrice(const aSymbol: string; const aPrice: TSCRealNumber): TSCRealNumber; begin result:=RoundTo(aPrice,-GetPricePrecision(aSymbol)) end; function TStockBrokerBase.PointToPrice(const aSymbol: string; const aPoint: integer): TSCRealNumber; begin result:=aPoint/GetPricesInPoint(aSymbol); end; function TStockBrokerBase.PriceToMoney(const aSymbol: string; const aPrice: TSCRealNumber; const aLots: TStockOrderLots): TStockRealNumber; begin //Не учитывает стоимость пункта в $. Всегда считает его 1:1 result:=PriceToPoint(aSymbol,aPrice)*aLots*10; end; function TStockBrokerBase.PriceToPoint(const aSymbol: string; const aPrice: TSCRealNumber): integer; begin result:=Round(aPrice*GetPricesInPoint(aSymbol)); end; { TStockBrokerMessage } function TStockBrokerMessage.Color: TColor; begin result:=FColor; end; constructor TStockBrokerMessage.Create(const aText: string; aColor: TColor); begin inherited Create; FText:=aText; FColor:=aColor; end; function TStockBrokerMessage.Text: string; begin result:=FText; end; end.
(* AVR Basic Compiler Copyright 1997-2002 Silicon Studio Ltd. Copyright 2008 Trioflex OY http://www.trioflex.com *) unit ToolSrv; {*************************************************************** Generic Services for Tool Output Processing. Must compile/link under Delphi/FPC and run in console/gui mode. ****************************************************************} interface uses ToolStd, IniFiles, Classes, SysUtils; type EAbstractError = class(Exception); TWriteStringProc = procedure(str: string); // // Generic Memory Image... // All Code Generation should call some Descendants of.. // TMemoryImage = class(TComponent) private FPC: Cardinal; FLastPC: Cardinal; procedure SetPC(const Value: Cardinal); procedure SetLastPC(const Value: Cardinal); public FROM: Array[0..$FFFF] of WORD; procedure LoadFromFile(FileName: string); virtual; abstract; procedure SaveToFile(FileName: string); virtual; abstract; procedure emit(Data: byte); overload; virtual; abstract; procedure emit(Data: word); overload; virtual; abstract; published property PC: Cardinal read FPC write SetPC; property LastPC: Cardinal read FLastPC write SetLastPC; end; TDumbMemoryImage = class(TMemoryImage) private public procedure LoadFromFile(FileName: string); override; procedure SaveToFile(FileName: string); override; procedure emit(Data: byte); override; procedure emit(Data: word); override; published end; var InstallDir: string; TemplateDir: string; // Global Memory Image.. MI: TMemoryImage; linenum: integer; // BAD BAD.. procedure WriteToolOutput(line: string); function MsgByNum(Num: Integer): string; // Retrieve Common Messages implementation var MsgIni: TIniFile; InternalMsgList: TStringList; // We hold Messages here procedure WriteToolOutput(line: string); begin WriteStdOutput(line); end; function MsgByNum(Num: Integer): string; begin // if not Assigned(InternalMsgList) then begin Exit; end; // Get Message... Result := InternalMsgList.Values[IntToStr(Num)]; end; { TMemoryImage } procedure TMemoryImage.SetLastPC(const Value: Cardinal); begin FLastPC := Value; end; procedure TMemoryImage.SetPC(const Value: Cardinal); begin FPC := Value; end; { TDumbMemoryImage } procedure TDumbMemoryImage.emit(Data: byte); begin FPC := FPC and $FFFF; FROM[FPC] := Data; // Low Byte? // Inc(FPC); if FPC>FLastPC then FLastPC := FPC; end; procedure TDumbMemoryImage.emit(Data: word); begin FPC := FPC and $FFFF; FROM[FPC] := Data; // Low Byte? // Inc(FPC); if FPC>FLastPC then FLastPC := FPC; end; procedure TDumbMemoryImage.LoadFromFile(FileName: string); begin // end; procedure TDumbMemoryImage.SaveToFile(FileName: string); begin // end; initialization // Load Messages... MsgIni := TIniFile.Create('C:\c2\common.txt'); InternalMsgList := TStringList.Create; // Read Messages... MI := TDumbMemoryImage.Create(nil); finalization //InternalMsgList.Free ? end.
unit Comp_UFlipPanel; interface uses Controls, Messages, Classes, Windows, Graphics, Types, Comp_UControls, Comp_UTypes, Comp_UIntf; const szFlipPanelHeaderHeight = 20; { Padding } pdStandard = 2; pdDouble = pdStandard * 2; pdEditToText = 4; pdTextToIcon = 4; pdHorz = 2; pdVert = 1; type TScCollectionControl = class(TScControl) //class(TScStyledControl) private FAlpha: Byte; function GetControlName: string; procedure SetAlpha(const Value: Byte); protected procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; { Windows Messages } procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED; procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; { Properties } property DoubleBuffered; published property Alpha: Byte read FAlpha write SetAlpha default 255; property ControlName: string read GetControlName; end; TScBorders = set of (bdBottom, bdLeft, bdRight, bdTop); TScPanelStyle = (pnSolid, pnGradient, pnInverseGradient); TScPanel = class(TScCollectionControl) private FBorders: TScBorders; FCaption: WideString; FEffects: TScPaintEffects; FPen: TPen; procedure SetBorders(const Value: TScBorders); procedure SetCaption(const Value: WideString); procedure SetEffects(const Value: TScPaintEffects); procedure SetPen(const Value: TPen); protected procedure CreateParams(var Params: TCreateParams); override; procedure DoCaptionChange; virtual; procedure DoChange(Sender: TObject); function GetPanelRect: TRect; virtual; procedure Paint; override; { Windows Messages } procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Methods } procedure Assign(Source: TPersistent); override; published { Properties } property Borders: TScBorders read FBorders write SetBorders default [bdBottom, bdLeft, bdRight, bdTop]; property Caption: WideString read FCaption write SetCaption; property Effects: TScPaintEffects read FEffects write SetEffects default []; property Pen: TPen read FPen write SetPen; end; TScHeaderLayout = (hlLeftToRight, hlRightToLeft); TScFlipChangeArea = (faButton, faHeader, faNone); TScGlyphPosition = (gpBeforeText, gpAfterText); TScFlipPanel = class(TScPanel, ITogglable) private FExpanded: Boolean; FFlipChangeArea: TScFlipChangeArea; FFullHeight: Integer; FGlyph: TPicture; FGlyphCollapse: TBitmap; FGlyphExpand: TBitmap; FGlyphPosition: TScGlyphPosition; FHeaderBorderColor: TColor; FHeaderColor: TColor; FHeaderFont: TFont; FHeaderHeight: Integer; FHeaderIndent: Integer; FHeaderLayout: TScHeaderLayout; FHeaderState: TScButtonState; FHeaderStyle: TScAppearanceStyle; FHeaderStyleOptions: TScStyleOptions; FHotTrack: Boolean; FPanelPadding: TPadding; FParentHeaderFont: Boolean; FShowHeader: Boolean; FShowToggleButton: Boolean; FToggleButtonStyle: TScToggleButtonStyle; function GetToggleButtonStyle: TScToggleButtonStyle; function GetToggleSize: TSize; procedure SetExpanded(const Value: Boolean); procedure SetGlyph(const Value: TPicture); procedure SetGlyphCollapse(const Value: TBitmap); procedure SetGlyphExpand(const Value: TBitmap); procedure SetGlyphPosition(const Value: TScGlyphPosition); procedure SetHeaderBorderColor(const Value: TColor); procedure SetHeaderColor(const Value: TColor); procedure SetHeaderFont(const Value: TFont); procedure SetHeaderHeight(const Value: Integer); procedure SetHeaderIndent(const Value: Integer); procedure SetHeaderLayout(const Value: TScHeaderLayout); procedure SetHeaderState(const Value: TScButtonState); procedure SetHeaderStyle(const Value: TScAppearanceStyle); procedure SetHeaderStyleOptions(const Value: TScStyleOptions); procedure SetHotTrack(const Value: Boolean); procedure SetPanelPadding(const Value: TPadding); procedure SetParentHeaderFont(const Value: Boolean); procedure SetShowHeader(const Value: Boolean); procedure SetShowToggleButton(const Value: Boolean); procedure SetToggleStyle(const Value: TScToggleButtonStyle); protected { Event Handlers } procedure DoChange; dynamic; procedure DoCaptionChange; override; procedure DoHeaderChange(Sender: TObject); procedure DoHeaderFontChange(Sender: TObject); procedure DoInnerPaddingChange(Sender: TObject); procedure DoPaddingChange(Sender: TObject); override; function GetHeaderRect: TRect; virtual; function GetPanelRect: TRect; override; function GetToggleRect: TRect; virtual; { Stream Methods } procedure DefineProperties(Filer: TFiler); override; procedure ReadFullHeight(Reader: TReader); procedure WriteFullHeight(Writer: TWriter); { Overrided Methods } procedure AdjustClientRect(var Rect: TRect); override; procedure CreateParams(var Params: TCreateParams); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; { Methods } procedure InvalidateHeader; procedure PaintHeader(HeaderRect: TRect); virtual; procedure PaintToggle(X: Integer); { Delphi Messages } procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; { WinApi Messages } procedure WMSize(var Message: TWMSize); message WM_SIZE; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Methods } procedure Assign(Source: TPersistent); override; procedure Flip; { Properties } property ToggleRect: TRect read GetToggleRect; property ToggleSize: TSize read GetToggleSize; property HeaderState: TScButtonState read FHeaderState write SetHeaderState; published { Properties } property Expanded: Boolean read FExpanded write SetExpanded default True; property FlipChangeArea: TScFlipChangeArea read FFlipChangeArea write FFlipChangeArea default faButton; property Glyph: TPicture read FGlyph write SetGlyph; property GlyphCollapse: TBitmap read FGlyphCollapse write SetGlyphCollapse; property GlyphExpand: TBitmap read FGlyphExpand write SetGlyphExpand; property GlyphPosition: TScGlyphPosition read FGlyphPosition write SetGlyphPosition default gpBeforeText; property HeaderBorderColor: TColor read FHeaderBorderColor write SetHeaderBorderColor default clBtnShadow; property HeaderColor: TColor read FHeaderColor write SetHeaderColor default clBtnFace; property HeaderFont: TFont read FHeaderFont write SetHeaderFont; property HeaderHeight: Integer read FHeaderHeight write SetHeaderHeight default szFlipPanelHeaderHeight; property HeaderLayout: TScHeaderLayout read FHeaderLayout write SetHeaderLayout default hlLeftToRight; property HeaderStyle: TScAppearanceStyle read FHeaderStyle write SetHeaderStyle default stNative; property HeaderStyleOptions: TScStyleOptions read FHeaderStyleOptions write SetHeaderStyleOptions default [soNativeStyles, soVCLStyles]; property HeaderIndent: Integer read FHeaderIndent write SetHeaderIndent default pdDouble; property HotTrack: Boolean read FHotTrack write SetHotTrack default False; property PanelPadding: TPadding read FPanelPadding write SetPanelPadding; property ParentHeaderFont: Boolean read FParentHeaderFont write SetParentHeaderFont default True; property ShowHeader: Boolean read FShowHeader write SetShowHeader default True; property ShowToggleButton: Boolean read FShowToggleButton write SetShowToggleButton default True; property ToggleButtonStyle: TScToggleButtonStyle read GetToggleButtonStyle write SetToggleStyle default tsSquare; end; var UnicodeSupported: Boolean; implementation uses SysUtils, Forms, Math, Comp_UGraphics; {$REGION 'TScCollectionControl'} { TScCollectionControl } procedure TScCollectionControl.Assign(Source: TPersistent); begin inherited; if Source is TScCollectionControl then begin Alpha := TScCollectionControl(Source).Alpha; end; end; constructor TScCollectionControl.Create(AOwner: TComponent); begin inherited; FAlpha := 255; end; procedure TScCollectionControl.CreateParams(var Params: TCreateParams); begin inherited; with Params do begin if Alpha < 255 then ExStyle := ExStyle or WS_EX_TRANSPARENT; end; end; function TScCollectionControl.GetControlName: string; begin Result := ClassName; end; procedure TScCollectionControl.Paint; begin inherited; if Alpha < 255 then begin EraseBackground(Self, Canvas); end; end; procedure TScCollectionControl.SetAlpha(const Value: Byte); var Update: Boolean; begin if Value <> FAlpha then begin { Not solid anymore } Update := FAlpha = 255; FAlpha := Value; { Call CreateParams } if Update then RecreateWnd; Invalidate; end; end; procedure TScCollectionControl.WMEraseBkgnd(var Message: TWmEraseBkgnd); begin Message.Result := 1; end; procedure TScCollectionControl.WMWindowPosChanged(var Message: TWMWindowPosChanged); begin inherited; if Alpha < 255 then Invalidate; end; procedure TScCollectionControl.WMWindowPosChanging(var Message: TWMWindowPosChanging); begin inherited; if Alpha < 255 then Invalidate; end; {$ENDREGION} {$REGION 'TScPanel'} { TScPanel } procedure TScPanel.Assign(Source: TPersistent); begin inherited; if Source is TScPanel then begin Borders := TScPanel(Source).Borders; Pen.Assign(TScPanel(Source).Pen); end; end; constructor TScPanel.Create(AOwner: TComponent); begin inherited; ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks, csReplicatable, csSetCaption]; FBorders := [bdBottom, bdLeft, bdRight, bdTop]; FEffects := []; FPen := TPen.Create; end; procedure TScPanel.CreateParams(var Params: TCreateParams); begin inherited; with Params do begin with WindowClass do Style := Style and not CS_HREDRAW and not CS_VREDRAW; end; end; destructor TScPanel.Destroy; begin FreeAndNil(FPen); inherited; end; procedure TScPanel.DoCaptionChange; begin end; procedure TScPanel.DoChange(Sender: TObject); begin Invalidate; end; function TScPanel.GetPanelRect: TRect; begin Result := ClientRect; end; procedure TScPanel.Paint; var FillColor: TColor; begin inherited; { Panel (content) paint } if RectInRect(ClientRect, GetPanelRect) then begin { Default, no style } FillColor := Color; { Only Delphi Style can have own color } // if CanStyle(soVCLStyles) then // begin // FillColor := TScPanelPaintStyle.GetFillColor(Self, FillColor); // end; { Fill with Color } ColorOverlay(Canvas, GetPanelRect, FillColor, Alpha); { Apply Filters & Effects } PaintEffects(Canvas, GetPanelRect, Effects); end; end; procedure TScPanel.SetBorders(const Value: TScBorders); begin if Value <> FBorders then begin FBorders := Value; Invalidate; end; end; procedure TScPanel.SetCaption(const Value: WideString); begin if Value <> FCaption then begin FCaption := Value; { Virtual } DoCaptionChange; end; end; procedure TScPanel.SetEffects(const Value: TScPaintEffects); begin if Value <> FEffects then begin FEffects := Value; Invalidate; end; end; procedure TScPanel.SetPen(const Value: TPen); begin FPen.Assign(Value); if Assigned(FPen) then FPen.OnChange := DoChange; Invalidate; end; procedure TScPanel.WMEraseBkgnd(var Message: TWmEraseBkgnd); begin Message.Result := 1; end; procedure TScPanel.WMWindowPosChanged(var Message: TWMWindowPosChanged); begin inherited; end; {$ENDREGION} {$REGION 'TScFlipPanel'} { TScFlipPanel } procedure TScFlipPanel.AdjustClientRect(var Rect: TRect); begin inherited; Inc(Rect.Top, FHeaderHeight + FPanelPadding.Top); Inc(Rect.Left, FPanelPadding.Left); Dec(Rect.Bottom, FPanelPadding.Bottom); Dec(Rect.Right, FPanelPadding.Right); end; procedure TScFlipPanel.Assign(Source: TPersistent); begin inherited; if Source is TScFlipPanel then begin Expanded := TScFlipPanel(Source).Expanded; FlipChangeArea := TScFlipPanel(Source).FlipChangeArea; Glyph.Assign(TScFlipPanel(Source).Glyph); GlyphCollapse.Assign(TScFlipPanel(Source).Glyph); GlyphExpand.Assign(TScFlipPanel(Source).Glyph); GlyphPosition := TScFlipPanel(Source).GlyphPosition; HeaderBorderColor := TScFlipPanel(Source).HeaderBorderColor; HeaderColor := TScFlipPanel(Source).HeaderColor; HeaderFont.Assign(TScFlipPanel(Source).HeaderFont); HeaderHeight := TScFlipPanel(Source).HeaderHeight; HeaderIndent := TScFlipPanel(Source).HeaderIndent; HeaderStyle := TScFlipPanel(Source).HeaderStyle; HotTrack := TScFlipPanel(Source).HotTrack; ParentHeaderFont := TScFlipPanel(Source).ParentHeaderFont; ShowHeader := TScFlipPanel(Source).ShowHeader; ShowToggleButton := TScFlipPanel(Source).ShowToggleButton; ToggleButtonStyle := TScFlipPanel(Source).ToggleButtonStyle; end; end; procedure TScFlipPanel.CMDialogChar(var Message: TCMDialogChar); begin inherited; with Message do begin if IsAccel(CharCode, Caption) then begin Flip; Result := 1; end else inherited; end; end; procedure TScFlipPanel.CMFontChanged(var Message: TMessage); begin inherited; if ParentHeaderFont then begin HeaderFont.OnChange := nil; HeaderFont := Font; end; end; procedure TScFlipPanel.CMMouseLeave(var Message: TMessage); begin inherited; HeaderState := HeaderState - [bsHover]; end; procedure TScFlipPanel.CMTextChanged(var Message: TMessage); begin inherited; end; constructor TScFlipPanel.Create(AOwner: TComponent); begin inherited; FExpanded := True; FFlipChangeArea := faButton; FGlyph := TPicture.Create; FGlyph.OnChange := DoHeaderChange; FGlyphCollapse := TBitmap.Create; FGlyphCollapse.OnChange := DoHeaderChange; FGlyphExpand := TBitmap.Create; FGlyphExpand.OnChange := DoHeaderChange; FGlyphPosition := gpBeforeText; FHeaderBorderColor := clBtnShadow; FHeaderColor := clBtnFace; FHeaderFont := TFont.Create; FHeaderFont.OnChange := DoHeaderFontChange; FHeaderHeight := szFlipPanelHeaderHeight; FHeaderIndent := pdDouble; FHeaderLayout := hlLeftToRight; FHeaderState := []; FHeaderStyle := stNative; FHeaderStyleOptions := [soNativeStyles, soVCLStyles]; FHotTrack := False; FPanelPadding := TPadding.Create(nil); FPanelPadding.OnChange := DoInnerPaddingChange; FParentHeaderFont := True; FShowToggleButton := True; FShowHeader := True; FToggleButtonStyle := tsSquare; Height := 128; Width := 128; end; procedure TScFlipPanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin with WindowClass do Style := Style or CS_HREDRAW or CS_VREDRAW; end; end; procedure TScFlipPanel.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('FullHeight', ReadFullHeight, WriteFullHeight, True); end; destructor TScFlipPanel.Destroy; begin FreeAndNil(FGlyph); FreeAndNil(FGlyphCollapse); FreeAndNil(FGlyphExpand); FreeAndNil(FHeaderFont); FreeAndNil(FPanelPadding); inherited; end; procedure TScFlipPanel.DoCaptionChange; begin InvalidateHeader; end; procedure TScFlipPanel.DoChange; begin end; procedure TScFlipPanel.DoHeaderChange(Sender: TObject); begin InvalidateHeader; end; procedure TScFlipPanel.DoHeaderFontChange(Sender: TObject); begin if not (csLoading in ComponentState) then begin FParentHeaderFont := False; end; InvalidateHeader; end; procedure TScFlipPanel.DoInnerPaddingChange(Sender: TObject); begin Invalidate; Realign; end; procedure TScFlipPanel.DoPaddingChange(Sender: TObject); begin inherited; Invalidate; end; procedure TScFlipPanel.Flip; begin Expanded := not Expanded; end; function TScFlipPanel.GetToggleButtonStyle: TScToggleButtonStyle; begin Result := FToggleButtonStyle; end; function TScFlipPanel.GetToggleRect: TRect; var Y: Integer; begin Y := Ceil(HeaderHeight / 2) - Ceil(ToggleSize.cy / 2); case FHeaderLayout of hlLeftToRight: Result := Bounds(FHeaderIndent, Y, ToggleSize.cx, ToggleSize.cy); hlRightToLeft: Result := Bounds(ClientWidth - FHeaderIndent - ToggleSize.cx, Y, ToggleSize.cx, ToggleSize.cy); end; end; function TScFlipPanel.GetToggleSize: TSize; var D: Integer; begin case FToggleButtonStyle of tsStyleNative: Result := Size(9, 9); tsTriangle: begin D := Round(HeaderHeight / 2.66); Result := Size(D, D); end; tsSquare: Result := Size(9, 9); tsGlyph: begin if Expanded and Assigned(GlyphCollapse) then Result := Size(GlyphCollapse.Width, GlyphCollapse.Height) else if Assigned(GlyphExpand) then Result := Size(GlyphExpand.Width, GlyphExpand.Height); end; end; end; function TScFlipPanel.GetHeaderRect: TRect; begin Result := Bounds(0, 0, ClientWidth, HeaderHeight); end; function TScFlipPanel.GetPanelRect: TRect; begin Result := inherited GetPanelRect; Inc(Result.Top, HeaderHeight); end; procedure TScFlipPanel.InvalidateHeader; begin InvalidateRect(GetHeaderRect); end; procedure TScFlipPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if PtInRect(GetHeaderRect, Point(X, Y)) then HeaderState := HeaderState + [bsPressed]; end; procedure TScFlipPanel.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if HotTrack and PtInRect(GetHeaderRect, Point(X, Y)) then HeaderState := HeaderState + [bsHover] else HeaderState := HeaderState - [bsHover]; end; procedure TScFlipPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var CanFlip: Boolean; begin inherited; CanFlip := False; case FlipChangeArea of faButton: CanFlip := ShowToggleButton and PtInRect(GetToggleRect, Point(X, Y)); faHeader: CanFlip := PtInRect(GetHeaderRect, Point(X, Y)); faNone: ; end; { Set Expanded } if CanFlip then Flip; HeaderState := HeaderState - [bsPressed]; end; procedure TScFlipPanel.Paint; var PanelRect: TRect; PaddingColor: TColor; begin inherited Paint; if csDesigning in ComponentState then begin PanelRect := ClientRect; Inc(PanelRect.Top, FHeaderHeight); PaddingColor := IfThen(IsColorLight(Color), DarkerColor(Color, 5), LighterColor(Color, 25)); FillPadding(Canvas, PaddingColor, PanelRect, PanelPadding); end; PaintHeader(GetHeaderRect); end; procedure TScFlipPanel.PaintToggle(X: Integer); var Y, C: Integer; Bitmap: TBitmap; begin Y := FHeaderHeight div 2; with Canvas do case FToggleButtonStyle of tsStyleNative: begin TScTreeStyledView.PaintToggle(Canvas, Self.Handle, ToggleRect, Expanded, HeaderState, HeaderStyleOptions); end; tsTriangle: if Expanded then begin Y := Y - ToggleSize.cy div 2; if bsHover in FHeaderState then begin Brush.Color := ColorOf(seMenu); end else begin Brush.Color := $00444444; end; Pen.Color := Brush.Color; C := ToggleSize.cy - 1; Polygon([ Point(X, Y + C), Point(X + C, Y + C), Point(X + C, Y), Point(X, Y + C) ]); end else begin Y := Y - Pred(ToggleSize.cy); if bsHover in FHeaderState then begin Brush.Color := ColorOf(seBtnFramePressed); Pen.Color := Brush.Color; end else begin Brush.Color := clWhite; Pen.Color := $00888683; end; Polygon([ Point(X, Y), Point(X + ToggleSize.cx - 2, Y + ToggleSize.cx - 2), Point(X, Y + (ToggleSize.cx - 2) * 2), Point(X, Y) ]); end; tsSquare: begin Pen.Color := clGray; Brush.Color := HeaderColor; Rectangle(ToggleRect); C := Floor(ToggleSize.cx / 2); Polyline([ Point(ToggleRect.Left + 2, ToggleRect.Top + C), Point(ToggleRect.Right - 2, ToggleRect.Top + C) ]); if not Expanded then Polyline([ Point(ToggleRect.Left + C, ToggleRect.Top + 2), Point(ToggleRect.Left + C, ToggleRect.Bottom - 2) ]); end; tsGlyph: begin Bitmap := nil; Y := Floor(HeaderHeight / 2) - Floor(ToggleSize.cy / 2); if Expanded and Assigned(GlyphCollapse) then Bitmap := GlyphCollapse else if Assigned(GlyphExpand) then Bitmap := GlyphExpand; if Assigned(Bitmap) then begin Bitmap.TransparentColor := Bitmap.Canvas.Pixels[0, Bitmap.Height - 1]; Bitmap.Transparent := True; Draw(X, Y, Bitmap); end; end; end; end; procedure TScFlipPanel.PaintHeader(HeaderRect: TRect); var Location, GlyphLocation: TPoint; CaptionRect: TRect; CaptionAlignment: TAlignment; begin with Canvas do begin { Background } if (not HotTrack) or (FHeaderState <> []) then begin case FHeaderStyle of stNative: if SupportStyle(HeaderStyleOptions) then begin TScHeaderStyle.Paint(Canvas, Self.Handle, HeaderRect, HeaderState, HeaderStyleOptions); end else begin Brush.Color := HeaderColor; FillRect(HeaderRect); end; stUserDefined: begin Brush.Color := HeaderColor; Pen.Color := HeaderBorderColor; Rectangle(HeaderRect); end; stModern: begin Brush.Color := HeaderColor; if bsHover in FHeaderState then Brush.Color := ColorOf(seBtnFace); if bsPressed in FHeaderState then Brush.Color := ColorOf(seBtnFacePressed); if Expanded then begin Pen.Color := ColorOf(seBtnFacePressed); Rectangle(HeaderRect); end else FillRect(HeaderRect); end; end; end else begin Brush.Color := Color; FillRect(HeaderRect); end; case FHeaderLayout of hlLeftToRight: Location := Point(FHeaderIndent, 0); hlRightToLeft: Location := Point(ClientWidth - FHeaderIndent, 0); end; { Button } if ShowToggleButton then begin if FHeaderLayout = hlRightToLeft then Dec(Location.X, ToggleSize.cx); PaintToggle(Location.X); case FHeaderLayout of hlLeftToRight: Inc(Location.X, pdDouble + ToggleSize.cx); hlRightToLeft: Dec(Location.X, pdDouble); end; end; { Icon } if Assigned(FGlyph) and Assigned(FGlyph.Graphic) and not FGlyph.Graphic.Empty then begin GlyphLocation := Location; case GlyphPosition of gpAfterText: begin case FHeaderLayout of hlLeftToRight: GlyphLocation.X := HeaderRect.Right - FGlyph.Width - pdDouble; hlRightToLeft: GlyphLocation.X := pdDouble; end; end; gpBeforeText: begin if FHeaderLayout = hlRightToLeft then Dec(GlyphLocation.X, FGlyph.Width); case FHeaderLayout of hlLeftToRight: Inc(Location.X, FGlyph.Width + pdDouble); hlRightToLeft: Dec(Location.X, FGlyph.Width + pdDouble); end; end; end; GlyphLocation.Y := HeaderHeight div 2 - FGlyph.Height div 2; Canvas.Draw(GlyphLocation.X, GlyphLocation.Y, FGlyph.Graphic); end; { Title } Font.Assign(HeaderFont); case FHeaderLayout of hlLeftToRight: begin CaptionRect := Rect(Location.X, 0, ClientWidth, FHeaderHeight); CaptionAlignment := taLeftJustify; end; else begin CaptionRect := Rect(0, 0, Location.X, FHeaderHeight); CaptionAlignment := taRightJustify; end; end; DrawTextRect(Canvas, CaptionRect, CaptionAlignment, taVerticalCenter, Caption, wkEllipsis); end; end; procedure TScFlipPanel.ReadFullHeight(Reader: TReader); begin FFullHeight := Reader.ReadInteger; if not FExpanded then begin Height := FHeaderHeight; end else Height := FFullHeight; end; procedure TScFlipPanel.SetExpanded(const Value: Boolean); begin if Value <> FExpanded then begin FExpanded := Value; InvalidateHeader; if FExpanded then begin ClientHeight := FFullHeight; end else begin FFullHeight := ClientHeight; ClientHeight := HeaderHeight; end; end; end; procedure TScFlipPanel.SetGlyph(const Value: TPicture); begin FGlyph.Assign(Value); if Assigned(FGlyph) then FGlyph.OnChange := DoHeaderChange; end; procedure TScFlipPanel.SetGlyphCollapse(const Value: TBitmap); begin if FGlyphCollapse <> Value then begin FGlyphCollapse.Assign(Value); if Assigned(FGlyphCollapse) then FGlyphCollapse.OnChange := DoHeaderChange; end; end; procedure TScFlipPanel.SetGlyphExpand(const Value: TBitmap); begin if FGlyphExpand <> Value then begin FGlyphExpand.Assign(Value); if Assigned(FGlyphExpand) then FGlyphExpand.OnChange := DoHeaderChange; end; end; procedure TScFlipPanel.SetGlyphPosition(const Value: TScGlyphPosition); begin if Value <> FGlyphPosition then begin FGlyphPosition := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderBorderColor(const Value: TColor); begin if Value <> FHeaderBorderColor then begin FHeaderBorderColor := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderColor(const Value: TColor); begin if Value <> FHeaderColor then begin FHeaderColor := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderFont(const Value: TFont); begin FHeaderFont.Assign(Value); FHeaderFont.OnChange := DoHeaderFontChange; end; procedure TScFlipPanel.SetHeaderHeight(const Value: Integer); begin if Value <> FHeaderHeight then begin FHeaderHeight := Value; Invalidate; Realign; end; end; procedure TScFlipPanel.SetHeaderIndent(const Value: Integer); begin if Value <> FHeaderIndent then begin FHeaderIndent := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderState(const Value: TScButtonState); begin if Value <> FHeaderState then begin FHeaderState := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderStyle(const Value: TScAppearanceStyle); begin if Value <> FHeaderStyle then begin FHeaderStyle := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderStyleOptions(const Value: TScStyleOptions); begin if Value <> FHeaderStyleOptions then begin FHeaderStyleOptions := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHeaderLayout(const Value: TScHeaderLayout); begin if Value <> FHeaderLayout then begin FHeaderLayout := Value; InvalidateHeader; end; end; procedure TScFlipPanel.SetHotTrack(const Value: Boolean); begin if Value <> FHotTrack then begin FHotTrack := Value; Invalidate; end; end; procedure TScFlipPanel.SetPanelPadding(const Value: TPadding); begin FPanelPadding := Value; FPanelPadding.OnChange := DoInnerPaddingChange; end; procedure TScFlipPanel.SetParentHeaderFont(const Value: Boolean); begin if FParentHeaderFont <> Value then begin FParentHeaderFont := Value; if FParentHeaderFont then FHeaderFont.Assign(Font); InvalidateHeader; end; end; procedure TScFlipPanel.SetShowToggleButton(const Value: Boolean); begin if Value <> FShowToggleButton then begin FShowToggleButton := Value; Invalidate; end; end; procedure TScFlipPanel.SetShowHeader(const Value: Boolean); begin if Value <> FShowHeader then begin FShowHeader := Value; Invalidate; end; end; procedure TScFlipPanel.SetToggleStyle(const Value: TScToggleButtonStyle); begin if Value <> FToggleButtonStyle then begin FToggleButtonStyle := Value; InvalidateHeader; end; end; procedure TScFlipPanel.WMSize(var Message: TWMSize); var OldHeaderHeight: Integer; begin inherited; if not Expanded then begin OldHeaderHeight := HeaderHeight; HeaderHeight := ClientHeight; Inc(FFullHeight, HeaderHeight - OldHeaderHeight); end else begin FFullHeight := ClientHeight; end; end; procedure TScFlipPanel.WriteFullHeight(Writer: TWriter); begin Writer.WriteInteger(FFullHeight); end; end.
{#################################################################################################################### TINJECT - Componente de comunicação (Não Oficial) www.tinject.com.br Novembro de 2019 #################################################################################################################### Owner.....: Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385 Developer.: Joathan Theiller - jtheiller@hotmail.com - #################################################################################################################### Obs: - Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR Mike W. Lustosa; - Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor; - Mantenha sempre a versao mais atual acima das demais; - Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de compilação (último digito); #################################################################################################################### Evolução do Código #################################################################################################################### Autor........: Email........: Data.........: Identificador: Modificação..: #################################################################################################################### } unit uTInject.Console; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, StrUtils, uCEFWinControl, uCEFChromiumCore, uCEFTypes, uCEFInterfaces, uCEFConstants, uCEFWindowParent, uCEFChromium, //units adicionais obrigatórias uTInject.Classes, uTInject.constant, uTInject.Diversos, Vcl.StdCtrls, Vcl.ComCtrls, System.ImageList, Vcl.ImgList, System.JSON, Vcl.Buttons, Vcl.Imaging.pngimage, Rest.Json, Vcl.Imaging.jpeg, uCEFSentinel, uTInject.FrmQRCode, Vcl.WinXCtrls; type TProcedure = procedure() of object; TFrmConsole = class(TForm) Chromium1: TChromium; Pnl_Top: TPanel; Img_Brasil: TImage; Lbl_Caption: TLabel; CEFSentinel1: TCEFSentinel; Pnl_Geral: TPanel; CEFWindowParent1: TCEFWindowParent; lbl_Versao: TLabel; Img_LogoInject: TImage; procedure Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); procedure Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); procedure Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; const popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var extra_info: ICefDictionaryValue; var noJavascriptAccess, Result: Boolean); procedure Chromium1Close(Sender: TObject; const browser: ICefBrowser; var aAction: TCefCloseBrowserAction); procedure Chromium1OpenUrlFromTab(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; out Result: Boolean); procedure Chromium1TitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Chromium1ConsoleMessage(Sender: TObject; const browser: ICefBrowser; level: Cardinal; const message, source: ustring; line: Integer; out Result: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); Procedure ProcessQrCode(Var pClass: TObject); procedure CEFSentinel1Close(Sender: TObject); Procedure ProcessPhoneBook(PCommand: string); procedure ProcessGroupBook(PCommand: string); procedure FormShow(Sender: TObject); procedure App_EventMinimize(Sender: TObject); procedure Chromium1BeforeDownload(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); procedure Chromium1DownloadUpdated(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); procedure lbl_VersaoMouseEnter(Sender: TObject); procedure Chromium1BeforeContextMenu(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); procedure Button2Click(Sender: TObject); procedure Image2Click(Sender: TObject); protected // You have to handle this two messages to call NotifyMoveOrResizeStarted or some page elements will be misaligned. procedure WMMove(var aMessage : TWMMove); message WM_MOVE; procedure WMMoving(var aMessage : TMessage); message WM_MOVING; // You also have to handle these two messages to set GlobalCEFApp.OsmodalLoop procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP; procedure WMExitMenuLoop (var aMessage: TMessage); message WM_EXITMENULOOP; procedure BrowserDestroyMsg(var aMessage : TMessage); message CEF_DESTROY; procedure RequestCloseInject(var aMessage : TMessage); message FrmConsole_Browser_Direto; procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; Procedure OnTimerMonitoring(Sender: TObject); procedure OnTimerConnect(Sender: TObject); procedure OnTimerGetQrCode(Sender: TObject); Procedure ExecuteCommandConsole(Const PResponse: TResponseConsoleMessage); private { Private declarations } LPaginaId, Fzoom : integer; FCanClose : Boolean; FDirTemp : String; FConectado : Boolean; FTimerConnect : TTimer; FTimerMonitoring : TTimer; FOnNotificationCenter : TNotificationCenter; FGetProfilePicThumbURL : string; FCountBattery : Integer; FCountBatteryMax : Integer; FrmQRCode : TFrmQRCode; FFormType : TFormQrCodeType; FHeaderAtual : TTypeHeader; FChatList : TChatList; FMonitorLowBattry : Boolean; FgettingContact : Boolean; FgettingGroups : Boolean; FgettingChats : Boolean; FOnErrorInternal : TOnErroInternal; FOwner : TComponent; Procedure ReleaseConnection; Procedure Int_FrmQRCodeClose(Sender: TObject); Function GetAutoBatteryLeveL: Boolean; Procedure ISLoggedin; procedure ExecuteJS(PScript: WideString; PDirect: Boolean = false; Purl:String = 'about:blank'; pStartline: integer=0); procedure ExecuteJSDir(PScript: WideString; Purl:String = 'about:blank'; pStartline: integer=0); procedure QRCodeForm_Start; procedure QRCodeWeb_Start; Procedure ResetEvents; procedure SetOwner(const Value: TComponent); Procedure SendNotificationCenterDirect(PValor: TTypeHeader; Const PSender : TObject= nil); Procedure Form_Start; Procedure Form_Normal; public { Public declarations } Function ConfigureNetWork:Boolean; Procedure SetZoom(Pvalue: Integer); Property Conectado: Boolean Read FConectado; Property OwnerForm: TComponent Read FOwner Write SetOwner; Procedure StartQrCode(PQrCodeType :TFormQrCodeType; PViewForm:Boolean); Procedure StopQrCode(PQrCodeType: TFormQrCodeType); Property FormQrCode : TFrmQRCode Read FrmQRCode; Property ChatList : TChatList Read FChatList; property OnErrorInternal : TOnErroInternal Read FOnErrorInternal Write FOnErrorInternal; Property MonitorLowBattry : Boolean Read FMonitorLowBattry Write FMonitorLowBattry; Property OnNotificationCenter : TNotificationCenter Read FOnNotificationCenter Write FOnNotificationCenter; procedure GetProfilePicThumbURL(AProfilePicThumbURL: string); Procedure Connect; Procedure DisConnect; procedure Send(vNum, vText:string); procedure SendButtons(phoneNumber, titleText, buttons, footerText: string; etapa: string = ''); procedure SendButtonList(phoneNumber, titleText1, titleText2, titleButton, options: string; etapa: string = ''); procedure SendPool(vGroupID, vTitle, vSurvey: string); procedure CheckDelivered; procedure SendContact(vNumDest, vNum:string; vNameContact: string = ''); procedure SendBase64(vBase64, vNum, vFileName, vText:string); procedure SendLinkPreview(vNum, vLinkPreview, vText: string); procedure SendLocation(vNum, vLat, vLng, vName, vAddress: string); procedure Logout(); procedure ReloaderWeb; procedure StopWebBrowser; procedure GetAllContacts(PIgnorarLeitura1: Boolean = False); procedure GetAllGroups(PIgnorarLeitura1: Boolean = False); procedure GroupAddParticipant(vIDGroup, vNumber: string); procedure GroupRemoveParticipant(vIDGroup, vNumber: string); procedure GroupPromoteParticipant(vIDGroup, vNumber: string); procedure GroupDemoteParticipant(vIDGroup, vNumber: string); procedure GroupLeave(vIDGroup: string); procedure GroupDelete(vIDGroup: string); procedure GroupJoinViaLink(vLinkGroup: string); procedure getGroupInviteLink(vIDGroup: string); procedure revokeGroupInviteLink(vIDGroup: string); procedure setNewName(newName: string); procedure setNewStatus(newStatus: string); procedure getStatus(vTelefone: string); procedure CleanChat(vTelefone: string); procedure fGetMe; procedure NewCheckIsValidNumber(vNumber:String); procedure GetAllChats; procedure GetUnreadMessages; procedure GetBatteryLevel; procedure CheckIsValidNumber(vNumber:string); procedure CheckIsConnected; procedure GetMyNumber; procedure CreateGroup(vGroupName, PParticipantNumber: string); procedure listGroupContacts(vIDGroup: string); procedure listGroupAdmins(vIDGroup: string); //Para monitorar o qrcode via REST procedure ReadMessages(vID: string); procedure DeleteMessages(vID: string); procedure ReadMessagesAndDelete(vID: string); procedure StartMonitor(Seconds: Integer); procedure StopMonitor; end; var FrmConsole: TFrmConsole; implementation uses System.NetEncoding, Vcl.Dialogs, uTInject.ConfigCEF, uTInject, uCEFMiscFunctions, Data.DB, uTInject.FrmConfigNetWork, Winapi.ShellAPI; {$R *.dfm} procedure TFrmConsole.App_EventMinimize(Sender: TObject); begin Hide; end; procedure TFrmConsole.BrowserDestroyMsg(var aMessage : TMessage); begin CEFWindowParent1.Free; SleepNoFreeze(10); SendNotificationCenterDirect(Th_Disconnected); SleepNoFreeze(150); SendNotificationCenterDirect(Th_Destroying); SleepNoFreeze(10); end; procedure TFrmConsole.Button2Click(Sender: TObject); begin Chromium1.LoadURL(FrmConsole_JS_URL); end; procedure TFrmConsole.WMMove(var aMessage : TWMMove); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TFrmConsole.WMMoving(var aMessage : TMessage); begin inherited; if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted; end; procedure TFrmConsole.WMSysCommand(var Message: TWMSysCommand); begin if(Message.CmdType = SC_MINIMIZE)then Hide else inherited; end; procedure TFrmConsole.ExecuteJS(PScript: WideString; PDirect: Boolean; Purl:String; pStartline: integer); var lThread : TThread; begin if Assigned(GlobalCEFApp) then Begin if GlobalCEFApp.ErrorInt Then Exit; end; if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); If Chromium1.Browser <> nil then begin if PDirect Then Begin Chromium1.Browser.MainFrame.ExecuteJavaScript(PScript, Purl, pStartline); Exit; end; lThread := TThread.CreateAnonymousThread(procedure begin TThread.Synchronize(nil, procedure begin if Assigned(FrmConsole) then FrmConsole.Chromium1.Browser.MainFrame.ExecuteJavaScript(PScript, Purl, pStartline) end); end); lThread.Start; end; end; procedure TFrmConsole.ExecuteJSDir(PScript: WideString; Purl: String; pStartline: integer); begin Chromium1.Browser.MainFrame.ExecuteJavaScript(PScript, Purl, pStartline) end; procedure TFrmConsole.QRCodeWeb_Start; begin ExecuteJS(FrmConsole_JS_WEBmonitorQRCode, False); end; procedure TFrmConsole.QRCodeForm_Start; begin ExecuteJS(FrmConsole_JS_monitorQRCode, False); end; procedure TFrmConsole.OnTimerConnect(Sender: TObject); var lNovoStatus: Boolean; begin lNovoStatus := True; FTimerConnect.Enabled := False; try If TInject(FOwner).Status = Server_Connected then Begin ExecuteJSDir(TInject(FOwner).InjectJS.JSScript.Text); SleepNoFreeze(40); If Assigned(TInject(FOwner).OnAfterInjectJs) Then TInject(FOwner).OnAfterInjectJs(FOwner); //Auto monitorar mensagens não lidas StartMonitor(TInject(FOwner).Config.SecondsMonitor); SleepNoFreeze(40); lNovoStatus := False; SendNotificationCenterDirect(Th_Initializing); End; finally FTimerConnect.Enabled := lNovoStatus; end; end; procedure TFrmConsole.OnTimerGetQrCode(Sender: TObject); begin TTimer(Sender).Enabled := False; try try if (FFormType in [Ft_Desktop, Ft_none]) Then QRCodeForm_Start else QRCodeWeb_Start; Except end; finally TTimer(Sender).Enabled := True; end; end; procedure TFrmConsole.OnTimerMonitoring(Sender: TObject); begin //Testa se existe alguma desconexão por parte do aparelho... if Application.Terminated then Exit; FTimerMonitoring.Enabled := False; try if not TInject(FOwner).authenticated then Exit; If MonitorLowBattry THen Begin if GetAutoBatteryLeveL then GetBatteryLevel; End; //Falta implementar isso...] ISLoggedin; finally FTimerMonitoring.Enabled := FConectado; end; end; procedure TFrmConsole.ProcessGroupBook(PCommand: string); var LAllGroups : TRetornoAllGroups; begin LAllGroups := TRetornoAllGroups.Create(PCommand); try if Assigned(TInject(FOwner).OnGetAllGroupList ) then TInject(FOwner).OnGetAllGroupList(LAllGroups); finally FreeAndNil(LAllGroups); end; end; procedure TFrmConsole.ProcessPhoneBook(PCOmmand: String); var LAllContacts : TRetornoAllContacts; begin LAllContacts := TRetornoAllContacts.Create(PCommand); try if Assigned(TInject(FOwner).OnGetAllContactList ) then TInject(FOwner).OnGetAllContactList(LAllContacts); finally FreeAndNil(LAllContacts); end; end; procedure TFrmConsole.ProcessQrCode(var pClass: TObject); Var LResultQrCode : TResultQRCodeClass ; begin //Retorno do CODIGO QRCODE.. //Se a janela estiver aberta ele envia a imagem.. if not (pClass is TQrCodeClass) then Exit; if (TQR_Http in TQrCodeClass(pClass).Tags) or (TQR_Img in TQrCodeClass(pClass).Tags) then Begin FrmQRCode.hide; Exit; End; try LResultQrCode := TResultQRCodeClass(TQrCodeClass(pClass).Result); //e difente.. portanto.. verificamos se existe imagem la no form.. se existir caimos fora!! se nao segue o fluxo if not LResultQrCode.AImageDif then Begin if FrmQRCode.Timg_QrCode.Picture <> nil Then Exit; End; LResultQrCode.InjectWorking := true; FrmQRCode.Timg_QrCode.Picture.Assign(LResultQrCode.AQrCodeImage); FrmQRCode.SetView(FrmQRCode.Timg_QrCode); If Assigned(TInject(FOwner).OnGetQrCode) then TInject(FOwner).OnGetQrCode(self, LResultQrCode); Except FrmQRCode.SetView(FrmQRCode.Timg_Animacao); end; end; procedure TFrmConsole.GetAllContacts(PIgnorarLeitura1: Boolean = False); begin if PIgnorarLeitura1 then Begin ReleaseConnection; Exit; End; if FgettingContact then Exit; FgettingContact := True; FrmConsole.ExecuteJS(FrmConsole_JS_GetAllContacts, False); end; procedure TFrmConsole.GetAllGroups(PIgnorarLeitura1: Boolean); begin if PIgnorarLeitura1 then Begin ReleaseConnection; Exit; End; FgettingGroups := True; FrmConsole.ExecuteJS(FrmConsole_JS_GetAllGroups, False); end; function TFrmConsole.GetAutoBatteryLeveL: Boolean; begin Result := False; if not FConectado then Exit; Inc(FCountBattery); if FCountBattery > FCountBatteryMax then Begin Result := true; FCountBattery := 0; End; end; procedure TFrmConsole.GetBatteryLevel; begin ExecuteJS(FrmConsole_JS_GetBatteryLevel, False); end; procedure TFrmConsole.GetMyNumber; begin ExecuteJS(FrmConsole_JS_GetMyNumber, False); end; procedure TFrmConsole.GetProfilePicThumbURL(AProfilePicThumbURL: string); var LJS: String; begin LJS := FrmConsole_JS_VAR_getProfilePicThumb; LJS := FrmConsole_JS_AlterVar(LJS, '<#PROFILE_PICTHUMB_URL#>', Trim(AProfilePicThumbURL)); ExecuteJS(LJS, False); end; procedure TFrmConsole.GetUnreadMessages; begin ExecuteJS(FrmConsole_JS_GetUnreadMessages, False); end; procedure TFrmConsole.GroupAddParticipant(vIDGroup, vNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupAddParticipant; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); FrmConsole_JS_AlterVar(LJS, '#PARTICIPANT_NUMBER#', Trim(vNumber)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupDelete(vIDGroup: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupDelete; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupDemoteParticipant(vIDGroup, vNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupDemoteParticipant; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); FrmConsole_JS_AlterVar(LJS, '#PARTICIPANT_NUMBER#', Trim(vNumber)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupJoinViaLink(vLinkGroup: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupJoinViaLink; FrmConsole_JS_AlterVar(LJS, '#GROUP_LINK#', Trim(vLinkGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupLeave(vIDGroup: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupLeave; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupPromoteParticipant(vIDGroup, vNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupPromoteParticipant; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); FrmConsole_JS_AlterVar(LJS, '#PARTICIPANT_NUMBER#', Trim(vNumber)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GroupRemoveParticipant(vIDGroup, vNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_groupRemoveParticipant; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); FrmConsole_JS_AlterVar(LJS, '#PARTICIPANT_NUMBER#', Trim(vNumber)); ExecuteJS(LJS, true); end; procedure TFrmConsole.GetAllChats; begin if FgettingChats then Exit; FgettingChats := True; FrmConsole.ExecuteJS(FrmConsole_JS_GetAllChats, False); end; procedure TFrmConsole.StartMonitor(Seconds: Integer); var LJS: String; begin LJS := FrmConsole_JS_VAR_StartMonitor; ExecuteJSDir(FrmConsole_JS_AlterVar(LJS, '#TEMPO#' , Seconds.ToString)); end; procedure TFrmConsole.StartQrCode(PQrCodeType: TFormQrCodeType; PViewForm: Boolean); begin FFormType := PQrCodeType; if PQrCodeType = Ft_Http then begin FrmQRCode.hide; SendNotificationCenterDirect(Th_ConnectingFt_HTTP); QRCodeWeb_Start; if PViewForm then Show; end Else Begin SleepNoFreeze(30); if PQrCodeType = Ft_None then Begin If not Assigned(TInject(FOwner).OnGetQrCode) then raise Exception.Create(MSG_ExceptNotAssignedOnGetQrCode); End; SendNotificationCenterDirect(Th_ConnectingFt_Desktop); if not FrmQRCode.Showing then FrmQRCode.ShowForm(PQrCodeType); end; end; procedure TFrmConsole.StopMonitor; begin ExecuteJS(FrmConsole_JS_StopMonitor, true); end; procedure TFrmConsole.StopQrCode(PQrCodeType: TFormQrCodeType); begin FrmQRCode.HIDE; if PQrCodeType = Ft_Http then DisConnect; end; procedure TFrmConsole.StopWebBrowser; begin LPaginaId := 0; try StopMonitor; Except end; FTimerConnect.Enabled := False; FTimerMonitoring.Enabled := False; Chromium1.StopLoad; Chromium1.Browser.StopLoad; SendNotificationCenterDirect(Th_Abort); LPaginaId := 0; end; procedure TFrmConsole.ReadMessages(vID: string); var LJS: String; begin LJS := FrmConsole_JS_VAR_ReadMessages; ExecuteJS(FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#' , Trim(vID)), False); end; procedure TFrmConsole.DeleteMessages(vID: string); var LJS: String; begin LJS := FrmConsole_JS_VAR_DeleteMessages; ExecuteJS(FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vID)), False); end; Procedure TFrmConsole.DisConnect; begin try if not FConectado then Exit; try if Assigned(FrmQRCode) then FrmQRCode.FTimerGetQrCode.Enabled := False; Except //Pode nao ter sido destruido na primeira tentativa end; FTimerConnect.Enabled := False; FTimerMonitoring.Enabled := False; try GlobalCEFApp.QuitMessageLoop; StopMonitor; Except //nao manda ERRO end; ClearLastQrcodeCtr; Chromium1.StopLoad; Chromium1.Browser.StopLoad; Chromium1.CloseBrowser(True); SleepNoFreeze(200); LPaginaId := 0; Except end; FConectado := False; end; //Marca como lida e deleta a conversa procedure TFrmConsole.ReadMessagesAndDelete(vID: string); begin ReadMessages (Trim(vID)); DeleteMessages(Trim(vID)); end; procedure TFrmConsole.ReleaseConnection; begin // if TInject(FOwner).Status <> Inject_Initialized then // Exit; FgettingContact := False; Application.ProcessMessages; SendNotificationCenterDirect(Th_Initialized); end; procedure TFrmConsole.ReloaderWeb; begin if not FConectado then Exit; Chromium1.StopLoad; Chromium1.Browser.ReloadIgnoreCache; end; procedure TFrmConsole.RequestCloseInject(var aMessage: TMessage); begin FCanClose := False; SendNotificationCenterDirect(Th_Disconnecting); ResetEvents; GlobalCEFApp.QuitMessageLoop; Visible := False; DisConnect; Repeat SleepNoFreeze(20); Until FHeaderAtual = Th_Destroying; SleepNoFreeze(200); FCanClose := true; Close; end; procedure TFrmConsole.ResetEvents; begin Chromium1.OnBeforeDownload := nil; Chromium1.OnConsoleMessage := nil; Chromium1.OnDownloadUpdated := nil; Chromium1.OnLoadEnd := nil; Chromium1.OnOpenUrlFromTab := nil; Chromium1.OnDownloadImageFinished := nil; Chromium1.OnTextResultAvailable := nil; Chromium1.OnTitleChange := nil; end; procedure TFrmConsole.SendBase64(vBase64, vNum, vFileName, vText: string); var Ljs, LLine: string; LBase64: TStringList; i: integer; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); vText := CaractersWeb(vText); vFileName := ExtractFileName(vFileName); //AjustNameFile(vFileName) Alterado em 20/02/2020 by Lucas LBase64 := TStringList.Create; TRY LBase64.Text := vBase64; for i := 0 to LBase64.Count -1 do LLine := LLine + LBase64[i]; vBase64 := LLine; //LJS := FrmConsole_JS_VAR_SendTyping + FrmConsole_JS_VAR_SendBase64; LJS := FrmConsole_JS_VAR_SendBase64; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNum)); FrmConsole_JS_AlterVar(LJS, '#MSG_NOMEARQUIVO#', Trim(vFileName)); FrmConsole_JS_AlterVar(LJS, '#MSG_CORPO#', Trim(vText)); FrmConsole_JS_AlterVar(LJS, '#MSG_BASE64#', Trim(vBase64)); ExecuteJS(LJS, True); FINALLY freeAndNil(LBase64); END; end; procedure TFrmConsole.SendButtons(phoneNumber, titleText, buttons, footerText, etapa: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); titleText := CaractersWeb(titleText); //LJS := FrmConsole_JS_VAR_SendTyping + FrmConsole_JS_VAR_SendButtons; LJS := FrmConsole_JS_VAR_SendButtons; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(phoneNumber)); FrmConsole_JS_AlterVar(LJS, '#MSG_TITLE#', Trim(titleText)); FrmConsole_JS_AlterVar(LJS, '#MSG_BUTTONS#', Trim(buttons)); FrmConsole_JS_AlterVar(LJS, '#MSG_FOOTER#', Trim(footerText)); ExecuteJS(LJS, true); end; procedure TFrmConsole.SendButtonList(phoneNumber, titleText1, titleText2, titleButton, options: string; etapa: string = ''); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); titleText1 := CaractersWeb(titleText1); titleText2 := CaractersWeb(titleText2); titleButton := CaractersWeb(titleButton); LJS := FrmConsole_JS_VAR_SendButtonList; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(phoneNumber)); FrmConsole_JS_AlterVar(LJS, '#MSG_TITLE1#', Trim(titleText1)); FrmConsole_JS_AlterVar(LJS, '#MSG_TITLE2#', Trim(titleText2)); FrmConsole_JS_AlterVar(LJS, '#MSG_TITLEBUTTON#',Trim(titleButton)); FrmConsole_JS_AlterVar(LJS, '#MSG_OPTIONS#', Trim(options)); ExecuteJS(LJS, true); end; procedure TFrmConsole.SendContact(vNumDest, vNum: string; vNameContact: string = ''); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_SendContact; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE_DEST#', Trim(vNumDest)); FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNum)); ExecuteJS(LJS, true); end; procedure TFrmConsole.SendLinkPreview(vNum, vLinkPreview, vText: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); vText := CaractersWeb(vText); //LJS := FrmConsole_JS_VAR_SendTyping + FrmConsole_JS_VAR_SendLinkPreview; LJS := FrmConsole_JS_VAR_SendLinkPreview; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNum)); FrmConsole_JS_AlterVar(LJS, '#MSG_LINK#', Trim(vLinkPreview)); FrmConsole_JS_AlterVar(LJS, '#MSG_CORPO#', Trim(vText)); ExecuteJS(LJS, true); end; procedure TFrmConsole.SendLocation(vNum, vLat, vLng, vName, vAddress: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); vName := CaractersWeb(vName); vAddress := CaractersWeb(vAddress); LJS := FrmConsole_JS_VAR_SendLocation; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNum)); FrmConsole_JS_AlterVar(LJS, '#MSG_LAT#', Trim(vLat)); FrmConsole_JS_AlterVar(LJS, '#MSG_LNG#', Trim(vLng)); FrmConsole_JS_AlterVar(LJS, '#MSG_NAME#', Trim(vName)); FrmConsole_JS_AlterVar(LJS, '#MSG_ADDRESS#', Trim(vAddress)); ExecuteJS(LJS, true); end; procedure TFrmConsole.SetOwner(const Value: TComponent); begin if FOwner = Value Then Exit; FOwner := Value; if FOwner = Nil then Exit; if (GlobalCEFApp = nil) or (TInject(FOwner).InjectJS.Ready = false) then raise Exception.Create(MSG_ExceptGlobalCef); end; procedure TFrmConsole.SetZoom(Pvalue: Integer); var I: Integer; begin if Pvalue = Fzoom then Exit; Fzoom := Pvalue; Chromium1.ResetZoomStep; Pvalue := Pvalue * -1; for I := 0 to Pvalue-1 do Chromium1.DecZoomStep; end; procedure TFrmConsole.SendNotificationCenterDirect(PValor: TTypeHeader; Const PSender : TObject); begin FHeaderAtual := PValor; If Assigned(OnNotificationCenter) then OnNotificationCenter(PValor, '', PSender); Application.ProcessMessages; end; procedure TFrmConsole.SendPool(vGroupID, vTitle, vSurvey: string); var Ljs: string; begin vTitle := CaractersWeb(vTitle); LJS := FrmConsole_JS_VAR_SendSurvey; FrmConsole_JS_AlterVar(LJS, '#MSG_GROUPID#', Trim(vGroupID)); FrmConsole_JS_AlterVar(LJS, '#MSG_TITLE#', Trim(vTitle)); FrmConsole_JS_AlterVar(LJS, '#MSG_SURVEY#', Trim(vSurvey)); ExecuteJS(LJS, true); end; procedure TFrmConsole.Send(vNum, vText: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); vText := CaractersWeb(vText); //LJS := FrmConsole_JS_VAR_SendTyping + FrmConsole_JS_VAR_SendMsg; LJS := FrmConsole_JS_VAR_SendMsg; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNum)); FrmConsole_JS_AlterVar(LJS, '#MSG_CORPO#', Trim(vText)); ExecuteJS(LJS, true); end; procedure TFrmConsole.WMEnterMenuLoop(var aMessage: TMessage); begin inherited; if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True; end; procedure TFrmConsole.WMExitMenuLoop(var aMessage: TMessage); begin inherited; if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False; end; procedure TFrmConsole.CEFSentinel1Close(Sender: TObject); begin // FCanClose := True; PostMessage(Handle, WM_CLOSE, 0, 0); end; procedure TFrmConsole.CheckIsValidNumber(vNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_CheckIsValidNumber; FrmConsole_JS_AlterVar(LJS, '#MSG_PHONE#', Trim(vNumber)); ExecuteJS(LJS, False); end; procedure TFrmConsole.NewCheckIsValidNumber(vNumber:String); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_checkNumberStatus; FrmConsole_JS_AlterVar(LJS, '#PHONE#', Trim(vNumber)); ExecuteJS(LJS, False); end; procedure TFrmConsole.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser); begin { Agora que o navegador está totalmente inicializado, podemos enviar uma mensagem para o formulário principal para carregar a página inicial da web.} //PostMessage(Handle, CEFBROWSER_CREATED, 0, 0); FTimerConnect.Enabled := True; PostMessage(Handle, CEF_AFTERCREATED, 0, 0); end; procedure TFrmConsole.Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser); begin CEFSentinel1.Start; end; procedure TFrmConsole.Chromium1BeforeContextMenu(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); begin Model.Clear; end; procedure TFrmConsole.Chromium1BeforeDownload(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback); //Var // LNameFile : String; begin { if not(Chromium1.IsSameBrowser(browser)) or (downloadItem = nil) or not(downloadItem.IsValid) then Exit; LNameFile := FDownloadFila.SetNewStatus(downloadItem.OriginalUrl, TDw_Start); if LNameFile = '' Then Begin Chromium1.StopLoad; browser.StopLoad; exit; End; callback.cont(LNameFile, False); } end; procedure TFrmConsole.Chromium1BeforePopup(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl, targetFrameName: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; const popupFeatures: TCefPopupFeatures; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings; var extra_info: ICefDictionaryValue; var noJavascriptAccess, Result: Boolean); begin // bloqueia todas as janelas pop-up e novas guias ShellExecute(Handle, 'open', PChar(targetUrl), '', '', 1); Result := (targetDisposition in [WOD_NEW_FOREGROUND_TAB, WOD_NEW_BACKGROUND_TAB, WOD_NEW_POPUP, WOD_NEW_WINDOW]); end; procedure TFrmConsole.Chromium1Close(Sender: TObject; const browser: ICefBrowser; var aAction: TCefCloseBrowserAction); begin Chromium1.ShutdownDragAndDrop; PostMessage(Handle, CEF_DESTROY, 0, 0); aAction := cbaDelay; end; procedure TFrmConsole.ExecuteCommandConsole( const PResponse: TResponseConsoleMessage); var LOutClass : TObject; LClose : Boolean; LResultStr : String; begin //Nao veio nada if (PResponse.JsonString = '') or (PResponse.JsonString = FrmConsole_JS_RetornoVazio) Then Exit; if (PResponse.TypeHeader = Th_None) then Begin if LResultStr <> '' then Begin LogAdd(LResultStr, MSG_WarningClassUnknown); FOnErrorInternal(Self, MSG_ExceptJS_ABRUnknown, LResultStr); End; exit; End; //Nao veio nada LResultStr := PResponse.Result; if (LResultStr = FrmConsole_JS_RetornoVazio) Then Begin LogAdd(PResponse.JsonString, 'CONSOLE'); Exit; End; If not (PResponse.TypeHeader in [Th_getQrCodeForm, Th_getQrCodeWEB]) Then FrmQRCode.Hide; Case PResponse.TypeHeader of Th_getAllContacts : Begin ProcessPhoneBook(LResultStr); Exit; End; Th_getAllGroups : begin LOutClass := TRetornoAllGroups.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_getAllGroupAdmins : begin LOutClass := TRetornoAllGroupAdmins.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_getAllChats : Begin if Assigned(FChatList) then FChatList.Free; FChatList := TChatList.Create(LResultStr); SendNotificationCenterDirect(PResponse.TypeHeader, FChatList); FgettingChats := False; End; Th_getUnreadMessages: begin LOutClass := TChatList.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; FgettingChats := False; end; Th_GetAllGroupContacts: begin LOutClass := TClassAllGroupContacts.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_getQrCodeWEB, Th_getQrCodeForm : Begin LOutClass := TQrCodeClass.Create(PResponse.JsonString, [], []); try ProcessQrCode(LOutClass); SendNotificationCenterDirect(Th_GetQrCodeWEB); finally FreeAndNil(LOutClass); end; End; Th_GetBatteryLevel : begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseBattery.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, TResponseBattery(LOutClass).Result); FreeAndNil(LOutClass); End; end; //Mike teste Th_getIsDelivered: begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseIsDelivered.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, TResponseIsDelivered(LOutClass).Result); FreeAndNil(LOutClass); End; end; Th_getMyNumber : Begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseMyNumber.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, TResponseMyNumber(LOutClass).Result); FreeAndNil(LOutClass); End; End; Th_GetCheckIsValidNumber : begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseCheckIsValidNumber.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, '', LOutClass); FreeAndNil(LOutClass); End; end; Th_GetProfilePicThumb : begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseGetProfilePicThumb.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, '', LOutClass); FreeAndNil(LOutClass); End; end; Th_GetCheckIsConnected : begin If Assigned(FOnNotificationCenter) Then Begin LOutClass := TResponseCheckIsConnected.Create(LResultStr); FOnNotificationCenter(PResponse.TypeHeader, '', LOutClass); FreeAndNil(LOutClass); End; end; Th_OnChangeConnect : begin LOutClass := TOnChangeConnect.Create(LResultStr); LClose := TOnChangeConnect(LOutClass).Result; FreeAndNil(LOutClass); if not LClose Then Begin FTimerConnect.Enabled := False; FTimerMonitoring.Enabled := False; ResetEvents; FOnNotificationCenter(Th_ForceDisconnect, ''); Exit; End; end; Th_GetStatusMessage : begin LResultStr := copy(LResultStr, 11, length(LResultStr)); //REMOVENDO RESULT LResultStr := copy(LResultStr, 0, length(LResultStr)-1); // REMOVENDO } LOutClass := TResponseStatusMessage.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_GetGroupInviteLink : begin if Assigned(TInject(FOwner).OnGetInviteGroup) then TInject(FOwner).OnGetInviteGroup(LResultStr); end; Th_GetMe : begin LResultStr := copy(LResultStr, 11, length(LResultStr)); //REMOVENDO RESULT LResultStr := copy(LResultStr, 0, length(LResultStr)-1); // REMOVENDO } LOutClass := TGetMeClass.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_NewCheckIsValidNumber : begin LResultStr := copy(LResultStr, 11, length(LResultStr)); //REMOVENDO RESULT LResultStr := copy(LResultStr, 0, length(LResultStr)-1); // REMOVENDO } LOutClass := TReturnCheckNumber.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; Th_GetIncomingCall : begin LOutClass := TReturnIncomingCall.Create(LResultStr); try SendNotificationCenterDirect(PResponse.TypeHeader, LOutClass); finally FreeAndNil(LOutClass); end; end; end; end; procedure TFrmConsole.Chromium1ConsoleMessage(Sender: TObject; const browser: ICefBrowser; level: Cardinal; const message, source: ustring; line: Integer; out Result: Boolean); var AResponse : TResponseConsoleMessage; begin //testa se e um JSON de forma RAPIDA! if (Copy(message, 0, 2) <> '{"') then Begin LogAdd(message, 'CONSOLE IGNORADO'); Exit; End else Begin if (message = FrmConsole_JS_Ignorar) or (message = FrmConsole_JS_RetornoVazio) then Exit; End; LogAdd(message, 'CONSOLE'); if message <> 'Uncaught (in promise) TypeError: output.update is not a function' then AResponse := TResponseConsoleMessage.Create( message ); try if AResponse = nil then Exit; ExecuteCommandConsole(AResponse); // if Assigned(FControlSend) then // FControlSend.Release; finally FreeAndNil(AResponse); end; end; procedure TFrmConsole.Chromium1DownloadUpdated(Sender: TObject; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); begin { if not(Chromium1.IsSameBrowser(browser)) then exit; if not Assigned(FDownloadFila) then Exit; if (not downloadItem.IsComplete) and (not downloadItem.IsCanceled) then Exit; try if downloadItem.IsComplete then FDownloadFila.SetNewStatus(downloadItem.Url, TDw_Completed) else FDownloadFila.SetNewStatus(downloadItem.Url, TDw_CanceledErro); Except on E : Exception do LogAdd(e.Message, 'ERROR DOWNLOAD ' + downloadItem.FullPath); end; } end; procedure TFrmConsole.Chromium1OpenUrlFromTab(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean; out Result: Boolean); begin //Bloqueia popup do windows e novas abas Result := (targetDisposition in [WOD_NEW_FOREGROUND_TAB, WOD_NEW_BACKGROUND_TAB, WOD_NEW_POPUP, WOD_NEW_WINDOW]); end; procedure TFrmConsole.Chromium1TitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring); begin LPaginaId := LPaginaId + 1; if (LPaginaId > 3) and (LPaginaId < 10) then begin Form_Normal; If Assigned(OnNotificationCenter) then SendNotificationCenterDirect(Th_Connected); end; if (LPaginaId <= 3) and (FFormType = Ft_Http) then SetZoom(-2); ExecuteJS(FrmConsole_JS_refreshOnlyQRCode, true); end; function TFrmConsole.ConfigureNetWork: Boolean; var lForm: TFrmConfigNetWork; begin Result := True; lForm := TFrmConfigNetWork.Create(nil); try case Chromium1.ProxyScheme of psSOCKS4 : lForm.ProxySchemeCb.ItemIndex := 1; psSOCKS5 : lForm.ProxySchemeCb.ItemIndex := 2; else lForm.ProxySchemeCb.ItemIndex := 0; end; lForm.ProxyTypeCbx.ItemIndex := Chromium1.ProxyType; lForm.ProxyServerEdt.Text := Chromium1.ProxyServer; lForm.ProxyPortEdt.Text := inttostr(Chromium1.ProxyPort); lForm.ProxyUsernameEdt.Text := Chromium1.ProxyUsername; lForm.ProxyPasswordEdt.Text := Chromium1.ProxyPassword; lForm.ProxyScriptURLEdt.Text := Chromium1.ProxyScriptURL; lForm.ProxyByPassListEdt.Text := Chromium1.ProxyByPassList; lForm.HeaderNameEdt.Text := Chromium1.CustomHeaderName; lForm.HeaderValueEdt.Text := Chromium1.CustomHeaderValue; lForm.MaxConnectionsPerProxyEdt.Value := Chromium1.MaxConnectionsPerProxy; if (lForm.ShowModal = mrOk) then begin Chromium1.ProxyType := lForm.ProxyTypeCbx.ItemIndex; Chromium1.ProxyServer := lForm.ProxyServerEdt.Text; Chromium1.ProxyPort := strtoint(lForm.ProxyPortEdt.Text); Chromium1.ProxyUsername := lForm.ProxyUsernameEdt.Text; Chromium1.ProxyPassword := lForm.ProxyPasswordEdt.Text; Chromium1.ProxyScriptURL := lForm.ProxyScriptURLEdt.Text; Chromium1.ProxyByPassList := lForm.ProxyByPassListEdt.Text; Chromium1.CustomHeaderName := lForm.HeaderNameEdt.Text; Chromium1.CustomHeaderValue := lForm.HeaderValueEdt.Text; Chromium1.MaxConnectionsPerProxy := lForm.MaxConnectionsPerProxyEdt.Value; case lForm.ProxySchemeCb.ItemIndex of 1 : Chromium1.ProxyScheme := psSOCKS4; 2 : Chromium1.ProxyScheme := psSOCKS5; else Chromium1.ProxyScheme := psHTTP; end; try Chromium1.UpdatePreferences; GlobalCEFApp.IniFIle.WriteInteger ('Config NetWork', 'ProxyType', Chromium1.ProxyType); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyServer', Chromium1.ProxyServer); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyPort', Chromium1.ProxyPort.ToString); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyUsername', Chromium1.ProxyUsername); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyPassword', Chromium1.ProxyPassword); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyScriptURL', Chromium1.ProxyScriptURL); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'ProxyByPassList', Chromium1.ProxyByPassList); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'CustomHeaderName', Chromium1.CustomHeaderName); GlobalCEFApp.IniFIle.WriteString ('Config NetWork', 'CustomHeaderValue', Chromium1.CustomHeaderValue); GlobalCEFApp.IniFIle.WriteInteger ('Config NetWork', 'MaxConnectionsPerProxy', Chromium1.MaxConnectionsPerProxy); GlobalCEFApp.IniFIle.WriteInteger ('Config NetWork', 'ProxyScheme', lForm.ProxySchemeCb.ItemIndex); ReloaderWeb; Except Result := False; end; end; finally FreeAndNil(lForm); end; end; Procedure TFrmConsole.Connect; var LInicio: Cardinal; begin if Assigned(GlobalCEFApp) then Begin if GlobalCEFApp.ErrorInt Then Exit; end; try if FConectado then Exit; Form_Start; SendNotificationCenterDirect(Th_Connecting); LInicio := GetTickCount; FConectado := Chromium1.CreateBrowser(CEFWindowParent1); Repeat FConectado := (Chromium1.Initialized); if not FConectado then Begin Sleep(10); Application.ProcessMessages; if (GetTickCount - LInicio) >= 15000 then Break; End; Until FConectado; finally FTimerMonitoring.Enabled := FConectado; if not FConectado then begin SendNotificationCenterDirect(Th_Disconnected); raise Exception.Create(MSG_ConfigCEF_ExceptBrowse); end else begin Chromium1.OnConsoleMessage := Chromium1ConsoleMessage; Chromium1.OnOpenUrlFromTab := Chromium1OpenUrlFromTab; Chromium1.OnTitleChange := Chromium1TitleChange; end; end; end; procedure TFrmConsole.CreateGroup(vGroupName, PParticipantNumber: string); var Ljs: string; begin if not FConectado then raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_CreateGroup; FrmConsole_JS_AlterVar(LJS, '#GROUP_NAME#', Trim(vGroupName)); FrmConsole_JS_AlterVar(LJS, '#PARTICIPANT_NUMBER#', Trim(PParticipantNumber)); ExecuteJS(LJS, true); end; procedure TFrmConsole.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCanClose Then action := cafree else action := caHide; end; procedure TFrmConsole.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := FCanClose; if not CanClose then Hide; end; procedure TFrmConsole.FormCreate(Sender: TObject); var Lciclo: Integer; lBuffer : Array[0..144] of Char; begin GetTempPath(144,lBuffer); FDirTemp := IncludeTrailingPathDelimiter( StrPas(lBuffer)); Fzoom := 1; CEFWindowParent1.Visible := True; CEFWindowParent1.Align := alClient; FCanClose := False; FCountBattery := 0; // FControlSend := TControlSend.Create(Self); FrmQRCode := TFrmQRCode.Create(Self); FrmQRCode.CLoseForm := Int_FrmQRCodeClose; FrmQRCode.FTimerGetQrCode.OnTimer := OnTimerGetQrCode; FrmQRCode.hide; GlobalCEFApp.Chromium := Chromium1; Chromium1.DefaultURL := FrmConsole_JS_URL; FTimerMonitoring := TTimer.Create(nil); FTimerMonitoring.Interval := 1000 * 10; //10 segundos.. FTimerMonitoring.Enabled := False; FTimerMonitoring.OnTimer := OnTimerMonitoring; FTimerConnect := TTimer.Create(nil); FTimerConnect.Interval := 1000; FTimerConnect.Enabled := False; FTimerConnect.OnTimer := OnTimerConnect; //Pega Qntos ciclos o timer vai ser executado em um MINUTO... Lciclo := 60 div (FTimerMonitoring.Interval div 1000); FCountBatteryMax := Lciclo * 3; //(Ser executado a +- cada 3minutos) //Configuracao de proxy (nao testada) //Carregar COnfiguraão de rede // Chromium1.ProxyType := GlobalCEFApp.IniFIle.ReadInteger ('Config NetWork', 'ProxyType', 0); // Chromium1.ProxyServer := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'ProxyServer', ''); // Chromium1.ProxyPort := GlobalCEFApp.IniFIle.ReadInteger ('Config NetWork', 'ProxyPort', 80); // Chromium1.ProxyUsername := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'ProxyUsername', ''); // Chromium1.ProxyPassword := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'ProxyPassword', ''); // Chromium1.ProxyScriptURL := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'ProxyScriptURL', ''); // Chromium1.ProxyByPassList := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'ProxyByPassList', ''); // Chromium1.CustomHeaderName := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'CustomHeaderName', ''); // Chromium1.CustomHeaderValue := GlobalCEFApp.IniFIle.ReadString ('Config NetWork', 'CustomHeaderValue', ''); // Chromium1.MaxConnectionsPerProxy := GlobalCEFApp.IniFIle.ReadInteger ('Config NetWork', 'MaxConnectionsPerProxy', 32); // Lciclo := GlobalCEFApp.IniFIle.ReadInteger ('Config NetWork', 'ProxyScheme', 0); // case Lciclo of // 1 : Chromium1.ProxyScheme := psSOCKS4; // 2 : Chromium1.ProxyScheme := psSOCKS5; // else Chromium1.ProxyScheme := psHTTP; // end; // Chromium1.UpdatePreferences; end; procedure TFrmConsole.FormDestroy(Sender: TObject); begin if Assigned(FrmQRCode) then Begin FrmQRCode.PodeFechar := True; // FrmQRCode.close; End; if Assigned(FTimerMonitoring) then Begin FTimerMonitoring.Enabled := False; FreeAndNil(FTimerMonitoring); End; if Assigned(FTimerConnect) then Begin FTimerConnect.Enabled := False; FreeAndNil(FTimerConnect); End; SendNotificationCenterDirect(Th_Destroy); end; procedure TFrmConsole.FormShow(Sender: TObject); begin Lbl_Caption.Caption := Text_FrmConsole_Caption; Lbl_Versao.Caption := 'V. ' + TInjectVersion; end; procedure TFrmConsole.Form_Normal; begin SetZoom(TInject(FOwner).Config.Zoom); Pnl_Geral.Enabled := true; Height := 605; //580 Width := 1000; //680 BorderStyle := bsSizeable; LPaginaId := 20; end; procedure TFrmConsole.Form_Start; begin LPaginaId := 0; Height := 605; //580 Width := 1000; //680 Pnl_Geral.Enabled := True; BorderStyle := bsDialog; end; procedure TFrmConsole.Image2Click(Sender: TObject); var TempPoint : Tpoint; begin TempPoint.X := 200; TempPoint.Y := 200; Chromium1.ShowDevTools(TempPoint, nil); end; procedure TFrmConsole.Int_FrmQRCodeClose(Sender: TObject); begin if FFormType = Ft_Desktop then StopWebBrowser; end; procedure TFrmConsole.CheckDelivered; begin ExecuteJS(FrmConsole_JS_CheckDelivered, False); end; procedure TFrmConsole.CheckIsConnected; var Ljs: string; begin ExecuteJS(FrmConsole_JS_VAR_IsConnected, False); end; Procedure TFrmConsole.ISLoggedin; begin ExecuteJS(FrmConsole_JS_IsLoggedIn, false); end; procedure TFrmConsole.lbl_VersaoMouseEnter(Sender: TObject); const BYTES_PER_MEGABYTE = 1024 * 1024; var LTempMessage : string; begin LTempMessage := Text_System_memUse + inttostr(GlobalCEFApp.UsedMemory div BYTES_PER_MEGABYTE) + ' Mb' + #13 + Text_System_memTot + inttostr(GlobalCEFApp.TotalSystemMemory div BYTES_PER_MEGABYTE) + ' Mb' + #13 + Text_System_memFree + inttostr(GlobalCEFApp.AvailableSystemMemory div BYTES_PER_MEGABYTE) + ' Mb' + #13 + Text_System_memFree + inttostr(GlobalCEFApp.SystemMemoryLoad) + ' %'; Lbl_Versao.Hint := LTempMessage; end; procedure TFrmConsole.listGroupAdmins(vIDGroup: string); var Ljs: string; begin LJS := FrmConsole_JS_GetGroupAdmins; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.listGroupContacts(vIDGroup: string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_listGroupContacts; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.revokeGroupInviteLink(vIDGroup: string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_removeGroupInviteLink; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.getGroupInviteLink(vIDGroup: string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_getGroupInviteLink; FrmConsole_JS_AlterVar(LJS, '#GROUP_ID#', Trim(vIDGroup)); ExecuteJS(LJS, true); end; procedure TFrmConsole.setNewName(newName : string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_setProfileName; FrmConsole_JS_AlterVar(LJS, '#NEW_NAME#', Trim(newName)); ExecuteJS(LJS, true); end; procedure TFrmConsole.setNewStatus(newStatus : string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_setMyStatus; FrmConsole_JS_AlterVar(LJS, '#NEW_STATUS#', Trim(newStatus)); ExecuteJS(LJS, true); end; procedure TFrmConsole.fGetMe(); var Ljs: string; begin LJS := FrmConsole_JS_VAR_getMe; ExecuteJS(LJS, true); end; procedure TFrmConsole.getStatus(vTelefone : string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_getStatus; FrmConsole_JS_AlterVar(LJS, '#PHONE#', Trim(vTelefone)); ExecuteJS(LJS, true); end; procedure TFrmConsole.CleanChat(vTelefone : string); var Ljs: string; begin LJS := FrmConsole_JS_VAR_ClearChat; FrmConsole_JS_AlterVar(LJS, '#PHONE#', Trim(vTelefone)); ExecuteJS(LJS, true); end; procedure TFrmConsole.Logout; var Ljs: string; begin //if not FConectado then // raise Exception.Create(MSG_ConfigCEF_ExceptConnetServ); LJS := FrmConsole_JS_VAR_Logout; ExecuteJS(LJS, true); end; end.
{*************************************************************** * * Project : Whois Windows GUI Client Demo * Unit Name: fMain * Purpose : * Author : Allen O'Neill <email: allen_oneill@hotmail.com> * Date : 11/27/00 8:27:58 AM * History : Windows client created * ****************************************************************} unit fMain; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, {$ENDIF} Classes, SysUtils, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdWhois; type TfrmMain = class(TForm) mmoResults: TMemo; edtDomainToCheck: TEdit; cboWhoisHosts: TComboBox; btnCheck: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; btnExit: TButton; IdWhois: TIdWhois; procedure btnCheckClick(Sender: TObject); procedure btnExitClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.xfm} procedure TfrmMain.btnCheckClick(Sender: TObject); begin try mmoResults.Clear; with IdWhois do Begin Host := trim(cboWhoisHosts.text); mmoResults.Lines.Text := whois(trim(edtDomainToCheck.text)); // no need to connect - whois function does this for us if connected then disconnect; End; except on E : Exception do ShowMessage(E.Message); end; end; procedure TfrmMain.btnExitClick(Sender: TObject); begin application.terminate; end; end.
{ *************************************************************************** } { } { NLDQuadris - www.nldelphi.com Open Source Delphi designtime component } { } { aka "NLDEasterEgg" } { } { Initiator: Albert de Weerd (aka NGLN) } { License: Free to use, free to modify } { Website: http://www.nldelphi.com/forum/showthread.php?t=31097 } { SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDQuadris } { } { *************************************************************************** } { } { Date: March 22, 2009 } { Version: 1.0.0.2 } { } { *************************************************************************** } unit NLDQuadris; {$BOOLEVAL OFF} interface uses Windows, Classes, Contnrs, ImgList, Controls, Graphics, Messages, ExtCtrls, NLDJoystick; const ColCount = 6; RowCount = 10; type EQuadrisError = class(EComponentError); TAnimKind = (akCycle, akPendulum); TAnimOrder = (aoUp, aoDown); TColRange = 0..ColCount - 1; TRowRange = 0..RowCount - 1; TColHeight = 0..RowCount; TItemID = type Integer; TQuadrisOption = (qoAutoIncLevel, qoRandomColumn, qoRandomDirection, qoShowNext, qoStartOnFocus, qoPauseOnUnfocus, qoWithHandicap); TQuadrisOptions = set of TQuadrisOption; TThemeName = type String; TQuadrisLevel = 1..9; TWind = (North, East, South, West); const DefGameOptions = [qoAutoIncLevel, qoShowNext, qoStartOnFocus, qoPauseOnUnfocus, qoWithHandicap]; DefLevel = 1; DefScore = 0; type TCustomQuadris = class; TQuadrisItems = class; TGameOverEvent = procedure(Sender: TCustomQuadris; var StartAgain: Boolean) of object; TPointsEvent = procedure(Sender: TCustomQuadris; Points, Multiplier: Word) of object; TQuadrisEvent = procedure(Sender: TCustomQuadris) of object; TMoveEvent = procedure(Sender: TCustomQuadris; Succeeded: Boolean) of object; TQuadrisColors = record Light: TColor; Lighter: TColor; Dark: TColor; Darker: TColor; end; TItemMotion = record Speed: Double; {PixelsPerSecond} StartTick: Cardinal; StartTop: Integer; FinishTop: Integer; end; TItemImageLists = class(TObjectList) private function GetItem(Index: TItemID): TCustomImageList; procedure SetItem(Index: TItemID; Value: TCustomImageList); function GetDefImageIndex(Index: Integer): Integer; procedure SetDefImageIndex(Index: Integer; Value: Integer); public property Items[Index: TItemID]: TCustomImageList read GetItem write SetItem; default; property DefImageIndexes[Index: Integer]: Integer read GetDefImageIndex write SetDefImageIndex; end; TItem = class(TGraphicControl) private FAnimIndex: Integer; FAnimOrder: TAnimOrder; FAutoFinished: Boolean; FBackground: TCanvas; FCol: TColRange; FDropping: Boolean; FFadeImages: TCustomImageList; FFadeIndex: Integer; FID: TItemID; FImages: TCustomImageList; FItems: TQuadrisItems; FMotion: TItemMotion; FQuadris: TCustomQuadris; FRow: TColHeight; procedure Animate; procedure Fade; function Fading: Boolean; function GetCol: TColRange; function GetRow: TColHeight; protected constructor CreateLinked(AQuadris: TCustomQuadris; AID: TItemID); procedure Paint; override; public constructor Create(AOwner: TComponent); override; procedure MoveTo(ACol: TColRange; ARow: TColHeight; NewFinish: TRowRange); procedure DropTo(ARow: TRowRange); procedure Repaint; override; procedure Update; override; property Col: TColRange read GetCol; property ID: TItemID read FID; property Row: TColHeight read GetRow; end; TPairData = record ID1: TItemID; ID2: TItemID; Col: TColRange; Row: TRowRange; Dir: TWind; end; TPair = record Item1: TItem; Item2: TItem; Dir: TWind; end; TGridCoord = record Col: TColRange; Row: TRowRange; end; TItems = class(TObjectList) private function GetItem(Index: Integer): TItem; public property Items[Index: Integer]: TItem read GetItem; default; end; TQuadrisItems = class(TItems) private FBombing: Boolean; FBombItemID: TItemID; FDeleting: LongBool; FDropping: LongBool; FFadeItemID: TItemID; FGrid: array[TColRange, TRowRange] of TItem; FMaxItemID: TItemID; FNextPairData: TPairData; FCurrentPair: TPair; FQuadris: TCustomQuadris; FToTrace: array of TGridCoord; FTraceCycle: Integer; procedure BeginDelete; procedure BeginDrop; function ColHeight(ACol: TColRange): TColHeight; function DropSpeed: Double; procedure EndDelete; procedure EndDrop; function FallSpeed: Double; procedure GridNeeded(InclCurrentPair: Boolean); procedure MoveCurrentPair(ACol: TColRange; ARow: TRowRange; ADir: TWind); function RandomNextPairData: TPairData; procedure Squeeze; procedure ThrowBombs; procedure Trace; function ValidateMovement(Direction: TWind): Boolean; public procedure Clear; override; constructor Create(AQuadris: TCustomQuadris); procedure Animate; procedure Drop; function Empty: Boolean; function MoveLeft: Boolean; function MoveRight: Boolean; function Rotate: Boolean; procedure SetDelay(ADelay: Cardinal); procedure ThrowNextPair; procedure Update; end; TItemsView = class(TCustomControl) private FQuadris: TCustomQuadris; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; protected procedure Paint; override; public function CanFocus: Boolean; override; constructor Create(AOwner: TComponent); override; procedure SetFocus; override; end; TFadeLabel = class(TGraphicControl) private FCaption: String; FStartTick: Cardinal; procedure SetCaption(const Value: String); protected procedure Paint; override; public procedure Animate; constructor Create(AOwner: TComponent); override; property Caption: String write SetCaption; end; TFixedSizeControl = class(TCustomControl) private function GetAnchors: TAnchors; function GetHeight: Integer; function GetWidth: Integer; procedure SetAnchors(Value: TAnchors); protected function CanAutoSize(var NewWidth: Integer; var NewHeight: Integer): Boolean; override; function CanResize(var NewWidth: Integer; var NewHeight: Integer): Boolean; override; property Anchors: TAnchors read GetAnchors write SetAnchors default [akLeft, akTop]; public constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property Height: Integer read GetHeight stored False; property Width: Integer read GetWidth stored False; end; TCustomQuadris = class(TFixedSizeControl) private FAnimInterval: Cardinal; FAnimKind: TAnimKind; FAnimTimer: TTimer; FBackground: TBitmap; FColors: TQuadrisColors; FItemImageLists: TItemImageLists; FItems: TQuadrisItems; FLevel: TQuadrisLevel; FOnBonus: TPointsEvent; FOnDrop: TQuadrisEvent; FOnGameOver: TGameOverEvent; FOnLevel: TQuadrisEvent; FOnMove: TMoveEvent; FOnPoints: TPointsEvent; FOnRotate: TMoveEvent; FOptions: TQuadrisOptions; FPaused: Boolean; FPauseTick: Cardinal; FPointsLabel: TFadeLabel; FScore: Cardinal; FStartLevel: TQuadrisLevel; FStreamedRunning: Boolean; FTheme: TThemeName; FThemeColor: TColor; FUpdateTimer: TTimer; FView: TItemsView; procedure GameOver; function GetColor: TColor; function GetRunning: Boolean; procedure InitJoystick; function IsColorStored: Boolean; procedure PaintView; procedure Points(TracedCount, TraceCycle: Word); procedure JoystickButtonDown(Sender: TNLDJoystick; Buttons: TJoyButtons); procedure JoystickMove(Sender: TNLDJoystick; const JoyPos: TJoyRelPos; Buttons: TJoyButtons); procedure LoadTheme(const ATheme: TThemeName); function MaxLevelScore(ALevel: TQuadrisLevel): Cardinal; procedure OnAnimTimer(Sender: TObject); procedure OnUpdateTimer(Sender: TObject); procedure SetColor(Value: TColor); procedure SetLevel(Value: TQuadrisLevel); procedure SetOptions(Value: TQuadrisOptions); procedure SetRunning(Value: Boolean); procedure SetTheme(const Value: TThemeName); procedure UpdateLevel; procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure WMKillFocus(var Message: TWMSetFocus); message WM_KILLFOCUS; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMVisibleChanged(var Message: TMessage); message CM_VISIBLECHANGED; protected procedure DoBonus(Points, Multiplier: Word); virtual; procedure DoDrop; virtual; procedure DoGameOver(var StartAgain: Boolean); virtual; procedure DoLevel; virtual; procedure DoMove(Succeeded: Boolean); virtual; procedure DoPoints(Points, Multiplier: Word); virtual; procedure DoRotate(Succeeded: Boolean); virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; property Color: TColor read GetColor write SetColor stored IsColorStored; property Level: TQuadrisLevel read FLevel write SetLevel default DefLevel; property OnBonus: TPointsEvent read FOnBonus write FOnBonus; property OnDrop: TQuadrisEvent read FOnDrop write FOnDrop; property OnGameOver: TGameOverEvent read FOnGameOver write FOnGameOver; property OnLevel: TQuadrisEvent read FOnLevel write FOnLevel; property OnMove: TMoveEvent read FOnMove write FOnMove; property OnPoints: TPointsEvent read FOnPoints write FOnPoints; property OnRotate: TMoveEvent read FOnRotate write FOnRotate; property Options: TQuadrisOptions read FOptions write SetOptions default DefGameOptions; property ParentColor default False; property Running: Boolean read GetRunning write SetRunning default False; property Score: Cardinal read FScore default DefScore; property Theme: TThemeName read FTheme write SetTheme; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetThemeNames: TStrings; procedure Pause; procedure Start; procedure Stop; property TabStop default True; published property Height stored False; property Width stored False; end; TNLDQuadris = class(TCustomQuadris) published property Anchors; property Color; property Ctl3D; property DragKind; property DragCursor; property DragMode; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnStartDock; property OnStartDrag; property ParentColor; property ParentCtl3D; property ParentShowHint; property PopupMenu; property ShowHint; property TabStop; property Visible; published property Level; property OnBonus; property OnDrop; property OnGameOver; property OnLevel; property OnMove; property OnPoints; property OnRotate; property Options; property Running; property Score; property Theme; end; procedure Register; implementation {$R Items.RES} uses SysUtils, CommCtrl, Forms, Math; procedure Register; begin RegisterComponents('NLDelphi', [TNLDQuadris]); end; resourcestring RsErrInvalidCreationF = 'Invalid creation of a %s control.'; type TRGB = record R: Byte; G: Byte; B: Byte; end; function GetRGB(AColor: TColor): TRGB; begin AColor := ColorToRGB(AColor); Result.R := GetRValue(AColor); Result.G := GetGValue(AColor); Result.B := GetBValue(AColor); end; function MixColor(Base, MixWith: TColor; const Factor: Double): TColor; var FBase, FMixWith: TRGB; begin if (Factor < 0) or (Factor > 1) then Result := Base else begin FBase := GetRGB(Base); FMixWith := GetRGB(MixWith); with FBase do begin R := R + Round((FMixWith.R - R) * Factor); G := G + Round((FMixWith.G - G) * Factor); B := B + Round((FMixWith.B - B) * Factor); Result := RGB(R, G, B); end; end; end; procedure NotifyKeyboardActivity; begin SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, nil, 0); end; function StrToAnimKind(const S: String): TAnimKind; begin Result := TAnimKind(StrToInt(S)); end; { TItemImagesLists } function TItemImageLists.GetDefImageIndex(Index: Integer): Integer; begin Result := Items[Index].Tag; end; function TItemImageLists.GetItem(Index: TItemID): TCustomImageList; begin Result := TCustomImageList(inherited Items[Index]); end; procedure TItemImageLists.SetDefImageIndex(Index: Integer; Value: Integer); begin Items[Index].Tag := Value; end; procedure TItemImageLists.SetItem(Index: TItemID; Value: TCustomImageList); begin inherited Items[Index] := Value; end; { TItem } const DefItemSize = 26; procedure TItem.Animate; begin case FQuadris.FAnimKind of akCycle: if FAnimIndex = FImages.Count - 1 then FAnimIndex := 0 else Inc(FAnimIndex); akPendulum: begin if FAnimIndex = FImages.Count - 1 then FAnimOrder := aoDown else if FAnimIndex = 0 then FAnimOrder := aoUp; if FAnimOrder = aoUp then Inc(FAnimIndex) else Dec(FAnimIndex); end; end; if Fading then Fade; end; constructor TItem.Create(AOwner: TComponent); begin raise EQuadrisError.CreateFmt(rsErrInvalidCreationF, [ClassName]); end; constructor TItem.CreateLinked(AQuadris: TCustomQuadris; AID: TItemID); begin inherited Create(nil); ControlStyle := [csOpaque, csFixedWidth, csFixedHeight, csDisplayDragImage, csNoStdEvents]; FID := AID; FQuadris := AQuadris; FItems := FQuadris.FItems; Width := DefItemSize; Height := DefItemSize; Top := -Height + 1; FBackground := FQuadris.FBackground.Canvas; FFadeIndex := -1; FFadeImages := FQuadris.FItemImageLists[FItems.FFadeItemID]; FImages := FQuadris.FItemImageLists[FID]; FMotion.Speed := FItems.FallSpeed; FMotion.StartTick := GetTickCount; FMotion.StartTop := Top; Parent := FQuadris.FView; end; procedure TItem.DropTo(ARow: TRowRange); begin FDropping := True; FMotion.Speed := FItems.DropSpeed; FMotion.StartTop := Top; FMotion.StartTick := GetTickCount; FMotion.FinishTop := (RowCount - ARow - 1) * Height; FItems.BeginDrop; Update; end; procedure TItem.Fade; begin if FFadeIndex = -1 then begin SendToBack; FItems.BeginDelete; end; if FFadeIndex < FFadeImages.Count - 1 then Inc(FFadeIndex) else begin FItems.EndDelete; FItems.Remove(Self); end; end; function TItem.Fading: Boolean; begin Result := FFadeIndex > -1; end; function TItem.GetCol: TColRange; begin Result := Left div Width; end; function TItem.GetRow: TColHeight; begin Result := RowCount - 1 - Ceil(Top / Height); end; procedure TItem.MoveTo(ACol: TColRange; ARow: TColHeight; NewFinish: TRowRange); begin FCol := ACol; FRow := ARow; FMotion.FinishTop := (RowCount - NewFinish - 1) * Height; Update; end; procedure TItem.Paint; var DC1: HDC; DC2: HDC; BITMAP1: HBITMAP; BITMAP2: HBITMAP; begin DC1 := CreateCompatibleDC(Canvas.Handle); BITMAP1 := CreateCompatibleBitmap(Canvas.Handle, Width, Height); SelectObject(DC1, BITMAP1); if Fading then begin DC2 := CreateCompatibleDC(Canvas.Handle); BITMAP2 := CreateCompatibleBitmap(Canvas.Handle, Width, Height); SelectObject(DC2, BITMAP2); ImageList_Draw(FFadeImages.Handle, FFadeIndex, DC1, 0, 0, ILD_NORMAL); ImageList_Draw(FImages.Handle, FAnimIndex, DC2, 0, 0, ILD_MASK); BitBlt(DC1, 0, 0, Width, Height, DC2, 0, 0, NOTSRCERASE); BitBlt(DC2, 0, 0, Width, Height, FBackground.Handle, Left, Top, SRCCOPY); BitBlt(DC2, 0, 0, Width, Height, DC1, 0, 0, SRCINVERT); BitBlt(Canvas.Handle, 0, 0, Width, Height, DC2, 0, 0, SRCCOPY); ImageList_Draw(FImages.Handle, FAnimIndex, DC2, 0, 0, ILD_NORMAL); BitBlt(DC2, 0, 0, Width, Height, DC1, 0, 0, SRCAND); BitBlt(Canvas.Handle, 0, 0, Width, Height, DC2, 0, 0, SRCPAINT); DeleteObject(BITMAP2); DeleteDC(DC2); end else begin ImageList_Draw(FImages.Handle, FAnimIndex, DC1, 0, 0, ILD_MASK); BitBlt(DC1, 0, 0, Width, Height, FBackground.Handle, Left, Top, SRCAND); ImageList_Draw(FImages.Handle, FAnimIndex, DC1, 0, 0, ILD_TRANSPARENT); BitBlt(Canvas.Handle, 0, 0, Width, Height, DC1, 0, 0, SRCCOPY); end; DeleteObject(BITMAP1); DeleteDC(DC1); end; procedure TItem.Repaint; begin if HasParent then Paint; {Faster then Invalidate} end; procedure TItem.Update; var NewLeft: Integer; NewTop: Integer; NewBoundsRect: TRect; UpdateRect: TRect; begin if FMotion.Speed > 0 then begin NewLeft := FCol * Width; if FRow <> Row then Inc(FMotion.StartTop, (Row - FRow) * Height); with FMotion do NewTop := StartTop + Round(Speed * (GetTickCount - StartTick) * 0.001); if NewTop >= FMotion.FinishTop then begin NewTop := FMotion.FinishTop; if FDropping then begin FItems.EndDrop; FDropping := False; end else FAutoFinished := True; FMotion.StartTop := NewTop; FMotion.Speed := 0; end; NewBoundsRect := Rect(NewLeft, NewTop, Newleft + Width, NewTop + Height); SubTractRect(UpdateRect, BoundsRect, NewBoundsRect); if HasParent then InvalidateRect(Parent.Handle, @UpdateRect, False); UpdateBoundsRect(NewBoundsRect); FCol := Col; FRow := Row; end; Repaint; end; { TItems } function TItems.GetItem(Index: Integer): TItem; begin Result := TItem(inherited Items[Index]); end; { TQuadrisItems } { Start | NextPair <------------. | | Stop <-- Yes <-- GameOver? | | | ,-------> No | | | | No Move&Rotate | | | | `---- Finished? | | | Yes | | | Drop | | | Stop <-- Yes <-- GameOver? | | | No |<------. | | | ,---> Dropping Dropping | | | | | | Trace Yes No | | | | | Delete? --> No --> Bombs? ----' | | | Yes | | | Points | | | Deleting | | `----- Squeeze } type TDirDelta = packed record X: -1..1; Y: -1..1; end; const Delta: array[TWind] of TDirDelta = ((X:0; Y:1), (X:1; Y:0), (X:0; Y:-1), (X:-1; Y:0)); DefDropSpeed = 200; DefMaxFallSpeed = 90; DefMinFallSpeed = 10; LeftCol: TColRange = Low(TColRange); RightCol: TColRange = High(TColRange); BottomRow: TRowRange = Low(TRowRange); TopRow: TRowRange = High(TRowRange); WindCount = 4; procedure TQuadrisItems.Animate; var i: Integer; begin i := 0; while i < Count do begin Items[i].Animate; Inc(i); end; end; procedure TQuadrisItems.BeginDelete; begin Inc(FDeleting); end; procedure TQuadrisItems.BeginDrop; begin Inc(FDropping); end; procedure TQuadrisItems.Clear; begin inherited Clear; FNextPairData := RandomNextPairData; FDeleting := False; FDropping := False; FBombing := False; SetLength(FToTrace, 0); FTraceCycle := 0; end; function TQuadrisItems.ColHeight(ACol: TColRange): TColHeight; begin for Result := BottomRow to TopRow do if FGrid[ACol, Result] = nil then Exit; Result := High(TColHeight); end; constructor TQuadrisItems.Create(AQuadris: TCustomQuadris); begin inherited Create(True); FQuadris := AQuadris; Clear; end; procedure TQuadrisItems.Drop; var Coord1: TGridCoord; Coord2: TGridCoord; begin if FDropping or FDeleting then Exit; GridNeeded(False); Coord1.Col := FCurrentPair.Item1.Col; Coord2.Col := FCurrentPair.Item2.Col; case FCurrentPair.Dir of North: begin Coord1.Row := ColHeight(Coord1.Col); Coord2.Row := Coord1.Row + 1; if Coord1.Row = TopRow then begin FQuadris.GameOver; Exit; end; end; East, West: begin Coord1.Row := ColHeight(Coord1.Col); Coord2.Row := ColHeight(Coord2.Col); end; South: begin Coord2.Row := ColHeight(Coord1.Col); Coord1.Row := Coord2.Row + 1; end; end; SetLength(FToTrace, 2); FToTrace[0] := Coord1; FToTrace[1] := Coord2; BeginDrop; FCurrentPair.Item1.DropTo(Coord1.Row); FCurrentPair.Item2.DropTo(Coord2.Row); EndDrop; FQuadris.DoDrop; end; function TQuadrisItems.DropSpeed: Double; begin Result := DefDropSpeed; end; function TQuadrisItems.Empty: Boolean; begin Result := Count - Integer(FDeleting) = 0; end; procedure TQuadrisItems.EndDelete; begin Dec(FDeleting); if not FDeleting then Squeeze; end; procedure TQuadrisItems.EndDrop; begin Dec(FDropping); if not FDropping then if FBombing then begin FBombing := False; ThrowNextPair; end else Trace; end; function TQuadrisItems.FallSpeed: Double; begin Result := DefMinFallSpeed + (FQuadris.FLevel / High(TQuadrisLevel)) * (DefMaxFallSpeed - DefMinFallSpeed); end; procedure TQuadrisItems.GridNeeded(InclCurrentPair: Boolean); const Subtract: array[Boolean] of Integer = (3, 1); var i: Integer; begin FillChar(FGrid, SizeOf(FGrid), 0); for i := 0 to Count - Subtract[InclCurrentPair] do with Items[i] do if not Fading then FGrid[Col, Row] := Items[i]; end; function TQuadrisItems.MoveLeft: Boolean; begin if FDropping or FDeleting then Result := False else begin GridNeeded(False); Result := ValidateMovement(West); if Result then with FCurrentPair, Item1 do MoveCurrentPair(Col - 1, Row, Dir); end; end; procedure TQuadrisItems.MoveCurrentPair(ACol: TColRange; ARow: TRowRange; ADir: TWind); begin FCurrentPair.Dir := ADir; case ADir of North, East, West: FCurrentPair.Item1.MoveTo(ACol, ARow, ColHeight(ACol)); South: FCurrentPair.Item1.MoveTo(ACol, ARow, ColHeight(ACol) + 1); end; case ADir of North: FCurrentPair.Item2.MoveTo(ACol, ARow + 1, ColHeight(ACol) + 1); East: FCurrentPair.Item2.MoveTo(ACol + 1, ARow, ColHeight(ACol + 1)); South: FCurrentPair.Item2.MoveTo(ACol, ARow - 1, ColHeight(ACol)); West: FCurrentPair.Item2.MoveTo(ACol - 1, ARow, ColHeight(ACol - 1)); end; end; function TQuadrisItems.MoveRight: Boolean; begin if FDropping or FDeleting then Result := False else begin GridNeeded(False); Result := ValidateMovement(East); if Result then with FCurrentPair, Item1 do MoveCurrentPair(Col + 1, Row, Dir); end; end; function TQuadrisItems.RandomNextPairData: TPairData; begin with Result do begin ID1 := Random(FMaxItemID); ID2 := Random(FMaxItemID); if qoRandomDirection in FQuadris.Options then Dir := TWind(Random(WindCount)) else Dir := East; if qoRandomColumn in FQuadris.Options then begin Col := Random(ColCount - 1); if Dir = West then Inc(Col); end else Col := (ColCount - 1) div 2; Row := TopRow; if Dir = North then Dec(Row); end; end; function TQuadrisItems.Rotate: Boolean; var Col: TColRange; Row: TColHeight; Dir: TWind; procedure IncDir; begin if Dir = High(TWind) then Dir := Low(TWind) else Inc(Dir); end; begin if FDropping or FDeleting then Result := False else begin GridNeeded(False); Result := True; Col := FCurrentPair.Item1.Col; Row := FCurrentPair.Item1.Row; Dir := FCurrentPair.Dir; case Dir of North: if ValidateMovement(East) then IncDir else if ValidateMovement(West) then begin IncDir; Dec(Col); end else begin IncDir; IncDir; Inc(Row); end; East: if ValidateMovement(South) then IncDir else Result := False; South: if ValidateMovement(West) then IncDir else if FGrid[Col + 1, Row] = nil then begin IncDir; Inc(Col); end else begin IncDir; IncDir; Dec(Row); end; West: IncDir; end; if Result then MoveCurrentPair(Col, Row, Dir); end; end; procedure TQuadrisItems.SetDelay(ADelay: Cardinal); var i: Integer; begin for i := 0 to Count - 1 do with Items[i].FMotion do StartTick := StartTick + ADelay; end; procedure TQuadrisItems.Squeeze; var Col: TColRange; Row: TRowRange; FromCoord: TGridCoord; ToCoord: TGridCoord; begin BeginDrop; GridNeeded(True); for Col := LeftCol to RightCol do for Row := BottomRow to TopRow do if FGrid[Col, Row] = nil then begin ToCoord.Col := Col; ToCoord.Row := Row; FromCoord := ToCoord; while FromCoord.Row < TopRow do begin Inc(FromCoord.Row); if FGrid[FromCoord.Col, FromCoord.Row] <> nil then begin FGrid[ToCoord.Col, ToCoord.Row] := FGrid[FromCoord.Col, FromCoord.Row]; FGrid[FromCoord.Col, FromCoord.Row] := nil; FGrid[ToCoord.Col, ToCoord.Row].DropTo(ToCoord.Row); SetLength(FToTrace, Length(FToTrace) + 1); FToTrace[Length(FToTrace) - 1] := ToCoord; Break; end; end; end; EndDrop; end; procedure TQuadrisItems.ThrowBombs; var iBomb: Integer; Col: TColRange; Row: TColHeight; Item: TItem; begin FBombing := True; BeginDrop; if FQuadris.FLevel > 2 then begin GridNeeded(True); for iBomb := 1 to Random(FQuadris.FLevel div 2) do if Random(5) = 0 then begin Col := Random(ColCount); Row := ColHeight(Col); if Row < RowCount then begin Item := TItem.CreateLinked(FQuadris, FBombItemID); Add(Item); Item.MoveTo(Col, TopRow, Row); Item.DropTo(Row); end; end; end; EndDrop; end; procedure TQuadrisItems.ThrowNextPair; begin if (not FDropping) and (not FDeleting) then with FNextPairData do begin GridNeeded(True); if (FGrid[Col, Row] = nil) and (FGrid[Col + Delta[Dir].X, Row + Delta[Dir].Y] = nil) then begin FCurrentPair.Item1 := TItem.CreateLinked(FQuadris, ID1); FCurrentPair.Item2 := TItem.CreateLinked(FQuadris, ID2); Add(FCurrentPair.Item1); Add(FCurrentPair.Item2); MoveCurrentPair(Col, Row, Dir); FNextPairData := RandomNextPairData; FQuadris.PaintView; end else FQuadris.GameOver; end; end; procedure TQuadrisItems.Trace; var TracedItems: array of TGridCoord; TracedBombs: array of TGridCoord; Checked: array[TColRange, TRowRange] of Boolean; procedure InitTrace; begin SetLength(TracedItems, 0); SetLength(TracedBombs, 0); FillChar(Checked, SizeOf(Checked), 0); end; procedure TraceQuadris(ACol: TColRange; ARow: TRowRange; TraceID: TItemID); var IsBomb: Boolean; begin Checked[ACol, ARow] := True; IsBomb := FGrid[ACol, ARow].ID = FBombItemID; if (FGrid[ACol, ARow].ID = TraceID) or IsBomb then begin if IsBomb then begin SetLength(TracedBombs, Length(TracedBombs) + 1); TracedBombs[Length(TracedBombs) - 1].Col := ACol; TracedBombs[Length(TracedBombs) - 1].Row := ARow; end else begin SetLength(TracedItems, Length(TracedItems) + 1); TracedItems[Length(TracedItems) - 1].Col := ACol; TracedItems[Length(TracedItems) - 1].Row := ARow; end; if (ARow < TopRow) and (not Checked[ACol, ARow + 1]) and (FGrid[ACol, ARow + 1] <> nil) and (not (IsBomb and (FGrid[ACol, ARow + 1].ID = TraceID))) then TraceQuadris(ACol, ARow + 1, TraceID); if (ACol < RightCol) and (not Checked[ACol + 1, ARow]) and (FGrid[ACol + 1, ARow] <> nil) and (not (IsBomb and (FGrid[ACol + 1, ARow].ID = TraceID))) then TraceQuadris(ACol + 1, ARow, TraceID); if (ARow > BottomRow) and (not Checked[ACol, ARow - 1]) and (FGrid[ACol, ARow - 1] <> nil) and (not (IsBomb and (FGrid[ACol, ARow - 1].ID = TraceID))) then TraceQuadris(ACol, ARow - 1, TraceID); if (ACol > LeftCol) and (not Checked[ACol - 1, ARow]) and (FGrid[ACol - 1, ARow] <> nil) and (not (IsBomb and (FGrid[ACol - 1, ARow].ID = TraceID))) then TraceQuadris(ACol - 1, ARow, TraceID); end; end; var Deleted: Boolean; iTrace: Integer; TracedCount: Integer; iTraced: Integer; begin Deleted := False; if Length(FToTrace) > 0 then begin GridNeeded(True); Inc(FTraceCycle); for iTrace := 0 to Length(FToTrace) - 1 do begin InitTrace; with FToTrace[iTrace] do TraceQuadris(Col, Row, FGrid[Col, Row].ID); TracedCount := Length(TracedItems); if TracedCount >= 4 then begin for iTraced := 0 to TracedCount - 1 do with TracedItems[iTraced] do FGrid[Col, Row].Fade; for iTraced := 0 to Length(TracedBombs) - 1 do with TracedBombs[iTraced] do FGrid[Col, Row].Fade; Deleted := True; FQuadris.Points(TracedCount, FTraceCycle); end; end; SetLength(FToTrace, 0); end; if not Deleted then begin FTraceCycle := 0; if qoWithHandicap in FQuadris.Options then ThrowBombs else ThrowNextPair; end; end; procedure TQuadrisItems.Update; var i: Integer; begin i := 0; while i < Count do begin Items[i].Update; Inc(i); end; if Count > 1 then if FCurrentPair.Item1.FAutoFinished or FCurrentPair.Item2.FAutoFinished then Drop; end; function TQuadrisItems.ValidateMovement(Direction: TWind): Boolean; var Col: TColRange; Row: TRowRange; begin Col := FCurrentPair.Item1.Col; Row := FCurrentPair.Item1.Row; case Direction of East: case FCurrentPair.Dir of North, West: Result := (Col < RightCol) and (FGrid[Col + 1, Row] = nil); East: Result := (Col < RightCol - 1) and (FGrid[Col + 2, Row] = nil); else {South:} Result := (Col < RightCol) and (FGrid[Col + 1, Row - 1] = nil); end; West: case FCurrentPair.Dir of North, East: Result := (Col > LeftCol) and (FGrid[Col - 1, Row] = nil); South: Result := (Col > LeftCol) and (FGrid[Col - 1, Row - 1] = nil); else {West:} Result := (Col > LeftCol + 1) and (FGrid[Col - 2, Row] = nil); end; South: case FCurrentPair.Dir of North: Result := Row > ColHeight(Col); East: Result := (Row > ColHeight(Col)) and (Row > ColHeight(Col + 1)); South: Result := Row > ColHeight(Col) + 1; else {West:} Result := (Row > ColHeight(Col)) and (Row > ColHeight(Col - 1)); end; else {North:} Result := False; end; end; { TItemsView } function TItemsView.CanFocus: Boolean; begin Result := False; end; constructor TItemsView.Create(AOwner: TComponent); begin if not (AOwner is TCustomQuadris) then raise EQuadrisError.CreateFmt(rsErrInvalidCreationF, [ClassName]); inherited Create(AOwner); ControlStyle := [csOpaque, csFixedWidth, csFixedHeight, csDisplayDragImage, csNoStdEvents]; FQuadris := TCustomQuadris(AOwner); end; procedure TItemsView.Paint; begin with Canvas, ClipRect do BitBlt(Handle, Left, Top, Right - Left, Bottom - Top, FQuadris.FBackground.Canvas.Handle, Left, Top, SRCCOPY); end; procedure TItemsView.SetFocus; begin FQuadris.SetFocus; end; procedure TItemsView.WMLButtonDown(var Message: TWMLButtonDown); begin FQuadris.SetFocus; inherited; end; { TFadeLabel } const DefLabelAnimDuration = 1500; DefFontName = 'Arial'; DefFontSize = 8; procedure TFadeLabel.Animate; var Duration: Cardinal; begin if FCaption <> '' then begin Duration := GetTickCount - FStartTick; if Duration < DefLabelAnimDuration then Canvas.Font.Color := MixColor(clBlack, clWhite, Duration/DefLabelAnimDuration) else FCaption := ''; Invalidate; end; end; constructor TFadeLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csFixedWidth, csFixedHeight, csNoStdEvents, csDisplayDragImage]; Canvas.Brush.Style := bsClear; Canvas.Font.Name := DefFontName; Canvas.Font.Size := DefFontSize; end; procedure TFadeLabel.Paint; var R: TRect; begin R := ClientRect; DrawText(Canvas.Handle, PChar(FCaption), -1, R, DT_CENTER or DT_VCENTER or DT_SINGLELINE); end; procedure TFadeLabel.SetCaption(const Value: String); begin FStartTick := GetTickCount; FCaption := Value; end; { TFixedSizeControl } const DefViewWidth = ColCount * DefItemSize; DefViewHeight = RowCount * DefItemSize; DefMargin = 12; DefWidth = DefViewWidth + 3 * DefMargin + 2 * DefItemSize; DefHeight = DefViewHeight + 2 * DefMargin; function TFixedSizeControl.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := False; end; function TFixedSizeControl.CanResize(var NewWidth, NewHeight: Integer): Boolean; begin Result := False; end; constructor TFixedSizeControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csFixedWidth, csFixedHeight]; end; function TFixedSizeControl.GetAnchors: TAnchors; begin Result := inherited Anchors; end; function TFixedSizeControl.GetHeight: Integer; begin Result := inherited Height; end; function TFixedSizeControl.GetWidth: Integer; begin Result := inherited Width; end; procedure TFixedSizeControl.SetAnchors(Value: TAnchors); begin if Value <> Anchors then begin if [akLeft, akRight] * Value = [akLeft, akRight] then if akLeft in Anchors then Exclude(Value, akLeft) else Exclude(Value, akRight); if [akTop, akBottom] * Value = [akTop, akBottom] then if akTop in Anchors then Exclude(Value, akTop) else Exclude(Value, akBottom); inherited Anchors := Value; end; end; procedure TFixedSizeControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited SetBounds(ALeft, ATop, DefWidth, DefHeight); end; { TCustomQuadris } resourcestring RsErrThemesMissing = 'Unable to create Quadris control:' + #10#13#10#13'There are no theme resources found.'; RsErrResCorruptF = 'Unable to load Quadris theme %s due to ' + 'corrupt resource data.'; const DefResourceThemeType = 'QTHEME'; DefResourceBmpPrefix = 'Q'; DefUpdateTimerInterval = 40; DefFadeAnimInterval = 60; var InternalThemeNames: TStrings; GlobalThemeNames: TStrings; procedure TCustomQuadris.CMEnabledChanged(var Message: TMessage); begin inherited; if not Enabled then Pause; end; procedure TCustomQuadris.CMVisibleChanged(var Message: TMessage); begin inherited; if not Visible then Pause; end; constructor TCustomQuadris.Create(AOwner: TComponent); begin if GetThemeNames.Count <= 0 then raise EQuadrisError.Create(RsErrThemesMissing); inherited Create(AOwner); ControlStyle := ControlStyle + [csCaptureMouse, csClickEvents, csDoubleClicks, csOpaque, csDisplayDragImage]; Canvas.Font.Name := DefFontName; Canvas.Font.Size := DefFontSize; TabStop := True; ParentColor := False; FAnimTimer := TTimer.Create(Self); FAnimTimer.Enabled := False; FAnimTimer.OnTimer := OnAnimTimer; FBackground := TBitmap.Create; FUpdateTimer := TTimer.Create(Self); FUpdateTimer.Enabled := False; FUpdateTimer.Interval := DefUpdateTimerInterval; FUpdateTimer.OnTimer := OnUpdateTimer; FItemImageLists := TItemImageLists.Create(True); FLevel := DefLevel; FStartLevel := FLevel; FScore := DefScore; FItems := TQuadrisItems.Create(Self); FOptions := DefGameOptions; FView := TItemsView.Create(Self); FView.SetBounds(DefMargin, DefMargin, DefViewWidth, DefViewHeight); FView.Parent := Self; FPointsLabel := TFadeLabel.Create(Self); FPointsLabel.SetBounds(0, 2 * DefMargin, DefViewWidth, DefMargin); FPointsLabel.Parent := FView; InitJoystick; SetTheme(GetThemeNames[0]); end; destructor TCustomQuadris.Destroy; begin Stop; FItems.Free; FItemImageLists.Free; FBackground.Free; inherited Destroy; end; procedure TCustomQuadris.DoBonus(Points, Multiplier: Word); begin if Assigned(FOnBonus) then FOnBonus(Self, Points, Multiplier); end; procedure TCustomQuadris.DoDrop; begin if Assigned(FOnDrop) then FOnDrop(Self); end; procedure TCustomQuadris.DoGameOver(var StartAgain: Boolean); begin if Assigned(FOnGameOver) then FOnGameOver(Self, StartAgain); end; procedure TCustomQuadris.DoLevel; begin if Assigned(FOnLevel) then FOnLevel(Self); end; procedure TCustomQuadris.DoMove(Succeeded: Boolean); begin if Assigned(FOnMove) then FOnMove(Self, Succeeded); end; procedure TCustomQuadris.DoPoints(Points, Multiplier: Word); begin if Assigned(FOnPoints) then FOnPoints(Self, Points, Multiplier); end; procedure TCustomQuadris.DoRotate(Succeeded: Boolean); begin if Assigned(FOnRotate) then FOnRotate(Self, Succeeded); end; procedure TCustomQuadris.GameOver; var StartAgain: Boolean; begin Stop; StartAgain := False; DoGameOver(StartAgain); if StartAgain then Start; end; function TCustomQuadris.GetColor: TColor; begin Result := inherited Color; end; function TCustomQuadris.GetRunning: Boolean; begin if csDesigning in ComponentState then Result := FStreamedRunning else Result := FUpdateTimer.Enabled; end; class function TCustomQuadris.GetThemeNames: TStrings; function EnumResNamesProc(hModule: Cardinal; lpszType, lpszName: PChar; LParam: Integer): BOOL; stdcall; begin TStrings(InternalThemeNames).Add(lpszName); Result := True; end; begin if InternalThemeNames = nil then begin InternalThemeNames := TStringList.Create; GlobalThemeNames := TStringList.Create; EnumResourceNames(HInstance, DefResourceThemeType, @EnumResNamesProc, 0); end; TStrings(GlobalThemeNames).Assign(InternalThemeNames); Result := GlobalThemeNames; end; procedure TCustomQuadris.InitJoystick; begin Joystick.Advanced := True; Joystick.Active := True; if Joystick.Active then begin Joystick.OnButtonDown := JoystickButtonDown; Joystick.OnMove := JoystickMove; Joystick.RepeatButtonDelay := 350; Joystick.RepeatMoveDelay := 350; end; end; function TCustomQuadris.IsColorStored: Boolean; begin Result := Color <> FThemeColor; end; procedure TCustomQuadris.JoystickButtonDown(Sender: TNLDJoystick; Buttons: TJoyButtons); begin if JoyBtn1 in Buttons then PostMessage(Handle, WM_KEYDOWN, VK_DOWN, 0); NotifyKeyboardActivity; end; procedure TCustomQuadris.JoystickMove(Sender: TNLDJoystick; const JoyPos: TJoyRelPos; Buttons: TJoyButtons); begin if JoyPos.X < 0 then PostMessage(Handle, WM_KEYDOWN, VK_LEFT, 0) else if JoyPos.X > 0 then PostMessage(Handle, WM_KEYDOWN, VK_RIGHT, 0) else if JoyPos.Y < 0 then PostMessage(Handle, WM_KEYDOWN, VK_UP, 0) else if JoyPos.Y > 0 then PostMessage(Handle, WM_KEYDOWN, VK_DOWN, 0); NotifyKeyboardActivity; end; procedure TCustomQuadris.LoadTheme(const ATheme: TThemeName); var Stream: TStream; Strings: TStrings; Bitmap: TBitmap; ThemeID: Integer; ItemCount: Integer; FrameCount: Integer; iItem: Integer; ImageList: TCustomImageList; iFrame: Integer; ItemName: String; begin FItems.Clear; FItemImageLists.Clear; try Stream := TResourceStream.Create(HInstance, ATheme, DefResourceThemeType); Strings := TStringList.Create; Bitmap := TBitmap.Create; try Strings.LoadFromStream(Stream); ThemeID := StrToInt(Strings.Values['ThemeID']); ItemCount := StrToInt(Strings.Values['ItemCount']); FrameCount := StrToInt(Strings.Values['FrameCount']); FAnimInterval := StrToInt(Strings.Values['Interval']); FAnimTimer.Interval := FAnimInterval; FThemeColor := StrToInt(Strings.Values['Color']); Color := FThemeColor; FAnimKind := StrToAnimKind(Strings.Values['AnimKind']); FBackground.LoadFromResourceName(HInstance, ATheme); for iItem := 0 to ItemCount - 1 do begin ImageList := TCustomImageList.Create(nil); ImageList.Width := DefItemSize; ImageList.Height := DefItemSize; ImageList.BkColor := clBlack; FItemImageLists.Add(ImageList); FItemImageLists.DefImageIndexes[iItem] := StrToInt(Strings.Values[IntToStr(iItem)]); for iFrame := 0 to FrameCount - 1 do begin ItemName := Format('%s%d_%d_%d', [DefResourceBmpPrefix, ThemeID, iItem, iFrame]); Bitmap.LoadFromResourceName(HInstance, ItemName); if iItem = ItemCount - 1 then ImageList.AddMasked(Bitmap, clNone) else ImageList.AddMasked(Bitmap, clDefault); end; end; FItems.FFadeItemID := ItemCount - 1; FItems.FBombItemID := ItemCount - 2; FItems.FMaxItemID := ItemCount - 2; FTheme := ATheme; Invalidate; finally Bitmap.Free; Strings.Free; Stream.Free; end; except on EOutOfMemory do raise; else raise EQuadrisError.CreateFmt(rsErrResCorruptF, [ATheme]); end; end; function TCustomQuadris.MaxLevelScore(ALevel: TQuadrisLevel): Cardinal; begin Result := (ALevel + 1) * 50 * ALevel; end; procedure TCustomQuadris.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); SetFocus; end; procedure TCustomQuadris.OnAnimTimer(Sender: TObject); begin FItems.Animate; FPointsLabel.Animate; end; procedure TCustomQuadris.OnUpdateTimer(Sender: TObject); begin if FItems.FDeleting then FAnimTimer.Interval := DefFadeAnimInterval else FAnimTimer.Interval := FAnimInterval; FItems.Update; end; procedure TCustomQuadris.Paint; var R: TRect; begin Canvas.Brush.Color := Color; R := ClientRect; if Ctl3D then Frame3D(Canvas, R, FColors.Darker, FColors.Lighter, 1); Canvas.FillRect(R); R := FView.BoundsRect; InflateRect(R, 1, 1); Frame3D(Canvas, R, FColors.Dark, FColors.Light, 1); PaintView; end; procedure TCustomQuadris.PaintView; var R: TRect; begin R.Left := DefMargin * 2 + FView.Width; if qoShowNext in Options then begin R.Top := DefMargin - 4; R.Right := Width - DefMargin; R.Bottom := R.Top + 2 * Canvas.Font.Size; DrawText(Canvas.Handle, PChar('Next:'), -1, R, 0); OffsetRect(R, 0, 2 * Canvas.Font.Size); R.Right := R.Left + 2 * DefItemSize; R.Bottom := R.Top + 2 * DefItemSize; with R do BitBlt(Canvas.Handle, Left, Top, Right - Left, Bottom - Top, FBackground.Canvas.Handle, 0, 0, SRCCOPY); InflateRect(R, 1, 1); Frame3D(Canvas, R, FColors.Dark, FColors.Light, 1); with FItems.FNextPairData, FItemImageLists do begin case Dir of North: begin Items[ID1].Draw(Canvas, R.Left + DefItemSize div 2, R.Top + DefItemSize, DefImageIndexes[ID1], dsTransparent, itImage); Items[ID2].Draw(Canvas, R.Left + DefItemSize div 2, R.Top, DefImageIndexes[ID2], dsTransparent, itImage); end; East: begin Items[ID1].Draw(Canvas, R.Left, R.Top + DefItemSize div 2, DefImageIndexes[ID1], dsTransparent, itImage); Items[ID2].Draw(Canvas, R.Left + DefItemSize, R.Top + DefItemSize div 2, DefImageIndexes[ID2], dsTransparent, itImage); end; South: begin Items[ID1].Draw(Canvas, R.Left + DefItemSize div 2, R.Top, DefImageIndexes[ID1], dsTransparent, itImage); Items[ID2].Draw(Canvas, R.Left + DefItemSize div 2, R.Top + DefItemSize, DefImageIndexes[ID2], dsTransparent, itImage); end; West: begin Items[ID1].Draw(Canvas, R.Left + DefItemSize, R.Top + DefItemSize div 2, DefImageIndexes[ID1], dsTransparent, itImage); Items[ID2].Draw(Canvas, R.Left, R.Top + DefItemSize div 2, DefImageIndexes[ID2], dsTransparent, itImage); end end; end; R.Top := R.Bottom + 2 * Canvas.Font.Size; R.Right := Width - Defmargin; R.Bottom := R.Top + 2 * Canvas.Font.Size; end else begin R.Top := DefMargin - 4; R.Right := Width - DefMargin; R.Bottom := R.Top + 2 * Canvas.Font.Size; end; DrawText(Canvas.Handle, PChar('Score:'), -1, R, 0); OffsetRect(R, 0, 2 * Canvas.Font.Size); Frame3D(Canvas, R, FColors.Dark, FColors.Light, 1); Canvas.FillRect(R); DrawText(Canvas.Handle, PChar(IntToStr(FScore)), -1, R, DT_CENTER); InflateRect(R, 1, 1); OffsetRect(R, 0, 3 * Canvas.Font.Size); DrawText(Canvas.Handle, PChar('Level:'), -1, R, 0); OffsetRect(R, 0, 2 * Canvas.Font.Size); Frame3D(Canvas, R, FColors.Dark, FColors.Light, 1); Canvas.FillRect(R); DrawText(Canvas.Handle, PChar(IntToStr(FLevel)), -1, R, DT_CENTER); end; procedure TCustomQuadris.Pause; begin if Running then begin Stop; FPauseTick := GetTickCount; FPaused := True; end; end; procedure TCustomQuadris.Points(TracedCount, TraceCycle: Word); begin Inc(FScore, FLevel * TracedCount * TraceCycle); PaintView; DoPoints(FLevel * TracedCount, TraceCycle); if TraceCycle = 1 then FPointsLabel.Caption := Format('%d', [FLevel * TracedCount]) else FPointsLabel.Caption := Format('%d x %d', [TraceCycle, FLevel * TracedCount]); if FItems.Empty then begin Inc(FScore, ColCount * RowCount * FLevel); PaintView; DoBonus(ColCount * RowCount, FLevel); end; UpdateLevel; end; procedure TCustomQuadris.SetColor(Value: TColor); begin if Color <> Value then begin if Value = clDefault then inherited Color := FThemeColor else inherited Color := Value; FColors.Light := MixColor(Color, clWhite, 0.25); FColors.Lighter := MixColor(Color, clWhite, 0.5); FColors.Dark := MixColor(Color, clBlack, 0.25); FColors.Darker := MixColor(Color, clBlack, 0.5); Invalidate; end; end; procedure TCustomQuadris.SetLevel(Value: TQuadrisLevel); begin if FLevel <> Value then begin FLevel := Value; if not Running then FStartLevel := FLevel; Invalidate; end; end; procedure TCustomQuadris.SetOptions(Value: TQuadrisOptions); begin if FOptions <> Value then begin if (qoShowNext in (FOptions - Value)) or (qoShowNext in (Value - FOptions)) then Invalidate; if Focused and (qoStartOnFocus in (Value - FOptions)) then Start; if (not Focused) and (qoPauseOnUnfocus in (Value - FOptions)) then Pause; FOptions := Value; end; end; procedure TCustomQuadris.SetRunning(Value: Boolean); begin if csDesigning in ComponentState then FStreamedRunning := Value else if Running <> Value then begin if Value then Start else Pause; end; end; procedure TCustomQuadris.SetTheme(const Value: TThemeName); begin if FTheme <> Value then begin if Running then Stop; LoadTheme(Value); end; end; procedure TCustomQuadris.Start; begin if not Running then begin if FPaused then begin FItems.SetDelay(GetTickCount - FPauseTick); FPaused := False; end else begin FItems.Clear; FScore := DefScore; FLevel := FStartLevel; FItems.ThrowNextPair; end; FAnimTimer.Enabled := True; FUpdateTimer.Enabled := True; end; end; procedure TCustomQuadris.Stop; begin FUpdateTimer.Enabled := False; FAnimTimer.Enabled := False; end; procedure TCustomQuadris.UpdateLevel; begin if qoAutoIncLevel in Options then if FLevel < High(TQuadrisLevel) then if FScore > MaxLevelScore(FLevel) then begin Inc(FLevel); DoLevel; end; end; procedure TCustomQuadris.WMGetDlgCode(var Message: TMessage); begin if TabStop then Message.Result := DLGC_WANTARROWS else Message.Result := DLGC_WANTARROWS or DLGC_WANTTAB; end; procedure TCustomQuadris.WMKeyDown(var Message: TWMKeyDown); begin if Running then case Message.CharCode of VK_LEFT: DoMove(FItems.MoveLeft); VK_UP: DoRotate(FItems.Rotate); VK_RIGHT: DoMove(FItems.MoveRight); VK_DOWN, VK_SPACE: FItems.Drop; end; inherited; end; procedure TCustomQuadris.WMKillFocus(var Message: TWMSetFocus); begin inherited; if qoPauseOnUnfocus in Options then Pause; end; procedure TCustomQuadris.WMSetFocus(var Message: TWMSetFocus); begin inherited; if qoStartOnFocus in Options then Start; end; initialization Randomize; finalization if InternalThemeNames <> nil then InternalThemeNames.Free; if GlobalThemeNames <> nil then GlobalThemeNames.Free; end.
program _demo; Array[0] var M : AlglibInteger; N : AlglibInteger; K : AlglibInteger; Y : TReal1DArray; X : TReal2DArray; C : TReal1DArray; Rep : LSFitReport; State : LSFitState; Info : AlglibInteger; EpsF : Double; EpsX : Double; MaxIts : AlglibInteger; I : AlglibInteger; J : AlglibInteger; A : Double; B : Double; begin Write(Format('Fitting 0.5(1+cos(x)) on [-pi,+pi] with exp(-alpha*x^2)'#13#10'',[])); // // Fitting 0.5(1+cos(x)) on [-pi,+pi] with Gaussian exp(-alpha*x^2): // * without Hessian (gradient only) // * using alpha=1 as initial value // * using 1000 uniformly distributed points to fit to // // Notes: // * N - number of points // * M - dimension of space where points reside // * K - number of parameters being fitted // N := 1000; M := 1; K := 1; A := -Pi; B := +Pi; // // Prepare task matrix // SetLength(Y, N); SetLength(X, N, M); SetLength(C, K); I:=0; while I<=N-1 do begin X[I,0] := A+(B-A)*I/(N-1); Y[I] := 0.5*(1+Cos(X[I,0])); Inc(I); end; C[0] := 1.0; EpsF := 0.0; EpsX := 0.0001; MaxIts := 0; // // Solve // LSFitNonlinearFG(X, Y, C, N, M, K, True, State); LSFitNonlinearSetCond(State, EpsF, EpsX, MaxIts); while LSFitNonlinearIteration(State) do begin if State.NeedF then begin // // F(x) = Exp(-alpha*x^2) // State.F := Exp(-State.C[0]*AP_Sqr(State.X[0])); end; if State.NeedFG then begin // // F(x) = Exp(-alpha*x^2) // dF/dAlpha = (-x^2)*Exp(-alpha*x^2) // State.F := Exp(-State.C[0]*AP_Sqr(State.X[0])); State.G[0] := -AP_Sqr(State.X[0])*State.F; end; end; LSFitNonlinearResults(State, Info, C, Rep); Write(Format('alpha: %0.3f'#13#10'',[ C[0]])); Write(Format('rms.err: %0.3f'#13#10'',[ Rep.RMSError])); Write(Format('max.err: %0.3f'#13#10'',[ Rep.MaxError])); Write(Format('Termination type: %0d'#13#10'',[ Info])); Write(Format(''#13#10''#13#10'',[])); end.
unit xElecFunction; interface uses xElecPoint, Math, xElecLine; /// <summary> /// 已知 A,B向量,求两个向量的和向量C /// </summary> procedure GetCValue(APoint, BPoint, CPoint : TElecPoint); /// <summary> /// 已知两边和两边夹角求第三边 /// </summary> procedure GetOtherValue(APoint, BPoint, CPoint : TElecPoint); /// <summary> /// 调整角度 (把角度调整到0-360度范围内) /// </summary> function AdjustAngle(dAngle : Double) : Double; /// <summary> /// 获取角度所在象限 /// </summary> function GetQuadrantSN(dAngle : Double) : Integer; /// <summary> /// 计算两点的电流值 /// </summary> /// <param name="AHigtPoint">电流高端点</param> /// <param name="ALowPoint">电流低端点</param> /// <param name="AOutCurrentPoint">两点电流值</param> procedure GetTwoPointCurrent(AHigtPoint, ALowPoint : TElecLine; AOutCurrentPoint : TElecPoint); implementation procedure GetTwoPointCurrent(AHigtPoint, ALowPoint : TElecLine; AOutCurrentPoint : TElecPoint); var i : Integer; APointA, APointB, APointC : TElecPoint; nWID, nWValueIn, nWValueOut : Integer; AElecLineIn : TElecLine; begin if Assigned(AHigtPoint) and Assigned(AHigtPoint) and Assigned(AHigtPoint) then begin APointA := TElecPoint.Create; APointB := TElecPoint.Create; APointC := TElecPoint.Create; if AHigtPoint.CurrentList.Count > 0 then begin for i := 0 to AHigtPoint.CurrentList.Count - 1 do begin AElecLineIn := TElecLine(AHigtPoint.CurrentList.Objects[i]); nWID := AElecLineIn.WID; nWValueIn := AHigtPoint.Current.WeightValue[nWID].WValue; nWValueOut := ALowPoint.Current.WeightValue[nWID].WValue; if (nWID <> C_WEIGHT_VALUE_INVALID) and (nWValueIn <> C_WEIGHT_VALUE_INVALID) and (nWValueOut <> C_WEIGHT_VALUE_INVALID) then begin APointA.Value := AElecLineIn.Current.Value; if nWValueOut > nWValueIn then begin APointA.Angle := AdjustAngle(AElecLineIn.Current.Angle + 180); end else begin APointA.Angle := AElecLineIn.Current.Angle; end; if i = 0 then begin APointC.Value := APointA.Value; APointC.Angle := APointA.Angle; end else begin GetCValue(APointA, APointB, APointC); end; APointB.Value := APointC.Value; APointB.Angle := APointC.Angle; end; end; end; AOutCurrentPoint.Angle := APointC.Angle; AOutCurrentPoint.Value := APointC.Value; APointA.Free; APointB.Free; APointC.Free; end; end; function GetQuadrantSN(dAngle : Double) : Integer; var dValue : Double; begin dValue := AdjustAngle(dAngle); if (dValue >= 0) and (dValue < 90) then Result := 1 else if (dValue >= 90) and (dValue < 180) then Result := 2 else if (dValue >= 180) and (dValue < 270) then Result := 3 else if (dValue >= 270) and (dValue < 360) then Result := 4 else Result := 1; end; function AdjustAngle(dAngle : Double) : Double; var dTemp : Integer; begin dTemp := Round(dAngle*1000); dTemp := dTemp mod 360000; Result := dTemp / 1000; if Result < 0 then Result := 360 + Result; end; procedure GetOtherValue(APoint, BPoint, CPoint : TElecPoint); var dABAngle : Double; // ab夹角 dAngle : Double; begin // 用余弦定理,c^2=a^2+b^2-2abcosC // 正弦定理 a/sinA=c/sinC=b/sinB if Assigned(APoint) and Assigned(BPoint) and Assigned(CPoint) then begin dABAngle := BPoint.Angle-APoint.Angle; // 值 CPoint.Value := Sqrt(Sqr(APoint.Value) + Sqr(BPoint.Value) - 2*APoint.Value*BPoint.Value * Cos(DegToRad(dABAngle))); // 角度 if CPoint.Value* sin(DegToRad(dABAngle)) <> 0 then begin dAngle := RadToDeg(ArcSin(BPoint.Value/CPoint.Value*sin(DegToRad(dABAngle)))); CPoint.Angle := APoint.Angle - dAngle; // if dAngle > APoint.Angle then // begin // CPoint.Angle := APoint.Angle + dAngle; // end // else // begin // CPoint.Angle := APoint.Angle - dAngle; // end; end; end; end; procedure GetCValue(APoint, BPoint, CPoint : TElecPoint); var dABAngle : Double; // ab夹角 dAngle : Double; begin // 用余弦定理,c^2=a^2+b^2-2abcosC // 正弦定理 a/sinA=c/sinC=b/sinB if Assigned(APoint) and Assigned(BPoint) and Assigned(CPoint) then begin dABAngle := abs(180- abs(BPoint.Angle-APoint.Angle)); // 值 CPoint.Value := Sqrt(Sqr(APoint.Value) + Sqr(BPoint.Value) - 2*APoint.Value*BPoint.Value * Cos(DegToRad(dABAngle))); // 角度 if CPoint.Value* sin(DegToRad(dABAngle)) <> 0 then begin dAngle := RadToDeg(ArcSin(BPoint.Value/CPoint.Value*sin(DegToRad(dABAngle)))); if BPoint.Angle > APoint.Angle then begin if abs(BPoint.Angle-APoint.Angle) < 180 then begin CPoint.Angle := AdjustAngle(APoint.Angle + dAngle); end else begin CPoint.Angle := AdjustAngle(APoint.Angle - dAngle); end; end else begin if abs(BPoint.Angle-APoint.Angle) < 180 then begin CPoint.Angle := AdjustAngle(APoint.Angle - dAngle); end else begin CPoint.Angle := AdjustAngle(APoint.Angle + dAngle); end; end; end; end; end; end.
unit BrickCamp.JsonUser; interface uses System.Sysutils, BrickCamp.Common.JsonContract; type TJsonUser = class(TJsonContractBase) private [ JSONName( 'name' ) ] FName: string; [ JSONName( 'Id' ) ] FId: Integer; public property Id: Integer read FId write FId; property Name: string read FName write FName; class function FromJson( const JsonStr: string ): TJsonUser; function ToKey( ): string; override; end; implementation { TJsonUser } class function TJsonUser.FromJson(const JsonStr: string): TJsonUser; begin result := _FromJson(JsonStr) as TJsonUser; end; function TJsonUser.ToKey: string; begin Result := ClassName + IntToStr(Id); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC connection metadata base class } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.Meta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys; type TFDPhysConnectionMetadata = class (TInterfacedObject, IUnknown, IFDPhysConnectionMetadata) private FMetadataCache: TFDDatSManager; FMaximumNameParts: Integer; FNameParts: array of String; FServerVersion: TFDVersion; FClientVersion: TFDVersion; FIsUnicode: Boolean; FQuoteChars: TFDByteSet; function UnQuoteBase(const AName: String; ACh1, ACh2: Char): String; function IsQuotedBase(const AName: String; ACh1, ACh2: Char): Boolean; function IsNameQuoted(const AName: String): Boolean; function NormObjName(const AName: String; APart: TFDPhysNamePart): String; function QuoteNameIfReq(const AName: String; APart: TFDPhysNamePart): String; function IsRDBMSKind(const AStr: String; out ACurrent: Boolean): Boolean; function FetchNoCache(AMetaKind: TFDPhysMetaInfoKind; AScope: TFDPhysObjectScopes; AKinds: TFDPhysTableKinds; const ACatalog, ASchema, ABaseObject, AWildCard: String; AOverload: Word): TFDDatSTable; function CheckFetchToCache(AMetaKind: TFDPhysMetaInfoKind; const AFilter: String; var ATable: TFDDatSTable; var AView: TFDDatSView): Boolean; procedure AddWildcard(AView: TFDDatSView; const AColumn, AWildcard: String; APart: TFDPhysNamePart); procedure FetchToCache(AMetaKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject: String; AOverload: Word; ADataTable: TFDDatSTable); function DefineMetadataTableName(AKind: TFDPhysMetaInfoKind): String; function GetCacheFilter(const ACatalog, ASchema, AObjField, AObj, ASubObjField, ASubObj: String): String; function ConvertNameCaseExpr(const AColumn, AValue: String; APart: TFDPhysNamePart): String; function ConvertNameCaseConst(const AValue: String; APart: TFDPhysNamePart): String; procedure ParseMetaInfoParams(const ACatalog, ASchema, ABaseObjName, AObjName: String; out AParsedName: TFDPhysParsedName); function GetTableFieldsBase(AMetaKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; protected [Weak] FConnectionObj: TFDPhysConnection; FKeywords: TFDStringList; FCISearch: Boolean; // IUnknown function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall; // IFDPhysConnectionMetadata function GetKind: TFDRDBMSKind; virtual; function GetClientVersion: TFDVersion; virtual; function GetServerVersion: TFDVersion; virtual; function GetIsUnicode: Boolean; virtual; function GetIsFileBased: Boolean; virtual; function GetTxSupported: Boolean; virtual; function GetTxNested: Boolean; virtual; function GetTxMultiple: Boolean; virtual; function GetTxSavepoints: Boolean; virtual; function GetTxAutoCommit: Boolean; virtual; function GetTxAtomic: Boolean; virtual; function GetEventSupported: Boolean; virtual; function GetEventKinds: String; virtual; function GetGeneratorSupported: Boolean; virtual; function GetParamNameMaxLength: Integer; virtual; function GetNameParts: TFDPhysNameParts; virtual; function GetNameQuotedSupportedParts: TFDPhysNameParts; virtual; function GetNameQuotedCaseSensParts: TFDPhysNameParts; virtual; function GetNameQuotedCaseSens(const AName: String; APart: TFDPhysNamePart): Boolean; virtual; function GetNameCaseSensParts: TFDPhysNameParts; virtual; function GetNameDefLowCaseParts: TFDPhysNameParts; virtual; function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; virtual; function GetCatalogSeparator: Char; virtual; function GetSchemaSeparator: Char; virtual; function GetInsertHBlobMode: TFDPhysInsertHBlobMode; virtual; function GetIdentitySupported: Boolean; virtual; function GetIdentityInsertSupported: Boolean; virtual; function GetIdentityInWhere: Boolean; virtual; function GetNamedParamMark: TFDPhysParamMark; virtual; function GetPositionedParamMark: TFDPhysParamMark; virtual; function GetSelectOptions: TFDPhysSelectOptions; virtual; function GetLockNoWait: Boolean; virtual; function GetAsyncAbortSupported: Boolean; virtual; function GetAsyncNativeTimeout: Boolean; virtual; function GetCommandSeparator: String; virtual; function GetLineSeparator: TFDTextEndOfLine; virtual; function GetArrayExecMode: TFDPhysArrayExecMode; virtual; function GetLimitOptions: TFDPhysLimitOptions; virtual; function GetNullLocations: TFDPhysNullLocations; virtual; function GetServerCursorSupported: Boolean; virtual; function GetColumnOriginProvided: Boolean; virtual; function GetCreateTableOptions: TFDPhysCreateTableOptions; virtual; function GetBackslashEscSupported: Boolean; virtual; function DecodeObjName(const AName: String; out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; AOpts: TFDPhysDecodeOptions): Boolean; function EncodeObjName(const AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; AOpts: TFDPhysEncodeOptions): String; function QuoteObjName(const AName: String; APart: TFDPhysNamePart): String; function UnQuoteObjName(const AName: String): String; function IsKeyword(const AName: String): Boolean; function IsNameValid(const AName: String): Boolean; virtual; function TranslateEscapeSequence(var ASeq: TFDPhysEscapeData): String; virtual; function GetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; function GetTruncateSupported: Boolean; virtual; function GetDefValuesSupported: TFDPhysDefaultValues; virtual; function GetInlineRefresh: Boolean; virtual; function GetCatalogs(const AWildCard: String): TFDDatSView; virtual; function GetSchemas(const ACatalog, AWildCard: String): TFDDatSView; virtual; function GetTables(AScope: TFDPhysObjectScopes; AKinds: TFDPhysTableKinds; const ACatalog, ASchema, AWildCard: String): TFDDatSView; virtual; function GetTableFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; virtual; function GetTableIndexes(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; virtual; function GetTableIndexFields(const ACatalog, ASchema, ATable, AIndex, AWildCard: String): TFDDatSView; virtual; function GetTablePrimaryKey(const ACatalog, ASchema, ATable: String): TFDDatSView; virtual; function GetTablePrimaryKeyFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; virtual; function GetTableForeignKeys(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; function GetTableForeignKeyFields(const ACatalog, ASchema, ATable, AForeignKey, AWildCard: String): TFDDatSView; function GetPackages(AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; virtual; function GetPackageProcs(const ACatalog, ASchema, APackage, AWildCard: String): TFDDatSView; virtual; function GetProcs(AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; virtual; function GetProcArgs(const ACatalog, ASchema, APackage, AProc, AWildCard: String; AOverload: Word): TFDDatSView; virtual; function GetGenerators(AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; virtual; function GetResultSetFields(const ASQLKey: String): TFDDatSView; virtual; function GetTableTypeFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; virtual; procedure DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); virtual; procedure RefreshMetadataCache(const AObjName: String = ''); // other function InternalEncodeObjName(const AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand): String; virtual; function InternalDecodeObjName(const AName: String; out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; ARaise: Boolean): Boolean; virtual; procedure InternalOverrideNameByCommand(var AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand); virtual; function InternalEscapeBoolean(const AStr: String): String; virtual; function InternalEscapeDate(const AStr: String): String; virtual; function InternalEscapeTime(const AStr: String): String; virtual; function InternalEscapeDateTime(const AStr: String): String; virtual; function InternalEscapeFloat(const AStr: String): String; virtual; function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; virtual; function InternalEscapeEscape(AEscape: Char; const AStr: String): String; virtual; function InternalEscapeInto(const AStr: String): String; virtual; function InternalEscapeString(const AStr: String): String; virtual; function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; virtual; // utility procedure UnsupportedEscape(const ASeq: TFDPhysEscapeData); procedure EscapeFuncToID(var ASeq: TFDPhysEscapeData); function AddEscapeSequenceArgs(const ASeq: TFDPhysEscapeData): String; procedure ConfigNameParts; procedure ConfigQuoteChars; procedure AddMetadataCol(ATable: TFDDatSTable; const AName: String; AType: TFDDataType); public constructor Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean); destructor Destroy; override; end; implementation uses {$IFDEF MSWINDOWS} // Preventing from "Inline has not expanded" Winapi.Windows, {$ENDIF} System.SysUtils, FireDAC.Stan.Error, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Option; {-------------------------------------------------------------------------------} { TFDPhysConnectionMetadata } {-------------------------------------------------------------------------------} constructor TFDPhysConnectionMetadata.Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVersion: TFDVersion; AIsUnicode: Boolean); begin inherited Create; FConnectionObj := AConnectionObj; FKeywords := TFDStringList.Create(dupAccept, True, False); FKeywords.CommaText := 'ABSOLUTE,ACTION,ADA,ADD,ALL,ALLOCATE,ALTER,AND,ANY,ARE,AS,' + 'ASC,ASSERTION,AT,AUTHORIZATION,AVG,' + 'BEGIN,BETWEEN,BIT,BIT_LENGTH,BOTH,BY,CASCADE,CASCADED,CASE,CAST,CATALOG,' + 'CHAR,CHAR_LENGTH,CHARACTER,CHARACTER_LENGTH,CHECK,CLOSE,COALESCE,' + 'COLLATE,COLLATION,COLUMN,COMMIT,CONNECT,CONNECTION,CONSTRAINT,' + 'CONSTRAINTS,CONTINUE,CONVERT,CORRESPONDING,COUNT,CREATE,CROSS,CURRENT,' + 'CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,' + 'DATE,DAY,DEALLOCATE,DEC,DECIMAL,DECLARE,DEFAULT,DEFERRABLE,' + 'DEFERRED,DELETE,DESC,DESCRIBE,DESCRIPTOR,DIAGNOSTICS,DISCONNECT,' + 'DISTINCT,DOMAIN,DOUBLE,DROP,' + 'ELSE,END,END-EXEC,ESCAPE,EXCEPT,EXCEPTION,EXEC,EXECUTE,' + 'EXISTS,EXTERNAL,EXTRACT,' + 'FALSE,FETCH,FIRST,FLOAT,FOR,FOREIGN,FORTRAN,FOUND,FROM,FULL,' + 'GET,GLOBAL,GO,GOTO,GRANT,GROUP,HAVING,HOUR,' + 'IDENTITY,IMMEDIATE,IN,INCLUDE,INDEX,INDICATOR,INITIALLY,INNER,' + 'INPUT,INSENSITIVE,INSERT,INT,INTEGER,INTERSECT,INTERVAL,INTO,IS,ISOLATION,' + 'JOIN,KEY,LANGUAGE,LAST,LEADING,LEFT,LEVEL,LIKE,LOCAL,LOWER,' + 'MATCH,MAX,MIN,MINUTE,MODULE,MONTH,' + 'NAMES,NATIONAL,NATURAL,NCHAR,NEXT,NO,NONE,NOT,NULL,NULLIF,NUMERIC,' + 'OCTET_LENGTH,OF,ON,ONLY,OPEN,OPTION,OR,ORDER,OUTER,OUTPUT,OVERLAPS,' + 'PAD,PARTIAL,PASCAL,PLI,POSITION,PRECISION,PREPARE,PRESERVE,' + 'PRIMARY,PRIOR,PRIVILEGES,PROCEDURE,PUBLIC,' + 'READ,REAL,REFERENCES,RELATIVE,RESTRICT,REVOKE,RIGHT,ROLLBACK,ROWS' + 'SCHEMA,SCROLL,SECOND,SECTION,SELECT,SESSION,SESSION_USER,SET,SIZE,' + 'SMALLINT,SOME,SPACE,SQL,SQLCA,SQLCODE,SQLERROR,SQLSTATE,SQLWARNING,' + 'SUBSTRING,SUM,SYSTEM_USER,' + 'TABLE,TEMPORARY,THEN,TIME,TIMESTAMP,TIMEZONE_HOUR,TIMEZONE_MINUTE,' + 'TO,TRAILING,TRANSACTION,TRANSLATE,TRANSLATION,TRIM,TRUE,' + 'UNION,UNIQUE,UNKNOWN,UPDATE,UPPER,USAGE,USER,USING,' + 'VALUE,VALUES,VARCHAR,VARYING,VIEW,WHEN,WHENEVER,WHERE,WITH,WORK,WRITE,' + 'YEAR,ZONE'; ConfigNameParts; ConfigQuoteChars; FServerVersion := AServerVersion; FClientVersion := AClientVersion; FIsUnicode := AIsUnicode; FCISearch := (FConnectionObj <> nil) and FConnectionObj.ConnectionDef.AsBoolean[S_FD_ConnParam_Common_MetaCaseIns]; end; {-------------------------------------------------------------------------------} destructor TFDPhysConnectionMetadata.Destroy; begin FConnectionObj := nil; FDFreeAndNil(FMetadataCache); FDFreeAndNil(FKeywords); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata._AddRef: Integer; begin if FConnectionObj = nil then Result := inherited _AddRef else Result := FConnectionObj._AddRef; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata._Release: Integer; begin if FConnectionObj = nil then Result := inherited _Release else Result := FConnectionObj._Release; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := inherited QueryInterface(IID, Obj); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.ConfigNameParts; var i: TFDPhysNamePart; begin FMaximumNameParts := 0; for i := Low(TFDPhysNamePart) to High(TFDPhysNamePart) do if (i <> npDBLink) and (i in GetNameParts) then Inc(FMaximumNameParts); SetLength(FNameParts, FMaximumNameParts); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.ConfigQuoteChars; var eQuote: TFDPhysNameQuoteLevel; begin FQuoteChars := []; for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin Include(FQuoteChars, Byte(GetNameQuoteChar(eQuote, nsLeft))); Include(FQuoteChars, Byte(GetNameQuoteChar(eQuote, nsRight))); end; Exclude(FQuoteChars, 0); Exclude(FQuoteChars, Byte(' ')); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.UnQuoteBase(const AName: String; ACh1, ACh2: Char): String; begin if IsQuotedBase(AName, ACh1, ACh2) then Result := Copy(AName, 2, Length(AName) - 2) else Result := AName; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.UnQuoteObjName(const AName: String): String; var eQuote: TFDPhysNameQuoteLevel; begin for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin Result := UnQuoteBase(AName, GetNameQuoteChar(eQuote, nsLeft), GetNameQuoteChar(eQuote, nsRight)); if Result <> AName then Break; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.IsQuotedBase(const AName: String; ACh1, ACh2: Char): Boolean; begin Result := (Length(AName) > 2) and not FDInSet(ACh1, [#0, ' ']) and not FDInSet(ACh2, [#0, ' ']) and (AName[1] = ACh1) and (AName[Length(AName)] = ACh2); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.IsNameQuoted(const AName: String): Boolean; var eQuote: TFDPhysNameQuoteLevel; begin if not ((Length(AName) > 2) and (Byte(AName[1]) in FQuoteChars)) then Result := False else for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin Result := IsQuotedBase(AName, GetNameQuoteChar(eQuote, nsLeft), GetNameQuoteChar(eQuote, nsRight)); if Result then Break; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.IsNameValid(const AName: String): Boolean; var i: Integer; begin Result := True; for i := 1 to Length(AName) do if not ((i = 1) and FDInSet(AName[i], ['a' .. 'z', 'A' .. 'Z', '_']) or (i > 1) and FDInSet(AName[i], ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '$', '#'])) then begin Result := False; Break; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameQuotedCaseSens(const AName: String; APart: TFDPhysNamePart): Boolean; begin Result := APart in GetNameQuotedCaseSensParts; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.NormObjName(const AName: String; APart: TFDPhysNamePart): String; begin Result := AName; if Result <> '' then if not IsNameQuoted(Result) then if APart in GetNameCaseSensParts then begin // QwQw -> QwQw // Q w Q w -> "Q w Q w" // "Q w Q w" -> "Q w Q w" // SELECT -> "SELECT" if not IsNameValid(Result) or IsKeyword(Result) then Result := QuoteObjName(Result, APart); end else begin // QwQw -> QWQW | qwqw // Q w Q w -> "Q W Q W" | "q w q w" // "Q w Q w" -> "Q w Q w" // SELECT -> "SELECT" if APart in GetNameDefLowCaseParts then Result := AnsiLowerCase(Result) else Result := AnsiUpperCase(Result); if not IsNameValid(Result) or IsKeyword(Result) then Result := QuoteObjName(Result, APart); end else if not GetNameQuotedCaseSens(AName, APart) then if APart in GetNameDefLowCaseParts then Result := AnsiLowerCase(Result) else Result := AnsiUpperCase(Result); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.QuoteObjName(const AName: String; APart: TFDPhysNamePart): String; var eQuote: TFDPhysNameQuoteLevel; ch1, ch2: Char; begin Result := AName; if (Result <> '') and not IsNameQuoted(Result) and (APart in GetNameQuotedSupportedParts()) then for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin ch1 := GetNameQuoteChar(eQuote, nsLeft); ch2 := GetNameQuoteChar(eQuote, nsRight); if not FDInSet(ch1, [#0, ' ']) and not FDInSet(ch2, [#0, ' ']) and (StrScan(PChar(AName), ch1) = nil) and (StrScan(PChar(AName), ch2) = nil) then begin Result := ch1 + Result + ch2; Break; end; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.QuoteNameIfReq(const AName: String; APart: TFDPhysNamePart): String; begin Result := AName; if (AName <> '') and not IsNameQuoted(AName) then if not IsNameValid(AName) or IsKeyword(AName) then Result := QuoteObjName(AName, APart) else if not (APart in GetNameCaseSensParts) and GetNameQuotedCaseSens(AName, APart) then begin if APart in GetNameDefLowCaseParts then Result := AnsiLowerCase(AName) else Result := AnsiUpperCase(AName); if Result <> AName then Result := QuoteObjName(AName, APart); end; end; {-------------------------------------------------------------------------------} type __TADPhysConnection = class(TFDPhysConnection) end; procedure TFDPhysConnectionMetadata.InternalOverrideNameByCommand( var AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand); var rBaseName: TFDPhysParsedName; begin if AParsedName.FCatalog = '' then AParsedName.FCatalog := ACommand.CatalogName; if AParsedName.FSchema = '' then AParsedName.FSchema := ACommand.SchemaName; if AParsedName.FBaseObject = '' then begin AParsedName.FBaseObject := ACommand.BaseObjectName; if (Pos(GetCatalogSeparator, AParsedName.FBaseObject) <> 0) or (Pos(GetSchemaSeparator, AParsedName.FBaseObject) <> 0) then begin InternalDecodeObjName(AParsedName.FBaseObject, rBaseName, ACommand, True); if rBaseName.FCatalog <> '' then AParsedName.FCatalog := rBaseName.FCatalog; if rBaseName.FSchema <> '' then AParsedName.FSchema := rBaseName.FSchema; if rBaseName.FObject <> '' then AParsedName.FBaseObject := rBaseName.FObject; end; end; if AParsedName.OverInd = 0 then AParsedName.OverInd := ACommand.Overload; if FConnectionObj <> nil then __TADPhysConnection(FConnectionObj). InternalOverrideNameByCommand(AParsedName, ACommand); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalDecodeObjName(const AName: String; out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; ARaise: Boolean): Boolean; var lWasLink, lWasCat: Boolean; iStName, i, iPart, nParts: Integer; c, cQuote1, cQuote2, cCatDelim, cSchDelim: Char; eParts: TFDPhysNameParts; eQuote: TFDPhysNameQuoteLevel; eInQuotes: TFDPhysNameQuoteLevels; procedure ClearName; begin AParsedName.FCatalog := ''; AParsedName.FSchema := ''; AParsedName.FBaseObject := ''; AParsedName.FObject := ''; AParsedName.FLink := ''; AParsedName.FOverload := ''; end; procedure Error; begin Result := False; ClearName; if ARaise then FDException(Self, [S_FD_LPhys], er_FD_AccNameHasErrors, [AName]); end; procedure ExtractNamePart; begin if (iPart + 1 > FMaximumNameParts) or (i - iStName < 0) then Error else begin FNameParts[iPart] := Trim(Copy(AName, iStName, i - iStName)); Inc(iPart); end; end; function NextPart: String; begin if iPart > 0 then begin Dec(iPart); Result := FNameParts[iPart]; end; end; begin Result := True; ClearName; if AName = '' then Exit; eParts := GetNameParts; cCatDelim := GetCatalogSeparator; cSchDelim := GetSchemaSeparator; eInQuotes := []; lWasLink := False; lWasCat := False; iStName := 1; iPart := 0; i := 1; while i <= Length(AName) do begin c := AName[i]; if (Byte(c) in FQuoteChars) then for eQuote := Low(TFDPhysNameQuoteLevel) to High(TFDPhysNameQuoteLevel) do begin cQuote1 := GetNameQuoteChar(eQuote, nsLeft); cQuote2 := GetNameQuoteChar(eQuote, nsRight); if c = cQuote1 then begin if (eInQuotes = [eQuote]) or (eInQuotes = []) then if cQuote1 = cQuote2 then if eQuote in eInQuotes then Exclude(eInQuotes, eQuote) else Include(eInQuotes, eQuote) else if not (eQuote in eInQuotes) then Include(eInQuotes, eQuote); Break; end else if c = cQuote2 then begin if eInQuotes = [eQuote] then Exclude(eInQuotes, eQuote); Break; end; end else if (c = cCatDelim) and (npCatalog in eParts) or (c = cSchDelim) and (npSchema in eParts) or (c = '.') and (npBaseObject in eParts) then begin if eInQuotes = [] then begin ExtractNamePart; if not Result then Exit; iStName := i + 1; if (c = cCatDelim) and (cCatDelim <> cSchDelim) then lWasCat := True; end; end else if c = '@' then begin if eInQuotes = [] then begin ExtractNamePart; if not Result then Exit; AParsedName.FLink := Copy(AName, i + 1, Length(AName)); lWasLink := True; Break; end; end; Inc(i); end; if not lWasLink then begin ExtractNamePart; if not Result then Exit; end; if eInQuotes <> [] then begin Error; Exit; end; nParts := iPart; AParsedName.FObject := NextPart; if nParts = FMaximumNameParts then AParsedName.FBaseObject := NextPart; if (npSchema in eParts) and ((iPart >= 2) or not lWasCat) then AParsedName.FSchema := NextPart; if npCatalog in eParts then AParsedName.FCatalog := NextPart; if iPart <> 0 then Error; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.DecodeObjName(const AName: String; out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; AOpts: TFDPhysDecodeOptions): Boolean; begin if not (doSubObj in AOpts) then begin Result := InternalDecodeObjName(AName, AParsedName, ACommand, not (doNotRaise in AOpts)); if not Result then Exit; if ACommand <> nil then InternalOverrideNameByCommand(AParsedName, ACommand); if doNormalize in AOpts then begin AParsedName.FCatalog := NormObjName(AParsedName.FCatalog, npCatalog); AParsedName.FSchema := NormObjName(AParsedName.FSchema, npSchema); AParsedName.FBaseObject := NormObjName(AParsedName.FBaseObject, npBaseObject); AParsedName.FObject := NormObjName(AParsedName.FObject, npObject); end; if doUnquote in AOpts then begin AParsedName.FCatalog := UnQuoteObjName(AParsedName.FCatalog); AParsedName.FSchema := UnQuoteObjName(AParsedName.FSchema); AParsedName.FBaseObject := UnQuoteObjName(AParsedName.FBaseObject); AParsedName.FObject := UnQuoteObjName(AParsedName.FObject); end; if not (doMetaParams in AOpts) and (AParsedName.FBaseObject = '') and (AParsedName.FObject = '') then begin AParsedName.FCatalog := ''; AParsedName.FSchema := ''; AParsedName.FLink := ''; end; end else begin Result := True; AParsedName.FCatalog := ''; AParsedName.FSchema := ''; AParsedName.FLink := ''; AParsedName.FBaseObject := ''; AParsedName.FObject := AName; if doNormalize in AOpts then AParsedName.FObject := NormObjName(AParsedName.FObject, npObject); if doUnquote in AOpts then AParsedName.FObject := UnQuoteObjName(AParsedName.FObject); end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEncodeObjName(const AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand): String; var eParts: TFDPhysNameParts; lWasCat: Boolean; iLen: Integer; begin Result := ''; eParts := GetNameParts; lWasCat := False; if (npCatalog in eParts) and (AParsedName.FCatalog <> '') and not GetIsFileBased then begin Result := Result + AParsedName.FCatalog + GetCatalogSeparator; lWasCat := True; end; if (npSchema in eParts) and (lWasCat and (GetCatalogSeparator = GetSchemaSeparator) or (AParsedName.FSchema <> '')) then Result := Result + AParsedName.FSchema + GetSchemaSeparator; if (npBaseObject in eParts) and (AParsedName.FBaseObject <> '') then Result := Result + AParsedName.FBaseObject + GetSchemaSeparator; if (npObject in eParts) and (AParsedName.FObject <> '') then Result := Result + AParsedName.FObject + GetSchemaSeparator; if Result <> '' then begin iLen := Length(Result); while (iLen > 0) and ((Result[iLen] = GetSchemaSeparator) or (Result[iLen] = GetCatalogSeparator)) do Dec(iLen); SetLength(Result, iLen); end; if (npDBLink in eParts) and (AParsedName.FLink <> '') then Result := Result + '@' + AParsedName.FLink; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.EncodeObjName(const AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand; AOpts: TFDPhysEncodeOptions): String; var rName: TFDPhysParsedName; eParts: TFDPhysNameParts; begin eParts := GetNameParts; rName := AParsedName; if eoBeautify in AOpts then begin if not (npCatalog in eParts) or (npCatalog in FConnectionObj.RemoveDefaultMeta) or (rName.FCatalog = '*') or (AnsiCompareText(FConnectionObj.DefaultCatalog, rName.FCatalog) = 0) then rName.FCatalog := ''; if not (npSchema in eParts) or (npSchema in FConnectionObj.RemoveDefaultMeta) or (rName.FSchema = '*') or (AnsiCompareText(FConnectionObj.DefaultSchema, rName.FSchema) = 0) then rName.FSchema := ''; if rName.FBaseObject = '*' then rName.FBaseObject := ''; if rName.FObject = '*' then rName.FObject := ''; if not (eoQuote in AOpts) then begin rName.FCatalog := QuoteNameIfReq(rName.FCatalog, npCatalog); rName.FSchema := QuoteNameIfReq(rName.FSchema, npSchema); rName.FBaseObject := QuoteNameIfReq(rName.FBaseObject, npBaseObject); rName.FObject := QuoteNameIfReq(rName.FObject, npObject); end; end else if eoNormalize in AOpts then begin rName.FCatalog := NormObjName(rName.FCatalog, npCatalog); rName.FSchema := NormObjName(rName.FSchema, npSchema); rName.FBaseObject := NormObjName(rName.FBaseObject, npBaseObject); rName.FObject := NormObjName(rName.FObject, npObject); end; if eoQuote in AOpts then begin rName.FCatalog := QuoteObjName(rName.FCatalog, npCatalog); rName.FSchema := QuoteObjName(rName.FSchema, npSchema); rName.FBaseObject := QuoteObjName(rName.FBaseObject, npBaseObject); rName.FObject := QuoteObjName(rName.FObject, npObject); end; Result := InternalEncodeObjName(rName, ACommand); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.IsKeyword(const AName: String): Boolean; begin Result := FKeywords.IndexOf(AName) >= 0; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.IsRDBMSKind(const AStr: String; out ACurrent: Boolean): Boolean; var oManMeta: IFDPhysManagerMetadata; iKind: TFDRDBMSKind; begin FDPhysManager.CreateMetadata(oManMeta); iKind := oManMeta.GetRDBMSKind(AStr); Result := iKind <> TFDRDBMSKinds.Unknown; ACurrent := iKind = GetKind; end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.UnsupportedEscape(const ASeq: TFDPhysEscapeData); begin FDException(Self, [S_FD_LPhys], er_FD_AccEscapeIsnotSupported, [ASeq.FName]); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.EscapeFuncToID(var ASeq: TFDPhysEscapeData); var sName: String; eFunc: TFDPhysEscapeFunction; begin sName := ASeq.FName; // character if sName = 'ASCII' then eFunc := efASCII else if sName = 'LTRIM' then eFunc := efLTRIM else if sName = 'REPLACE' then eFunc := efREPLACE else if sName = 'RTRIM' then eFunc := efRTRIM else if sName = 'DECODE' then eFunc := efDECODE else if sName = 'BIT_LENGTH' then eFunc := efBIT_LENGTH else if sName = 'CHAR' then eFunc := efCHAR else if (sName = 'CHAR_LENGTH') or (sName = 'CHARACTER_LENGTH') then eFunc := efCHAR_LENGTH else if sName = 'CONCAT' then eFunc := efCONCAT else if sName = 'INSERT' then eFunc := efINSERT else if sName = 'LCASE' then eFunc := efLCASE else if sName = 'LEFT' then eFunc := efLEFT else if sName = 'LENGTH' then eFunc := efLENGTH else if sName = 'LOCATE' then eFunc := efLOCATE else if sName = 'OCTET_LENGTH' then eFunc := efOCTET_LENGTH else if sName = 'POSITION' then eFunc := efPOSITION else if sName = 'REPEAT' then eFunc := efREPEAT else if sName = 'RIGHT' then eFunc := efRIGHT else if sName = 'SPACE' then eFunc := efSPACE else if sName = 'SUBSTRING' then eFunc := efSUBSTRING else if sName = 'UCASE' then eFunc := efUCASE // numeric else if sName = 'ACOS' then eFunc := efACOS else if sName = 'ASIN' then eFunc := efASIN else if sName = 'ATAN' then eFunc := efATAN else if sName = 'CEILING' then eFunc := efCEILING else if sName = 'DEGREES' then eFunc := efDEGREES else if sName = 'LOG' then eFunc := efLOG else if sName = 'LOG10' then eFunc := efLOG10 else if sName = 'PI' then eFunc := efPI else if sName = 'RADIANS' then eFunc := efRADIANS else if sName = 'RANDOM' then eFunc := efRANDOM else if sName = 'TRUNCATE' then eFunc := efTRUNCATE else if sName = 'ABS' then eFunc := efABS else if sName = 'COS' then eFunc := efCOS else if sName = 'EXP' then eFunc := efEXP else if sName = 'FLOOR' then eFunc := efFLOOR else if sName = 'MOD' then eFunc := efMOD else if sName = 'POWER' then eFunc := efPOWER else if sName = 'ROUND' then eFunc := efROUND else if sName = 'SIGN' then eFunc := efSIGN else if sName = 'SIN' then eFunc := efSIN else if sName = 'SQRT' then eFunc := efSQRT else if sName = 'TAN' then eFunc := efTAN // date and time else if (sName = 'CURRENT_DATE') or (sName = 'CURDATE') then eFunc := efCURDATE else if (sName = 'CURRENT_TIME') or (sName = 'CURTIME') then eFunc := efCURTIME else if (sName = 'CURRENT_TIMESTAMP') or (sName = 'NOW') then eFunc := efNOW else if sName = 'DAYNAME' then eFunc := efDAYNAME else if sName = 'DAYOFMONTH' then eFunc := efDAYOFMONTH else if sName = 'DAYOFWEEK' then eFunc := efDAYOFWEEK else if sName = 'DAYOFYEAR' then eFunc := efDAYOFYEAR else if sName = 'EXTRACT' then eFunc := efEXTRACT else if sName = 'HOUR' then eFunc := efHOUR else if sName = 'MINUTE' then eFunc := efMINUTE else if sName = 'MONTH' then eFunc := efMONTH else if sName = 'MONTHNAME' then eFunc := efMONTHNAME else if sName = 'QUARTER' then eFunc := efQUARTER else if sName = 'SECOND' then eFunc := efSECOND else if sName = 'TIMESTAMPADD' then eFunc := efTIMESTAMPADD else if sName = 'TIMESTAMPDIFF' then eFunc := efTIMESTAMPDIFF else if sName = 'WEEK' then eFunc := efWEEK else if sName = 'YEAR' then eFunc := efYEAR // system else if sName = 'CATALOG' then eFunc := efCATALOG else if sName = 'SCHEMA' then eFunc := efSCHEMA else if sName = 'IFNULL' then eFunc := efIFNULL else if (sName = 'IF') or (sName = 'IIF') then eFunc := efIF else if sName = 'LIMIT' then eFunc := efLIMIT // convert else if sName = 'CONVERT' then eFunc := efCONVERT else begin eFunc := efNONE; // unsupported ATAN2, COT UnsupportedEscape(ASeq); end; ASeq.FFunc := eFunc; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.AddEscapeSequenceArgs(const ASeq: TFDPhysEscapeData): String; var i: Integer; begin Result := ''; for i := 0 to Length(ASeq.FArgs) - 1 do begin if i > 0 then Result := Result + ', '; Result := Result + ASeq.FArgs[i]; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.TranslateEscapeSequence( var ASeq: TFDPhysEscapeData): String; var rName: TFDPhysParsedName; i: Integer; s: String; lCurrent: Boolean; begin case ASeq.FKind of eskFloat: Result := InternalEscapeFloat(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskDate: Result := InternalEscapeDate(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskTime: Result := InternalEscapeTime(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskDateTime: Result := InternalEscapeDateTime(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskIdentifier: begin rName.FObject := UnQuoteBase(ASeq.FArgs[0], '''', ''''); Result := EncodeObjName(rName, nil, [eoQuote]); end; eskBoolean: Result := InternalEscapeBoolean(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskString: Result := InternalEscapeString(UnQuoteBase(ASeq.FArgs[0], '''', '''')); eskFunction: begin EscapeFuncToID(ASeq); // LIMIT has a syntax of a function, but it is special escape sequence, // processed internally by command preprocessor and TFDPhysCommand if ASeq.FFunc = efLIMIT then Result := '' else try Result := InternalEscapeFunction(ASeq); except on E: Exception do begin if not (E is EFDException) then FDException(Self, [S_FD_LPhys], er_FD_AccEscapeBadSyntax, [ASeq.FName, E.Message]) else raise; end; end; end; eskIIF: begin i := 0; Result := ''; while i < (Length(ASeq.FArgs) and not 1) do begin s := Trim(ASeq.FArgs[i]); lCurrent := False; if IsRDBMSKind(s, lCurrent) then begin if lCurrent then begin Result := ASeq.FArgs[i + 1]; Break; end; end else if s <> '' then begin Result := ASeq.FArgs[i + 1]; Break; end; Inc(i, 2); end; if i = Length(ASeq.FArgs) - 1 then Result := ASeq.FArgs[i]; end; eskIF: begin Result := ''; s := Trim(ASeq.FArgs[0]); lCurrent := False; if IsRDBMSKind(s, lCurrent) then begin if lCurrent then Result := 'True'; end else if s <> '' then Result := 'True'; end; eskFI: Result := ''; eskEscape: Result := InternalEscapeEscape(ASeq.FArgs[0][1], ASeq.FArgs[1]); eskInto: Result := InternalEscapeInto(ASeq.FArgs[0]); end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; begin Result := InternalGetSQLCommandKind(ATokens); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalGetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; var sToken: String; oToks: TFDStringList; iRecAdd: Integer; begin sToken := ATokens[0]; if sToken = 'SELECT' then if (ATokens.Count > 1) and (ATokens[1] = 'INTO') then Result := skInsert else Result := skSelect else if sToken = 'WITH' then begin if (ATokens.Count >= 2) and (ATokens[1] = 'RECURSIVE') then iRecAdd := 1 else iRecAdd := 0; if (ATokens.Count >= 4 + iRecAdd) and ((ATokens.Count - 1 - iRecAdd) mod 2 = 1) then begin oToks := TFDStringList.Create; try oToks.Add(ATokens[ATokens.Count - 1]); Result := InternalGetSQLCommandKind(oToks); if Result = skOther then Result := skNotResolved; finally FDFree(oToks); end; end else Result := skNotResolved; end else if sToken = 'UPDATE' then Result := skUpdate else if sToken = 'INSERT' then Result := skInsert else if sToken = 'MERGE' then Result := skMerge else if (sToken = 'DELETE') or (sToken = 'TRUNCATE') then Result := skDelete else if sToken = 'DROP' then Result := skDrop else if sToken = 'CREATE' then Result := skCreate else if sToken = 'ALTER' then Result := skAlter else if sToken = 'COMMIT' then Result := skCommit else if sToken = 'ROLLBACK' then if ATokens.Count < 2 then Result := skNotResolved else if (ATokens.Count >= 3) and ((ATokens[1] = 'WORK') or (ATokens[1] = 'TRANSACTION')) and (ATokens[2] = 'TO') or (ATokens.Count >= 2) and (ATokens[1] = 'TO') then Result := skOther else Result := skRollback else if sToken = 'SET' then Result := skSet else Result := skOther; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetInsertHBlobMode: TFDPhysInsertHBlobMode; begin Result := hmInInsert; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetIdentitySupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetIdentityInsertSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetIdentityInWhere: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Other; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetClientVersion: TFDVersion; begin Result := FClientVersion; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetServerVersion: TFDVersion; begin Result := FServerVersion; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetIsUnicode: Boolean; begin Result := FIsUnicode; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetIsFileBased: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameQuotedSupportedParts: TFDPhysNameParts; begin Result := GetNameParts; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts; begin Result := GetNameParts; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameDefLowCaseParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetParamNameMaxLength: Integer; begin Result := 32; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameParts: TFDPhysNameParts; begin Result := [npBaseObject, npObject]; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; begin if AQuote = ncDefault then Result := '"' else Result := #0; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetCatalogSeparator: Char; begin Result := '.'; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetSchemaSeparator: Char; begin Result := '.'; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNamedParamMark: TFDPhysParamMark; begin Result := prQMark; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetPositionedParamMark: TFDPhysParamMark; begin Result := GetNamedParamMark; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxNested: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxMultiple: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxSavepoints: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxAutoCommit: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTxAtomic: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetEventSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetEventKinds: String; begin Result := ''; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetGeneratorSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTruncateSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetDefValuesSupported: TFDPhysDefaultValues; begin Result := dvDef; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetInlineRefresh: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetSelectOptions: TFDPhysSelectOptions; begin Result := [soWithoutFrom]; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetLockNoWait: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetAsyncAbortSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetAsyncNativeTimeout: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetCommandSeparator: String; begin Result := ';'; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetLineSeparator: TFDTextEndOfLine; begin Result := elDefault; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetArrayExecMode: TFDPhysArrayExecMode; begin Result := aeUpToFirstError; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetLimitOptions: TFDPhysLimitOptions; begin Result := [loRows]; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetNullLocations: TFDPhysNullLocations; begin Result := [nlAscFirst, nlDescLast]; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetServerCursorSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetColumnOriginProvided: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetCreateTableOptions: TFDPhysCreateTableOptions; begin Result := [ctDefaultFirst]; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetBackslashEscSupported: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeBoolean(const AStr: String): String; begin Result := AStr; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeDate(const AStr: String): String; begin Result := AnsiQuotedStr(AStr, ''''); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeTime(const AStr: String): String; begin Result := AnsiQuotedStr(AStr, ''''); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeDateTime(const AStr: String): String; begin Result := AnsiQuotedStr(AStr, ''''); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeFloat(const AStr: String): String; begin Result := AStr; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeString(const AStr: String): String; begin Result := AnsiQuotedStr(AStr, ''''); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; begin Result := ASeq.FName; if Length(ASeq.FArgs) > 0 then Result := Result + '(' + AddEscapeSequenceArgs(ASeq) + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeEscape(AEscape: Char; const AStr: String): String; begin Result := AStr + ' ESCAPE ' + QuotedStr(AEscape); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.InternalEscapeInto(const AStr: String): String; begin Result := ''; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.DefineMetadataTableName(AKind: TFDPhysMetaInfoKind): String; var sDB: String; begin ASSERT((FConnectionObj <> nil) and (FConnectionObj.ConnectionDef <> nil)); sDB := FConnectionObj.ConnectionDef.Params.ExpandedDatabase; case AKind of mkCatalogs: Result := C_FD_SysNamePrefix + '#' + sDB + '#CATALOGS'; mkSchemas: Result := C_FD_SysNamePrefix + '#' + sDB + '#SCHEMAS'; mkTables: Result := C_FD_SysNamePrefix + '#' + sDB + '#TABLES'; mkTableFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#TABLEFIELDS'; mkIndexes: Result := C_FD_SysNamePrefix + '#' + sDB + '#INDEXES'; mkIndexFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#INDEXFIELDS'; mkPrimaryKey: Result := C_FD_SysNamePrefix + '#' + sDB + '#PRIMARYKEYS'; mkPrimaryKeyFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#PRIMARYKEYFIELDS'; mkForeignKeys: Result := C_FD_SysNamePrefix + '#' + sDB + '#FOREIGNKEYS'; mkForeignKeyFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#FOREIGNKEYFIELDS'; mkPackages: Result := C_FD_SysNamePrefix + '#' + sDB + '#PACKAGES'; mkProcs: Result := C_FD_SysNamePrefix + '#' + sDB + '#PROCS'; mkProcArgs: Result := C_FD_SysNamePrefix + '#' + sDB + '#PROCARGS'; mkGenerators: Result := C_FD_SysNamePrefix + '#' + sDB + '#GENERATORS'; mkResultSetFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#RESULTSETFIELDS'; mkTableTypeFields: Result := C_FD_SysNamePrefix + '#' + sDB + '#TABLETYPEFIELDS'; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.AddMetadataCol(ATable: TFDDatSTable; const AName: String; AType: TFDDataType); var oCol: TFDDatSColumn; begin oCol := TFDDatSColumn.Create; oCol.Name := AName; oCol.SourceName := ''; oCol.SourceID := ATable.Columns.Count + 1; oCol.SourceDataType := AType; oCol.SourceSize := LongWord(-1); oCol.Attributes := [caBase, caAllowNull, caReadOnly, caSearchable]; oCol.DataType := AType; if AType = dtWideString then oCol.Size := C_FD_MaxNameLen; ATable.Columns.Add(oCol); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); procedure Add(const AName: String; AType: TFDDataType); begin AddMetadataCol(ATable, AName, AType); end; begin case AKind of mkCatalogs: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); end; mkSchemas: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); end; mkTables: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('TABLE_TYPE', dtInt32); // TFDPhysTableKind Add('TABLE_SCOPE', dtInt32); // TFDPhysObjectScopes end; mkTableFields, mkTableTypeFields: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('COLUMN_NAME', dtWideString); Add('COLUMN_POSITION', dtInt32); Add('COLUMN_DATATYPE', dtInt32); // TFDDataType Add('COLUMN_TYPENAME', dtWideString); Add('COLUMN_ATTRIBUTES',dtUInt32); // TFDDataAttributes Add('COLUMN_PRECISION', dtInt32); Add('COLUMN_SCALE', dtInt32); Add('COLUMN_LENGTH', dtInt32); end; mkIndexes, mkPrimaryKey: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('INDEX_NAME', dtWideString); Add('CONSTRAINT_NAME', dtWideString); Add('INDEX_TYPE', dtInt32); // TFDPhysIndexKind end; mkIndexFields, mkPrimaryKeyFields: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('INDEX_NAME', dtWideString); Add('COLUMN_NAME', dtWideString); Add('COLUMN_POSITION', dtInt32); Add('SORT_ORDER', dtWideString); Add('FILTER', dtWideString); end; mkForeignKeys: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('FKEY_NAME', dtWideString); Add('PKEY_CATALOG_NAME',dtWideString); Add('PKEY_SCHEMA_NAME', dtWideString); Add('PKEY_TABLE_NAME', dtWideString); Add('DELETE_RULE', dtInt32); Add('UPDATE_RULE', dtInt32); end; mkForeignKeyFields: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('TABLE_NAME', dtWideString); Add('FKEY_NAME', dtWideString); Add('COLUMN_NAME', dtWideString); Add('PKEY_COLUMN_NAME', dtWideString); Add('COLUMN_POSITION', dtInt32); end; mkPackages: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('PACKAGE_NAME', dtWideString); Add('PACKAGE_SCOPE', dtInt32); // TFDPhysObjectScopes end; mkProcs: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('PACK_NAME', dtWideString); Add('PROC_NAME', dtWideString); Add('OVERLOAD', dtInt32); Add('PROC_TYPE', dtInt32); // TFDPhysProcedureKind Add('PROC_SCOPE', dtInt32); // TFDPhysObjectScopes Add('IN_PARAMS', dtInt32); Add('OUT_PARAMS', dtInt32); end; mkProcArgs: begin Add('RECNO', dtInt32); // 0 Add('CATALOG_NAME', dtWideString); // 1 Add('SCHEMA_NAME', dtWideString); // 2 Add('PACK_NAME', dtWideString); // 3 Add('PROC_NAME', dtWideString); // 4 Add('OVERLOAD', dtInt32); // 5 Add('PARAM_NAME', dtWideString); // 6 Add('PARAM_POSITION', dtInt32); // 7 Add('PARAM_TYPE', dtInt32); // 8 - TParamType Add('PARAM_DATATYPE', dtInt32); // 9 - TFDDataType Add('PARAM_TYPENAME', dtWideString); // 10 Add('PARAM_ATTRIBUTES', dtUInt32); // 11 - TFDDataAttributes Add('PARAM_PRECISION', dtInt32); // 12 Add('PARAM_SCALE', dtInt32); // 13 Add('PARAM_LENGTH', dtInt32); // 14 end; mkGenerators: begin Add('RECNO', dtInt32); Add('CATALOG_NAME', dtWideString); Add('SCHEMA_NAME', dtWideString); Add('GENERATOR_NAME', dtWideString); Add('GENERATOR_SCOPE', dtInt32); // TFDPhysObjectScopes end; mkResultSetFields: begin Add('RECNO', dtInt32); Add('RESULTSET_KEY', dtWideString); ATable.Columns[0].Size := 1024; end; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.FetchNoCache(AMetaKind: TFDPhysMetaInfoKind; AScope: TFDPhysObjectScopes; AKinds: TFDPhysTableKinds; const ACatalog, ASchema, ABaseObject, AWildCard: String; AOverload: Word): TFDDatSTable; var oCommand: IFDPhysMetaInfoCommand; oResOpts: TFDResourceOptions; oFtchOpts: TFDFetchOptions; begin Result := TFDDatSTable.Create(DefineMetadataTableName(AMetaKind)); Result.CountRef(0); try (FConnectionObj as IFDPhysConnection).CreateMetaInfoCommand(oCommand); oResOpts := oCommand.Options.ResourceOptions; if oResOpts.CmdExecMode = amAsync then oResOpts.CmdExecMode := amBlocking; oFtchOpts := oCommand.Options.FetchOptions; oFtchOpts.RecsSkip := -1; oFtchOpts.RecsMax := -1; oCommand.ObjectScopes := AScope; oCommand.TableKinds := AKinds; oCommand.CatalogName := ACatalog; oCommand.SchemaName := ASchema; oCommand.BaseObjectName := ABaseObject; oCommand.Wildcard := AWildCard; oCommand.Overload := AOverload; oCommand.MetaInfoKind := AMetaKind; oCommand.Prepare; oCommand.Define(Result); oCommand.Open; if oCommand.State = csOpen then oCommand.Fetch(Result, True); except FDFree(Result); raise; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.FetchToCache(AMetaKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ABaseObject, AObject: String; AOverload: Word; ADataTable: TFDDatSTable); var oCommand: IFDPhysMetaInfoCommand; oResOpts: TFDResourceOptions; oFtchOpts: TFDFetchOptions; oRow: TFDDatSRow; rName: TFDPhysParsedName; begin (FConnectionObj as IFDPhysConnection).CreateMetaInfoCommand(oCommand); oResOpts := oCommand.Options.ResourceOptions; if oResOpts.CmdExecMode = amAsync then oResOpts.CmdExecMode := amBlocking; oFtchOpts := oCommand.Options.FetchOptions; oFtchOpts.RecsSkip := -1; oFtchOpts.RecsMax := -1; oCommand.CatalogName := ACatalog; oCommand.SchemaName := ASchema; oCommand.BaseObjectName := ABaseObject; oCommand.CommandText := AObject; oCommand.Overload := AOverload; oCommand.MetaInfoKind := AMetaKind; oCommand.Prepare; if ADataTable.Columns.Count = 0 then oCommand.Define(ADataTable); oCommand.Open; if oCommand.State = csOpen then oCommand.Fetch(ADataTable, True); if (oCommand.RowsAffected = 0) and (AMetaKind in [mkPrimaryKeyFields, mkIndexes, mkPrimaryKey, mkForeignKeys]) then begin ParseMetaInfoParams(ACatalog, ASchema, ABaseObject, AObject, rName); ADataTable.EnforceConstraints := False; try oRow := ADataTable.NewRow; oRow.ValueS['RECNO'] := -1; oRow.ValueS['CATALOG_NAME'] := rName.FCatalog; oRow.ValueS['SCHEMA_NAME'] := rName.FSchema; if AMetaKind = mkPrimaryKeyFields then oRow.ValueS['TABLE_NAME'] := rName.FBaseObject else oRow.ValueS['TABLE_NAME'] := rName.FObject; ADataTable.Rows.Add(oRow); finally ADataTable.EnforceConstraints := True; end; end; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.CheckFetchToCache(AMetaKind: TFDPhysMetaInfoKind; const AFilter: String; var ATable: TFDDatSTable; var AView: TFDDatSView): Boolean; var i: Integer; sTabName: String; begin sTabName := DefineMetadataTableName(AMetaKind); if FMetadataCache = nil then FMetadataCache := TFDDatSManager.Create; i := FMetadataCache.Tables.IndexOfName(sTabName); if i = -1 then begin ATable := FMetadataCache.Tables.Add(sTabName); DefineMetadataStructure(ATable, AMetaKind); end else ATable := FMetadataCache.Tables.ItemsI[i]; AView := ATable.Select(AFilter); Result := AView.Rows.Count = 0; if Result then AView.RowFilter := AFilter + ' AND RECNO >= 0' else if (AView.Rows.Count = 1) and (AView.Rows[0].GetData(0) < 0) then AView.Rows.RemoveAt(0, True); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.ConvertNameCaseExpr(const AColumn, AValue: String; APart: TFDPhysNamePart): String; begin if FCISearch then Result := 'UPPER(' + AColumn + ')' else if not GetNameQuotedCaseSens(AValue, APart) then if APart in GetNameDefLowCaseParts then Result := 'LOWER(' + AColumn + ')' else Result := 'UPPER(' + AColumn + ')' else Result := AColumn; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.ConvertNameCaseConst(const AValue: String; APart: TFDPhysNamePart): String; begin if FCISearch then Result := AnsiUpperCase(AValue) else if not GetNameQuotedCaseSens(AValue, APart) then if APart in GetNameDefLowCaseParts then Result := AnsiLowerCase(AValue) else Result := AnsiUpperCase(AValue) else Result := AValue; end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.AddWildcard(AView: TFDDatSView; const AColumn, AWildcard: String; APart: TFDPhysNamePart); begin if AWildcard <> '' then AView.RowFilter := AView.RowFilter + ' AND ' + ConvertNameCaseExpr(AColumn, AWildcard, APart) + ' LIKE ' + QuotedStr(ConvertNameCaseConst(AWildcard, APart)); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetCacheFilter(const ACatalog, ASchema, AObjField, AObj, ASubObjField, ASubObj: String): String; procedure AddCond(const AColumn, AValue: String; APart: TFDPhysNamePart); begin if Result <> '' then Result := Result + ' AND '; if GetIsFileBased and (APart = npBaseObject) then Result := Result + 'CmpFileName(' + AColumn + ',' + QuotedStr(AValue) + ')' else if GetIsFileBased and (APart = npCatalog) then Result := Result + 'CmpFilePath(' + AColumn + ',' + QuotedStr(AValue) + ')' else Result := Result + ConvertNameCaseExpr(AColumn, AValue, APart) + ' = ' + QuotedStr(ConvertNameCaseConst(AValue, APart)); end; begin Result := ''; if ACatalog <> '' then AddCond('CATALOG_NAME', ACatalog, npCatalog); if ASchema <> '' then AddCond('SCHEMA_NAME', ASchema, npSchema); if AObj <> '' then AddCond(AObjField, AObj, npBaseObject); if ASubObj <> '' then AddCond(ASubObjField, ASubObj, npObject); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.ParseMetaInfoParams(const ACatalog, ASchema, ABaseObjName, AObjName: String; out AParsedName: TFDPhysParsedName); var sObjName: String; rName2: TFDPhysParsedName; begin if ABaseObjName <> '' then sObjName := ABaseObjName else sObjName := AObjName; DecodeObjName(sObjName, AParsedName, nil, [doUnquote, doNormalize]); if ABaseObjName <> '' then begin AParsedName.FBaseObject := AParsedName.FObject; DecodeObjName(AObjName, rName2, nil, [doUnquote, doNormalize, doSubObj]); AParsedName.FObject := rName2.FObject; end; if (AParsedName.FCatalog = '') and (ACatalog <> '') then AParsedName.FCatalog := UnQuoteObjName(NormObjName(ACatalog, npCatalog)); if (AParsedName.FSchema = '') and (ASchema <> '') then AParsedName.FSchema := UnQuoteObjName(NormObjName(ASchema, npSchema)); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetCatalogs(const AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkCatalogs, [], [], '', '', '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetSchemas(const ACatalog, AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkSchemas, [], [], ACatalog, '', '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTables(AScope: TFDPhysObjectScopes; AKinds: TFDPhysTableKinds; const ACatalog, ASchema, AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkTables, AScope, AKinds, ACatalog, ASchema, '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableFieldsBase(AMetaKind: TFDPhysMetaInfoKind; const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, '', ATable, rName); if CheckFetchToCache(AMetaKind, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''), oTab, Result) then FetchToCache(AMetaKind, ACatalog, ASchema, '', ATable, 0, oTab); AddWildcard(Result, 'COLUMN_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; begin Result := GetTableFieldsBase(mkTableFields, ACatalog, ASchema, ATable, AWildCard); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableTypeFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; begin Result := GetTableFieldsBase(mkTableTypeFields, ACatalog, ASchema, ATable, AWildCard); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableIndexes(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, '', ATable, rName); if CheckFetchToCache(mkIndexes, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''), oTab, Result) then FetchToCache(mkIndexes, ACatalog, ASchema, '', ATable, 0, oTab); AddWildcard(Result, 'INDEX_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableIndexFields(const ACatalog, ASchema, ATable, AIndex, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, ATable, AIndex, rName); if CheckFetchToCache(mkIndexFields, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FBaseObject, 'INDEX_NAME', rName.FObject), oTab, Result) then FetchToCache(mkIndexFields, ACatalog, ASchema, ATable, AIndex, 0, oTab); AddWildcard(Result, 'COLUMN_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTablePrimaryKey(const ACatalog, ASchema, ATable: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, '', ATable, rName); if CheckFetchToCache(mkPrimaryKey, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''), oTab, Result) then FetchToCache(mkPrimaryKey, ACatalog, ASchema, '', ATable, 0, oTab); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTablePrimaryKeyFields(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, '', ATable, rName); if CheckFetchToCache(mkPrimaryKeyFields, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''), oTab, Result) then FetchToCache(mkPrimaryKeyFields, ACatalog, ASchema, ATable, '', 0, oTab); AddWildcard(Result, 'COLUMN_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableForeignKeys(const ACatalog, ASchema, ATable, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, '', ATable, rName); if CheckFetchToCache(mkForeignKeys, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''), oTab, Result) then FetchToCache(mkForeignKeys, ACatalog, ASchema, '', ATable, 0, oTab); AddWildcard(Result, 'FK_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetTableForeignKeyFields(const ACatalog, ASchema, ATable, AForeignKey, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, ATable, AForeignKey, rName); if CheckFetchToCache(mkForeignKeyFields, GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FBaseObject, 'FK_NAME', rName.FObject), oTab, Result) then FetchToCache(mkForeignKeyFields, ACatalog, ASchema, ATable, AForeignKey, 0, oTab); AddWildcard(Result, 'COLUMN_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetPackages(AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkPackages, AScope, [], ACatalog, ASchema, '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetPackageProcs(const ACatalog, ASchema, APackage, AWildCard: String): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, APackage, '', rName); if CheckFetchToCache(mkProcs, GetCacheFilter(rName.FCatalog, rName.FSchema, 'PACK_NAME', rName.FBaseObject, '', ''), oTab, Result) then FetchToCache(mkProcs, ACatalog, ASchema, APackage, '', 0, oTab); AddWildcard(Result, 'PROC_NAME', AWildCard, npBaseObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetProcs(AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkProcs, AScope, [], ACatalog, ASchema, '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetProcArgs(const ACatalog, ASchema, APackage, AProc, AWildCard: String; AOverload: Word): TFDDatSView; var rName: TFDPhysParsedName; oTab: TFDDatSTable; sProc, sFlt: String; begin Result := nil; oTab := nil; ParseMetaInfoParams(ACatalog, ASchema, APackage, AProc, rName); if (GetKind = TFDRDBMSKinds.MSSQL) and (Pos(';', AProc) = 0) and (AOverload > 0) then sProc := rName.FObject + ';' + IntToStr(AOverload) else sProc := rName.FObject; sFlt := GetCacheFilter(rName.FCatalog, rName.FSchema, 'PACK_NAME', rName.FBaseObject, 'PROC_NAME', sProc); if AOverload <> 0 then begin if sFlt <> '' then sFlt := sFlt + ' AND '; sFlt := sFlt + 'OVERLOAD = ' + IntToStr(AOverload); end; if CheckFetchToCache(mkProcArgs, sFlt, oTab, Result) then FetchToCache(mkProcArgs, ACatalog, ASchema, APackage, AProc, AOverload, oTab); AddWildcard(Result, 'PARAM_NAME', AWildCard, npObject); end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetGenerators( AScope: TFDPhysObjectScopes; const ACatalog, ASchema, AWildCard: String): TFDDatSView; begin Result := FetchNoCache(mkGenerators, AScope, [], ACatalog, ASchema, '', AWildCard, 0).DefaultView; end; {-------------------------------------------------------------------------------} function TFDPhysConnectionMetadata.GetResultSetFields(const ASQLKey: String): TFDDatSView; var oTab: TFDDatSTable; begin Result := nil; oTab := nil; if CheckFetchToCache(mkResultSetFields, 'RESULTSET_KEY = ' + QuotedStr(ASQLKey), oTab, Result) then FetchToCache(mkResultSetFields, '', '', '', ASQLKey, 0, oTab); end; {-------------------------------------------------------------------------------} procedure TFDPhysConnectionMetadata.RefreshMetadataCache(const AObjName: String = ''); var rName: TFDPhysParsedName; sFlt: String; procedure TabClear(AMetaKind: TFDPhysMetaInfoKind); var oTab: TFDDatSTable; oView: TFDDatSView; begin CheckFetchToCache(AMetaKind, sFlt, oTab, oView); oView.DeleteAll(True); FDFree(oView); end; begin if FMetadataCache <> nil then if AObjName = '' then FMetadataCache.Clear else begin ParseMetaInfoParams('', '', '', AObjName, rName); if rName.FObject <> '' then begin sFlt := GetCacheFilter(rName.FCatalog, rName.FSchema, 'TABLE_NAME', rName.FObject, '', ''); TabClear(mkTableFields); TabClear(mkIndexes); TabClear(mkIndexFields); TabClear(mkPrimaryKey); TabClear(mkPrimaryKeyFields); TabClear(mkForeignKeys); TabClear(mkForeignKeyFields); TabClear(mkTableTypeFields); sFlt := GetCacheFilter(rName.FCatalog, rName.FSchema, 'PACK_NAME', rName.FObject, '', ''); TabClear(mkProcs); TabClear(mkProcArgs); sFlt := GetCacheFilter(rName.FCatalog, rName.FSchema, 'PROC_NAME', rName.FObject, '', ''); TabClear(mkProcArgs); end; if (rName.FBaseObject <> '') and (rName.FObject <> '') then begin sFlt := GetCacheFilter(rName.FCatalog, rName.FSchema, 'PACK_NAME', rName.FBaseObject, 'PROC_NAME', rName.FObject); TabClear(mkProcs); end; end; end; end.
(** This module contains constants for use through the application. @Version 1.0 @Author David Hoyle @Date 10 Dec 2017 **) Unit ITHelper.Constants; Interface Const (** A constant to represent the bug fix revisions for the version number. **) strRevisions = ' abcedfghijklmnopqrstuvwxyz'; Implementation End.
unit uFormPasso10; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine, dxSkinXmas2008Blue, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, dxGDIPlusClasses, cxImage, cxLabel, cxCheckBox; type TFormPasso10 = class(TForm) Panel2: TPanel; cxButtonMandarImpressao: TcxButton; cxImagePrinter: TcxImage; cxLabelTittle: TcxLabel; cxLabel2: TcxLabel; cxLabel1: TcxLabel; cxLabelPreco: TcxLabel; cxButtonRevisar: TcxButton; cxCheckBoxConcordo: TcxCheckBox; cxLabel3: TcxLabel; cxButtonEliminar: TcxButton; cxCheckBoxEngano: TcxCheckBox; procedure FormShow(Sender: TObject); procedure cxCheckBoxConcordoClick(Sender: TObject); procedure cxCheckBoxEnganoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormPasso10: TFormPasso10; implementation {$R *.dfm} procedure TFormPasso10.cxCheckBoxConcordoClick(Sender: TObject); begin cxButtonRevisar.Enabled := cxCheckBoxConcordo.checked; if cxCheckBoxEngano.checked then begin cxCheckBoxEngano.checked := false; cxCheckBoxEnganoClick(nil); end; cxButtonEliminar.visible := false; cxButtonMandarImpressao.Enabled := true; end; procedure TFormPasso10.cxCheckBoxEnganoClick(Sender: TObject); begin cxButtonRevisar.Enabled := false; if cxCheckBoxConcordo.checked then begin cxCheckBoxConcordo.checked := false; cxCheckBoxConcordoClick(nil); end; cxButtonEliminar.visible := true; cxButtonMandarImpressao.Enabled := false; end; procedure TFormPasso10.FormShow(Sender: TObject); begin cxButtonEliminar.visible := false; cxButtonRevisar.Enabled := true; cxButtonMandarImpressao.Enabled := false; cxCheckBoxConcordo.OnClick := nil; cxCheckBoxEngano.OnClick := nil; cxCheckBoxConcordo.checked := false; cxCheckBoxEngano.checked := false; cxCheckBoxConcordo.OnClick := cxCheckBoxConcordoClick; cxCheckBoxEngano.OnClick := cxCheckBoxEnganoClick;; end; end.
unit loginScreen; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, jpeg, mainscreen, uEncrypt; type TfrmLoginScreen = class(TForm) edtLoginPassword: TEdit; lblAdminLogin: TLabel; btnLogin: TButton; Image1: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; procedure btnLoginClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure edtLoginPasswordClick(Sender: TObject); procedure edtLoginPasswordEndDock(Sender, Target: TObject; X, Y: Integer); private { Private declarations } public { Public declarations } end; var frmLoginScreen: TfrmLoginScreen; implementation {$R *.dfm} procedure TfrmLoginScreen.btnLoginClick(Sender: TObject); var encryptor : TEncryption; begin {An encryption engine object is created. This will allow the the loginScreen form to access the saved and encrypted password stored in the project folder by calling it as the result of the encryptor.getPassword function.} encryptor := TEncryption.Create; {If the password stored in the project folder, once unencrypted, does not match the text string entered by the user in the edit box then the form will indicate with colour and a message that the password is incorrect. If the password entered does match then the form will be hidden and the main screen will be shown.} if edtLoginPassword.Text = encryptor.getPassword then begin mainScreen.frmMainScreen.Show; loginScreen.frmLoginScreen.Hide; end else begin edtLoginPassword.Color := clRed; frmLoginScreen.Caption := 'TRY AGAIN'; Label4.Show; edtLoginPassword.Text := ''; end; end; procedure TfrmLoginScreen.FormActivate(Sender: TObject); begin {The label that says the password entered is incorrect is initially hidden.} Label4.Hide; end; procedure TfrmLoginScreen.edtLoginPasswordClick(Sender: TObject); begin {The colour changes of the edit box are cleared when it is clicked on. This makes it easier to see the contents.} edtLoginPassword.Color := clSilver; {The label that indicates the previously entered password was incorrect is hidden.} Label4.Hide; end; procedure TfrmLoginScreen.edtLoginPasswordEndDock(Sender, Target: TObject; X, Y: Integer); begin destroy; end; end.
unit TestOSFile.Handle; interface uses Windows, OSFile, Dialogs, SysUtils, TestFramework, OSFile.Handle, OS.Handle; type // Test methods for class TOSFileWithHandle TConcreteOSFileWithHandle = class(TOSFileWithHandle) public function IsHandleValid(const HandleToCheck: THandle): Boolean; protected function GetMinimumPrivilege: TCreateFileDesiredAccess; override; end; TestTOSFileWithHandle = class(TTestCase) strict private FOSFileWithHandle: TConcreteOSFileWithHandle; public procedure SetUp; override; procedure TearDown; override; published procedure TestIsHandleValid; procedure TestGetDesiredAccessFromTCreateFileDesiredAccess; end; implementation procedure TestTOSFileWithHandle.SetUp; begin FOSFileWithHandle := TConcreteOSFileWithHandle.Create(''); end; procedure TestTOSFileWithHandle.TearDown; begin FOSFileWithHandle.Free; FOSFileWithHandle := nil; end; procedure TestTOSFileWithHandle.TestIsHandleValid; begin CheckEquals(false, IsHandleValid(INVALID_HANDLE_VALUE), 'Handle test failure - INVALID_HANDLE_VALUE'); CheckEquals(false, IsHandleValid(0), 'Handle test failure - 0'); CheckEquals(true, IsHandleValid(1), 'Handle test failure - 1'); end; procedure TestTOSFileWithHandle. TestGetDesiredAccessFromTCreateFileDesiredAccess; begin CheckEquals(0, GetDesiredAccessFromTCreateFileDesiredAccess( TCreateFileDesiredAccess.DesiredNone), 'TCreateFileDesiredAccess.DesiredNone'); CheckEquals(GENERIC_READ, GetDesiredAccessFromTCreateFileDesiredAccess( TCreateFileDesiredAccess.DesiredReadOnly), 'TCreateFileDesiredAccess.DesiredReadOnly'); CheckEquals(GENERIC_READ or GENERIC_WRITE, GetDesiredAccessFromTCreateFileDesiredAccess( TCreateFileDesiredAccess.DesiredReadWrite), 'TCreateFileDesiredAccess.DesiredReadWrite'); StartExpectingException(EArgumentOutOfRangeException); GetDesiredAccessFromTCreateFileDesiredAccess( TCreateFileDesiredAccess(5)); StopExpectingException('Wrong TCreateFileDesiredAccess (5)'); end; { TConcreteOSFileWithHandle } function TConcreteOSFileWithHandle.GetMinimumPrivilege: TCreateFileDesiredAccess; begin result := TCreateFileDesiredAccess.DesiredNone; end; function TConcreteOSFileWithHandle.IsHandleValid( const HandleToCheck: THandle): Boolean; begin result := IsHandleValid(HandleToCheck); end; initialization // Register any test cases with the test runner RegisterTest(TestTOSFileWithHandle.Suite); end.
unit uAdditionalIps; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.ImageList, Vcl.ImgList, acAlphaImageList, Vcl.Menus, System.RegularExpressions; type TfAdditionalIps = class(TForm) lbIPs: TListBox; SaveBtn: TButton; pmMenu: TPopupMenu; miAdd: TMenuItem; miEdit: TMenuItem; miDelete: TMenuItem; ilMenu: TsAlphaImageList; procedure SaveBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure pmMenuPopup(Sender: TObject); procedure miAddClick(Sender: TObject); procedure miEditClick(Sender: TObject); procedure miDeleteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var fAdditionalIps: TfAdditionalIps; implementation {$R *.dfm} uses uSettings; const FileName = 'additional-ips.yml'; procedure TfAdditionalIps.FormCreate(Sender: TObject); begin Constraints.MaxWidth := Width; Constraints.MinWidth := Width; end; procedure TfAdditionalIps.FormShow(Sender: TObject); var i: Integer; s: string; begin ShowWindow(Application.Handle, SW_HIDE); CenteringWindow(Handle, GetDesktopWindow); lbIPs.Clear; with TStringList.Create do try if not FileExists(ExtractFilePath(ParamStr(0)) + FileName) then SaveToFile(ExtractFilePath(ParamStr(0)) + FileName); LoadFromFile(ExtractFilePath(ParamStr(0)) + FileName); for i := 0 to Pred(Count) do begin s := Strings[i]; System.Delete(s, 1, 2); lbIPs.Items.Add(s); end; finally Free; end; end; procedure TfAdditionalIps.miAddClick(Sender: TObject); var s: string; begin if InputQuery('Добавление IP', '', s) and TRegEx.IsMatch(s.Trim, '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') then lbIPs.Items.Add(s.Trim); end; procedure TfAdditionalIps.miDeleteClick(Sender: TObject); begin if MessageBox(Handle, PChar(Format('Действительно хотите удалить %s?', [lbIPS.Items[lbIPs.ItemIndex]])), 'Подтверждение', MB_YESNO) = IDYES then lbIPs.DeleteSelected; end; procedure TfAdditionalIps.miEditClick(Sender: TObject); var s: string; begin s := lbIPs.Items[lbIPs.ItemIndex]; if InputQuery('Редактирование IP', '', s) and TRegEx.IsMatch(s.Trim, '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') then lbIPs.Items[lbIPs.ItemIndex] := s.Trim; end; procedure TfAdditionalIps.pmMenuPopup(Sender: TObject); begin miEdit.Enabled := (lbIPs.ItemIndex <> -1); miDelete.Enabled := (lbIPs.ItemIndex <> -1); end; procedure TfAdditionalIps.SaveBtnClick(Sender: TObject); var i: Integer; begin with TStringList.Create do try for i := 0 to Pred(lbIPs.Items.Count) do begin Add('- ' + lbIPs.Items[i]) end; SaveToFile(ExtractFilePath(ParamStr(0)) + FileName); finally Free; end; Close; fSettings.miRestart.Click; end; end.
unit uFormMapReduce; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, Vcl.ExtCtrls; type TIndObjDict = TDictionary<TObject, Byte>; TIndObjPair = TPair<TObject, Byte>; TIndObjArr = TArray<TIndObjPair>; TSuit = (CMap, CMapParallel, CReduce, CForEach); TFormMapReduce = class(TForm) EditArrayElems: TEdit; MemoOutput: TMemo; LabelOutput: TLabel; LabelArrayElems: TLabel; ButtonMap: TButton; ButtonMapParallel: TButton; ButtonReduce: TButton; ButtonForEach: TButton; LabelStats: TLabel; RadioGroupShowResult: TRadioGroup; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnClickProcess(Sender: TObject); private FIndexedObjectsDict: TIndObjDict; public { Public declarations } end; var FormMapReduce: TFormMapReduce; implementation uses MapReduce, MapParallel, System.Diagnostics, System.DateUtils; {$R *.dfm} function BuildObjectDict(AIndexedObjectsArr: TIndObjArr): TIndObjDict; var X: TIndObjPair; begin Result := TIndObjDict.Create(); for X in AIndexedObjectsArr do begin Result.Add(X.Key, X.Value); end; end; procedure FillLines(ASender: TObject; AInputText: string; AOutputLines: TStrings; ASuitDict: TIndObjDict; ANeedResult: boolean); var TempArr: TArray<string>; TmpStr: string; begin AOutputLines.Clear; TmpStr := string.Empty; case TSuit(ASuitDict.Items[ASender]) of CMap: begin TempArr := TMapReduce<string>.Map( // string(AInputText).Split(['|']), function(const X: string; const I: Integer): string begin Result := I.ToString + ' ' + X; end); end; CMapParallel: begin TempArr := TMapParallel<string,string>.Map( // string(AInputText).Split(['|']), function(const X: string; const I: Integer): string begin Result := I.ToString + ' ' + X; end); end; CReduce: begin TmpStr := TMapReduce<string>.Reduce( // string(AInputText).Split(['|']), string.Empty, function(const Accumulator: string; const X: string; const I: Integer): string begin if I = 0 then Result := I.ToString + ' ' + X else Result := Accumulator + sLineBreak + I.ToString + ' ' + X; end); end; CForEach: begin TempArr := string(AInputText).Split(['|']); TMapReduce<string>.ForEachArrChange(TempArr, procedure(var X: string; const I: Integer; var Done: boolean) begin X := X + ' ★'; end); end; else raise Exception.Create('Unknown button'); end; if ANeedResult then if TmpStr = string.Empty then AOutputLines.AddStrings(TempArr) else AOutputLines.Text := TmpStr; end; procedure TFormMapReduce.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(FIndexedObjectsDict); end; procedure TFormMapReduce.FormCreate(Sender: TObject); begin FIndexedObjectsDict := BuildObjectDict([ // TIndObjPair.Create(ButtonMap, Byte(CMap)), // TIndObjPair.Create(ButtonMapParallel, Byte(CMapParallel)), // TIndObjPair.Create(ButtonReduce, Byte(CReduce)), // TIndObjPair.Create(ButtonForEach, Byte(CForEach))]); end; procedure TFormMapReduce.BtnClickProcess(Sender: TObject); var SW: TStopwatch; begin SW := TStopwatch.StartNew; FillLines(Sender, EditArrayElems.Text, MemoOutput.Lines, FIndexedObjectsDict, not RadioGroupShowResult.ItemIndex.ToBoolean); SW.Stop; LabelStats.Caption := FormatDateTime('hh:nn:ss:zzz', EncodeTime(SW.Elapsed.Hours, SW.Elapsed.Minutes, SW.Elapsed.Seconds, SW.Elapsed.Milliseconds)); end; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Demo.EventEnginePlayground.EventThread; {$I ADAPT.inc} interface uses System.Classes, ADAPT.EventEngine.Intf; { This function returns an Interfaced Reference to our "Test Event Thread". We wouldn't always need to have access to this, but for the sake of demonstration, I'm showing how it can be done as there are plenty of contexts wherein you might want to. } function TestEventThread: IADEventThread; implementation uses ADAPT.EventEngine, ADAPT.Demo.EventEnginePlayground.Events; var GTestEventThread: TADEventThread; // This Variable will hold our internal Instance. NOTE IT IS INTERNAL ONLY! type { This is the Class Definition for our "Test Event Thread". It constructs and contains the "Test Event Listener", and provides the Callback to be invoked each time a "Test Event" instance is transacted through the Event Engine. It performs a "transformation" on the given String Message, then emits a "Test Response Event" containing the result. } TTestEventThread = class(TADEventThread) private FListener: IADEventListener; end; { Necessary "macro" to return an Interfaced Reference to our Internal Event Thread Instance. } function TestEventThread: IADEventThread; begin Result := GTestEventThread; end; { Since the "Test Event Thread" needs to run for the lifetime of our application, we managage its lifetime using the "Initialization" and "Finalization". } initialization GTestEventThread := TTestEventThread.Create; finalization GTestEventThread.Free; end.
unit ClntCons; interface uses Windows, Classes, SysUtils, CommCons; type PPayRec = ^TPayRec; {Документ в базе} TPayRec = packed record { Запись о док-те в БД } dbIdHere: longint; { Идер в здесь } { 0 0k} dbIdKorr: longint; { Идер в банке } { 4 1k} dbIdIn: longint; { Идер во входящих } { 8 2k} dbIdOut: longint; { Идер в исходящих } { 12 3k} dbIdArc: longint; { Идер в архиве } { 16 4k} dbIdDel: longint; { Идер в удаленных } { 20 5k} dbVersion:longint; { Номер версии } { 24 } dbState: word; { Состояние док-та } { 28 } dbDateS: word; { Дата отправки } { 30 } dbTimeS: word; { Время отправки } { 32 } dbDateR: word; { Дата получения банком } { 34 } dbTimeR: word; { Время получения банком } { 36 } dbDateP: word; { Дата обработки банком } { 38 } dbTimeP: word; { Время обработки банком } { 40 } dbDocVarLen: word; { Длина документа } { 42 } dbDoc: TDocRec; { Документ с эл. подписью и ответом } { 44 } end; type PaydocEditRecord = function(Sender: TComponent; PayRecPtr: PPayRec; EditMode: Integer; New: Boolean): Boolean; implementation end.
unit Ths.Erp.Database.Table.SysUserAccessRight; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, StrUtils, RTTI, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TSysUserAccessRight = class(TTable) private FSourceCode: TFieldDB; FIsRead: TFieldDB; FIsAddRecord: TFieldDB; FIsUpdate: TFieldDB; FIsDelete: TFieldDB; FIsSpecial: TFieldDB; FUserName: TFieldDB; //not a database field FSourceName: TFieldDB; protected published constructor Create(OwnerDatabase: TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property PermissionCode: TFieldDB read FSourceCode write FSourceCode; Property IsRead: TFieldDB read FIsRead write FIsRead; Property IsAddRecord: TFieldDB read FIsAddRecord write FIsAddRecord; Property IsUpdate: TFieldDB read FIsUpdate write FIsUpdate; Property IsDelete: TFieldDB read FIsDelete write FIsDelete; Property IsSpecial: TFieldDB read FIsSpecial write FIsSpecial; Property UserName: TFieldDB read FUserName write FUserName; //not a database field Property SourceName : TFieldDB read FSourceName write FSourceName; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TSysUserAccessRight.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_user_access_right'; SourceCode := '1'; FSourceCode := TFieldDB.Create('source_code', ftString, ''); FIsRead := TFieldDB.Create('is_read', ftBoolean, False); FIsAddRecord := TFieldDB.Create('is_add_record', ftBoolean, False); FIsUpdate := TFieldDB.Create('is_update', ftBoolean, False); FIsDelete := TFieldDB.Create('is_delete', ftBoolean, False); FIsSpecial := TFieldDB.Create('is_special', ftBoolean, False); FUserName := TFieldDB.Create('user_name', ftString, ''); FSourceName := TFieldDB.Create('source_name', ftString, ''); end; procedure TSysUserAccessRight.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FSourceCode.FieldName, 'ps.' + FSourceName.FieldName, TableName + '.' + FIsRead.FieldName, TableName + '.' + FIsAddRecord.FieldName, TableName + '.' + FIsUpdate.FieldName, TableName + '.' + FIsDelete.FieldName, TableName + '.' + FIsSpecial.FieldName, TableName + '.' + FUserName.FieldName ]) + 'JOIN sys_permission_source ps ON ps.source_code=' + TableName + '.' + FSourceCode.FieldName + ' ' + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FSourceCode.FieldName).DisplayLabel := 'SOURCE CODE'; Self.DataSource.DataSet.FindField(FSourceName.FieldName).DisplayLabel := 'SOURCE NAME'; Self.DataSource.DataSet.FindField(FIsRead.FieldName).DisplayLabel := 'READ?'; Self.DataSource.DataSet.FindField(FIsAddRecord.FieldName).DisplayLabel := 'ADD RECORD?'; Self.DataSource.DataSet.FindField(FIsUpdate.FieldName).DisplayLabel := 'UPDATE?'; Self.DataSource.DataSet.FindField(FIsDelete.FieldName).DisplayLabel := 'DELETE?'; Self.DataSource.DataSet.FindField(FIsSpecial.FieldName).DisplayLabel := 'SPECIAL?'; Self.DataSource.DataSet.FindField(FUserName.FieldName).DisplayLabel := 'USER NAME'; end; end; end; procedure TSysUserAccessRight.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FSourceCode.FieldName, TableName + '.' + FIsRead.FieldName, TableName + '.' + FIsAddRecord.FieldName, TableName + '.' + FIsUpdate.FieldName, TableName + '.' + FIsDelete.FieldName, TableName + '.' + FIsSpecial.FieldName, TableName + '.' + FUserName.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FSourceCode.Value := FormatedVariantVal(FieldByName(FSourceCode.FieldName).DataType, FieldByName(FSourceCode.FieldName).Value); FIsRead.Value := FormatedVariantVal(FieldByName(FIsRead.FieldName).DataType, FieldByName(FIsRead.FieldName).Value); FIsAddRecord.Value := FormatedVariantVal(FieldByName(FIsAddRecord.FieldName).DataType, FieldByName(FIsAddRecord.FieldName).Value); FIsUpdate.Value := FormatedVariantVal(FieldByName(FIsUpdate.FieldName).DataType, FieldByName(FIsUpdate.FieldName).Value); FIsDelete.Value := FormatedVariantVal(FieldByName(FIsDelete.FieldName).DataType, FieldByName(FIsDelete.FieldName).Value); FIsSpecial.Value := FormatedVariantVal(FieldByName(FIsSpecial.FieldName).DataType, FieldByName(FIsSpecial.FieldName).Value); FUserName.Value := FormatedVariantVal(FieldByName(FUserName.FieldName).DataType, FieldByName(FUserName.FieldName).Value); List.Add(Self.Clone()); Next; end; EmptyDataSet; Close; end; end; end; procedure TSysUserAccessRight.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FSourceCode.FieldName, FIsRead.FieldName, FIsAddRecord.FieldName, FIsUpdate.FieldName, FIsDelete.FieldName, FIsSpecial.FieldName, FUserName.FieldName ]); NewParamForQuery(QueryOfInsert, FSourceCode); NewParamForQuery(QueryOfInsert, FIsRead); NewParamForQuery(QueryOfInsert, FIsAddRecord); NewParamForQuery(QueryOfInsert, FIsUpdate); NewParamForQuery(QueryOfInsert, FIsDelete); NewParamForQuery(QueryOfInsert, FIsSpecial); NewParamForQuery(QueryOfInsert, FUserName); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSysUserAccessRight.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FSourceCode.FieldName, FIsRead.FieldName, FIsAddRecord.FieldName, FIsUpdate.FieldName, FIsDelete.FieldName, FIsSpecial.FieldName, FUserName.FieldName ]); NewParamForQuery(QueryOfUpdate, FSourceCode); NewParamForQuery(QueryOfUpdate, FIsRead); NewParamForQuery(QueryOfUpdate, FIsAddRecord); NewParamForQuery(QueryOfUpdate, FIsUpdate); NewParamForQuery(QueryOfUpdate, FIsDelete); NewParamForQuery(QueryOfUpdate, FIsSpecial); NewParamForQuery(QueryOfUpdate, FUserName); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TSysUserAccessRight.Clone():TTable; begin Result := TSysUserAccessRight.Create(Database); Id.Clone(TSysUserAccessRight(Result).Id); FSourceCode.Clone(TSysUserAccessRight(Result).FSourceCode); FIsRead.Clone(TSysUserAccessRight(Result).FIsRead); FIsAddRecord.Clone(TSysUserAccessRight(Result).FIsAddRecord); FIsUpdate.Clone(TSysUserAccessRight(Result).FIsUpdate); FIsDelete.Clone(TSysUserAccessRight(Result).FIsDelete); FIsSpecial.Clone(TSysUserAccessRight(Result).FIsSpecial); FUserName.Clone(TSysUserAccessRight(Result).FUserName); //not a database field FSourceName.Clone(TSysUserAccessRight(Result).FSourceName); end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIToolBar.pas // Creator : Shen Min // Date : 2002-12-12 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIToolBar; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, ToolWin, ComCtrls, Graphics, Forms, Imglist, SUIThemes, SUIMgr; type TsuiToolBar = class(TToolBar) private m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_ButtonColor : TColor; m_ButtonBorderColor : TColor; m_ButtonDownColor : TColor; procedure DrawBar(Sender: TToolBar; const ARect: TRect; var DefaultDraw: Boolean); procedure DrawButton(Sender: TToolBar; Button: TToolButton; State: TCustomDrawState; var DefaultDraw: Boolean); procedure DrawDownButton( ACanvas : TCanvas; ARect : TRect; ImgLst : TCustomImageList; ImageIndex : Integer; Caption : TCaption; DropDown : Boolean ); procedure DrawHotButton( ACanvas : TCanvas; ARect : TRect; ImgLst : TCustomImageList; ImageIndex : Integer; Caption : TCaption; DropDown : Boolean ); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetButtonBorderColor(const Value: TColor); procedure SetButtonColor(const Value: TColor); procedure SetButtonDownColor(const Value: TColor); procedure SetFileTheme(const Value: TsuiFileTheme); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property ButtonColor : TColor read m_ButtonColor write SetButtonColor; property ButtonBorderColor : TColor read m_ButtonBorderColor write SetButtonBorderColor; property ButtonDownColor : TColor read m_ButtonDownColor write SetButtonDownColor; property Color; property Transparent; end; implementation uses SUIPublic; function ReplaceStr(const Source : String; const FindStr : String; const ReplaceStr : String) : String; var p : Integer; begin Result := Source; p := Pos(FindStr, Source); while p <> 0 do begin Result := Copy(Result, 1, p - 1) + ReplaceStr + Copy(Result, p + Length(FindStr), Length(Result)); p := Pos(FindStr, Result); end; end; function RemoveHotKey(const Source : String) : String; begin Result := ReplaceStr(Source, '&', ''); end; { TsuiToolBar } constructor TsuiToolBar.Create(AOwner: TComponent); begin inherited; if not (csDesigning in ComponentState) then OnCustomDrawButton := DrawButton; OnCustomDraw := DrawBar; Flat := true; Transparent := false; UIStyle := GetSUIFormStyle(AOwner); end; procedure TsuiToolBar.DrawBar(Sender: TToolBar; const ARect: TRect; var DefaultDraw: Boolean); begin if Transparent then DoTrans(Canvas, self); end; procedure TsuiToolBar.DrawButton( Sender: TToolBar; Button: TToolButton; State: TCustomDrawState; var DefaultDraw: Boolean ); var ACanvas : TCanvas; ARect : TRect; ImgLst : TCustomImageList; X, Y : Integer; DropDown : Boolean; begin ACanvas := Sender.Canvas; ARect := Button.BoundsRect; DropDown := (Button.Style = tbsDropDown); if cdsHot in State then begin if (HotImages <> nil) then ImgLst := HotImages else ImgLst := Images; if cdsSelected in State then DrawDownButton(ACanvas, ARect, ImgLst, Button.ImageIndex, Button.Caption, DropDown) else DrawHotButton(ACanvas, ARect, ImgLst, Button.ImageIndex, Button.Caption, DropDown); if DropDown then begin ACanvas.Brush.Color := clBlack; ACanvas.Pen.Color := clBlack; X := ARect.Right - 9; Y := (ARect.Bottom - ARect.Top) div 2; ACanvas.Polygon([Point(X, Y), Point(X + 4, Y), Point(X + 2, Y + 2)]); X := ARect.Right - 8; Y := (ARect.Bottom - ARect.Top) div 2; ACanvas.Polygon([Point(X, Y), Point(X + 2, Y), Point(X + 1, Y + 1)]); ACanvas.MoveTo(ARect.Right - 14, ARect.Top); ACanvas.LineTo(ARect.Right - 14, ARect.Bottom); end; DefaultDraw := false; end else if (cdsSelected in State) or (cdsChecked in State) then begin if (HotImages <> nil) then ImgLst := HotImages else ImgLst := Images; DrawHotButton(ACanvas, ARect, ImgLst, Button.ImageIndex, Button.Caption, DropDown); DefaultDraw := false; end; end; procedure TsuiToolBar.DrawDownButton( ACanvas : TCanvas; ARect : TRect; ImgLst : TCustomImageList; ImageIndex : Integer; Caption : TCaption; DropDown : Boolean ); var nLeft : Integer; nWidth : Integer; R : TRect; begin ACanvas.Brush.Color := m_ButtonDownColor; ACanvas.Pen.Color := m_ButtonBorderColor; ACanvas.Rectangle(ARect); if ImgLst = nil then begin if ShowCaptions then begin if not List then begin nWidth := ACanvas.TextWidth(RemoveHotKey(Caption)); if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - nWidth) div 2 else nLeft := (ARect.Right - ARect.Left - nWidth) div 2; R := Rect(ARect.Left + nLeft, ARect.Top + 5, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + nLeft, ARect.Top + 5, Caption); end else begin R := Rect(ARect.Left + 8, ARect.Top + 3, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + 8, ARect.Top + 3, Caption); end; end; Exit; end; if not List then begin if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - ImgLst.Width) div 2 else nLeft := (ARect.Right - ARect.Left - ImgLst.Width) div 2; ImgLst.Draw(ACanvas, ARect.Left + nLeft, ARect.Top + 3, ImageIndex); end else begin ImgLst.Draw(ACanvas, ARect.Left + 5, ARect.Top + 3, ImageIndex); end; if ShowCaptions then begin if not List then begin nWidth := ACanvas.TextWidth(RemoveHotKey(Caption)); if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - nWidth) div 2 else nLeft := (ARect.Right - ARect.Left - nWidth) div 2; R := Rect(ARect.Left + nLeft, ARect.Top + ImgLst.Height + 4, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + nLeft, ARect.Top + ImgLst.Height + 4, Caption); end else begin R := Rect(ARect.Left + ImgLst.Width + 7, ARect.Top + 4 + (ImgLst.Height - 16) div 2, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + ImgLst.Width + 7, ARect.Top + 4, Caption); end; end; end; procedure TsuiToolBar.DrawHotButton( ACanvas : TCanvas; ARect : TRect; ImgLst : TCustomImageList; ImageIndex : Integer; Caption : TCaption; DropDown : Boolean ); var nLeft : Integer; nWidth : Integer; R : TRect; begin ACanvas.Brush.Color := m_ButtonColor; ACanvas.Pen.Color := m_ButtonBorderColor; ACanvas.Rectangle(ARect); if ImgLst = nil then begin if ShowCaptions then begin if not List then begin nWidth := ACanvas.TextWidth(RemoveHotKey(Caption)); if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - nWidth) div 2 else nLeft := (ARect.Right - ARect.Left - nWidth) div 2; R := Rect(ARect.Left + nLeft, ARect.Top + 4, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + nLeft, ARect.Top + 4, Caption); end else begin R := Rect(ARect.Left + 8, ARect.Top + 3, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + 8, ARect.Top + 3, Caption); end; end; Exit; end; if not List then begin if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - ImgLst.Width) div 2 else nLeft := (ARect.Right - ARect.Left - ImgLst.Width) div 2; ImgLst.Draw(ACanvas, ARect.Left + nLeft, ARect.Top + 3, ImageIndex); end else begin ImgLst.Draw(ACanvas, ARect.Left + 5, ARect.Top + 3, ImageIndex); end; if ShowCaptions then begin if not List then begin nWidth := ACanvas.TextWidth(RemoveHotKey(Caption)); if DropDown then nLeft := (ARect.Right - 14 - ARect.Left - nWidth) div 2 else nLeft := (ARect.Right - ARect.Left - nWidth) div 2; R := Rect(ARect.Left + nLeft, ARect.Top + ImgLst.Height + 4, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + nLeft, ARect.Top + ImgLst.Height + 4, Caption); end else begin R := Rect(ARect.Left + ImgLst.Width + 7, ARect.Top + 4 + (ImgLst.Height - 16) div 2, ARect.Right, ARect.Bottom); DrawText(ACanvas.Handle, PChar(Caption), -1, R, DT_LEFT); // ACanvas.TextOut(ARect.Left + ImgLst.Width + 7, ARect.Top + 4, Caption); end; end; end; procedure TsuiToolBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiToolBar.SetButtonBorderColor(const Value: TColor); begin m_ButtonBorderColor := Value; Repaint(); end; procedure TsuiToolBar.SetButtonColor(const Value: TColor); begin m_ButtonColor := Value; Repaint(); end; procedure TsuiToolBar.SetButtonDownColor(const Value: TColor); begin m_ButtonDownColor := Value; Repaint(); end; procedure TsuiToolBar.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiToolBar.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin m_ButtonBorderColor := m_FileTheme.GetColor(SUI_THEME_TOOLBAR_BUTTON_BORDER_COLOR); m_ButtonColor := m_FileTheme.GetColor(SUI_THEME_TOOLBAR_BUTTON_BACKGROUND_COLOR); m_ButtonDownColor := m_FileTheme.GetColor(SUI_THEME_TOOLBAR_BUTTON_DOWN_BACKGROUND_COLOR); end else begin m_ButtonBorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_TOOLBAR_BUTTON_BORDER_COLOR); m_ButtonColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_TOOLBAR_BUTTON_BACKGROUND_COLOR); m_ButtonDownColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_TOOLBAR_BUTTON_DOWN_BACKGROUND_COLOR); end; if {$IFDEF RES_MACOS} (m_UIStyle = MacOS) {$ELSE} false {$ENDIF} or {$IFDEF RES_PROTEIN} (m_UIStyle = Protein) {$ELSE} false {$ENDIF} then Transparent := true else Transparent := false; EdgeInner := esNone; EdgeOuter := esNone; Repaint(); end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Json; /// <summary> /// REST.Json implements a TJson class that offers several convenience methods: /// - converting Objects to Json and vice versa /// - formating Json /// </summary> interface uses System.JSON, REST.JsonReflect; type TJsonOption = (joIgnoreEmptyStrings, joIgnoreEmptyArrays, joDateIsUTC, joDateFormatUnix, joDateFormatISO8601, joDateFormatMongo, joDateFormatParse); TJsonOptions = set of TJsonOption; TJson = class(TObject) private class function ObjectToJsonValue(AObject: TObject; AOptions: TJsonOptions): TJSONValue; static; class procedure ProcessOptions(AJsonObject: TJSONObject; AOptions: TJsonOptions); static; public /// <summary> /// Converts any TObject descendant into its Json representation. /// </summary> class function ObjectToJsonObject(AObject: TObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): TJSONObject; /// <summary> /// Converts any TObject decendant into its Json string representation. The resulting string has proper Json /// encoding applied. /// </summary> class function ObjectToJsonString(AObject: TObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): string; class function JsonToObject<T: class, constructor>(AJsonObject: TJSONObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): T; overload; class function JsonToObject<T: class, constructor>(const AJson: string; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): T; overload; class procedure JsonToObject(AObject: TObject; AJsonObject: TJSONObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]); overload; class function Format(AJsonValue: TJSONValue): string; deprecated 'Use TJSONAncestor.Format instead'; /// <summary> /// Encodes the string representation of a TJSONValue descendant so that line breaks, tabulators etc are escaped /// using backslashes. /// </summary> /// <example> /// {"name":"something\else"} will be encoded as {"name":"something\\else"} /// </example> class function JsonEncode(AJsonValue: TJSONValue): string; overload; class function JsonEncode(const AJsonString: String): string; overload; end; implementation uses System.DateUtils, System.SysUtils, System.Rtti, System.Character, System.JSONConsts, System.Generics.Collections, REST.Json.Types; class function TJson.Format(AJsonValue: TJSONValue): string; begin Result := AJsonValue.Format; end; class function TJson.JsonToObject<T>(const AJson: string; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): T; var LJson: string; LJSONValue: TJSONValue; LJSONObject: TJSONObject; begin LJSONValue := TJSONObject.ParseJSONValue(AJson); LJSONObject := nil; try if Assigned(LJSONValue) and (LJSONValue is TJSONObject) then LJSONObject := LJSONValue as TJSONObject else begin LJson := AJson.Trim; if (LJson = '') and not Assigned(LJSONValue) or (LJson <> '') and Assigned(LJSONValue) and LJSONValue.Null then Exit(nil) else raise EConversionError.Create(SCannotCreateObject); end; Result := JsonToObject<T>(LJSONObject, AOptions); finally LJSONValue.Free; end; end; class function TJson.JsonEncode(AJsonValue: TJSONValue): string; var LBytes: TBytes; begin SetLength(LBytes, AJsonValue.ToString.Length * 6); // Length can not be predicted. Worst case: every single char gets escaped SetLength(LBytes, AJsonValue.ToBytes(LBytes, 0)); // adjust Array to actual length Result := TEncoding.UTF8.GetString(LBytes); end; class function TJson.JsonEncode(const AJsonString: string): string; var LJsonValue: TJSONValue; begin LJsonValue := TJSONObject.ParseJSONValue(AJsonString); try Result := JsonEncode(LJsonValue); finally LJsonValue.Free; end; end; class procedure TJson.JsonToObject(AObject: TObject; AJsonObject: TJSONObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]); var LUnMarshaler: TJSONUnMarshal; begin LUnMarshaler := TJSONUnMarshal.Create; try LUnMarshaler.DateTimeIsUTC := joDateIsUTC in AOptions; if joDateFormatUnix in AOptions then LUnMarshaler.DateFormat :=jdfUnix else if joDateFormatISO8601 in AOptions then LUnMarshaler.DateFormat := jdfISO8601 else if joDateFormatMongo in AOptions then LUnMarshaler.DateFormat := jdfMongo else if joDateFormatParse in AOptions then LUnMarshaler.DateFormat := jdfParse; ProcessOptions(AJsonObject, AOptions); LUnMarshaler.CreateObject(AObject.ClassType, AJsonObject, AObject); finally LUnMarshaler.Free; end; end; class function TJson.JsonToObject<T>(AJsonObject: TJSONObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): T; var LUnMarshaler: TJSONUnMarshal; begin if AJsonObject = nil then Exit(nil); LUnMarshaler := TJSONUnMarshal.Create; try LUnMarshaler.DateTimeIsUTC := joDateIsUTC in AOptions; if joDateFormatUnix in AOptions then LUnMarshaler.DateFormat :=jdfUnix else if joDateFormatISO8601 in AOptions then LUnMarshaler.DateFormat := jdfISO8601 else if joDateFormatMongo in AOptions then LUnMarshaler.DateFormat := jdfMongo else if joDateFormatParse in AOptions then LUnMarshaler.DateFormat := jdfParse; ProcessOptions(AJSONObject, AOptions); Result := LUnMarshaler.CreateObject(T, AJsonObject) as T; finally LUnMarshaler.Free; end; end; class function TJson.ObjectToJsonValue(AObject: TObject; AOptions: TJsonOptions): TJSONValue; var LMarshaler: TJSONMarshal; begin LMarshaler := TJSONMarshal.Create(TJSONConverter.Create); try LMarshaler.DateTimeIsUTC := joDateIsUTC in AOptions; if joDateFormatUnix in AOptions then LMarshaler.DateFormat :=jdfUnix else if joDateFormatISO8601 in AOptions then LMarshaler.DateFormat := jdfISO8601 else if joDateFormatMongo in AOptions then LMarshaler.DateFormat := jdfMongo else if joDateFormatParse in AOptions then LMarshaler.DateFormat := jdfParse; Result := LMarshaler.Marshal(AObject); if Result is TJSONObject then ProcessOptions(TJSONObject(Result), AOptions); finally LMarshaler.Free; end; end; class function TJson.ObjectToJsonObject(AObject: TObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): TJSONObject; var LJSONValue: TJSONValue; begin LJSONValue := ObjectToJsonValue(AObject, AOptions); if LJSONValue.Null then begin LJSONValue.Free; Result := nil; end else Result := LJSONValue as TJSONObject; end; class function TJson.ObjectToJsonString(AObject: TObject; AOptions: TJsonOptions = [joDateIsUTC, joDateFormatISO8601]): string; var LJSONValue: TJSONValue; begin LJSONValue := ObjectToJsonValue(AObject, AOptions); try Result := JsonEncode(LJSONValue); finally LJSONValue.Free; end; end; class procedure TJson.ProcessOptions(AJsonObject: TJSONObject; AOptions: TJsonOptions); var LPair: TJSONPair; LItem: TObject; i: Integer; function IsEmpty(ASet: TJsonOptions): Boolean; var LElement: TJsonOption; begin Result := True; for LElement in ASet do begin Result := False; break; end; end; begin if Assigned(AJsonObject) and not IsEmpty(AOptions) then for i := AJsonObject.Count - 1 downto 0 do begin LPair := TJSONPair(AJsonObject.Pairs[i]); if LPair.JsonValue is TJSONObject then ProcessOptions(TJSONObject(LPair.JsonValue), AOptions) else if LPair.JsonValue is TJSONArray then begin if (joIgnoreEmptyArrays in AOptions) and (TJSONArray(LPair.JsonValue).Count = 0) then AJsonObject.RemovePair(LPair.JsonString.Value).DisposeOf else for LItem in TJSONArray(LPair.JsonValue) do if LItem is TJSONObject then ProcessOptions(TJSONObject(LItem), AOptions) end else if (joIgnoreEmptyStrings in AOptions) and (LPair.JsonValue.value = '') then AJsonObject.RemovePair(LPair.JsonString.Value).DisposeOf; end; end; end.
unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, Controller, FMX.Edit, Winapi.ShellAPI, Winapi.Windows; type TfmMain = class(TForm) Label1: TLabel; btProcess: TButton; btProcessCsv: TButton; btSaveHead: TButton; Label4: TLabel; edLastPeriod: TEdit; btHelp: TButton; btDownloadCsv: TButton; procedure btDownloadCsvClick(Sender: TObject); procedure btHelpClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btProcessClick(Sender: TObject); procedure btProcessCsvClick(Sender: TObject); procedure btSaveHeadClick(Sender: TObject); strict private procedure UpdateGui; private FController: TTomatoAggController; procedure ShellExecute(sPath: string; sParams: string = ''; nCmdShow: Cardinal = SW_NORMAL); { Private declarations } protected public { Public declarations } published end; var fmMain: TfmMain; implementation uses taGlobals; const SSettingsDat = 'Settings.dat'; {$R *.fmx} procedure TfmMain.btDownloadCsvClick(Sender: TObject); begin ShellExecute('http://www.tomato.es/tomatoes.csv'); end; procedure TfmMain.btHelpClick(Sender: TObject); begin ShellExecute(DataPath('Help.txt')); end; procedure TfmMain.ShellExecute(sPath: string; sParams: string = ''; nCmdShow: Cardinal = SW_NORMAL); begin Winapi.ShellApi.ShellExecute(0, nil, pChar(sPath), pChar(sParams), nil, nCmdShow); end; procedure TfmMain.FormDestroy(Sender: TObject); begin FreeAndNil(FController); end; procedure TfmMain.FormCreate(Sender: TObject); begin FController := TTomatoAggController.Create(); //Button1Click(nil); FController.SerializeSettings(DataPath(SSettingsDat), False); Label1.Visible := False; btProcess.Visible := False; UpdateGui; end; procedure TfmMain.btProcessClick(Sender: TObject); begin FController.Process(False); end; procedure TfmMain.btProcessCsvClick(Sender: TObject); begin FController.Process(True); UpdateGui; end; procedure TfmMain.btSaveHeadClick(Sender: TObject); begin FController.SerializeSettings(DataPath(SSettingsDat), True); end; procedure TfmMain.UpdateGui; begin edLastPeriod.Text := FController.GetLastPeriodsStr; end; end.
unit uQuestionInfo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, xQuestionInfo; type TfQuestionInfo = class(TForm) pgcntrl1: TPageControl; tbsht1: TTabSheet; tbsht2: TTabSheet; pnlBottom: TPanel; lblQuestionName: TLabel; lblQuestionDescribe: TLabel; lblQuestionRemark: TLabel; edtQuestionName: TEdit; mmoQuestionDescribe: TMemo; mmoQuestionRemark: TMemo; pnlBR: TPanel; btnOK: TButton; btnCancel: TButton; private { Private declarations } protected FInfo : TQuestionInfo; public { Public declarations } /// <summary> /// 显示信息 /// </summary> procedure ShowInfo(AInfo : TQuestionInfo); virtual; /// <summary> /// 保存信息 /// </summary> procedure SaveInfo; virtual; end; var fQuestionInfo: TfQuestionInfo; implementation {$R *.dfm} procedure TfQuestionInfo.SaveInfo; begin if Assigned(FInfo) then begin FInfo.QName := edtQuestionName.Text; FInfo.QDescribe := mmoQuestionDescribe.Text; FInfo.QRemark1 := mmoQuestionRemark.Text; end; end; procedure TfQuestionInfo.ShowInfo(AInfo: TQuestionInfo); begin if Assigned(AInfo) then begin FInfo := AInfo; edtQuestionName.Text := FInfo.QName; mmoQuestionDescribe.Text := FInfo.QDescribe; mmoQuestionRemark.Text := FInfo.QRemark1; end; end; end.