text
stringlengths
14
6.51M
unit Standard; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, DBLookup, StdCtrls, DB, DBTables, Buttons, Spin, Grids, DBGrids,Printers; {function AccessValid(Name:string;Level:integer):Boolean;} function Encrypt(S,C:String):String; function Encript(S:String):String; function Decript(S:String):String; // function SameValueFound(FieldsPhrase:String):Boolean; implementation uses Main,pTimeData; { function AccessValid(Name:string;Level:integer):Boolean; begin Result:=False; if UpdSecurity.tSecurity.FindKey([Level,Name]) then if UpdSecurity.tSecurity.FieldByName('Authorize').AsString = 'Y' then Result:=True; if Result=False then messageDlg('Unauthorized Access',mtError,[mbOk],0); end;} function Encrypt(S,C:String):String; {Description: ENCRYPT searches in S a character between 0 and 9 and converts it into letters specified in C. } var Encrypted: String; x: SmallInt; begin Encrypted:=''; C:=UpperCase(C); if length(C)< 10 then for x:=1 to 10-length(C) do C:=C+' '; for x := 1 to length(S) do begin if (S[x]>=chr(48)) and (S[x]<=chr(57)) then Encrypted:=Encrypted+C[strToInt(S[x])+1] else if S[x]=chr(46) then Encrypted := Encrypted+'-'; end; Result:= Encrypted; end; function Encript(S:String):String; var NewWord : String; ctr : Smallint; begin NewWord := '' ; S := UpperCase(S); for ctr := 1 to length(S) do NewWord := NewWord + Chr(Ord(S[ctr])+ctr); Result := NewWord; end; function Decript(S:String):String; var NewWord : String; ctr : Smallint; begin NewWord := '' ; S := UpperCase(S); for ctr := 1 to length(S) do NewWord := NewWord + Chr(Ord(S[ctr])-ctr); Result := NewWord; end; end.
// SuperIB // Copyright © 1999 David S. Becker // dhbecker@jps.net // www.jps.net/dhbecker/superib unit SIBFIBEA; interface uses Classes, SIBEABase, SIBAPI, FIBDatabase; type { TSIBfibEventAlerter } TSIBfibEventAlerter = class(TSIBEventAlerter) private FDatabase: TFIBDatabase; FAutoRegister: Boolean; procedure SetDatabase(const Value: TFIBDatabase); procedure SetAutoRegister(const Value: Boolean); function CanRegisterEvents:boolean; protected function GetNativeHandle: SIB_DBHandle; override; procedure SetNativeHandle(const Value: SIB_DBHandle); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; procedure ValidateDatabase(DB: TFIBDatabase); virtual; procedure AfterConnect(Sender:TObject); procedure BeforeDisconnect(Sender:TObject); public constructor Create(Owner: TComponent); override; destructor Destroy; override; published property Database: TFIBDatabase read FDatabase write SetDatabase; property AutoRegister: Boolean read FAutoRegister write SetAutoRegister default False; end; implementation uses SysUtils, SIBGlobals; resourcestring SIB_RS_FIB_SET_NATIVEHANDLE = 'SIBfibEventAlerter does not allow you to set the NativeHandle property'; SIB_RS_FIB_NO_DATABASE = 'Cannot register events, no database assigned or database not connected'; { TSIBfibEventAlerter } // we need to know when the component is deleted and clear out the property procedure TSIBfibEventAlerter.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FDatabase) then begin Database := nil; end; inherited; end; procedure TSIBfibEventAlerter.Loaded; begin if FAutoRegister and CanRegisterEvents then RegisterEvents; inherited; end; // Retrieve the native InterBase handle from the FreeIBComponents function TSIBfibEventAlerter.GetNativeHandle: SIB_DBHandle; begin ValidateDatabase(FDatabase); Result := SIB_DBHandle(FDatabase.Handle); FClientLibrary:=FDatabase.ClientLibrary; end; procedure TSIBfibEventAlerter.SetNativeHandle(const Value: SIB_DBHandle); begin raise ESIBError.Create(SIB_RS_FIB_SET_NATIVEHANDLE); end; constructor TSIBfibEventAlerter.Create(Owner: TComponent); begin inherited; FAutoRegister := False; FDatabase := nil; FClientLibrary:= nil; end; destructor TSIBfibEventAlerter.Destroy; begin Database := nil; // For unregister connect(disconnect) events inherited; end; procedure TSIBfibEventAlerter.SetDatabase(const Value: TFIBDatabase); var WasRegistered: Boolean; begin if (Value <> FDatabase) then begin WasRegistered := Registered; if WasRegistered then UnRegisterEvents; if Assigned(FDatabase) and not (csDesigning in ComponentState) and not (csDestroying in FDatabase.ComponentState) then begin FDatabase.RemoveEvent( AfterConnect, detOnConnect ); FDatabase.RemoveEvent( BeforeDisconnect, detBeforeDisconnect ); FClientLibrary:=nil; end; FDatabase := Value; if Assigned(FDatabase) and not (csDesigning in ComponentState) then try FDatabase.AddEvent(AfterConnect,detOnConnect); FDatabase.AddEvent(BeforeDisconnect,detBeforeDisconnect); finally if WasRegistered then RegisterEvents; end; end; end; // this routine is used to verify that the database is assigned and connected procedure TSIBfibEventAlerter.ValidateDatabase(DB: TFIBDatabase); begin if ((not Assigned(DB)) or (not DB.Connected)) then raise ESIBError.Create(SIB_RS_FIB_NO_DATABASE); end; function TSIBfibEventAlerter.CanRegisterEvents:boolean; begin Result:=(not (csDesigning in ComponentState)) and // (not (csLoading in ComponentState)) and (not Registered) and Assigned(Database) and Database.Connected ; end; procedure TSIBfibEventAlerter.SetAutoRegister(const Value: Boolean); begin FAutoRegister := Value; if FAutoRegister and CanRegisterEvents then RegisterEvents; end; procedure TSIBfibEventAlerter.AfterConnect(Sender: TObject); begin if ((not (csDesigning in ComponentState)) and Assigned(FDatabase)) then if (FAutoRegister and (not Registered)) then RegisterEvents; end; procedure TSIBfibEventAlerter.BeforeDisconnect(Sender: TObject); begin if ((not (csDesigning in ComponentState)) and Assigned(FDatabase)) then if Registered then UnRegisterEvents end; end.
unit LandlordSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, ADODB, System.Rtti, RzButton; type TfrmLandlordSearch = class(TfrmBaseSearch) procedure FormCreate(Sender: TObject); private { Private declarations } protected { Protected declarations } procedure SearchList; override; procedure SetReturn; override; procedure Add; override; procedure Cancel; override; end; implementation {$R *.dfm} uses Landlord, EntitiesData, LandlordDetail, AppConstants; { TfrmLandlordSearch } procedure TfrmLandlordSearch.Add; begin inherited; with TfrmLandlordDetail.Create(self), grSearch.DataSource.DataSet do begin llord.Add; ShowModal; if ModalResult = mrOK then begin // refresh the grid DisableControls; Close; Open; Locate('entity_id',llord.Id,[]); EnableControls; end; end; end; procedure TfrmLandlordSearch.FormCreate(Sender: TObject); begin dmEntities := TdmEntities.Create(self); (grSearch.DataSource.DataSet as TADODataSet).Parameters.ParamByName('@entity_type').Value := TRttiEnumerationType.GetName<TEntityTypes>(TEntityTypes.LL); inherited; end; procedure TfrmLandlordSearch.SearchList; var filter: string; begin inherited; if Trim(edSearchKey.Text) <> '' then filter := 'name like ''*' + edSearchKey.Text + '*''' else filter := ''; grSearch.DataSource.DataSet.Filter := filter; end; procedure TfrmLandlordSearch.SetReturn; begin with grSearch.DataSource.DataSet do begin llord.Id := FieldByName('entity_id').AsString; llord.Name := FieldByName('name').AsString;; llord.Mobile := FieldByName('mobile_no').AsString; llord.Telephone := FieldByName('home_phone').AsString; end; end; procedure TfrmLandlordSearch.Cancel; begin llord.Destroy; end; end.
unit uPlugin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, uDefine, gnugettext, neUtil, Math, ShellAPI, StrUtils; type TfrmPlugin = class(TForm) lvPlugins: TListView; Label2: TLabel; Label3: TLabel; Label4: TLabel; rbPluginEnable: TRadioButton; rbPluginDisable: TRadioButton; Label5: TLabel; Label6: TLabel; btnApply: TButton; lblName: TLabel; lblVersion: TLabel; lblLastUpdate: TLabel; edtWeight: TEdit; mmDescription: TMemo; Label11: TLabel; lblAuthor: TLabel; Label1: TLabel; lblSupport: TLabel; Label7: TLabel; lblBrief: TLabel; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure lvPluginsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lvPluginsDblClick(Sender: TObject); procedure lvPluginsMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } procedure UpdatePluginListView(PluginList: TPluginList); public { Public declarations } end; var frmPlugin: TfrmPlugin; Plugins: TPluginList; SelectedItem: Integer; implementation {$R *.dfm} uses uMain; procedure TfrmPlugin.FormShow(Sender: TObject); begin case gManagePluginType of ptGenerator: begin Caption := _('Manager Generator Plugin'); end; ptEvaluation: begin Caption := _('Manager Evaluation Plugin'); end; else begin Self.Close; raise Exception.Create(_('Error Plugin Type')); end; end; if gManagePluginType = ptGenerator then begin FillPluginList(gGenPlugins, gManagePluginType); Plugins := gGenPlugins; end else begin FillPluginList(gEvaPlugins, gManagePluginType); Plugins := gEvaPlugins; end; UpdatePluginListView(Plugins); lvPlugins.ItemIndex := -1; lvPluginsClick(lvPlugins); btnApply.Enabled := (lvPlugins.Items.Count > 0); end; procedure TfrmPlugin.FormCreate(Sender: TObject); begin TranslateComponent(Self); end; procedure TfrmPlugin.btnApplyClick(Sender: TObject); var p: TPlugin; begin if StrToIntDef(edtWeight.Text, -1) < 0 then begin ShowMessage(_('Weight must be an integer no less than zero')); Exit; end; if (SelectedItem <> -1) and (SelectedItem < Plugins.Count) then begin p := Plugins[SelectedItem]; if (p.Enable <> rbPluginEnable.Checked) or ((edtWeight.Text) <> IntToStr(p.Weight)) then begin btnApply.Enabled := False; p.Enable := rbPluginEnable.Checked; p.Weight := StrToIntDef(edtWeight.Text, 0); ChangePluginSetting(p); btnApply.Enabled := True; end; UpdatePluginListView(Plugins); ShowMessage(_('Plugin setting has been change')); end; end; procedure TfrmPlugin.lvPluginsClick(Sender: TObject); var Index: Integer; begin if (lvPlugins.ItemIndex <> -1) and (Plugins.Count > lvPlugins.ItemIndex) then begin Index := StrToIntDef(lvPlugins.Selected.SubItems[0], 0) - 1; Index := IfThen(Index < 0, lvPlugins.ItemIndex, Index); with TPlugin(Plugins[Index]) do begin lblName.Caption := Name; lblAuthor.Caption := Author; lblVersion.Caption := Version; lblLastUpdate.Caption := LastUpdate; lblSupport.Caption := IfThen(IsSupportRed, _('RedBall') + ' ', '') + IfThen(IsSupportBlue, _('BlueBall'), ''); lblBrief.Caption := Brief; rbPluginEnable.Checked := Enable; rbPluginDisable.Checked := not Enable; edtWeight.Text := IntToStr(Weight); mmDescription.Text := Description; end; SelectedItem := Index; end else begin lblName.Caption := ''; lblAuthor.Caption := ''; lblVersion.Caption := ''; lblLastUpdate.Caption := ''; lblSupport.Caption := ''; rbPluginEnable.Checked := False; rbPluginDisable.Checked := False; edtWeight.Text := ''; mmDescription.Text := ''; SelectedItem := -1; end; end; procedure TfrmPlugin.FormClose(Sender: TObject; var Action: TCloseAction); begin frmMain.FillPluginListView(gGenPlugins, gEvaPlugins); end; procedure TfrmPlugin.lvPluginsDblClick(Sender: TObject); var Index: Integer; begin if (lvPlugins.ItemIndex <> -1) and (Plugins.Count > lvPlugins.ItemIndex) then begin Index := StrToIntDef(lvPlugins.Selected.SubItems[0], 0) - 1; Index := IfThen(Index < 0, lvPlugins.ItemIndex, Index); ShellExecute(0, 'open', 'notepad.exe', PChar(Plugins[Index].Path), '', SW_SHOWNORMAL); end; end; procedure TfrmPlugin.lvPluginsMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: Integer; begin if Button = mbRight then begin if (lvPlugins.ItemIndex <> -1) and (Plugins.Count > lvPlugins.ItemIndex) then begin Index := StrToIntDef(lvPlugins.Selected.SubItems[0], 0) - 1; Index := IfThen(Index < 0, lvPlugins.ItemIndex, Index); ShellExecute(0, 'open', 'explorer.exe', PChar(ExtractFilePath(Plugins[Index].Path)), '', SW_SHOWNORMAL); end; end; end; procedure TfrmPlugin.UpdatePluginListView(PluginList: TPluginList); var p: TPlugin; i: Integer; begin lvPlugins.Clear; for i := 0 to PluginList.Count - 1 do begin p := PluginList[i]; GetPluginSetting(p); with lvPlugins.Items.Add do begin if p.Enable then begin Caption := _('Enable'); end else begin Caption := _('Disable'); end; SubItems.Add(IntToStr(i + 1)); SubItems.Add(p.Name); SubItems.Add(p.Version); SubItems.Add(p.LastUpdate); SubItems.Add(IntToStr(p.Weight)); end; end; end; end.
// Nama: Morgen Sudyanto // NIM: 16518380 unit upecahan; interface type pecahan = record n : integer; d : integer; end; function IsPecahanValid (n, d : integer) : boolean; { Menghasilkan true jika n dan d dapat membentuk pecahan yang valid dengan n sebagai pembilang dan d sebagai penyebut, yaitu jika n >= 0 dan d > 0 } procedure TulisPecahan (P : pecahan); { Menuliskan pecahan P ke layar dalam bentuk "P.n/P.d" } { Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi atau pun enter } { I.S.: P terdefinisi } { F.S.: P tercetak di layar dalam bentuk "P.n/P.d" } function IsLebihKecil (P1, P2 : pecahan) : boolean; { Menghasilkan true jika P1 lebih kecil dari P2 } { pecahan <n1,d1> lebih kecil dari pecahan <n2,d2> jika dan hanya jika: n1*d2 < n2*d1 } function Selisih (P1, P2 : pecahan) : pecahan; { Menghasilkan pecahan selisih antara P1 dengan P2 atau P1 - P2 } { Selisih pecahan <n1,d1> dengan <n2,d2> menghasilkan pecahan <n3,d3> dengan: n3 = n1*d2 - n2*d1 dan d3 = d1*d2. } { Prekondisi : P1 >= P2 } implementation function IsPecahanValid (n, d : integer) : boolean; begin IsPecahanValid:=((n>=0) and (d>0)); end; procedure TulisPecahan (P : pecahan); begin write(P.n); write('/'); write(P.d); end; function IsLebihKecil (P1, P2 : pecahan) : boolean; begin IsLebihKecil:=((P1.n*P2.d)<(P2.n*P1.d)); end; function Selisih (P1, P2 : pecahan) : pecahan; begin Selisih.n:=P1.n*P2.d-P2.n*P1.d; Selisih.d:=P1.d*P2.d; end; begin end.
// =============================================================================== // | THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF | // | ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO | // | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A | // | PARTICULAR PURPOSE. | // | Copyright (c)2010 ADMINSYSTEM SOFTWARE LIMITED | // | // | Project: It demonstrates how to use EASendMailObj to send email with synchronous mode // | // | Author: Ivan Lui ( ivan@emailarchitect.net ) // =============================================================================== unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, EASendMailObjLib_TLB, StdCtrls, ComCtrls, unit2; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label4: TLabel; textFrom: TEdit; textSubject: TEdit; GroupBox1: TGroupBox; Label6: TLabel; textServer: TEdit; chkAuth: TCheckBox; Label7: TLabel; Label8: TLabel; textUser: TEdit; textPassword: TEdit; chkSSL: TCheckBox; Label9: TLabel; lstCharset: TComboBox; Label10: TLabel; textAttachment: TEdit; btnAdd: TButton; btnClear: TButton; textBody: TMemo; btnSend: TButton; lstTo: TListView; btnAddRcpt: TButton; btnClearRcpt: TButton; chkTest: TCheckBox; Label3: TLabel; textThreads: TEdit; textStatus: TLabel; lstProtocol: TComboBox; procedure FormCreate(Sender: TObject); procedure InitCharset(); procedure btnSendClick(Sender: TObject); procedure chkAuthClick(Sender: TObject); function ChAnsiToWide(const StrA: AnsiString): WideString; procedure btnAddClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnAddRcptClick(Sender: TObject); procedure btnClearRcptClick(Sender: TObject); procedure Sending(); // FastSender event handler procedure OnSent(ASender: TObject; lRet: Integer; const ErrDesc: WideString; nKey: Integer; const tParam: WideString; const senderAddr: WideString; const Recipients: WideString); procedure OnConnected(ASender: TObject; nKey: Integer; const tParam: WideString); procedure OnAuthenticated(ASender: TObject; nKey: Integer; const tParam: WideString); procedure OnSending(ASender: TObject; lSent: Integer; lTotal: Integer; nKey: Integer; const tParam: WideString); procedure ChangeStatus(index: integer; status: AnsiString ); procedure WaitAllTaskFinished(); procedure SubmitTask( index: integer); procedure FormResize(Sender: TObject); private { Private declarations } public { Public declarations } end; const CRYPT_MACHINE_KEYSET = 32; CRYPT_USER_KEYSET = 4096; CERT_SYSTEM_STORE_CURRENT_USER = 65536; CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072; Max_QueuedCount = 100; var Form1: TForm1; m_arAttachments : TStringList; m_arCharset: array[0..27,0..1] of WideString; m_oFastSender: TFastSender; g_lSent: integer; g_lSend: integer; g_failure: integer; g_bSending: Boolean; g_bStopped: Boolean; g_lTotal: integer; implementation {$R *.dfm} // FastSender event handler procedure TForm1.OnSent(ASender: TObject; lRet: Integer; const ErrDesc: WideString; nKey: Integer; const tParam: WideString; const senderAddr: WideString; const Recipients: WideString); var desc: AnsiString; begin if lRet = 0 then if chkTest.Checked then desc := 'Test is ok!' else desc := 'Sent successfully!' else begin desc := ErrDesc; g_failure := g_failure + 1; end; g_lSent := g_lSent + 1; ChangeStatus(nKey, desc); end; procedure TForm1.OnConnected(ASender: TObject; nKey: Integer; const tParam: WideString); begin; ChangeStatus( nKey, 'Connected'); end; procedure TForm1.OnAuthenticated(ASender: TObject; nKey: Integer; const tParam: WideString); begin; ChangeStatus( nKey, 'Authorized'); end; procedure TForm1.OnSending(ASender: TObject; lSent: Integer; lTotal: Integer; nKey: Integer; const tParam: WideString); begin ChangeStatus( nKey, Format('Sending data %d/%d ...', [lSent, lTotal])); end; procedure TForm1.InitCharset(); var i, index: integer; begin index := 0; m_arCharset[index, 0] := 'Arabic(Windows)'; m_arCharset[index, 1] := 'windows-1256'; index := index + 1; m_arCharset[index, 0] := 'Baltic(ISO)'; m_arCharset[index, 1] := 'iso-8859-4'; index := index + 1; m_arCharset[index, 0] := 'Baltic(Windows)'; m_arCharset[index, 1] := 'windows-1257'; index := index + 1; m_arCharset[index, 0] := 'Central Euporean(ISO)'; m_arCharset[index, 1] := 'iso-8859-2'; index := index + 1; m_arCharset[index, 0] := 'Central Euporean(Windows)'; m_arCharset[index, 1] := 'windows-1250'; index := index + 1; m_arCharset[index, 0] := 'Chinese Simplified(GB18030)'; m_arCharset[index, 1] := 'GB18030'; index := index + 1; m_arCharset[index, 0] := 'Chinese Simplified(GB2312)'; m_arCharset[index, 1] := 'gb2312'; index := index + 1; m_arCharset[index, 0] := 'Chinese Simplified(HZ)'; m_arCharset[index, 1] := 'hz-gb-2312'; index := index + 1; m_arCharset[index, 0] := 'Chinese Traditional(Big5)'; m_arCharset[index, 1] := 'big5'; index := index + 1; m_arCharset[index, 0] := 'Cyrillic(ISO)'; m_arCharset[index, 1] := 'iso-8859-5'; index := index + 1; m_arCharset[index, 0] := 'Cyrillic(KOI8-R)'; m_arCharset[index, 1] := 'koi8-r'; index := index + 1; m_arCharset[index, 0] := 'Cyrillic(KOI8-U)'; m_arCharset[index, 1] := 'koi8-u'; index := index + 1; m_arCharset[index, 0] := 'Cyrillic(Windows)'; m_arCharset[index, 1] := 'windows-1251'; index := index + 1; m_arCharset[index, 0] := 'Greek(ISO)'; m_arCharset[index, 1] := 'iso-8859-7'; index := index + 1; m_arCharset[index, 0] := 'Greek(Windows)'; m_arCharset[index, 1] := 'windows-1253'; index := index + 1; m_arCharset[index, 0] := 'Hebrew(Windows)'; m_arCharset[index, 1] := 'windows-1255'; index := index + 1; m_arCharset[index, 0] := 'Japanese(JIS)'; m_arCharset[index, 1] := 'iso-2022-jp'; index := index + 1; m_arCharset[index, 0] := 'Korean'; m_arCharset[index, 1] := 'ks_c_5601-1987'; index := index + 1; m_arCharset[index, 0] := 'Korean(EUC)'; m_arCharset[index, 1] := 'euc-kr'; index := index + 1; m_arCharset[index, 0] := 'Latin 9(ISO)'; m_arCharset[index, 1] := 'iso-8859-15'; index := index + 1; m_arCharset[index, 0] := 'Thai(Windows)'; m_arCharset[index, 1] := 'windows-874'; index := index + 1; m_arCharset[index, 0] := 'Turkish(ISO)'; m_arCharset[index, 1] := 'iso-8859-9'; index := index + 1; m_arCharset[index, 0] := 'Turkish(Windows)'; m_arCharset[index, 1] := 'windows-1254'; index := index + 1; m_arCharset[index, 0] := 'Unicode(UTF-7)'; m_arCharset[index, 1] := 'utf-7'; index := index + 1; m_arCharset[index, 0] := 'Unicode(UTF-8)'; m_arCharset[index, 1] := 'utf-8'; index := index + 1; m_arCharset[index, 0] := 'Vietnames(Windows)'; m_arCharset[index, 1] := 'windows-1258'; index := index + 1; m_arCharset[index, 0] := 'Western European(ISO)'; m_arCharset[index, 1] := 'iso-8859-1'; index := index + 1; m_arCharset[index, 0] := 'Western European(Windows)'; m_arCharset[index, 1] := 'windows-1252'; for i:= 0 to 27 do begin lstCharset.AddItem(m_arCharset[i,0], nil); end; // Set default encoding to utf-8, it supports all languages. lstCharset.ItemIndex := 24; lstProtocol.AddItem('SMTP Protocol - Recommended', nil); lstProtocol.AddItem('Exchange Web Service - 2007/2010', nil); lstProtocol.AddItem('Exchange WebDav - 2000/2003', nil); lstProtocol.ItemIndex := 0; end; procedure TForm1.FormCreate(Sender: TObject); begin textSubject.Text := 'delphi mass email test'; textBody.Text := 'This sample demonstrates how to send mass email + multiple threads.' + #13#10 + #13#10 + 'From: [$from]' + #13#10 + 'To: [$to]' + #13#10 + 'Subject: [$subject]' + #13#10 + #13#10 + 'If no sever address was specified, the email will be delivered to the recipient''s server directly,' + 'However, if you don''t have a static IP address, ' + 'many anti-spam filters will mark it as a junk-email.' + #13#10; m_arAttachments := TStringList.Create(); InitCharset(); if m_oFastSender = nil then begin m_oFastSender := TFastSender.Create(Application); m_oFastSender.OnSent := OnSent; m_oFastSender.OnConnected := OnConnected; m_oFastSender.OnAuthenticated := OnAuthenticated; m_oFastSender.OnSending := OnSending; end; g_lSent := 0; g_lSend := 0; g_failure := 0; g_bSending := false; g_bStopped := true; g_lTotal :=0; textStatus.Caption := 'Ready'; end; procedure TForm1.btnSendClick(Sender: TObject); begin if btnSend.Caption = 'Cancel' then begin m_oFastSender.ClearQueuedMails(); btnSend.Enabled := false; g_bSending := false; exit; end; btnSend.Caption := 'Cancel'; btnAddRcpt.Enabled := false; btnClearRcpt.Enabled := False; btnAdd.Enabled := false; btnClear.Enabled := false; Sending(); end; procedure TForm1.Sending(); var i, nCount: integer; begin nCount := lstTo.Items.Count; m_oFastSender.MaxThreads := StrToInt(textThreads.Text); g_lSend := 0; g_lSent := 0; g_failure := 0; g_bSending := true; g_bStopped := false; for i := 0 to nCount - 1 do lstTo.Items[i].SubItems[0] := 'Ready'; while (g_bSending) and (g_lSend < nCount) do begin if m_oFastSender.GetQueuedCount() < Max_QueuedCount then begin ChangeStatus(g_lSend,'Queued ...'); SubmitTask(g_lSend); g_lSend := g_lSend + 1; end; Application.ProcessMessages(); end; WaitAllTaskFinished(); btnAdd.Enabled := true; btnClear.Enabled := true; btnAddRcpt.Enabled := true; btnClearRcpt.Enabled := true; btnSend.Enabled := true; btnSend.Caption := 'Send'; g_bStopped := true; end; procedure TForm1.ChangeStatus(index: integer; status: AnsiString ); var nSent, nError: integer; item: TListItem; begin item := lstTo.Items[index]; item.SubItems[0]:= status; nSent := g_lSent - g_failure; nError := g_failure; textStatus.Caption := Format( 'Total %d emails %d success, %d failed.', [lstTo.Items.Count, nSent, nError]); end; procedure TForm1.WaitAllTaskFinished(); begin while m_oFastSender.GetQueuedCount() > 0 do Application.ProcessMessages(); while not (m_oFastSender.GetIdleThreads() = m_oFastSender.GetCurrentThreads()) do Application.ProcessMessages(); end; procedure TForm1.SubmitTask( index: integer); var oSmtp: TMail; item: TListItem; i: integer; bodytext: AnsiString; begin item := lstTo.Items[index]; oSmtp := TMail.Create(Application); // The license code for EASendMail ActiveX Object, // for evaluation usage, please use "TryIt" as the license code. oSmtp.LicenseCode := 'TryIt'; //oSmtp.LogFileName = 'c:\smtp.txt'; //enable smtp log oSmtp.Charset := m_arCharset[lstCharset.ItemIndex, 1]; oSmtp.FromAddr := ChAnsiToWide(trim(textFrom.Text)); // Add recipient's oSmtp.AddRecipientEx(ChAnsiToWide(item.Caption), 0 ); // Set subject oSmtp.Subject := ChAnsiToWide(textSubject.Text); // Using HTML FORMAT to send mail // oSmtp.BodyFormat := 1; // Set body bodytext := textBody.Text; bodytext := StringReplace( bodytext, '[$from]', textFrom.Text, [rfIgnoreCase]); bodytext := StringReplace( bodytext, '[$to]', item.Caption, [rfIgnoreCase] ); bodytext := StringReplace( bodytext, '[$subject]', textSubject.Text, [rfIgnoreCase]); oSmtp.BodyText := ChAnsiToWide(bodytext); // Add attachments for i:= 0 to m_arAttachments.Count - 1 do begin oSmtp.AddAttachment(ChAnsiToWide(m_arAttachments[i])); end; oSmtp.ServerAddr := trim(textServer.Text); oSmtp.Protocol := lstProtocol.ItemIndex; if oSmtp.ServerAddr <> '' then begin if chkAuth.Checked then begin oSmtp.UserName := trim(textUser.Text); oSmtp.Password := trim(textPassword.Text); end; if chkSSL.Checked then begin oSmtp.SSL_init(); // If SSL port is 465, please add the following codes // oSmtp.ServerPort := 465; // oSmtp.SSL_starttls := 0; end; end; if chkTest.Checked then begin // only test if the server accept the recipient address, but do not send the email to the mailbox. m_oFastSender.Test(oSmtp.DefaultInterface, index, 'any value'); end else m_oFastSender.Send(oSmtp.DefaultInterface, index, 'any value'); end; procedure TForm1.chkAuthClick(Sender: TObject); begin textUser.Enabled := chkAuth.Checked; textPassword.Enabled := chkAuth.Checked; if( chkAuth.Checked ) then begin textUser.Color := clWindow; textPassword.Color := clWindow; end else begin textUser.Color := cl3DLight; textPassword.Color := cl3DLight; end; end; // before delphi doesn't support unicode very well in VCL, so // we have to convert the ansistring to unicode by current default codepage. function TForm1.ChAnsiToWide(const StrA: AnsiString): WideString; var nLen: integer; begin Result := StrA; if Result <> '' then begin // convert ansi string to widestring (unicode) by current system codepage nLen := MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, nil, 0); SetLength(Result, nLen - 1); if nLen > 1 then MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1); end; end; procedure TForm1.btnAddClick(Sender: TObject); var pFileDlg : TOpenDialog; fileName : string; index: integer; begin pFileDlg := TOpenDialog.Create(Form1); if pFileDlg.Execute() then begin fileName := pFileDlg.FileName; m_arAttachments.Add( fileName ); while true do begin index := Pos( '\', fileName ); if index <= 0 then break; fileName := Copy( fileName, index+1, Length(fileName)- index ); end; textAttachment.Text := textAttachment.Text + fileName + ';'; end; pFileDlg.Destroy(); end; procedure TForm1.btnClearClick(Sender: TObject); begin m_arAttachments.Clear(); textAttachment.Text := ''; end; procedure TForm1.btnAddRcptClick(Sender: TObject); var item: TListItem; begin Form2.textName.Text :=''; Form2.textEmail.Text := ''; if Form2.ShowModal() = mrOK then begin // for i := 0 to 9 do // begin item := lstTo.Items.Add(); item.Caption := Form2.textName.Text + ' <' + Form2.textEmail.Text + '>' ; item.SubItems.Add('ready'); // end; end end; procedure TForm1.btnClearRcptClick(Sender: TObject); begin lstTo.Items.Clear(); end; procedure TForm1.FormResize(Sender: TObject); begin if Form1.Width < 661 then Form1.Width := 661; if Form1.Height < 435 then Form1.Height := 435; textBody.Width := Form1.Width - 30; textBody.Height := Form1.Height - 340; btnSend.Top := textBody.Top + textBody.Height + 5; btnSend.Left := Form1.Width - 20 - btnSend.Width; textStatus.Top := btnSend.Top; GroupBox1.Left := Form1.Width - GroupBox1.Width - 20; textFrom.Width := Form1.Width - GroupBox1.Width - 110; textSubject.Width := textFrom.Width; lstTo.Width := textFrom.Width; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Classe de controle do Sintegra. The MIT License Copyright: Copyright (C) 2010 T2Ti.COM 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. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 1.0 ******************************************************************************* } unit SintegraController; interface uses Classes, SQLExpr, SysUtils, Sintegra60MVO, Sintegra60AVO, Sintegra60DVO, Generics.Collections; type TSintegraController = class protected public function Tabela60M: TObjectList<TSintegra60MVO>; function Tabela60A(Id: Integer): TObjectList<TSintegra60AVO>; function Tabela60D: TObjectList<TSintegra60DVO>; end; implementation uses UDataModule; var ConsultaSQL: String; Query: TSQLQuery; function TSintegraController.Tabela60M: TObjectList<TSintegra60MVO>; var Lista60M: TObjectList<TSintegra60MVO>; Sintegra60M: TSintegra60MVO; TotalRegistros: Integer; begin ConsultaSQL := 'select count(*) as TOTAL from SINTEGRA_60M'; try try Query := TSQLQuery.Create(nil); Query.SQLConnection := FDataModule.Conexao; Query.sql.Text := ConsultaSQL; Query.Open; TotalRegistros := Query.FieldByName('TOTAL').AsInteger; if TotalRegistros > 0 then begin Lista60M := TObjectList<TSintegra60MVO>.Create; ConsultaSQL := 'select * from SINTEGRA_60M'; Query.sql.Text := ConsultaSQL; Query.Open; Query.First; while not Query.Eof do begin Sintegra60M := TSintegra60MVO.Create; Sintegra60M.Id := Query.FieldByName('ID').AsInteger; Sintegra60M.DataEmissao := Query.FieldByName('DATA_EMISSAO').AsString; Sintegra60M.SerieImpressora := Query.FieldByName('NUMERO_SERIE_ECF').AsString; Sintegra60M.NumeroEquipamento := Query.FieldByName('NUMERO_EQUIPAMENTO').AsInteger; Sintegra60M.ModeloDocumentoFiscal := Query.FieldByName('MODELO_DOCUMENTO_FISCAL').AsString; Sintegra60M.COOInicial := Query.FieldByName('COO_INICIAL').AsInteger; Sintegra60M.COOFinal := Query.FieldByName('COO_FINAL').AsInteger; Sintegra60M.CRZ := Query.FieldByName('CRZ').AsInteger; Sintegra60M.CRO := Query.FieldByName('CRO').AsInteger; Sintegra60M.VendaBruta := Query.FieldByName('VALOR_VENDA_BRUTA').AsFloat; Sintegra60M.GrandeTotal := Query.FieldByName('VALOR_GRANDE_TOTAL').AsFloat; Lista60M.Add(Sintegra60M); Query.next; end; result := Lista60M; end // caso não exista a relacao, retorna um ponteiro nulo else result := nil; except result := nil; end; finally Query.Free; end; end; function TSintegraController.Tabela60A(Id: Integer): TObjectList<TSintegra60AVO>; var Lista60A: TObjectList<TSintegra60AVO>; Sintegra60A: TSintegra60AVO; TotalRegistros: Integer; begin ConsultaSQL := 'select count(*) AS TOTAL from SINTEGRA_60A where ID_SINTEGRA_60M='+IntToStr(Id); try try Query := TSQLQuery.Create(nil); Query.SQLConnection := FDataModule.Conexao; Query.sql.Text := ConsultaSQL; Query.Open; TotalRegistros := Query.FieldByName('TOTAL').AsInteger; if TotalRegistros > 0 then begin Lista60A := TObjectList<TSintegra60AVO>.Create; ConsultaSQL := 'select * from SINTEGRA_60A where ID_SINTEGRA_60M='+IntToStr(Id); Query.sql.Text := ConsultaSQL; Query.Open; Query.First; while not Query.Eof do begin Sintegra60A := TSintegra60AVO.Create; Sintegra60A.Id := Query.FieldByName('ID').AsInteger; Sintegra60A.Id60M := Query.FieldByName('ID_SINTEGRA_60M').AsInteger; Sintegra60A.SituacaoTributaria := Query.FieldByName('SITUACAO_TRIBUTARIA').AsString; Sintegra60A.Valor := Query.FieldByName('VALOR').AsFloat; Lista60A.Add(Sintegra60A); Query.next; end; result := Lista60A; end // caso não exista a relacao, retorna um ponteiro nulo else result := nil; except result := nil; end; finally Query.Free; end; end; function TSintegraController.Tabela60D: TObjectList<TSintegra60DVO>; var Lista60D: TObjectList<TSintegra60DVO>; Sintegra60D: TSintegra60DVO; begin ConsultaSQL := 'select '+ 'P.GTIN, P.DESCRICAO_PDV, U.NOME, VD.QUANTIDADE, VD.TOTAL_ITEM, VD.BASE_ICMS, VD.CST, VD.ICMS, VD.TAXA_ICMS '+ 'from ECF_VENDA_DETALHE VD, PRODUTO P, UNIDADE_PRODUTO U '+ 'where VD.ID_ECF_PRODUTO=P.ID and P.ID_UNIDADE_PRODUTO=U.ID'; try try Lista60D := TObjectList<TSintegra60DVO>.Create; Query := TSQLQuery.Create(nil); Query.SQLConnection := FDataModule.Conexao; Query.sql.Text := ConsultaSQL; Query.Open; Query.First; while not Query.Eof do begin Sintegra60D := TSintegra60DVO.Create; Sintegra60D.GTIN := Query.FieldByName('GTIN').AsString; Sintegra60D.Descricao := Query.FieldByName('DESCRICAO_PDV').AsString; Sintegra60D.SiglaUnidade := Query.FieldByName('NOME').AsString; Sintegra60D.Quantidade := Query.FieldByName('QUANTIDADE').AsFloat; Sintegra60D.ValorLiquido := Query.FieldByName('TOTAL_ITEM').AsFloat; Sintegra60D.BaseICMS := Query.FieldByName('BASE_ICMS').AsFloat; Sintegra60D.SituacaoTributaria := Query.FieldByName('CST').AsString; Sintegra60D.ValorICMS := Query.FieldByName('ICMS').AsFloat; Sintegra60D.AliquotaICMS := Query.FieldByName('TAXA_ICMS').AsFloat; Lista60D.Add(Sintegra60D); Query.next; end; result := Lista60D; except result := nil; end; finally Query.Free; end; end; end.
unit PascalCoin.RPC.API; interface uses System.JSON, PascalCoin.RPC.Interfaces, PascalCoin.Utils.Interfaces; type TPascalCoinAPI = class(TInterfacedObject, IPascalCoinAPI) private FClient: IPascalCoinRPCClient; FLastError: string; FTools: IPascalCoinTools; FNodeStatus: IPascalCoinNodeStatus; FLastStatusPoll: TDateTime; FNodeAvailability: TNodeAvailability; function PublicKeyParam(const AKey: String; const AKeyStyle: TKeyStyle) : TParamPair; protected function GetNodeURI: String; procedure SetNodeURI(const Value: String); function URI(const Value: string): IPascalCoinAPI; function GetCurrentNodeStatus: IPascalCoinNodeStatus; function GetLastError: String; function GetNodeAvailability: TNodeAvailability; function GetIsTestNet: Boolean; function GetJSONResult: TJSONValue; function GetJSONResultStr: string; function getaccount(const AAccountNumber: Cardinal): IPascalCoinAccount; function getwalletaccounts(const APublicKey: String; const AKeyStyle: TKeyStyle; const AMaxCount: Integer = -1) : IPascalCoinAccounts; function getwalletaccountscount(const APublicKey: String; const AKeyStyle: TKeyStyle): Integer; function getblock(const BlockNumber: Integer): IPascalCoinBlock; function nodestatus: IPascalCoinNodeStatus; function payloadEncryptWithPublicKey(const APayload: string; const AKey: string; const AKeyStyle: TKeyStyle): string; function getaccountoperations(const AAccount: Cardinal; const ADepth: Integer = 100; const AStart: Integer = 0; const AMax: Integer = 100): IPascalCoinList<IPascalCoinOperation>; function executeoperation(const RawOperation: string): IPascalCoinOperation; property JSONResult: TJSONValue read GetJSONResult; public constructor Create(AClient: IPascalCoinRPCClient; ATools: IPascalCoinTools); end; implementation uses System.SysUtils, System.DateUtils, REST.JSON, PascalCoin.RPC.Account, PascalCoin.RPC.Node, PascalCoin.KeyTool, PascalCoin.Utils.Classes, PascalCoin.RPC.Operation; { TPascalCoinAPI } function TPascalCoinAPI.executeoperation(const RawOperation: string) : IPascalCoinOperation; begin if FClient.RPCCall('executeoperations', [TParamPair.Create('rawoperations', RawOperation)]) then begin result := TJSON.JsonToObject<TPascalCoinOperation>((GetJSONResult as TJSONObject)); end else begin raise ERPCException.Create(FClient.ResultStr); end; end; function TPascalCoinAPI.getaccount(const AAccountNumber: Cardinal) : IPascalCoinAccount; begin if FClient.RPCCall('getaccount', [TParamPair.Create('account', AAccountNumber)]) then begin result := TJSON.JsonToObject<TPascalCoinAccount> ((GetJSONResult as TJSONObject)); end else begin raise ERPCException.Create(FClient.ResultStr); end; end; function TPascalCoinAPI.getaccountoperations(const AAccount: Cardinal; const ADepth: Integer = 100; const AStart: Integer = 0; const AMax: Integer = 100): IPascalCoinList<IPascalCoinOperation>; var lVal: TJSONValue; lOps: TJSONArray; lOp: IPascalCoinOperation; begin if FClient.RPCCall('getaccountoperations', [TParamPair.Create('account', AAccount), TParamPair.Create('depth', ADepth), TParamPair.Create('start', AStart), TParamPair.Create('max', AMax)]) then begin result := TPascalCoinList<IPascalCoinOperation>.Create; lOps := (GetJSONResult as TJSONArray); for lVal in lOps do begin lOp := TPascalCoinOperation.CreateFromJSON(lVal); result.Add(lOp); end; end else begin raise ERPCException.Create(FClient.ResultStr); end; end; function TPascalCoinAPI.getblock(const BlockNumber: Integer): IPascalCoinBlock; begin // if True then end; function TPascalCoinAPI.GetCurrentNodeStatus: IPascalCoinNodeStatus; begin if (not Assigned(FNodeStatus)) or (MinutesBetween(Now, FLastStatusPoll) > 5) then begin try FNodeStatus := Self.nodestatus; FNodeAvailability := TNodeAvailability.Avaialable; FLastStatusPoll := Now; except on E: Exception do begin FNodeAvailability := TNodeAvailability.NotAvailable; FLastError := E.Message; Result := Nil; end; end; end; result := FNodeStatus; end; function TPascalCoinAPI.GetIsTestNet: Boolean; begin Result := FNodeStatus.version.Contains('TESTNET'); end; function TPascalCoinAPI.GetJSONResult: TJSONValue; begin result := (TJSONObject.ParseJSONValue(FClient.ResultStr) as TJSONObject) .GetValue('result'); end; function TPascalCoinAPI.GetJSONResultStr: string; begin result := FClient.ResultStr; end; function TPascalCoinAPI.GetLastError: String; begin result := FLastError; end; function TPascalCoinAPI.GetNodeAvailability: TNodeAvailability; begin result := FNodeAvailability; end; function TPascalCoinAPI.GetNodeURI: String; begin result := FClient.NodeURI; end; function TPascalCoinAPI.getwalletaccounts(const APublicKey: String; const AKeyStyle: TKeyStyle; const AMaxCount: Integer): IPascalCoinAccounts; var lAccounts: TJSONArray; lAccount: TJSONValue; lMax: Integer; begin if AMaxCount = -1 then lMax := MaxInt else lMax := AMaxCount; if FClient.RPCCall('getwalletaccounts', [PublicKeyParam(APublicKey, AKeyStyle), TParamPair.Create('max', lMax)]) then begin result := TPascalCoinAccounts.Create; lAccounts := (GetJSONResult as TJSONArray); for lAccount in lAccounts do result.AddAccount(TJSON.JsonToObject<TPascalCoinAccount> ((lAccount as TJSONObject))); end else raise ERPCException.Create(FClient.ResultStr); end; function TPascalCoinAPI.getwalletaccountscount(const APublicKey: String; const AKeyStyle: TKeyStyle): Integer; begin if FClient.RPCCall('getwalletaccountscount', PublicKeyParam(APublicKey, AKeyStyle)) then result := GetJSONResult.AsType<Integer> else raise ERPCException.Create(FClient.ResultStr); end; function TPascalCoinAPI.nodestatus: IPascalCoinNodeStatus; begin result := nil; if FClient.RPCCall('nodestatus', []) then begin result := TPascalCoinNodeStatus.Create(GetJSONResult); end else raise ERPCException.Create(FClient.ResultStr); end; function TPascalCoinAPI.payloadEncryptWithPublicKey(const APayload, AKey: string; const AKeyStyle: TKeyStyle): string; begin if FClient.RPCCall('payloadencrypt', [TParamPair.Create('payload', APayload), TParamPair.Create('payload_method', 'pubkey'), PublicKeyParam(AKey, AKeyStyle)]) then result := GetJSONResult.AsType<string> else raise ERPCException.Create(FClient.ResultStr); end; function TPascalCoinAPI.PublicKeyParam(const AKey: String; const AKeyStyle: TKeyStyle): TParamPair; const _KeyType: Array [Boolean] of String = ('b58_pubkey', 'enc_pubkey'); begin case AKeyStyle of ksUnkown: result := TParamPair.Create(_KeyType[FTools.IsHexaString(AKey)], AKey); ksEncKey: result := TParamPair.Create('enc_pubkey', AKey); ksB58Key: result := TParamPair.Create('b58_pubkey', AKey); end; end; procedure TPascalCoinAPI.SetNodeURI(const Value: String); begin FClient.NodeURI := Value; GetCurrentNodeStatus; end; function TPascalCoinAPI.URI(const Value: string): IPascalCoinAPI; begin SetNodeURI(Value); result := Self; end; constructor TPascalCoinAPI.Create(AClient: IPascalCoinRPCClient; ATools: IPascalCoinTools); begin inherited Create; FClient := AClient; // FConfig := AConfig; FTools := ATools; end; end.
unit Dialogs4D.Input; interface uses Dialogs4D.Input.Intf; type TDialogInput = class(TInterfacedObject, IDialogInput) private /// <summary> /// Displays a dialog box for the user with an input box. /// </summary> /// <param name="Description"> /// Input box description. /// </param> /// <param name="Default"> /// Default value for the input box. /// </param> /// <returns> /// User defined value. /// </returns> function Show(const Description, Default: string): string; end; implementation uses {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} UniGuiDialogs, UniGuiTypes, {$ELSEIF DEFINED(MSWINDOWS)} Vcl.Dialogs, Vcl.Forms, Vcl.BlockUI.Intf, Vcl.BlockUI, {$ENDIF} System.SysUtils, Dialogs4D.Constants; {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} function TDialogInput.Show(const Description, Default: string): string; var UserValue: string; begin UserValue := Default; Prompt(Description, Default, mtInformation, [mbOk], UserValue, False); Result := UserValue; end; {$ELSEIF DEFINED(MSWINDOWS)} function TDialogInput.Show(const Description, Default: string): string; var BlockUI: IBlockUI; begin BlockUI := TBlockUI.Create(); Result := InputBox(PWideChar(Application.Title), PWideChar(Description), Default); end; {$ELSE} function TDialogInput.Show(const Description, Default: string): string; begin raise Exception.Create(DIRECTIVE_NOT_DEFINED); end; {$ENDIF} end.
unit DyLook; interface uses Windows,Messages,SysUtils,Classes,Controls,StdCtrls,ExtCtrls,Buttons, DB,DBCtrls,IBCustomDataSet,Variants; var DefLookupPause: integer = 500; UseFullSearch: boolean = true; type TDyLookupStyle = set of (lsFiltered,lsAllowScroll,lsAllowScrollOut,lsSQLFilter); TDyOnFilter = procedure (Sender:TObject; const filter:string) of object; TDyQuickLookup = class(TPersistent) private timer:TTimer; dataset:TDataSet; datafield:string; value:string; procedure OnTimer(Sender:TObject); public constructor Create; destructor Destroy; override; procedure Lookup(ds:TDataSet; df:TField; key:char); end; TDyDBLookup = class(TPersistent) private FQuoteChar: char; FState:set of (lsSearch,lsFind,lsScroll); FStyle:TDyLookupStyle; FDataLink:TFieldDataLink; FValue:string; FRecordCount:integer; FOnApply,FOnCancel:TNotifyEvent; Timer:integer; Handle:THandle; FOnFilter:TDyOnFilter; procedure SetDataSource(Value:TDataSource); procedure SetDataField(Value:string); procedure SetControl(Value:TComponent); procedure SetStyle(Value:TDyLookupStyle); function GetDataSource:TDataSource; function GetDataField:string; function GetControl:TComponent; procedure DataChange(Sender:TObject); function GetActive:boolean; procedure SetFilter(value:string); procedure RefreshFilter; public constructor Create(AQuoteChar:char); destructor Destroy; override; procedure LookupPause(Handle:THandle; Pause:integer=0; Timer:integer=1); function Lookup(Value:string):boolean; function LookupValue(Value:string):string; procedure Reset; function DoKey(Key:word; Shift:TShiftState):boolean; property Control:TComponent read GetControl write SetControl; property OnApply:TNotifyEvent read FOnApply write FOnApply; property OnCancel:TNotifyEvent read FOnCancel write FOnCancel; property Style:TDyLookupStyle read FStyle write SetStyle default [lsAllowScroll,lsAllowScrollOut]; property Active:boolean read GetActive; published property DataSource:TDataSource read GetDataSource write SetDataSource; property DataField:string read GetDataField write SetDataField; property RecordCount:integer read FRecordCount write FRecordCount default 8; property OnFilter:TDyOnFilter read FOnFilter write FOnFilter; property QuoteChar:char read FQuoteChar write FQuoteChar; end; TDySQLParser = class private sqlText,sqlOrderBy,sqlWhere:string; pSelect,pWhere,pGroupBy,pOrderBy,pEnd:integer; procedure parse; function GetSQL:string; function GetOrderBy:string; procedure SetOrderBy(value:string); function GetWhere:string; procedure SetWhere(value:string); public constructor Create(const sql:string); function OrderByUpdate(FieldName:string):boolean; overload; function OrderByState(FieldName:string):integer; overload; property OrderBy:String read GetOrderBy write SetOrderBy; property Where:String read GetWhere write SetWhere; property SQL:string read GetSQL; end; implementation //------------------------TDyGridLookup-------------------------------------- constructor TDyQuickLookup.Create; begin timer:=TTimer.Create(nil); timer.Interval:=DefLookupPause; timer.OnTimer:=OnTimer; timer.Enabled:=false; end; destructor TDyQuickLookup.Destroy; begin timer.Free; inherited; end; procedure TDyQuickLookup.OnTimer(Sender:TObject); begin timer.Enabled:=false; if (dataset is TIBCustomDataset) then begin TIBCustomDataset(dataset).LocateNext(datafield,value,[loCaseInsensitive, loPartialKey]); end else begin dataset.Locate(datafield,value,[loCaseInsensitive, loPartialKey]); end; value:=''; end; procedure TDyQuickLookup.Lookup(ds:TDataSet; df:TField; key:char); begin timer.Enabled:=false; dataset:=ds; datafield:=df.FieldName; value:=value+key; timer.Enabled:=true; end; //--------------------------TDyDBLookup-------------------------------------- constructor TDyDBLookup.Create(AQuoteChar:char); begin inherited Create; FQuoteChar := AQuoteChar; FRecordCount:=8; FStyle:=[lsAllowScroll,lsAllowScrollOut]; FDataLink:=TFieldDataLink.Create; FDataLink.OnDataChange:=DataChange; end; destructor TDyDBLookup.Destroy; begin FDataLink.Free; inherited; end; procedure TDyDBLookup.SetDataSource(Value:TDataSource); begin FDataLink.DataSource:=Value; end; function TDyDBLookup.GetDataSource:TDataSource; begin Result:=FDataLink.DataSource; end; procedure TDyDBLookup.SetDataField(Value:string); begin //if FDataLink.FieldName = Value then Exit; FDataLink.FieldName := Value; //if (Control is TControl) and (lsFiltered in FStyle) then TEdit(Control).Text:=''; //if (lsFiltered in FStyle) and (FValue <> '') then RefreshFilter; FValue := ''; end; function TDyDBLookup.GetDataField:string; begin Result:=FDataLink.FieldName; end; procedure TDyDBLookup.SetControl(Value:TComponent); begin FDataLink.Control:=Value; FState:=[]; FValue:=''; end; function TDyDBLookup.GetControl:TComponent; begin Result:=FDataLink.Control; end; procedure TDyDBLookup.SetFilter(value:string); begin if (FValue = value) then exit; FValue := Value; RefreshFilter; end; procedure TDyDBLookup.RefreshFilter; var filter,fname:string; p:integer; function sql_prepare(val: string): string; begin result := FQuoteChar; if UseFullSearch then result := result + '%'; result := result + val + '%' + FQuoteChar; end; begin filter:=''; if FValue<>'' then with FDataLink do begin if Field=nil then FValue:='' else if Field is TDateTimeField then try StrToDate(FValue); except FValue:=''; end else if Field is TIntegerField then try StrToInt(FValue); except FValue:=''; end else if Field is TFloatField then try StrToFloat(FValue); p:=Pos(',',FValue); if (p>0) then FValue[p]:='.'; except FValue:=''; end else if not (Field is TStringField) then begin FValue:=''; end; end; if FValue<>'' then with FDataLink do begin // if lsSQLFilter in FStyle then begin fname:=Field.Origin; if fname='' then fname:=Field.FieldName; if Field is TStringField then filter := 'upper(' + fname + ' collate pxw_cyrl) like ' + sql_prepare(AnsiUpperCase(FValue)) else if Field is TDateTimeField then filter := fname + '=' + FQuoteChar + FValue + FQuoteChar else if Field is TFloatField then filter := fname + '>' + FValue + '-0.00001 and ' + fname + '<' + FValue + '+0.00001' else filter := fname+' like ' + sql_prepare(FValue); end else begin if Field is TStringField then FValue := FValue + '*'; filter := '['+FieldName+'] = ''' + FValue + ''''; end; end; if lsSQLFilter in FStyle then begin if assigned(FOnFilter) then FOnFilter(self,filter); end else begin FDataLink.DataSet.Filter:=filter; FDataLink.DataSet.Filtered:=filter<>''; end; end; procedure TDyDBLookup.SetStyle(Value:TDyLookupStyle); begin if FStyle=Value then Exit; if not(lsFiltered in FStyle) then FValue:=''; FStyle:=Value; Include(FState,lsSearch); try SetFilter(''); if not (lsFiltered in FStyle) and FDataLink.Active and (FDataLink.Field<>nil) then TEdit(Control).Text:=FDataLink.Field.AsString else TEdit(Control).Text:=''; finally Exclude(FState,lsSearch); end; end; procedure TDyDBLookup.DataChange(Sender:TObject); begin if not (Control is TControl) or (lsSearch in FState) or (lsScroll in FState) or not(lsAllowScrollOut in FStyle) or (lsFiltered in FStyle) then Exit; with FDataLink do try Include(FState,lsSearch); if Active and (Field<>nil) then TEdit(Control).Text:=Field.AsString else TEdit(Control).Text:=''; if (Control is TCustomEdit) and TCustomEdit(Control).HandleAllocated then TEdit(Control).SelectAll; finally Exclude(FState,lsSearch); end; end; procedure TDyDBLookup.LookupPause(Handle:THandle; Pause:integer=0; Timer:integer=1); begin if lsSearch in FState then Exit; if Pause<=0 then Pause:=DefLookupPause; KillTimer(self.Handle,self.Timer); self.Handle:=Handle; self.Timer:=Timer; SetTimer(Handle,Timer,Pause,nil); end; function TDyDBLookup.Lookup(Value:string):boolean; var L1,L2:integer; F,S:boolean; V:variant; begin Result:=false; if lsSearch in FState then Exit; KillTimer(Handle,Timer); with FDataLink do try Include(FState,lsSearch); if lsFiltered in FStyle then begin SetFilter(Value); Result:=true; end else if Active and (Field<>nil) then begin F:=true; S:=true; L1:=Length(FValue); L2:=Length(Value); if Field is TDateTimeField then try if (lsFind in FState) and (Value<>FValue) then Exclude(FState,lsFind); S:=false; V:=StrToDate(Value); except V:=Null; end else if Field is TFloatField then try if (lsFind in FState) and (Value<>FValue) then Exclude(FState,lsFind); V:=StrToFloat(Value); except V:=Null; end else begin if Field is TStringField then V:=Copy(Value,1,Field.Size) else V:=Value; if not (lsFind in FState) and (FValue<>'') and (L2>=L1) then F:=FValue<>Copy(Value,1,L1) else if (lsFind in FState) and (Value<>FValue) then Exclude(FState,lsFind); end; if F and not (lsFind in FState) and (AnsiCompareText(Value,Copy(Field.AsString,1,L2))=0) then Include(FState,lsFind); //if F and not (lsFind in FState) then MessageBeep(MB_Ok); if F and ((lsFind in FState) or Dataset.Locate(FieldName,V,[loCaseInsensitive, loPartialKey])) then begin Result:=true; Include(FState,lsFind); if S and (Control is TCustomEdit) then with TEdit(Control) do begin Text:=Field.AsString; SelStart:=L2; SelLength:=Length(Text)-L2; end; end else begin Result:=false; Exclude(FState,lsFind); end; FValue:=Value; end; finally Exclude(FState,lsSearch); end; end; function TDyDBLookup.LookupValue(Value:string):string; begin if (Value<>'') and Lookup(Value) then Result:=FDataLink.Field.AsString else Result:=''; end; function TDyDBLookup.DoKey(Key:word; Shift:TShiftState):boolean; var L:integer; begin Result:=false; if FDataLink.Active and (lsAllowScroll in FStyle) then try Include(FState,lsScroll); case Key of VK_UP: begin FDataLink.Dataset.Prior; Result:=true; end; VK_DOWN: begin FDataLink.Dataset.Next; Result:=true; end; VK_HOME: if ssCtrl in Shift then begin FDataLink.Dataset.First; Result:=true; end; VK_END: if ssCtrl in Shift then begin FDataLink.Dataset.Last; Result:=true; end; VK_PRIOR: begin FDataLink.Dataset.MoveBy(-FRecordCount); Result:=true; end; VK_NEXT: begin FDataLink.Dataset.MoveBy(FRecordCount); Result:=true; end; end; finally Exclude(FState,lsScroll); end; if not Result then case Key of VK_BACK: if FDataLink.Active and(Control is TCustomEdit) and not (lsFiltered in FStyle) then begin with TEdit(Control) do if (SelLength<>0) and (SelStart>0) then begin L:=SelLength; SelStart:=SelStart-1; SelLength:=L+1; end; Result:=true; end; VK_RETURN: if assigned(FOnApply) then begin FOnApply(Control); Result:=true; end; VK_ESCAPE: if assigned(FOnCancel) then begin FOnCancel(Control); Result:=true; end; end; end; function TDyDBLookup.GetActive:boolean; begin with FDataLink do Result:=Active and (Field<>nil); end; procedure TDyDBLookup.Reset; begin try Include(FState,lsScroll); FDataLink.Reset; finally Exclude(FState,lsScroll); end; end; //======================TDySQLParser============================= constructor TDySQLParser.Create(const sql:string); begin sqlText:=sql; parse; end; procedure TDySQLParser.parse; var sql:string; begin sql:=AnsiLowerCase(sqlText); pSelect:=1; pEnd:=length(sqlText)+1; pOrderBy:=pos('order by',sql); if pOrderBy<=0 then pOrderBy:=pEnd; pGroupBy:=pos('group by',sql); if pGroupBy<=0 then pGroupBy:=pOrderBy; pWhere:=pos('where',sql); if pWhere<=0 then pWhere:=pGroupBy; end; function TDySQLParser.GetSQL:string; begin result:=copy(sqlText,pSelect,pWhere-pSelect)+' '+GetWhere+' '+copy(sqlText,pGroupBy,pOrderBy-pGroupBy)+' '+GetOrderBy; end; function TDySQLParser.GetOrderBy:string; begin if sqlOrderBy='' then result:=copy(sqlText,pOrderBy,pEnd-pOrderBy) else Result:=sqlOrderBy; end; procedure TDySQLParser.SetOrderBy(value:string); begin sqlOrderBy:=value; end; function TDySQLParser.GetWhere:string; begin result:=copy(sqlText,pWhere,pGroupBy-pWhere); if sqlWhere<>'' then begin if result<>'' then result:=result+' and ' else result:='where '; result:=result+sqlWhere; end; end; procedure TDySQLParser.SetWhere(value:string); begin sqlWhere:=value; end; function TDySQLParser.OrderByUpdate(FieldName:string):boolean; var N,LS,LF: integer; S: string; begin Result := false; if FieldName = '' then Exit; S := GetOrderBy; N := Pos(' ' + FieldName + ' ', S + ' '); { new } if N > 0 then begin LS := Length(S); LF := Length(FieldName); if (LS < N + LF + 2) or (S[N + LF + 2] = ',') // append desc to order by then begin S := Copy(S, 1, N + LF) + ' desc ' + Copy(S, N +LF + 2, LS) end // remove from order by else begin S := Copy(S, 1, N - 1) + Copy(S, N + LF + 8, LS); LS := Length(S); if S[LS] = ',' then S := Copy(S, 1, LS - 2); end; end else begin // append to order by if S = '' then S:='order by ' + FieldName else S := S + ' , ' + FieldName; end; S := Trim(S); if S = 'order by' then S := ''; { if GetKeyState(VK_CONTROL) and $80 = 0 then begin if N>0 then begin LS:=Length(S); LF:=Length(FieldName); if (LS<N+LF+2) or (S[N+LF+2]=',') then S:=Copy(S,1,N+LF)+' desc '+Copy(S,N+LF+2,LS) else S:=Copy(S,1,N+LF+1)+Copy(S,N+LF+7,LS); LS:=Length(S); if S[LS]=' ' then S:=Copy(S,1,LS-1); end else begin S:='order by '+FieldName; end; end else begin if N>0 then begin LS:=Length(S); LF:=Length(FieldName); if (LS<N+LF+2) or (S[N+LF+2]=',') then S:=Copy(S,1,N-1)+Copy(S,N+LF+3,LS) else S:=Copy(S,1,N-1)+Copy(S,N+LF+8,LS); LS:=Length(S); if S[LS]=',' then S:=Copy(S,1,LS-2) else if S='order by' then S:=''; end else begin if S='' then S:='order by '+FieldName else S:=S+' , '+FieldName; end; end; } SetOrderBy(S); Result:=true; end; function TDySQLParser.OrderByState(FieldName:string):integer; var N,LS,LF:integer; S:string; begin Result:=0; S:=GetOrderBy; if (FieldName='') or (S='') then Exit; N:=Pos(' '+FieldName+' ',S+' '); if N>0 then begin LS:=Length(S); LF:=Length(FieldName); if (LS<N+LF+2) or (S[N+LF+2]=',') then Result:=1 else Result:=-1; end; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC design time setup dialog } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.VCLUI.DesignTimeOptions; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, {$ENDIF} System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, FireDAC.VCLUI.OptsBase, FireDAC.Stan.Intf, FireDAC.Phys.Intf; type TfrmFDGUIxFormsDesignTimeOptions = class(TfrmFDGUIxFormsOptsBase) btnRefreshMetadata: TButton; GroupBox1: TGroupBox; Label2: TLabel; Label3: TLabel; edtCatalog: TEdit; edtSchema: TEdit; GroupBox2: TGroupBox; cbMy: TCheckBox; cbSystem: TCheckBox; cbOther: TCheckBox; GroupBox3: TGroupBox; Label6: TLabel; edtMask: TEdit; GroupBox4: TGroupBox; cbTable: TCheckBox; cbView: TCheckBox; cbSynonym: TCheckBox; cbTempTable: TCheckBox; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; GroupBox5: TGroupBox; cbTraceDT: TCheckBox; GroupBox6: TGroupBox; cbDClickFE: TCheckBox; cbFullName: TCheckBox; procedure btnRefreshMetadataClick(Sender: TObject); public class function Execute: Boolean; end; var GADDTCatalog, GADDTSchema: String; GADDTScope: TFDPhysObjectScopes; GADDTMask: String; GADDTTableKinds: TFDPhysTableKinds; GADDTFullName: Boolean; GADMoniEnabled: Boolean; GADDCFieldsEditor: Boolean; implementation {$R *.dfm} uses FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Comp.Client; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsDesignTimeOptions.btnRefreshMetadataClick(Sender: TObject); begin FDManager.RefreshMetadataCache; end; { --------------------------------------------------------------------------- } class function TfrmFDGUIxFormsDesignTimeOptions.Execute: Boolean; var oOpts: TfrmFDGUIxFormsDesignTimeOptions; oConf: TFDConfigFile; begin oOpts := TfrmFDGUIxFormsDesignTimeOptions.Create(nil); try oOpts.edtCatalog.Text := GADDTCatalog; oOpts.edtSchema.Text := GADDTSchema; oOpts.cbMy.Checked := osMy in GADDTScope; oOpts.cbSystem.Checked := osSystem in GADDTScope; oOpts.cbOther.Checked := osOther in GADDTScope; oOpts.edtMask.Text := GADDTMask; oOpts.cbTable.Checked := tkTable in GADDTTableKinds; oOpts.cbView.Checked := tkView in GADDTTableKinds; oOpts.cbSynonym.Checked := tkSynonym in GADDTTableKinds; oOpts.cbTempTable.Checked := tkTempTable in GADDTTableKinds; oOpts.cbFullName.Checked := GADDTFullName; oOpts.cbTraceDT.Checked := GADMoniEnabled; oOpts.cbDClickFE.Checked := GADDCFieldsEditor; Result := oOpts.ShowModal = mrOk; if Result then begin GADDTCatalog := oOpts.edtCatalog.Text; GADDTSchema := oOpts.edtSchema.Text; GADDTScope := []; if oOpts.cbMy.Checked then Include(GADDTScope, osMy); if oOpts.cbSystem.Checked then Include(GADDTScope, osSystem); if oOpts.cbOther.Checked then Include(GADDTScope, osOther); GADDTMask := oOpts.edtMask.Text; GADDTTableKinds := []; if oOpts.cbTable.Checked then Include(GADDTTableKinds, tkTable); if oOpts.cbView.Checked then Include(GADDTTableKinds, tkView); if oOpts.cbSynonym.Checked then Include(GADDTTableKinds, tkSynonym); if oOpts.cbTempTable.Checked then Include(GADDTTableKinds, tkTempTable); GADDTFullName := oOpts.cbFullName.Checked; GADMoniEnabled := oOpts.cbTraceDT.Checked; GADDCFieldsEditor := oOpts.cbDClickFE.Checked; oConf := TFDConfigFile.Create(False); try oConf.WriteString(S_FD_DesignTime, S_FD_DTCatalog, GADDTCatalog); oConf.WriteString(S_FD_DesignTime, S_FD_DTSchema, GADDTSchema); oConf.WriteInteger(S_FD_DesignTime, S_FD_DTScope, Longword(Pointer(@GADDTScope)^)); oConf.WriteString(S_FD_DesignTime, S_FD_DTMask, GADDTMask); oConf.WriteInteger(S_FD_DesignTime, S_FD_DTTableKinds, Longword(Pointer(@GADDTTableKinds)^)); oConf.WriteBool(S_FD_DesignTime, S_FD_DTFullName, GADDTFullName); oConf.WriteBool(S_FD_DesignTime, S_FD_DTTracing, GADMoniEnabled); oConf.WriteBool(S_FD_DesignTime, S_FD_DTDCFieldsEditor, GADDCFieldsEditor); finally FDFree(oConf); end; end; finally FDFree(oOpts); end; end; { --------------------------------------------------------------------------- } procedure Init; var i: Integer; oConf: TFDConfigFile; begin oConf := TFDConfigFile.Create(True); try if oConf.SectionExists(S_FD_DesignTime) then begin GADDTCatalog := oConf.ReadString(S_FD_DesignTime, S_FD_DTCatalog, ''); GADDTSchema := oConf.ReadString(S_FD_DesignTime, S_FD_DTSchema, ''); i := oConf.ReadInteger(S_FD_DesignTime, S_FD_DTScope, 0); GADDTScope := TFDPhysObjectScopes(Pointer(@i)^); GADDTMask := oConf.ReadString(S_FD_DesignTime, S_FD_DTMask, ''); i := oConf.ReadInteger(S_FD_DesignTime, S_FD_DTTableKinds, 0); GADDTTableKinds := TFDPhysTableKinds(Pointer(@i)^); GADDTFullName := oConf.ReadBool(S_FD_DesignTime, S_FD_DTFullName, True); GADMoniEnabled := oConf.ReadBool(S_FD_DesignTime, S_FD_DTTracing, False); GADDCFieldsEditor := oConf.ReadBool(S_FD_DesignTime, S_FD_DTDCFieldsEditor, False); end else begin GADDTCatalog := ''; GADDTSchema := ''; GADDTScope := [osMy, osOther]; GADDTMask := ''; GADDTTableKinds := [tkSynonym, tkTable, tkView]; GADDTFullName := True; GADMoniEnabled := False; GADDCFieldsEditor := False; end; finally FDFree(oConf); end; end; { --------------------------------------------------------------------------- } initialization Init; end.
unit BrickCamp.Model.IQuestion; interface uses Spring; type IQuestion = interface(IInterface) ['{5ECFEDBD-3635-4CFE-ABBA-F6AF16ECD1A7}'] function GetId: Integer; function GetProductId: Integer; function GetUserId: Integer; function GetText: string; function GetIsOpen: SmallInt; procedure SetProductId(const Value: Integer); procedure SetUserId(const Value: Integer); procedure SetText(const Value: string); procedure SetIsOpen(const Value: SmallInt); end; implementation end.
unit cCampaigns; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, System.SysUtils, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite, FireDAC.Comp.UI; type TCampaigns = class private {private declarations} ConnectionDB : TFDConnection; F_campaignId : Integer; F_name : String; F_description : String; F_master_user_id : Integer; function getCampaignId: Integer; function getDescription: String; function getName: String; function getUserId: Integer; procedure setCampaignId(const Value: Integer); procedure setDescription(const Value: String); procedure setUserId(const Value: Integer); procedure setName(const Value: String); public {public declarations} constructor Create(aConnection:TFDConnection); destructor Destroy; override; function Save : Boolean; function Update : Boolean; function Delete : Boolean; function Select(id:Integer) : Boolean; published property campaignId : Integer read getCampaignId write setCampaignId; property name : String read getName write setName; property description : String read getDescription write setDescription; property userId : Integer read getUserId write setUserId; end; implementation { TCampaigns } {$region 'CONSTRUCTOR AND DESTRUCTOR'} constructor TCampaigns.Create(aConnection:TFDConnection); begin ConnectionDB := aConnection; end; destructor TCampaigns.Destroy; begin inherited; end; {$endregion} {$region 'CRUD'} function TCampaigns.Save: Boolean; var Qry : TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConnectionDB; Qry.SQL.Text := 'INSERT INTO campaign ( '+ 'name, '+ 'description '+ ' ) '+ ' VALUES ( '+ ' :name,'+ ' :description '+ ' )'; Qry.ParamByName('name').AsString := Self.F_name; Qry.ParamByName('description').AsString := Self.F_description; Try ConnectionDB.StartTransaction; Qry.ExecSQL; ConnectionDB.Commit; Except ConnectionDB.Rollback; Result := False; End; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCampaigns.Delete: Boolean; var Qry : TFDQuery; begin if MessageDlg('Delete campaign:' +#13+#13+ 'ID:'+IntToStr(F_campaignId)+#13+ 'Campaign Name: ' +F_name,mtConfirmation,[mbYes, mbNo],0) = MrNo then begin Result := False; Abort; end; try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConnectionDB; Qry.SQL.Text := 'DELETE FROM campaign '+ ' WHERE id=:id '; Qry.ParamByName('id').AsInteger := F_campaignId; Try ConnectionDB.StartTransaction; Qry.ExecSQL; ConnectionDB.Commit; Except Result := False; ConnectionDB.Rollback; End; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCampaigns.Update: Boolean; var Qry : TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConnectionDB; Qry.SQL.Text := 'UPDATE campaign '+ ' SET name=:name, description=:description '+ ' WHERE id=:id '; Qry.ParamByName('id').AsInteger := Self.F_campaignId; Qry.ParamByName('name').AsString := Self.F_name; Qry.ParamByName('description').AsString := Self.F_description; Try ConnectionDB.StartTransaction; Qry.ExecSQL; ConnectionDB.Commit; Except Result := False; ConnectionDB.Rollback; End; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCampaigns.Select(id: Integer): Boolean; var Qry : TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConnectionDB; Qry.SQL.Text := 'SELECT '+ 'c.id, '+ 'c.name, '+ 'c.description, '+ 't.master_user_id, '+ 't.master_username '+ 'FROM '+ 'campaign c '+ 'LEFT JOIN ( '+ 'SELECT '+ 'u.id as master_user_id, '+ 'u.name as master_username,'+ 'uc.campaign_id '+ 'FROM '+ 'user u '+ 'INNER JOIN user_campaign as uc on u.id = uc.user_id '+ 'WHERE '+ 'u.user_type = 1 '+ ') t on c.id = t.campaign_id '+ 'WHERE c.id = :id'; Qry.ParamByName('id').AsInteger := id; Try ConnectionDB.StartTransaction; Qry.Open; Self.F_campaignId := Qry.FieldByName('id').AsInteger; Self.F_name := Qry.FieldByName('name').AsString; Self.F_description := Qry.FieldByName('description').AsString; Self.F_master_user_id := Qry.FieldByName('master_user_id').AsInteger; ConnectionDB.Commit; Except Result := False; ConnectionDB.Rollback; End; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$endregion} {$region 'GETS AND SETS'} function TCampaigns.getCampaignId: Integer; begin Result := Self.F_campaignId; end; function TCampaigns.getDescription: String; begin Result := Self.F_description; end; function TCampaigns.getName: String; begin Result := Self.F_name; end; function TCampaigns.getUserId: Integer; begin Result := Self.F_master_user_id; end; procedure TCampaigns.setCampaignId(const Value: Integer); begin Self.F_campaignId := Value; end; procedure TCampaigns.setDescription(const Value: String); begin Self.F_description := Value; end; procedure TCampaigns.setName(const Value: String); begin Self.F_name := Value; end; procedure TCampaigns.setUserId(const Value: Integer); begin Self.F_master_user_id := Value; end; {$endregion} end.
unit ReadingQuestionFrame; interface uses LTConsts, LTClasses, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfmReadingQuestion = class(TFrame) lbExample1: TLabel; lbExample2: TLabel; lbExample3: TLabel; lbExample4: TLabel; lbSelect: TLabel; Label1: TLabel; lbNumber: TLabel; lbQuestion: TLabel; procedure lbExample1Click(Sender: TObject); procedure lbExample2Click(Sender: TObject); procedure lbExample3Click(Sender: TObject); procedure lbExample4Click(Sender: TObject); private { Private declarations } FQuiz: TLRQuiz; FCorrect: string; FAnswer: string; public { Public declarations } procedure Binding(Quiz: TLRQuiz); function GetTestResultDetail: TTestResultDetail; end; implementation {$R *.dfm} { TfmReadingQuestion } procedure TfmReadingQuestion.Binding(Quiz: TLRQuiz); begin FQuiz := Quiz; lbNumber.Caption := IntToStr(FQuiz.QuizNumber); lbQuestion.Caption := FQuiz.Quiz; lbExample1.Caption := FQuiz.A; lbExample2.Caption := FQuiz.B; lbExample3.Caption := FQuiz.C; lbExample4.Caption := FQuiz.D; lbSelect.Caption := ' '; FAnswer := FQuiz.Answer; end; function TfmReadingQuestion.GetTestResultDetail: TTestResultDetail; begin Result := TTestResultDetail.Create; Result.QuizNumber := FQuiz.QuizNumber; Result.Answer := FCorrect; Result.Section := FQuiz.Kind; if FAnswer = FCorrect then begin Result.Correct := RIGHT; Result.Point := 3; end else begin Result.Correct := WRONG; Result.Point := 0; end; end; procedure TfmReadingQuestion.lbExample1Click(Sender: TObject); begin FCorrect := 'A'; lbSelect.Caption := FCorrect; end; procedure TfmReadingQuestion.lbExample2Click(Sender: TObject); begin FCorrect := 'B'; lbSelect.Caption := FCorrect; end; procedure TfmReadingQuestion.lbExample3Click(Sender: TObject); begin FCorrect := 'C'; lbSelect.Caption := FCorrect; end; procedure TfmReadingQuestion.lbExample4Click(Sender: TObject); begin FCorrect := 'D'; lbSelect.Caption := FCorrect; end; end.
unit oglVector; {$modeswitch typehelpers} interface uses Classes, SysUtils, Dialogs, Clipbrd, dglOpenGL; type TglFloatArray = array of glFloat; TVector2f = array[0..1] of GLfloat; TVector3f = array[0..2] of GLfloat; TVector4f = array[0..3] of GLfloat; TFace3D = array[0..2] of TVector3f; TFace3DArray = array of TFace3D; { TVector2fHelper } TVector2fHelper = type Helper for TVector2f private function GetX: GLfloat; function GetY: GLfloat; procedure SetX(AValue: GLfloat); procedure SetY(AValue: GLfloat); public property x: GLfloat read GetX write SetX; property y: GLfloat read GetY write SetY; procedure Rotate(Winkel: GLfloat); procedure Scale(Ax, Ay: GLfloat); procedure Translate(Ax, Ay: GLfloat); procedure Scale(s: GLfloat); procedure NormalCut; procedure Negate; end; { TVector3fHelper } TVector3fHelper = type Helper for TVector3f private function GetX: GLfloat; function GetY: GLfloat; function GetZ: GLfloat; function Getxy: TVector2f; procedure SetX(AValue: GLfloat); procedure SetY(AValue: GLfloat); procedure SetZ(AValue: GLfloat); procedure SetXY(AValue: TVector2f); public property x: GLfloat read GetX write SetX; property y: GLfloat read GetY write SetY; property z: GLfloat read GetZ write SetZ; property xy: TVector2f read GetXY write SetXY; procedure RotateA(Winkel: GLfloat); procedure RotateB(Winkel: GLfloat); procedure RotateC(Winkel: GLfloat); procedure Scale(Ax, Ay, Az: GLfloat); procedure Scale(s: GLfloat); procedure Translate(Ax, Ay, Az: GLfloat); procedure NormalCut; procedure Negate; procedure FromInt(i: UInt32); procedure WriteVectoren(var Vector: array of TVector3f); // Für Testzwecke procedure WriteVectoren_and_Normal(var Vectoren, Normal: array of TVector3f); end; { TVector4fHelper } TVector4fHelper = type Helper for TVector4f private function GetXYZ: TVector3f; procedure SetXYZ(AValue: TVector3f); public property xyz: TVector3f read GetXYZ write SetXYZ; function ToInt: Uint32; procedure FromInt(i: UInt32); procedure Scale(x, y, z, w: GLfloat); procedure Scale(s: GLfloat); end; function vec2(x, y: GLfloat): TVector2f; function vec3(x, y, z: GLfloat): TVector3f; function vec3(v: TVector2f; z: GLfloat): TVector3f; inline; function vec4(x, y, z, w: GLfloat): TVector4f; overload; function vec4(xyz: TVector3f; w: GLfloat): TVector4f; overload; procedure FaceToNormale(var Face, Normal: array of TFace3D); implementation procedure FaceToNormale(var Face, Normal: array of TFace3D); function GetCrossProduct(P0, P1, P2: TVector3f): TVector3f; var a, b: TVector3f; i: integer; begin for i := 0 to 2 do begin a[i] := P1[i] - P0[i]; b[i] := P2[i] - P0[i]; end; Result[0] := a[1] * b[2] - a[2] * b[1]; Result[1] := a[2] * b[0] - a[0] * b[2]; Result[2] := a[0] * b[1] - a[1] * b[0]; Result.NormalCut; ; end; var i: integer; v: TVector3f; begin if Length(Normal) < Length(Face) then begin ShowMessage('Fehler: Lenght(Normal) <> Length(Face)'); Exit; end; for i := 0 to Length(Face) - 1 do begin v := GetCrossProduct(Face[i, 0], Face[i, 1], Face[i, 2]); Normal[i, 0] := v; Normal[i, 1] := v; Normal[i, 2] := v; end; end; function vec2(x, y: GLfloat): TVector2f; inline; begin Result[0] := x; Result[1] := y; end; function vec3(x, y, z: GLfloat): TVector3f; inline; begin Result[0] := x; Result[1] := y; Result[2] := z; end; function vec3(v: TVector2f; z: GLfloat): TVector3f; inline; begin Result[0] := v[0]; Result[1] := v[1]; Result[2] := z; end; function vec4(x, y, z, w: GLfloat): TVector4f; inline; begin Result[0] := x; Result[1] := y; Result[2] := z; Result[3] := w; end; function vec4(xyz: TVector3f; w: GLfloat): TVector4f; inline; begin Result[0] := xyz[0]; Result[1] := xyz[1]; Result[2] := xyz[2]; Result[3] := w; end; { TVector2fHelper } function TVector2fHelper.GetX: GLfloat; inline; begin Result := Self[0]; end; function TVector2fHelper.GetY: GLfloat; inline; begin Result := Self[1]; end; procedure TVector2fHelper.SetX(AValue: GLfloat); inline; begin Self[0] := AValue; end; procedure TVector2fHelper.SetY(AValue: GLfloat); inline; begin Self[1] := AValue; end; procedure TVector2fHelper.Rotate(Winkel: GLfloat); var x0, y0, c, s: GLfloat; begin c := cos(Winkel); s := sin(Winkel); x0 := Self[0]; y0 := Self[1]; Self[0] := x0 * c - y0 * s; Self[1] := x0 * s + y0 * c; end; procedure TVector2fHelper.Scale(Ax, Ay: GLfloat); inline; begin Self[0] *= Ax; Self[1] *= Ay; end; procedure TVector2fHelper.Scale(s: GLfloat); inline; begin Scale(s, s); end; procedure TVector2fHelper.Translate(Ax, Ay: GLfloat); begin Self[0] += Ax; Self[1] += Ay; end; procedure TVector2fHelper.NormalCut; var i: integer; l: GLfloat; begin l := Sqrt(Sqr(Self[0]) + Sqr(Self[1])); if l = 0 then begin l := 1.0; end; for i := 0 to 1 do begin Self[i] := Self[i] / l; end; end; procedure TVector2fHelper.Negate; inline; begin Self[0] *= (-1); Self[1] *= (-1); end; { TVector3fHelper } function TVector3fHelper.GetX: GLfloat; inline; begin Result := Self[0]; end; function TVector3fHelper.GetY: GLfloat; inline; begin Result := Self[1]; end; function TVector3fHelper.GetZ: GLfloat; inline; begin Result := Self[2]; end; procedure TVector3fHelper.SetX(AValue: GLfloat); inline; begin Self[0] := AValue; end; procedure TVector3fHelper.SetY(AValue: GLfloat); inline; begin Self[1] := AValue; end; procedure TVector3fHelper.SetZ(AValue: GLfloat); inline; begin Self[2] := AValue; end; function TVector3fHelper.Getxy: TVector2f; inline; begin Result[0] := Self[0]; Result[1] := Self[1]; end; procedure TVector3fHelper.SetXY(AValue: TVector2f); inline; begin Self[0] := AValue[0]; Self[1] := AValue[1]; end; procedure TVector3fHelper.RotateA(Winkel: GLfloat); var y0, z0, c, s: GLfloat; begin c := cos(Winkel); s := sin(Winkel); y0 := Self[1]; z0 := Self[2]; Self[1] := y0 * c - z0 * s; Self[2] := y0 * s + z0 * c; end; procedure TVector3fHelper.RotateB(Winkel: GLfloat); var x0, z0, c, s: GLfloat; begin c := cos(Winkel); s := sin(Winkel); x0 := Self[0]; z0 := Self[2]; Self[0] := x0 * c - z0 * s; Self[2] := x0 * s + z0 * c; end; procedure TVector3fHelper.RotateC(Winkel: GLfloat); var x0, y0, c, s: GLfloat; begin c := cos(Winkel); s := sin(Winkel); x0 := Self[0]; y0 := Self[1]; Self[0] := x0 * c - y0 * s; Self[1] := x0 * s + y0 * c; end; procedure TVector3fHelper.Scale(Ax, Ay, Az: GLfloat); begin Self[0] *= Ax; Self[1] *= Ay; Self[2] *= Az; end; procedure TVector3fHelper.Scale(s: GLfloat); inline; begin Scale(s, s, s); end; procedure TVector3fHelper.Translate(Ax, Ay, Az: GLfloat); begin Self[0] += Ax; Self[1] += Ay; Self[2] += Az; end; procedure TVector3fHelper.NormalCut; var i: integer; l: GLfloat; begin l := Sqrt(Sqr(Self[0]) + Sqr(Self[1]) + Sqr(Self[2])); if l = 0 then begin l := 1.0; end; for i := 0 to 2 do begin Self[i] := Self[i] / l; end; end; procedure TVector3fHelper.Negate; var i: integer; begin for i := 0 to 2 do begin Self[i] *= (-1); end; end; procedure TVector3fHelper.FromInt(i: UInt32); begin Self[0] := i div $10000 mod $100 / $FF; Self[1] := i div $100 mod $100 / $FF; Self[2] := i div $1 mod $100 / $FF; end; procedure TVector3fHelper.WriteVectoren(var Vector: array of TVector3f); var i: integer; s: string; function f(f1: GLfloat): string; begin f := FormatFloat('###0.00', f1) + ' '; if Pos('-', f) = 0 then begin f := ' ' + f; end; end; begin s := ''; for i := 0 to Length(Vector) - 1 do begin if i mod 3 = 0 then begin s := s + 'Vectoren:' + #13#10; end; s := s + 'x: ' + f(Vector[i, 0]) + 'y: ' + f(Vector[i, 1]) + 'z: ' + f(Vector[i, 2]); if i mod 3 = 2 then begin s := s + #13#10#13#10; end else begin s := s + ' '; end; end; Clipboard.AsText := s; end; procedure TVector3fHelper.WriteVectoren_and_Normal(var Vectoren, Normal: array of TVector3f); var n, i: integer; s: string; function f(f1: GLfloat): string; begin Result := FormatFloat('###0.00', f1) + ' '; if Pos('-', Result) = 0 then begin Result := ' ' + Result; end; end; begin s := ''; if Length(Vectoren) <> Length(Normal) then begin s := 'Fehler: Ungleiche Anzahl Normale und Vectoren!'; end else begin for i := 0 to (Length(Vectoren) div 3) - 1 do begin n := i * 3; s := s + 'Vectoren:' + #13#10; s := s + 'x: ' + f(Vectoren[n + 0, 0]) + 'y: ' + f(Vectoren[n + 0, 1]) + 'z: ' + f(Vectoren[n + 0, 2]) + ' '; s := s + 'x: ' + f(Vectoren[n + 1, 0]) + 'y: ' + f(Vectoren[n + 1, 1]) + 'z: ' + f(Vectoren[n + 1, 2]) + ' '; s := s + 'x: ' + f(Vectoren[n + 2, 0]) + 'y: ' + f(Vectoren[n + 2, 1]) + 'z: ' + f(Vectoren[n + 2, 2]) + #13#10; s := s + 'Normale:' + #13#10; s := s + 'x: ' + f(Normal[n + 0, 0]) + 'y: ' + f(Normal[n + 0, 1]) + 'z: ' + f(Normal[n + 0, 2]) + ' '; s := s + 'x: ' + f(Normal[n + 1, 0]) + 'y: ' + f(Normal[n + 1, 1]) + 'z: ' + f(Normal[n + 1, 2]) + ' '; s := s + 'x: ' + f(Normal[n + 2, 0]) + 'y: ' + f(Normal[n + 2, 1]) + 'z: ' + f(Normal[n + 2, 2]) + #13#10#13#10; end; end; ShowMessage('Vectoren und Normale' + LineEnding + s); end; { TVector4fHelper } function TVector4fHelper.GetXYZ: TVector3f; inline; begin Result[0] := Self[0]; Result[1] := Self[1]; Result[2] := Self[2]; end; procedure TVector4fHelper.SetXYZ(AValue: TVector3f); inline; begin Self[0] := AValue[0]; Self[1] := AValue[1]; Self[2] := AValue[2]; end; function TVector4fHelper.ToInt: Uint32; function v(s: single): longword; inline; begin Result := Round(s * $FF); end; var i: integer; begin for i := 0 to 3 do begin if Self[i] < 0.0 then begin Self[i] := 0.0; end; if Self[i] > 1.0 then begin Self[i] := 1.0; end; end; Result := v(Self[0]) + v(Self[1]) * $100 + v(Self[2]) * $10000 + v(Self[3]) * $1000000; end; procedure TVector4fHelper.FromInt(i: UInt32); begin Self[0] := i div $10000 mod $100 / $FF; Self[1] := i div $100 mod $100 / $FF; Self[2] := i div $1 mod $100 / $FF; Self[3] := i div $1000000 / $FF; end; procedure TVector4fHelper.Scale(x, y, z, w: GLfloat); inline; begin Self[0] *= x; Self[1] *= y; Self[2] *= z; // Self[3] *= w; end; procedure TVector4fHelper.Scale(s: GLfloat); inline; begin Scale(s, s, s, s); end; end.
unit FrmRange; {$mode objfpc}{$H+} interface uses Controls, Forms, StdCtrls, OriEditors; type TRangeFrm = class(TFrame) fedMax: TOriFloatEdit; fedMin: TOriFloatEdit; labMin: TLabel; labMax: TLabel; private procedure SetMin(const Value: Double); procedure SetMax(const Value: Double); function GetMin: Double; function GetMax: Double; function GetActiveControl: TWinControl; public property Min: Double read GetMin write SetMin; property Max: Double read GetMax write SetMax; property ActiveControl: TWinControl read GetActiveControl; end; implementation {$R *.lfm} procedure TRangeFrm.SetMin(const Value: Double); begin fedMin.Value := Value; end; procedure TRangeFrm.SetMax(const Value: Double); begin fedMax.Value := Value; end; function TRangeFrm.GetMin: Double; begin Result := fedMin.Value; end; function TRangeFrm.GetMax: Double; begin Result := fedMax.Value; end; function TRangeFrm.GetActiveControl: TWinControl; begin Result := fedMin; end; end.
unit WIMHandler; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DateUtils, WIMGAPI, Windows, DOM, XMLRead, XMLWrite, xmlutils, Dialogs; const WIMAGERFIELDS = 'WIMAGERFIELDS'; type WIMContainer = class; WIMImage = class; WIMImageList = class; WIMImageField = class; { WIMContainer } WIMContainer = class(TObject) FFilePath, FTempPath: string; FOpened: boolean; FDesiredAccess, FDisposition, FFlagsAndAttributes, FCompressionType: DWORD; FXMLInfo: TXMLDocument; FImageCount: cardinal; private FHandle: THandle; FImages: WIMImageList; WIMImageNames: TStringList; procedure SetDesiredAccess(NewDesiredAccess: DWORD); procedure SetCompressionType(NewCompressionType: DWORD); procedure SetTempPath(); procedure SetTempPath(NewTempPath: string); procedure SetInformation(NewInformation: TXMLDocument); function GetXMLInformation: string; public property Access: DWORD read FDesiredAccess write SetDesiredAccess; property Compression: DWORD read FCompressionType write SetCompressionType; property TemporaryPath: string read FTempPath write SetTempPath; property Handle: THandle read FHandle; property Info: string read GetXMLInformation; property Images: WIMImageList read FImages; property ImageNames: TStringList read WIMImageNames; property XMLInfo: TXMLDocument read FXMLInfo write SetInformation; property FilePath: string read FFilePath; property Opened: boolean read FOpened; function Open(): boolean; procedure Close(); constructor Create(); constructor Create(SourceFilePath: string); constructor Create(SourceFilePath: string; Overwrite: boolean); destructor Free(); end; { WIMImage } WIMImage = class(TObject) FName, FDescription: string; FIndex, FSize: cardinal; FCreationDate, FModificationDate: SYSTEMTIME; FHandle: THandle; FXMLInfo, FXMLCustomInfo: TXMLDocument; FXMLCustomNode: TDOMNode; FFieldList: TStringList; FContainer: WIMContainer; private procedure SetImageName(NewImageName: string); procedure SetImageDescription(NewImageDescription: string); function GetCustomFields(): TStringList; function GetXMLCustomFields(): TDOMNodeList; procedure UpdateXMLInfo(); public property Name: string read FName write SetImageName; property Description: string read FDescription write SetImageDescription; property Parent: WIMContainer read FContainer write FContainer; property CreationDate: SYSTEMTIME read FCreationDate; property ModificationDate: SYSTEMTIME read FModificationDate; property Size: cardinal read FSize; property CustomFields: TStringList read GetCustomFields; property XMLCustomFields: TDOMNodeList read GetXMLCustomFields; function GetField(FieldName: string): string; procedure SetField(FieldName, FieldValue: string); function GetCustomField(FieldName: string): string; procedure SetCustomField(FieldName, FieldValue: string; Index: integer = 0); procedure AddCustomField(FieldName, FieldValue: string); procedure RenameCustomField(OldFieldName, NewFieldName: string); procedure ClearCustomFields(); procedure Apply(TargetDirectory: string); constructor Create(); constructor Create(CapturedHandle: THandle); constructor Create(CapturedHandle: THandle; NewName, NewDescription: string); destructor Free(); end; WIMImageList = class(TList) private function Get(Index: integer): WIMImage; procedure Put(Index: integer; NewImage: WIMImage); public property Items[Index: integer]: WIMImage read Get write Put; default; function Add(NewImage: WIMImage): integer; destructor Destroy(); override; end; { Used by WIMImage to implement custom fields } WIMImageField = class(THashTable) end; implementation constructor WIMContainer.Create(); begin FFilePath := ''; FTempPath := ''; FOpened := False; Self.FDesiredAccess := WIM_GENERIC_WRITE; Self.FDisposition := WIM_OPEN_EXISTING; Self.FFlagsAndAttributes := WIM_FLAG_VERIFY; Self.Compression := WIM_COMPRESS_NONE; end; constructor WIMContainer.Create(SourceFilePath: string); begin FFilePath := SourceFilePath; FTempPath := FFilePath + '_temp'; FOpened := False; FHandle := 0; Self.FDesiredAccess := WIM_GENERIC_WRITE; Self.FDisposition := WIM_OPEN_ALWAYS; Self.FFlagsAndAttributes := WIM_FLAG_VERIFY; Self.FCompressionType := WIM_COMPRESS_NONE; { Check whether the file exists } if not FileExists(FFilePath) then begin Self.FDisposition := WIM_CREATE_ALWAYS; end; end; { This constructor allows overwriting of any existing WIM file specified by SourceFilePath } constructor WIMContainer.Create(SourceFilePath: string; Overwrite: boolean); begin FFilePath := SourceFilePath; FTempPath := FFilePath + '_temp'; FOpened := False; Self.FDesiredAccess := WIM_GENERIC_WRITE; if Overwrite = True then Self.FDisposition := WIM_CREATE_ALWAYS else Self.FDisposition := WIM_OPEN_ALWAYS; Self.FCompressionType := WIM_COMPRESS_NONE; Self.FFlagsAndAttributes := WIM_FLAG_VERIFY; end; destructor WIMContainer.Free(); begin if FOpened = True then Self.Close; RemoveDir(TemporaryPath); end; function WIMContainer.Open(): boolean; var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer: PWideChar; dwResult, StructSize: DWORD; XMLDataString: TStringStream; ImageNodes: TDOMNodeList; ImageNode, NameNode: TDOMNode; i, ListLength: integer; n: string; ImageHandle: THandle; Image: WIMImage; begin if FOpened = True then begin Result := True; Exit; end; if not FileExists(FFilePath) then begin FOpened := False; end; { Flags must be one of WIM_FLAG_VERIFY or WIM_FLAG_SHAREWRITE } FFlagsAndAttributes := WIM_FLAG_VERIFY; FHandle := WIMCreateFile(StringToOleStr(FFilePath), FDesiredAccess, FDisposition, FFlagsAndAttributes, FCompressionType, @dwResult); if FHandle = 0 then begin raise Exception.Create('In Open method, failed to create file with error: ' + IntToStr(GetLastError())); Result := False; Exit; end; SetTempPath(); FImageCount := WIMGetImageCount(FHandle); StructSize := 0; OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin // throw error message LastError := GetLastError(); { Log the error message } FOpened := False; raise Exception.Create('Failed to get image information with error: ' + IntToStr(LastError)); Exit; end; { The information returned from WIMGetImageInformation is UTF16. PWideChar can be used. Also, Length(ImageInfo) reports as half of StructSize. This is probably normal behavior, because of zero-padding. The $FEFF must precede the XML to be copied via WIMSetImageInformation. } { $FEFF precedes ImageInfoBuffer. Must skip it for successful XML initialization } XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); ReadXMLFile(FXMLInfo, XMLDataString); { Initialize the WIMImageNames list. Though it seems straightforward to look for the 'NAME' tag, that tag may not always be added into the WIM info. In order to handle this scenario, look for the 'IMAGE' tag and for each one, check whether the node contains a 'NAME' tag. If it doesn't, add an empty string to the WIMImageNames list. } WIMImageNames := TStringList.Create(); ImageNodes := FXMLInfo.GetElementsByTagName('IMAGE'); ListLength := FImageCount; if not Assigned(FImages) then begin FImages := WIMImageList.Create(); FImages.Capacity := FImageCount; end; if FImageCount > 0 then begin for i := 0 to FImageCount - 1 do begin ImageNode := ImageNodes.Item[i]; NameNode := ImageNode.FindNode('NAME'); if NameNode = nil then n := '' else n := NameNode.TextContent; WIMImageNames.Add(n); SetTempPath(); try if OperationResult = False then LastError := GetLastError(); ImageHandle := WIMLoadImage(FHandle, i + 1); if ImageHandle = 0 then LastError := GetLastError(); Image := WIMImage.Create(ImageHandle); Image.FContainer := Self; FImages.Add(Image); finally end; end; end; if XMLDataString <> nil then XMLDataString.Free; if ImageInfoBuffer <> nil then LocalFree(HLOCAL(ImageInfoBuffer)); FOpened := True; Result := FOpened; end; procedure WIMContainer.Close(); var OperationResult: boolean; LastError: DWORD; TempDataString: TStringStream; begin if FOpened = True then begin if Assigned(WIMImageNames) then WIMImageNames.Free; if FImages <> nil then begin FImages.Destroy; FImages := nil; end; TempDataString := TStringStream.Create(''); WriteXML(FXMLInfo, TempDataString); if FXMLInfo <> nil then FXMLInfo.Free; if FHandle <> 0 then begin OperationResult := WIMCloseHandle(FHandle); if OperationResult = False then begin raise Exception.Create('In Close, failed to close the WIM Container with error: ' + IntToStr(GetLastError())); end; end; if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to close WIMContainer with error ' + IntToStr(LastError)); end; if DirectoryExists(TemporaryPath) then RemoveDir(TemporaryPath); end; FOpened := False; end; procedure WIMContainer.SetDesiredAccess(NewDesiredAccess: DWORD); begin { Of the four types of access offered by WIMGAPI, WIM_OPEN_EXISTING is the least destructive so default to it } if (NewDesiredAccess <> WIM_GENERIC_READ) and (NewDesiredAccess <> WIM_GENERIC_WRITE) and (NewDesiredAccess <> WIM_GENERIC_MOUNT) then FDesiredAccess := WIM_GENERIC_READ else FDesiredAccess := NewDesiredAccess; end; function WIMContainer.GetXMLInformation: string; var XMLText: TStringStream; begin XMLText := TStringStream.Create(''); WriteXML(FXMLInfo, XMLText); Result := XMLText.DataString; XMLText.Free; end; procedure WIMContainer.SetCompressionType(NewCompressionType: DWORD); begin if (NewCompressionType <> WIM_COMPRESS_NONE) and (NewCompressionType <> WIM_COMPRESS_XPRESS) and (NewCompressionType <> WIM_COMPRESS_LZX) then FCompressionType := WIM_COMPRESS_NONE else FCompressionType := NewCompressionType; end; procedure WIMContainer.SetTempPath(); var OperationResult: boolean; LastError: DWORD; NewTempPath: string; begin { For temporary directory creation, might actually want to create in the defined temp directories } NewTempPath := FFilePath + '_temp'; if not DirectoryExists(NewTempPath) then begin OperationResult := CreateDir(NewTempPath); if OperationResult = False then begin raise Exception.Create('Failed to set a temporary directory for file: ' + FFilePath); Exit; end; end; OperationResult := WIMSetTemporaryPath(FHandle, StringToOleStr(NewTempPath)); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set the temporary path: ' + IntToStr(LastError)); end; end; procedure WIMContainer.SetTempPath(NewTempPath: string); begin FTempPath := NewTempPath; SetTempPath(); end; procedure WIMContainer.SetInformation(NewInformation: TXMLDocument); var OldInfoBuffer, NewInfoBuffer: PWideChar; BufferSize: DWORD; OperationResult: boolean; XMLDataString: TStringStream; begin if not Assigned(NewInformation) then begin raise Exception.Create('NewInformation is not assigned'); end; XMLDataString := TStringStream.Create(''); WriteXML(NewInformation.DocumentElement, XMLDataString); { Clear out the old information } //XMLInfo.Free; ; ReadXMLFile(FXMLInfo, XMLDataString); NewInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); NewInfoBuffer^ := WIM_INFO_MARKER; StrCopy(@NewInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); OperationResult := WIMSetImageInformation(Handle, @NewInfoBuffer, StrLen(NewInfoBuffer) * SizeOf(PWideChar)); if not OperationResult = True then begin raise Exception.Create('Failed to get information for the WIM file'); end; Freememory(NewInfoBuffer); XMLDataString.Free; end; { WIMImage class. This class represents an image within the WIM file. } constructor WIMImage.Create(); begin FContainer := nil; FXMLInfo := nil; FXMLCustomInfo := nil; FXMLCustomNode := nil; FFieldList := nil; FName := ''; FDescription := ''; FHandle := 0; FIndex := 0; FSize := 0; ZeroMemory(@FCreationDate, SizeOf(FCreationDate)); ZeroMemory(@FModificationDate, SizeOf(FModificationDate)); end; constructor WIMImage.Create(CapturedHandle: THandle); begin Self.Create(CapturedHandle, '', ''); end; { By default, WIMGAPI doesn't set Name and Description. These are useful information and ImageX also saves them. Therefore, it's best for our program to add them as well. Name and Description are image-specific; they are found only within the <IMAGE> tags. } constructor WIMImage.Create(CapturedHandle: THandle; NewName, NewDescription: string); var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer: PWideChar; StructSize: DWORD; XMLText: string; TempFileTime: FILETIME; TempSystemTime: SYSTEMTIME; TempStr: string; TempCustomFields: TDOMNodeList; XMLDataString: TStringStream; Node, CustomNode, aNode: TDOMNode; rf: TReplaceFlags; i: integer; begin FContainer := nil; FXMLInfo := nil; FXMLCustomInfo := nil; FXMLCustomNode := nil; FFieldList := nil; FName := ''; FDescription := ''; FHandle := 0; FIndex := 0; FSize := 0; ZeroMemory(@FCreationDate, SizeOf(FCreationDate)); ZeroMemory(@FModificationDate, SizeOf(FModificationDate)); FName := ''; FDescription := ''; FHandle := CapturedHandle; OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to get image information with error ' + IntToStr(LastError)); end; XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); ReadXMLFile(FXMLInfo, XMLDataString); { DocumentElement is the root element. In this case, IMAGE } FIndex := StrToInt(FXMLInfo.DocumentElement.GetAttribute('INDEX')); ZeroMemory(@TempFileTime, SizeOf(TempFileTime)); ZeroMemory(@TempSystemTime, SizeOf(TempSystemTime)); rf := [rfIgnoreCase, rfReplaceAll]; XMLText := FXMLInfo.DocumentElement.FindNode('CREATIONTIME').FindNode( 'HIGHPART').TextContent; TempStr := StringReplace(XMLText, '0x', '$', rf); TempFileTime.dwHighDateTime := StrToInt64(TempStr); XMLText := FXMLInfo.DocumentElement.FindNode('CREATIONTIME').FindNode( 'LOWPART').TextContent; TempStr := StringReplace(XMLText, '0x', '$', rf); TempFileTime.dwLowDateTime := StrToInt64(TempStr); FileTimeToSystemTime(TempFileTime, TempSystemTime); FCreationDate := TempSystemTime; ZeroMemory(@TempFileTime, SizeOf(TempFileTime)); ZeroMemory(@TempSystemTime, SizeOf(TempSystemTime)); XMLText := FXMLInfo.DocumentElement.FindNode('LASTMODIFICATIONTIME').FindNode( 'HIGHPART').TextContent; TempStr := StringReplace(XMLText, '0x', '$', rf); TempFileTime.dwHighDateTime := StrToInt64(TempStr); XMLText := FXMLInfo.DocumentElement.FindNode('LASTMODIFICATIONTIME').FindNode( 'LOWPART').TextContent; TempStr := StringReplace(XMLText, '0x', '$', rf); TempFileTime.dwLowDateTime := StrToInt64(TempStr); FileTimeToSystemTime(TempFileTime, TempSystemTime); FModificationDate := TempSystemTime; FSize := StrToInt(FXMLInfo.DocumentElement.FindNode('TOTALBYTES').TextContent); if Length(NewName) > 0 then Name := NewName else begin Node := FXMLInfo.DocumentElement.FindNode('NAME'); if Node <> nil then FName := Node.TextContent; end; if Length(NewDescription) > 0 then Description := NewDescription else begin Node := FXMLInfo.DocumentElement.FindNode('DESCRIPTION'); if Node <> nil then FDescription := Node.TextContent; end; { TODO: Generate the custom fields list } { NOTE: Moving forward, there should be one WIMAGERFIELDS node } { NOTE: All custom fields are subnodes of the WIMAGERFIELDS node } { Ensure there's only one WIMAGERFIELDS node. Merge together mulitple nodes } CustomNode := FXMLInfo.DocumentElement.FindNode(WIMAGERFIELDS); if Assigned(CustomNode) then begin if Assigned(CustomNode.ChildNodes) then TempCustomFields := CustomNode.ChildNodes; FFieldList := TStringList.Create(); FFieldList.Capacity := TempCustomFields.Length; for i := 0 to TempCustomFields.Length do begin aNode := TempCustomFields.Item[i]; if Assigned(aNode) then begin //FFieldList.Add(aNode.TextContent); end; end; FXMLCustomNode := CustomNode; end; if XMLDataString <> nil then XMLDataString.Free; end; procedure WIMImage.UpdateXMLInfo(); var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer: PWideChar; StructSize: DWORD; XMLDataString: TStringStream; begin OperationResult := False; LastError := 0; ImageInfoBuffer := nil; StructSize := 0; XMLDataString := nil; if Assigned(FXMLInfo) = True then begin FXMLInfo.Free; end; OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to get image information with error ' + IntToStr(LastError)); end; XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); if Assigned(XMLDataString) = True then begin ReadXMLFile(FXMLInfo, XMLDataString); XMLDataString.Free; end else raise Exception.Create('Failed to update XML information'); end; procedure WIMImage.Apply(TargetDirectory: string); var TempBuffer: PWideChar; OperationResult: boolean; RegisterValue: DWORD; begin TempBuffer := StringToOleStr(TargetDirectory); OperationResult := False; RegisterValue := 0; if RegisterValue = INVALID_CALLBACK_VALUE then begin raise Exception.Create('Failed to register callback with error ' + IntToStr(GetLastError())); end; OperationResult := WIMApplyImage(FHandle, TempBuffer, WIM_FLAG_VERIFY); if OperationResult = False then begin raise Exception.Create('Failed to apply the image with error: ' + IntToStr(GetLastError())); end; OperationResult := WIMUnregisterMessageCallback(Parent.Handle, Pointer(RegisterValue)); if OperationResult = False then begin raise Exception.Create('Failed to unregister callback with error: ' + IntToStr(GetLastError())); end; end; destructor WIMImage.Free(); begin if Assigned(FFieldList) = True then FFieldList.Free; if Assigned(FXMLCustomInfo) = True then FXMLCustomInfo.Free; //if Assigned(FXMLCustomNode) = True then // FXMLCustomNode.Free; if Assigned(FXMLInfo) = True then FXMLInfo.Free; if FHandle <> 0 then WIMCloseHandle(FHandle); end; procedure WIMImage.SetImageName(NewImageName: string); begin SetField('NAME', NewImageName); FName := NewImageName; end; procedure WIMImage.SetImageDescription(NewImageDescription: string); begin SetField('DESCRIPTION', NewImageDescription); FDescription := NewImageDescription; end; { WIMager custom fields use the WIMAGERFIELDS node. This node contains other } { nodes, such as those created by the user. } procedure WIMImage.SetField(FieldName, FieldValue: string); var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer, FinalInfoBuffer: PWideChar; StructSize: DWORD; XML: TXMLDocument; XMLDataString: TStringStream; ImageNode, FieldNode: TDOMNode; ReplaceFlag: TReplaceFlags; begin OperationResult := False; LastError := 0; ImageInfoBuffer := nil; FinalInfoBuffer := nil; StructSize := 0; XML := nil; XMLDataString := nil; ImageNode := nil; FieldNode := nil; { The information returned from WIMGetImageInformation is UTF16. Some important things to remember: Pascal doesn't natively support UTF16. Therefore, it is necessary to do conversions. Also, Length(ImageInfo) reports as half of StructSize. This is probably normal behavior, because of zero-padding. The $FEFF must precede the XML to be copied via WIMSetImageInformation. } OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set temp path with error: ' + IntToStr(lastError)); end; XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); ReadXMLFile(XML, XMLDataString); ImageNode := XML.DocumentElement; { FieldName cannot have spaces } if Pos(' ', FieldName) > 0 then begin ReplaceFlag := [rfIgnoreCase, rfReplaceAll]; FieldName := StringReplace(FieldName, ' ', '', ReplaceFlag); end; FieldNode := ImageNode.FindNode(FieldName); if FieldNode = nil then FieldNode := XML.CreateElement(FieldName); FieldNode.TextContent := FieldValue; ImageNode.AppendChild(FieldNode); XMLDataString.Free; XMLDataString := TStringStream.Create(''); WriteXML(ImageNode, XMLDataString); FinalInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); { WIM requires the header, which is $FEFF } FinalInfoBuffer^ := WIM_INFO_MARKER; { Skip over the first element (the Header); don't overwrite it } StrCopy(@FinalInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); OperationResult := WIMSetImageInformation(FHandle, FinalInfoBuffer, StrLen(FinalInfoBuffer) * SizeOf(FinalInfoBuffer)); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set image information with error ' + IntToStr(LastError)); end; if FieldNode <> nil then FieldNode.Free; if ImageNode <> nil then ImageNode.Free; if XML <> nil then XML.Free; if XMLDataString <> nil then XMLDataString.Free; Freememory(FinalInfoBuffer); if ImageInfoBuffer <> nil then LocalFree(HLOCAL(imageInfobuffer)); end; function WIMImage.GetField(FieldName: string): string; var FieldNode: TDOMNode; FieldValue: string; ReplaceFlag: TReplaceFlags; begin FieldNode := nil; FieldValue := ''; { FieldName cannot have spaces } if Pos(' ', FieldName) > 0 then begin ReplaceFlag := [rfIgnoreCase, rfReplaceAll]; FieldName := StringReplace(FieldName, ' ', '', ReplaceFlag); end; FieldNode := FXMLInfo.DocumentElement.FindNode(FieldName); if FieldNode = nil then FieldValue := '' else FieldValue := FieldNode.TextContent; Result := FieldValue; end; { When creating a custom field, WIMager's behavior is specified as creating a node named WIMAGERFIELD which encloses the custom fields. } procedure WIMImage.AddCustomField(FieldName, FieldValue: string); var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer, FinalInfoBuffer: PWideChar; StructSize: DWORD; XML: TXMLDocument; XMLDataString: TStringStream; ImageNode, CustomNode, FieldNode: TDOMNode; ReplaceFlag: TReplaceFlags; begin OperationResult := False; LastError := 0; ImageInfoBuffer := nil; FinalInfoBuffer := nil; StructSize := 0; XML := nil; XMLDataString := nil; ImageNode := nil; CustomNode := nil; FieldNode := nil; { The information returned from WIMGetImageInformation is UTF16. Some important things to remember: Pascal doesn't natively support UTF16. Therefore, it is necessary to do conversions. Also, Length(ImageInfo) reports as half of StructSize. This is probably normal behavior, because of zero-padding. The $FEFF must precede the XML to be copied via WIMSetImageInformation. } OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set temp path with error: ' + IntToStr(lastError)); end; XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); ReadXMLFile(XML, XMLDataString); ImageNode := XML.DocumentElement; CustomNode := ImageNode.FindNode(WIMAGERFIELDS); if Assigned(CustomNode) = False then begin CustomNode := XML.CreateElement(WIMAGERFIELDS); ImageNode.AppendChild(CustomNode); end; { FieldName cannot have spaces } if Pos(' ', FieldName) > 0 then begin ReplaceFlag := [rfIgnoreCase, rfReplaceAll]; FieldName := UpperCase(StringReplace(FieldName, ' ', '', ReplaceFlag)); end; FieldNode := ImageNode.FindNode(FieldName); if FieldNode = nil then FieldNode := XML.CreateElement(UpperCase(FieldName)); FieldNode.TextContent := FieldValue; CustomNode.AppendChild(FieldNode); XMLDataString.Free; XMLDataString := TStringStream.Create(''); WriteXML(ImageNode, XMLDataString); FinalInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); { WIM requires the header, which is $FEFF } FinalInfoBuffer^ := WIM_INFO_MARKER; { Skip over the first element (the Header); don't overwrite it } StrCopy(@FinalInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); OperationResult := WIMSetImageInformation(FHandle, FinalInfoBuffer, StrLen(FinalInfoBuffer) * SizeOf(FinalInfoBuffer)); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set custom field information with error ' + IntToStr(LastError)); end; UpdateXMLInfo(); if FieldNode <> nil then FieldNode.Free; if CustomNode <> nil then CustomNode.Free; if ImageNode <> nil then ImageNode.Free; if XML <> nil then XML.Free; if XMLDataString <> nil then XMLDataString.Free; Freememory(FinalInfoBuffer); if ImageInfoBuffer <> nil then LocalFree(HLOCAL(imageInfobuffer)); end; { Renaming a custom field requires the following: validating the new field name } procedure WIMImage.RenameCustomField(OldFieldName, NewFieldName: string); var OldNode, NewNode: TDOMNode; begin OldNode := FXMLCustomInfo.FindNode(OldFieldName); if Assigned(OldNode) then begin NewNode := FXMLCustomInfo.CreateElement(NewFieldName); NewNode.TextContent := OldNode.TextContent; FXMLCustomInfo.ReplaceChild(NewNode, OldNode); end; raise Exception.Create('Implemented but not tested'); { Apparently, this won't work because the XML info is not being modified } OldNode := FXMLCustomNode.FindNode(OldFieldName); if Assigned(OldNode) then begin NewNode := FXMLCustomNode.OwnerDocument.CreateElement(NewFieldName); NewNode.TextContent := OldNode.TextContent; FXMLCustomNode.ReplaceChild(NewNode, OldNode); //raise Exception.Create('Implemented but not tested'); end; end; procedure WIMImage.ClearCustomFields; var CustomFieldNode: TDOMNode; XML: TStringStream; begin CustomFieldNode := FXMLInfo.DocumentElement.FindNode(WIMAGERFIELDS); if Assigned(CustomFieldNode) then begin FXMLInfo.DocumentElement.RemoveChild(CustomFieldNode); end; XML := TStringStream.Create(''); WriteXML(FXMLInfo, XML); raise Exception.Create('Unimplemented'); end; function WIMImage.GetCustomField(FieldName: string): string; var FieldNode: TDOMNode; FieldValue: string; ReplaceFlag: TReplaceFlags; begin FieldNode := nil; FieldValue := ''; { FieldName cannot have spaces } if Pos(' ', FieldName) > 0 then begin ReplaceFlag := [rfIgnoreCase, rfReplaceAll]; FieldName := StringReplace(FieldName, ' ', '', ReplaceFlag); end; if Assigned(FXMLInfo) = True then begin FXMLCustomNode := FXMLInfo.DocumentElement.FindNode(WIMAGERFIELDS); end; if Assigned(FXMLCustomNode) = True then begin FieldNode := FXMLCustomNode.FindNode(UpperCase(FieldName)); end; if Assigned(FieldNode) = False then FieldValue := '' else FieldValue := FieldNode.TextContent; Result := FieldValue; end; procedure WIMImage.SetCustomField(FieldName, FieldValue: string; Index: integer = 0); var OperationResult: boolean; LastError: DWORD; ImageInfoBuffer, FinalInfoBuffer: PWideChar; StructSize: DWORD; XML: TXMLDocument; XMLDataString: TStringStream; ImageNode, CustomFieldNode, FieldNode: TDOMNode; i: integer; ReplaceFlag: TReplaceFlags; begin OperationResult := False; LastError := 0; ImageInfoBuffer := nil; FinalInfoBuffer := nil; StructSize := 0; XML := nil; XMLDataString := nil; ImageNode := nil; FieldNode := nil; { The information returned from WIMGetImageInformation is UTF16. Some important things to remember: Pascal doesn't natively support UTF16. Therefore, it is necessary to do conversions. Also, Length(ImageInfo) reports as half of StructSize. This is probably normal behavior, because of zero-padding. The $FEFF must precede the XML to be copied via WIMSetImageInformation. } OperationResult := WIMGetImageInformation(FHandle, @ImageInfoBuffer, @StructSize); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set temp path with error: ' + IntToStr(lastError)); end; XMLDataString := TStringStream.Create(WideCharToString(@ImageInfoBuffer[1])); ReadXMLFile(XML, XMLDataString); ImageNode := XML.DocumentElement; { FieldName cannot have spaces } if Pos(' ', FieldName) > 0 then begin ReplaceFlag := [rfIgnoreCase, rfReplaceAll]; FieldName := StringReplace(FieldName, ' ', '', ReplaceFlag); end; { Must start with getting the custom field node } CustomFieldNode := ImageNode.FindNode(WIMAGERFIELDS); if not Assigned(CustomFieldNode) then raise Exception.Create('Failed to retrieve the custom field node'); FieldNode := CustomFieldNode.FindNode(FieldName); if FieldNode = nil then FieldNode := XML.CreateElement(FieldName); FieldNode.TextContent := FieldValue; ImageNode.AppendChild(CustomFieldNode); CustomFieldNode.AppendChild(FieldNode); { Will want to add an index attribute to each of the custom fields } { Doing so will help to identify duplicate fields } { TODO: Find a way to optimize this bit } for i := 0 to CustomFieldNode.ChildNodes.Count - 1 do begin TDOMElement(CustomFieldNode.ChildNodes[i]).SetAttribute('Index', IntToStr(i)); end; XMLDataString.Free; XMLDataString := TStringStream.Create(''); WriteXML(ImageNode, XMLDataString); FinalInfoBuffer := AllocMem(Length(XMLDataString.DataString) * SizeOf(PWideChar)); { WIM requires the header, which is $FEFF } FinalInfoBuffer^ := WIM_INFO_MARKER; { Skip over the first element (the Header); don't overwrite it } StrCopy(@FinalInfoBuffer[1], StringToOleStr(XMLDataString.DataString)); OperationResult := WIMSetImageInformation(FHandle, FinalInfoBuffer, StrLen(FinalInfoBuffer) * SizeOf(FinalInfoBuffer)); if OperationResult = False then begin LastError := GetLastError(); raise Exception.Create('Failed to set image information with error ' + IntToStr(LastError)); end; if FieldNode <> nil then FieldNode.Free; if ImageNode <> nil then ImageNode.Free; if XML <> nil then XML.Free; if XMLDataString <> nil then XMLDataString.Free; Freememory(FinalInfoBuffer); if ImageInfoBuffer <> nil then LocalFree(HLOCAL(imageInfobuffer)); end; { Returns the custom fields' names as a TStringList class } { NOTE: The returned item should always be fresh } function WIMImage.GetCustomFields(): TStringList; var i: integer; s: string; begin if Assigned(FXMLCustomNode) = False then begin FXMLCustomNode := FXMLInfo.FindNode(WIMAGERFIELDS); end; if Assigned(FXMLCustomNode) = True then begin if Assigned(FFieldList) then FFieldList.Clear; for i := 0 to FXMLCustomNode.ChildNodes.Length - 1 do begin FFieldList.Add(FXMLCustomNode.ChildNodes.Item[i].NodeName); end; end; if Assigned(FFieldList) = True then for i := 0 to FFieldList.Count - 1 do s := FFieldList[i]; Result := FFieldList; end; function WIMImage.GetXMLCustomFields(): TDOMNodeList; var FieldName, FieldValue, Index: string; begin if (Assigned(FXMLCustomNode) and Assigned(FXMLCustomNode.ChildNodes)) then begin Result := FXMLCustomNode.ChildNodes; end else Result := nil; end; function WIMImageList.Get(Index: integer): WIMImage; var Image: WIMImage; begin Result := WIMImage(inherited Items[Index]); end; procedure WIMImageList.Put(Index: integer; NewImage: WIMImage); begin inherited Items[Index]; end; function WIMImageList.Add(NewImage: WIMImage): integer; begin Result := inherited Add(NewImage); end; destructor WIMImageList.Destroy(); var i: integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; inherited; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl, ExtCtrls, ID3v1; type TMainForm = class(TForm) DriveList: TDriveComboBox; FolderList: TDirectoryListBox; FileList: TFileListBox; CloseButton: TButton; RemoveButton: TButton; SaveButton: TButton; InfoBevel: TBevel; IconImage: TImage; TagExistsLabel: TLabel; TagVersionLabel: TLabel; TitleLabel: TLabel; ArtistLabel: TLabel; AlbumLabel: TLabel; YearLabel: TLabel; CommentLabel: TLabel; TrackLabel: TLabel; GenreLabel: TLabel; TitleEdit: TEdit; ArtistEdit: TEdit; AlbumEdit: TEdit; TrackEdit: TEdit; YearEdit: TEdit; CommentEdit: TEdit; GenreComboBox: TComboBox; TagExistsValue: TEdit; TagVersionValue: TEdit; procedure CloseButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FileListChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SaveButtonClick(Sender: TObject); procedure RemoveButtonClick(Sender: TObject); private { Private declarations } FileTag: TID3v1; procedure ClearAll; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.ClearAll; begin { Clear all captions } TagExistsValue.Text := ''; TagVersionValue.Text := ''; TitleEdit.Text := ''; ArtistEdit.Text := ''; AlbumEdit.Text := ''; TrackEdit.Text := ''; YearEdit.Text := ''; GenreComboBox.ItemIndex := 0; CommentEdit.Text := ''; end; procedure TMainForm.CloseButtonClick(Sender: TObject); begin { Exit } Close; end; procedure TMainForm.FormCreate(Sender: TObject); var Iterator: Integer; begin { Create object } FileTag := TID3v1.Create; { Fill and initialize genres } GenreComboBox.Items.Add(''); for Iterator := 0 to MAX_MUSIC_GENRES - 1 do GenreComboBox.Items.Add(MusicGenre[Iterator]); { Reset } ClearAll; end; procedure TMainForm.FileListChange(Sender: TObject); begin { Clear captions } ClearAll; if FileList.FileName = '' then exit; if FileExists(FileList.FileName) then { Load tag data } if FileTag.ReadFromFile(FileList.FileName) then if FileTag.Exists then begin { Fill captions } TagExistsValue.Text := 'Yes'; if FileTag.VersionID = TAG_VERSION_1_0 then TagVersionValue.Text := '1.0' else TagVersionValue.Text := '1.1'; TitleEdit.Text := FileTag.Title; ArtistEdit.Text := FileTag.Artist; AlbumEdit.Text := FileTag.Album; TrackEdit.Text := IntToStr(FileTag.Track); YearEdit.Text := FileTag.Year; if FileTag.GenreID < MAX_MUSIC_GENRES then GenreComboBox.ItemIndex := FileTag.GenreID + 1; CommentEdit.Text := FileTag.Comment; end else { Tag not found } TagExistsValue.Text := 'No' else { Read error } ShowMessage('Can not read tag from the file: ' + FileList.FileName) else { File does not exist } ShowMessage('The file does not exist: ' + FileList.FileName); end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin { Free memory } FileTag.Free; end; procedure TMainForm.SaveButtonClick(Sender: TObject); var Value, Code: Integer; begin { Prepare tag data } FileTag.Title := TitleEdit.Text; FileTag.Artist := ArtistEdit.Text; FileTag.Album := AlbumEdit.Text; FileTag.Year := YearEdit.Text; Val(TrackEdit.Text, Value, Code); if (Code = 0) and (Value > 0) then FileTag.Track := Value else FileTag.Track := 0; if GenreComboBox.ItemIndex = 0 then FileTag.GenreID := DEFAULT_GENRE else FileTag.GenreID := GenreComboBox.ItemIndex - 1; FileTag.Comment := CommentEdit.Text; { Save tag data } if (not FileExists(FileList.FileName)) or (not FileTag.SaveToFile(FileList.FileName)) then ShowMessage('Can not save tag to the file: ' + FileList.FileName); FileListChange(Self); end; procedure TMainForm.RemoveButtonClick(Sender: TObject); begin { Delete tag data } if (FileExists(FileList.FileName)) and (FileTag.RemoveFromFile(FileList.FileName)) then ClearAll else ShowMessage('Can not remove tag from the file: ' + FileList.FileName); end; end.
unit Editor; interface {Процедура инциализации редактора } procedure InitEditor(); {Процедура отлова нажатия клавиш в редакторе } procedure HandleInputInEditor(); {Процедура обновления логики редактора } procedure UpdateEditor(dt : integer); {Процедура отрисовки редактора } procedure RenderEditor(); implementation uses GraphABC, GlobalVars, Renderer, UIAssets; type {Запись, которая хранит состояние карты редактора } EditorState = record Map : array[1..20, 1..20] of integer; MapX : word; MapY : word; end; {Вспомогательная запись для алгоритма поиска путей, хранящая координаты } Cell = record X : integer; Y : integer; end; const {Подсостояние при котором редактируется уровень } EditState = 1; {Подсостояние ввода названия карты и сохранения ее } SaveState = 2; var EditModeState : EditorState; CurrentX : integer; //Текущая позиция "курсора" на оси X CurrentY : integer; //Текущая позиция "курсора" на оси Y CurrentBlock : word; //Текущий выбранный блок CurrentUIBlock : word; //Текущий выбранный блок, отображаемый на графическом интерфейсе CurrentState : word; //Текущее подсостояние: EditState или SaveState MapName : string; //Название текущей карты MapCount : integer; //Кол-во всех созданных карт Problems : array[1..5] of string; //Вспомогательная переменная, хранящая ошибки при сохранении карты CountProblem : integer; //Кол-во ошибок {Процедура изменения имени текущей карты } {Параметры: _mapName - имя карты } procedure ChangeMapName(var _mapName : string); begin if (LastChar = VK_BACK) then begin if (Length(_mapName) > 0) then Delete(_mapName, Length(_mapName), 1); end; if ((Chr(LastChar).IsLetter) or (Chr(LastChar).IsDigit)) then begin if (Length(_mapName) < 12) then begin _mapName := _mapName + Chr(LastChar); end; end; end; {Функция, проверяющая есть ли такая карта или нет } {Параметры: _mapName - имя карты } function ContainsMap(_mapName : string) : boolean; var MapFile : Text; Maps : array[1..15] of string; begin Assign(MapFile, 'maps.txt'); Reset(MapFile); MapCount := 0; while (not Eof(MapFile) and (MapCount < 12)) do begin MapCount := MapCount + 1; Readln(MapFile, Maps[MapCount]); end; Close(MapFile); ContainsMap := false; for var i:=1 to MapCount do begin if (_mapName = Maps[i]) then begin ContainsMap := true; exit; end; end; end; {Процедура сохранения текущей карты } {Параметры: _mapName - имя карты } procedure SaveMapWithName(_mapName : string); var MapFile : Text; NewMap : Text; begin Append(MapFile, 'maps.txt'); Write(MapFile, ''); Writeln(MapFile, _mapName); Close(MapFile); Assign(NewMap, 'maps/' + _mapName + '.txt'); Rewrite(NewMap); for var i:=1 to EditModeState.MapY do begin for var j:=1 to EditModeState.MapX do begin Write(NewMap, EditModeState.Map[i, j]); end; Writeln(NewMap); end; Close(NewMap); end; {Фукнция проверки кол-во спавнов игрока и монстров } function CheckCountSpawns() : boolean; var SpawnPlayerCount : integer; SpawnEnemyCount : integer; begin CheckCountSpawns := false; SpawnPlayerCount := 0; SpawnEnemyCount := 0; for var i:=1 to EditModeState.MapY do begin for var j:=1 to EditModeState.MapX do begin case EditModeState.Map[i,j] of 4: SpawnEnemyCount := SpawnEnemyCount + 1; 5: SpawnPlayerCount := SpawnPlayerCount + 1; end; end; end; if (SpawnPlayerCount < 2) or (SpawnPlayerCount > 8) then begin CountProblem:=CountProblem+1; Problems[CountProblem]:='Кол-во спавнов игрока либо меньше 2, либо больше 8.'; end; if (SpawnEnemyCount < 1) or (SpawnEnemyCount > 4) then begin CountProblem:=CountProblem+1; Problems[CountProblem]:='Кол-во спавнов ИИ либо меньше 1, либо больше 4.'; end; if ((SpawnPlayerCount > 1) and (SpawnPlayerCount < 9) and (SpawnEnemyCount > 0) and (SpawnEnemyCount < 5)) then begin CheckCountSpawns := true; end; end; {Процедура проверяющая есть ли путь от одной точки к другой } {Параметры: startPos - начальная позиция } { tatgetPos - конечная позиция } function FindPath(startPos, targetPos : Cell) : boolean; var stop : boolean; NewMap : array[1..20, 1..20] of integer; x, y, step : integer; begin step:=0; stop:=false; for y:=1 to EditModeState.MapY do for x:=1 to EditModeState.MapX do if (EditModeState.Map[y, x] = 1) then NewMap[y, x] := -2 else NewMap[y, x] := -1; NewMap[startPos.Y, startPos.X] := 0; while ((not stop) and (NewMap[targetPos.Y, targetPos.X] = -1)) do begin stop := true; for y:=1 to EditModeState.MapY do for x:=1 to EditModeState.MapX do if (NewMap[y, x] = step) then begin if (y - 1 >= 1) and (NewMap[y - 1, x] <> - 2) and (NewMap[y - 1, x] = -1) then begin stop := false; NewMap[y - 1, x] := step + 1; end; if (y + 1 <= EditModeState.MapY) and (NewMap[y + 1, x] <> - 2) and (NewMap[y + 1, x] = -1) then begin stop := false; NewMap[y + 1, x] := step + 1; end; if (x - 1 >= 1) and (NewMap[y, x - 1] <> - 2) and (NewMap[y, x - 1] = -1) then begin stop := false; NewMap[y, x - 1] := step + 1; end; if (x + 1 <= EditModeState.MapX) and (NewMap[y, x + 1] <> - 2) and (NewMap[y, x + 1] = -1) then begin stop := false; NewMap[y, x + 1] := step + 1; end; end; step:=step+1; end; if (NewMap[targetPos.Y, targetPos.X] <> -1) then begin FindPath := true; end else begin FindPath := false; end; end; {Функция нахождения первого спавна игрока } function FindFirstSpawn() : Cell; var Pose : Cell; begin for var i:=1 to EditModeState.MapY do for var j:=1 to EditModeState.MapX do if (EditModeState.Map[i, j] = 5) then begin Pose.X := j; Pose.Y := i; FindFirstSpawn := Pose; exit; end; end; {Функция проверки, нет ли тупиков между спавнами } function CheckRoads() : boolean; var StartPos : Cell; OtherPos : array[1..11] of Cell; CountOtherPos : integer; begin CountOtherPos := 0; StartPos := FindFirstSpawn(); for var i:=1 to EditModeState.MapY do for var j:=1 to EditModeState.MapX do if ((EditModeState.Map[i, j] = 5) or (EditModeState.Map[i, j] = 4)) then begin if not ((i = StartPos.Y) and (j = StartPos.X)) then begin CountOtherPos:=CountOtherPos + 1; OtherPos[CountOtherPos].X := j; OtherPos[CountOtherPos].Y := i; end; end; CheckRoads := true; for var i:=1 to CountOtherPos do begin if (not FindPath(StartPos, OtherPos[i])) then begin CountProblem:=CountProblem + 1; Problems[CountProblem]:='Не найден путь для ' + i + '-ого спавна. Координаты: (' + StartPos.X + ';' + StartPos.Y + ') и (' + OtherPos[i].X + ';' + OtherPos[i].Y + ')'; CheckRoads := false; exit; end; end; end; {Функция проверки сохраняемой карты на ошибки } function RightMap() : boolean; begin if CheckCountSpawns() then begin if CheckRoads() then begin RightMap := true; end else begin RightMap := false; end; end else begin RightMap := false; end; end; procedure InitEditor; begin MapName:=''; CountProblem:=0; EditModeState.MapX := 15; EditModeState.MapY := 11; CurrentX := 2; CurrentY := 2; CurrentBlock := 0; CurrentUIBlock := 1; CurrentState := EditState; for var i:=1 to EditModeState.MapY do begin for var j:=1 to EditModeState.MapX do begin if ((i = 1) or (j = 1) or (i = EditModeState.MapY) or (j = EditModeState.MapX)) then EditModeState.Map[i, j] := 1 else EditModeState.Map[i, j] := 0; end; end; end; procedure HandleInputInSaveState(); begin if (inputKeys[VK_ENTER]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); CountProblem:=0; if (MapName = '') then begin CountProblem:=CountProblem+1; Problems[CountProblem]:='Пустое имя карты'; end; if (ContainsMap(MapName)) then begin CountProblem:=CountProblem+1; Problems[CountProblem]:='Такая карта уже существует'; end; if ((MapName <> '') and (not ContainsMap(MapName)) and (RightMap())) then begin if (MapCount >= 12) then begin CountProblem:=CountProblem+1; Problems[CountProblem]:='Количество созданых карт максимально'; end else begin SaveMapWithName(MapName); CurrentState := EditState; ChangeState(MenuState); end; end; end; end; if (inputKeys[VK_ESCAPE]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); MapName := ''; CurrentState := EditState; end; end; if (inputKeys[LastChar]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); ChangeMapName(MapName); end; end; end; procedure HandleInputInEditState(); begin if (inputKeys[VK_NumPad1 - 48]) then begin CurrentBlock := 0; CurrentUIBlock := 1; end; if (inputKeys[VK_NumPad2 - 48]) then begin CurrentBlock := 1; CurrentUIBlock := 2; end; if (inputKeys[VK_NumPad3 - 48]) then begin CurrentBlock := 2; CurrentUIBlock := 3; end; if (inputKeys[VK_NumPad4 - 48]) then begin CurrentBlock := 4; CurrentUIBlock := 4; end; if (inputKeys[VK_NumPad5 - 48]) then begin CurrentBlock := 5; CurrentUIBlock := 5; end; if (inputKeys[VK_DOWN] or inputKeys[VK_S]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); if ((CurrentY + 1) < 11) then CurrentY := CurrentY + 1; end; end; if (inputKeys[VK_UP] or inputKeys[VK_W]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); if ((CurrentY - 1) > 1) then CurrentY := CurrentY - 1; end; end; if (inputKeys[VK_RIGHT] or inputKeys[VK_D]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); if ((CurrentX + 1) < 15) then CurrentX := CurrentX + 1; end; end; if (inputKeys[VK_LEFT] or inputKeys[VK_A]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); if ((CurrentX - 1) > 1) then CurrentX := CurrentX - 1; end; end; if (inputKeys[VK_SPACE]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); EditModeState.Map[CurrentY, CurrentX] := CurrentBlock; end; end; if (inputKeys[VK_ENTER]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); CountProblem:=0; CurrentState := SaveState; end; end; if (inputKeys[VK_ESCAPE]) then begin if (Milliseconds() - LastChange > DelayInput) then begin LastChange := Milliseconds(); ChangeState(MenuState); end; end; end; procedure HandleInputInEditor; begin case CurrentState of EditState : begin HandleInputInEditState(); end; SaveState : begin HandleInputInSaveState(); end; end; end; procedure UpdateEditor; begin HandleInputInEditor(); end; procedure RenderInEditMode(); begin Window.Clear(clWhite); RenderGrass(0, 0, 0, TopOffset); for var i:=1 to EditModeState.MapY do begin for var j:=1 to EditModeState.MapX do begin case EditModeState.Map[i, j] of 1: begin RenderIron((j - 1) * 64, (i - 1) * 64, 0, TopOffset); end; 2: begin RenderBrick((j - 1) * 64, (i - 1) * 64, 0, TopOffset); end; 4: begin RenderEnemySpawner((j - 1) * 64, (i - 1) * 64, 0, TopOffset); end; 5: begin RenderPlayerSpawner((j - 1) * 64, (i - 1) * 64, 0, TopOffset); end; end; end; end; SetBrushStyle(bsClear); SetPenColor(clRed); SetPenWidth(5); Rectangle((CurrentX - 1) * 64, CurrentY * 64, (CurrentX - 1) * 64 + 64, CurrentY * 64 + 64); SetFontSize(26); TextOut(4, 16, 'Выбрано: '); RenderGrassBlock(160, 0, 0, 0); DrawTextCentered(160 + 32, 32, '1'); RenderIron(160 + 1 * 74, 0, 0, 0); DrawTextCentered(160 + 32 + 1 * 74, 32, '2'); RenderBrick(160 + 2 * 74, 0, 0, 0); DrawTextCentered(160 + 32 + 2 * 74, 32, '3'); RenderEnemySpawner(160 + 3 * 74, 0, 0, 0); DrawTextCentered(160 + 32 + 3 * 74, 32, '4'); RenderPlayerSpawner(160 + 4 * 74, 0, 0, 0); DrawTextCentered(160 + 32 + 4 * 74, 32, '5'); SetBrushStyle(bsClear); SetPenColor(clBlue); SetPenWidth(5); Rectangle(160 + (CurrentUIBlock - 1) * 74, 0, 160 + (CurrentUIBlock - 1) * 74 + 64, 64); end; procedure RenderInSaveMode(); begin SetBrushStyle(bsSolid); Window.Clear(); Background.Draw(0, 0); DrawLabel(Window.Width div 2, 78, 'Введите название карты'); DrawLabel(Window.Width div 2, 156, 'Чтобы закончить ввод - нажмите Enter.'); SetFontSize(26); DrawChooseLine(0, 220, Window.Width, 40); SetBrushStyle(bsClear); TextOut(Window.Width div 2 - 372, 220, 'Название карты: ' + MapName); for var i:=1 to CountProblem do begin DrawLabel(Window.Width div 2, 234 + 74 * i, Problems[i]); end; end; procedure RenderEditor; begin SetBrushStyle(bsSolid); case CurrentState of EditState : RenderInEditMode(); SaveState : RenderInSaveMode(); end; end; begin end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by Sérgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_IO * Implements generic input/output stream *********************************************************************************************************************** } {$IFDEF OXYGENE} namespace TERRA; {$ELSE} Unit TERRA_IO; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} {$I terra.inc} {$ENDIF} Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} SysUtils, TERRA_Utils; Const // Stream access/permission flags smRead = 1; smWrite = 2; smDynamic = 4; smShared = 8; smAppend = 16; smLargeAlloc = 32; smDefault = 7; //lfRead Or lfWrite or lfDynamic seASCII = 0; seUCS2_LE = 1; seUCS2_BE = 2; seUTF8 = 3; Type Stream = Class(TERRAObject) Protected _Pos:Cardinal; _Size:Cardinal; _Mode:Integer; _Name:AnsiString; _Encoding:Integer; Function GetEOF:Boolean;Virtual; Public Constructor Create(StreamMode:Integer=smDefault); Destructor Destroy; Override; Function Read(Data:Pointer; Length:Cardinal):Cardinal; Virtual; Function Write(Data:Pointer; Length:Cardinal):Cardinal; Virtual; Procedure ReadString(Var S:AnsiString; NullTerminated:Boolean = False);Virtual; Procedure WriteString(S:AnsiString; NullTerminated:Boolean = False);Virtual; Procedure ReadLine(Var S:AnsiString); Virtual; Procedure WriteLine(Const S:AnsiString=''); Virtual; Procedure WriteChars(Const S:AnsiString); Virtual; Procedure ReadLines(Var S:AnsiString); Procedure ReadUnicodeLine(Var S:AnsiString); Procedure WriteUnicodeLine(Const S:AnsiString; Encoding:Integer); Procedure WriteUnicodeChars(Const S:AnsiString; Encoding:Integer); Procedure Copy(Dest:Stream);Overload; Procedure Copy(Dest:Stream;Offset,Count:Integer);Overload; Procedure CopyText(Dest:Stream); Procedure Seek(NewPosition:Cardinal);Virtual; Procedure Skip(Size:Integer);Virtual; Procedure Truncate;Virtual; Property Position:Cardinal Read _Pos Write Seek; Property Size:Cardinal Read _Size; Property Mode:Integer Read _Mode; Property EOF:Boolean Read GetEOF; Property Name:AnsiString Read _Name Write _Name; Property Encoding:Integer Read _Encoding; End; MemoryStream = Class(Stream) Protected _Buffer:PByte; Public Constructor Create(BufferSize:Integer; Buffer:PByte = Nil; StreamMode:Integer=smDefault); Overload; Constructor Create(FileName:AnsiString; StreamMode:Integer=smDefault);Overload; {$IFDEF OXYGENE} Procedure Destroy;Override; {$ELSE} Destructor Destroy;Override; {$ENDIF} Procedure SetBuffer(BufferSize:Integer; Buffer:PByte); Procedure Resize(NewSize:Integer); Function Read(Data:Pointer; Length:Cardinal):Cardinal; Override; Function Write(Data:Pointer; Length:Cardinal):Cardinal; Override; Procedure Truncate;Override; Procedure Seek(NewPosition:Cardinal);Override; Property Buffer:PByte Read _Buffer; End; Implementation Uses TERRA_Error, TERRA_Log, TERRA_Application, TERRA_FileIO, TERRA_OS; // Stream Object Constructor Stream.Create(StreamMode:Integer=smDefault); Begin _Name:=''; _Mode:=StreamMode; _Pos:=0; End; Destructor Stream.Destroy; Begin // do nothing End; Procedure Stream.Copy(Dest:Stream); Var Count,BytesRead:Integer; Buffer:PByte; BufferSize:Integer; BlockSize:Integer; A,B:Integer; Begin Seek(0); Count:=Self.Size; If (Dest.Size-Dest.Position<Count)And(Dest.Mode And smDynamic=0) Then Count:=Dest.Size-Dest.Position; BufferSize:=65534; If Count<BufferSize Then BufferSize:=Count; {$IFDEF OXYGENE} Buffer := new Byte[BufferSize]; {$ELSE} GetMem(Buffer,BufferSize); {$ENDIF} BytesRead:=0; While BytesRead<Count Do Begin A:=Self.Size-Self.Position; B:=Dest.Size-Dest.Position; If Dest.Mode And smDynamic<>0 Then B:=A; BlockSize:=IntMin(IntMin(BufferSize,Count-BytesRead), IntMin(A,B)); Read(Buffer, BlockSize); Dest.Write(Pointer(Buffer), BlockSize); Inc(BytesRead,BlockSize); End; {$IFDEF OXYGENE} Buffer := Nil; {$ELSE} FreeMem(Buffer,BufferSize); {$ENDIF} End; Procedure Stream.Copy(Dest:Stream;Offset,Count:Integer); Var BytesRead:Integer; Buffer:PByte; BufferSize:Integer; BlockSize:Integer; A,B:Integer; Begin Seek(Offset); If (Dest.Size-Dest.Position<Count)And(Dest.Mode And smDynamic=0) Then Count:=Dest.Size-Dest.Position; BufferSize:=65534; If Count<BufferSize Then BufferSize:=Count; {$IFDEF OXYGENE} Buffer := new Byte[BufferSize]; {$ELSE} GetMem(Buffer,BufferSize); {$ENDIF} BytesRead:=0; While BytesRead<Count Do Begin A:=Self.Size-Self.Position; If A=0 Then Begin RaiseError('Buffer too small.'); Exit; End; B:=Dest.Size-Dest.Position; If Dest.Mode And smDynamic<>0 Then B:=A; BlockSize:=IntMin(IntMin(BufferSize,Count-BytesRead), IntMin(A,B)); Read(Buffer, BlockSize); Dest.Write(Pointer(Buffer), BlockSize); Inc(BytesRead,BlockSize); End; {$IFDEF OXYGENE} Buffer := nil; {$ELSE} FreeMem(Buffer,BufferSize); {$ENDIF} End; Procedure Stream.CopyText(Dest:Stream); Var C:AnsiChar; S:AnsiString; Begin S:=''; While Self.Position<Self.Size Do Begin Read(@C, 1); If (C=#10) Then Dest.WriteString(S) Else S:=S+C; End; End; Procedure Stream.Seek(NewPosition:Cardinal); Begin _Pos := NewPosition; End; Procedure Stream.Skip(Size:Integer); Begin If Size=0 Then Exit; Seek(_Pos+Size); End; Procedure Stream.Truncate; Begin Log(logWarning,'IO','Method not supported in this stream.'); End; Function Stream.Read(Data:Pointer; Length:Cardinal):Cardinal; Begin Result := 0; End; Function Stream.Write(Data:Pointer; Length:Cardinal):Cardinal; Begin Result := 0; End; Procedure Stream.ReadString(Var S:AnsiString; NullTerminated:Boolean = False); Var {$IFDEF OXYGENE} C:AnsiChar; I:Integer; {$ENDIF} Len:Word; N:Byte; Begin If (Not NullTerminated) Then Begin Read(@N, 1); If N=255 Then Read(@Len, 2) Else Len:=N; {$IFDEF OXYGENE} If (Len>0) Then S := new String('0', Len) Else S := nil; For I:=0 To (Len-1) Do Begin Read(@C, 1); S[I] := C; End; {$ELSE} SetLength(S,Len); If Len>0 Then Read(@(S[1]),Len); {$ENDIF} End Else Begin S := ''; Repeat Read(@N, 1); If (N=0) Then Break; S := S + Chr(N); Until (False); End; End; Procedure Stream.WriteString(S:AnsiString; NullTerminated:Boolean = False); Var Len:Word; N:Byte; {$IFDEF OXYGENE} I:Integer; C:AnsiChar; {$ENDIF} Begin Len := Length(S); If (NullTerminated) Then Begin {$IFDEF OXYGENE} For I:=0 To (Len-1) Do Begin C := S[I]; Write(Pointer(@C), 1); End; {$ELSE} Write(@S[1], Len); {$ENDIF} N := 0; Write(Pointer(@N), 1); End Else Begin If Len<255 Then N:=Len Else N:=255; Write(Pointer(@N), 1); If Len>=255 Then Write(Pointer(@Len), 2); {$IFDEF OXYGENE} For I:=0 To (Len-1) Do Begin C := S[I]; Write(Pointer(@C), 1); End; {$ELSE} If Len>0 Then Write(@S[1], Len); {$ENDIF} End; End; Procedure Stream.WriteChars(Const S:AnsiString); {$IFDEF OXYGENE} Var C:AnsiChar; I:Integer; {$ENDIF} Begin {$IFDEF OXYGENE} For I:=0 To (S.Length-1) Do Begin C := S[I]; Write(Pointer(@C), 1); End; {$ELSE} Write(@S[1],Length(S)); {$ENDIF} End; Procedure Stream.WriteLine(Const S:AnsiString); Begin WriteChars(S); WriteChars(#13#10); End; Procedure Stream.ReadLine(Var S:AnsiString); Var C:AnsiChar; Begin S:=''; C:=#0; While (C<>#10)And(Position<Size) Do Begin Read(@C, 1); If (C<>#10)Or(C<>#13) Then S:=S+C; End; S:=TrimRight(S); End; Function Stream.GetEOF:Boolean; Begin Result:=Position>=Size; End; Procedure Stream.ReadLines(Var S:AnsiString); Var S2:AnsiString; Begin S := ''; S2 := ''; While Not Self.EOF Do Begin Self.ReadLine(S2); S := S + S2 + CrLf; End; End; Procedure Stream.WriteUnicodeLine(Const S:AnsiString; Encoding: Integer); Begin WriteUnicodeChars(S, Encoding); WriteUnicodeChars(#13#10, Encoding); End; Procedure Stream.WriteUnicodeChars(Const S:AnsiString; Encoding: Integer); Var I:Integer; A,B:Byte; W:Word; Begin Case Encoding Of seASCII: Begin Self.Write(@S[1], Length(S)); End; seUTF8: Begin RaiseError('Write.Unicode.UTF8: Not implemented!'); End; seUCS2_LE: Begin I:=1; While I<=Length(S) Do Begin If (S[I]<#255) Then Begin A := 0; B := Byte(S[I]); Inc(I); End Else Begin Inc(I); A := Byte(S[I]); Inc(I); B := Byte(S[I]); Inc(I); End; W := (A Shl 8) + B; Self.Write(@W, 2); End; End; seUCS2_BE: Begin I:=1; While I<=Length(S) Do Begin If (S[I]<#255) Then Begin A := 0; B := Byte(S[I]); Inc(I); End Else Begin Inc(I); A := Byte(S[I]); Inc(I); B := Byte(S[I]); Inc(I); End; W := (B Shl 8) + A; Self.Write(@W, 2); End; End; End; End; Procedure Stream.ReadUnicodeLine(Var S:AnsiString); Var W:Word; A,B,C:Byte; Procedure GetNextTwoChars(); Begin Self.Read(@W, 2); If (_Encoding = seUCS2_LE) Then Begin B := W And $FF; A := (W Shr 8) And $FF; End Else Begin A := W And $FF; B := (W Shr 8) And $FF; End; End; Begin S := ''; If (Self.Position=0) Then Begin Self.Read(@A, 1); Self.Read(@B, 1); S := Char(A) + Char(B); _Encoding := seASCII; If (A = $FF) And (B = $FE) Then _Encoding := seUCS2_LE Else If (A = $FE) And (B = $FF) Then _Encoding := seUCS2_BE Else If (A = $EF) And (B = $BB) Then Begin Self.Read(@C, 1); If (C = $BF) Then _Encoding := seUTF8; S := S + Char(C); End; If (_Encoding<>seASCII) Then S := ''; End; A := 0; B := 0; While (Not Self.EOF) Do Begin Case _Encoding Of seASCII: Begin Self.Read(@A, 1); If (A = 13) Then Begin Self.Read(@B, 1); If (B<>10) Then Self.Skip(-1); Break; End Else If (A=10) Then Begin Break; End Else S := S + Char(A); End; seUTF8: Begin Self.Read(@A, 1); If (A = 13) Or (A=10) Then Break; If (A<$80) Then Begin S := S + Char(A); Continue; End; If ((A And $E0) = $E0) Then Begin Self.Read(@B, 1); Self.Read(@C, 1); if (B = 0) Or (C = 0) Then Continue; W := ((A And $0F) Shl 12) Or ((B And $3F) Shl 6) Or (C And $3F); B := W And $FF; A := (W Shr 8) And $FF; If (B=13) And (A=0) Then Break Else If (A=0) Then S := S + Char(B) Else S := S + #255+Char(A)+Char(B); Continue; End; If ((A And $C0) = $C0) Then Begin Self.Read(@B, 1); If (B = 0) Then Continue; W := ((A And $1F) Shl 6) Or (B And $3F); B := W And $FF; A := (W Shr 8) And $FF; If (B=13) And (A=0) Then Break Else If (A=0) Then S := S + Char(B) Else S := S + #255+Char(A)+Char(B); End; End; seUCS2_LE, seUCS2_BE: Begin GetNextTwoChars(); If (A=32) And (B=11) Then // invisible space Begin IntToString(2); End Else Begin If (B=13) And (A=0) Then Begin GetNextTwoChars(); If (B=10) And (A=0) Then IntToString(2) Else Self.Skip(-2); Break; End; If (B=10) And (A=0) Then Begin IntToString(2); Break; End; If (A=0) Then S := S + Char(B) Else S := S + #255+Char(A)+Char(B); End; End; End; End; End; // MemoryStream object Constructor MemoryStream.Create(BufferSize:Integer; Buffer:PByte; StreamMode:Integer); Begin _Size := BufferSize; _Pos := 0; { If (StreamMode And smDynamic<>0) Then StreamMode:=StreamMode Xor smDynamic;} If (Buffer = Nil) Then Begin If (StreamMode And smShared<>0) Then StreamMode:=StreamMode Xor smShared; If (_Size>0) Then GetMem(_Buffer, _Size); End Else Begin _Buffer := Buffer; If (StreamMode And smShared=0) Then StreamMode := StreamMode Or smShared; End; Inherited Create(StreamMode); End; Constructor MemoryStream.Create(FileName:AnsiString; StreamMode:Integer=smDefault); Var F:FileStream; Begin Inherited Create(StreamMode); F := FileStream.Open(FileName); _Size := F.Size; Create(_Size, Nil, StreamMode); Log(logDebug, 'IO', 'Loaded memory stream from '+FileName+', size = '+IntToString(_Size)); F.Read(_Buffer, _Size); F.Destroy; _Name := FileName; End; {$IFDEF OXYGENE} Procedure MemoryStream.Destroy; {$ELSE} Destructor MemoryStream.Destroy; {$ENDIF} Begin If (_Mode And smShared=0) And (Assigned(_Buffer)) Then Begin //Log.Write(logDebug,'IO','MemoryStream.Destroy','Releasing '+MemStr(Size)); FreeMem(_Buffer); End; _Size := 0; _Buffer:=Nil; End; Function MemoryStream.Read(Data:Pointer; Length:Cardinal):Cardinal; Var P, P2:PByte; I:Integer; Begin Result := 0; If (Length=0) Then Begin Exit; End; //Log(logDebug,'FileIO', 'Reading '+IntToString(Length)+' bytes from '+Self._Name); If Not Assigned(_Buffer) Then Begin RaiseError('Buffer not assigned.'); Exit; End; If (_Pos>=_Size) Then Begin {$IFDEF PC} RaiseError('Cannot read from memory in '+Self._Name+' ('+IntToString(_Pos)+'/'+IntToString(_Size)+')'); {$ENDIF} FillChar(Data^, Length, 0); Result := 0; Exit; End; If (_Pos+Length>_Size)Then Length:=_Size-_Pos; If (Length<=0) Then Exit; P := _Buffer; Inc(P, _Pos); P2 := PByte(Data); For I:=0 To (Length-1) Do Begin P2^ := P^; Inc(P2); Inc(P); End; Inc(_Pos,Length); Result := Length; End; Function MemoryStream.Write(Data:Pointer; Length:Cardinal):Cardinal; Var I:Integer; P,P2:PByte; NewSize:Integer; Begin Result := 0; If (_Pos+Length>_Size) Then Begin If (_Mode And smDynamic=0) Then Begin RaiseError('Cannot write to memory.'); Exit; End Else Begin If (_Mode And smLargeAlloc<>0) Then NewSize := _Size * 2 Else NewSize := _Size; If (_Size + Length>NewSize) Then NewSize := _Size + Length; Resize(NewSize); End; End; If Not Assigned(_Buffer) Then Begin RaiseError('Buffer not assigned.'); Exit; End; If (_Pos+Length>_Size)Then Length := _Size-_Pos; If (Length<=0) Then Exit; P := _Buffer; Inc(P, _Pos); P2 := PByte(Data); For I:=0 To (Length-1) Do Begin P^ := P2^; Inc(P2); Inc(P); End; Inc(_Pos, Length); Result:=Length; End; Procedure MemoryStream.Seek(NewPosition:Cardinal); Begin If NewPosition>_Size Then Begin RaiseError('Cannot seek in memory.'); Exit; End; _Pos := NewPosition; End; Procedure MemoryStream.Truncate; Var Temp:PByte; Begin Temp := _Buffer; GetMem(_Buffer, _Pos); Move(Temp^, _Buffer^, _Pos); FreeMem(Temp); _Size := _Pos; End; Procedure MemoryStream.Resize(NewSize:Integer); Var I, Min:Integer; Src, Dest:PByte; Ptr:Pointer; Begin If (NewSize = Self.Size) Then Exit; GetMem(Ptr, NewSize); If (Assigned(_Buffer)) And (NewSize>0) Then Begin Src := _Buffer; Dest := Ptr; Min := IntMin(_Size, NewSize); For I:=0 To Pred(Min) Do Begin Dest^ := Src^; Inc(Dest); Inc(Src); End; FreeMem(_Buffer, _Size); End; _Size := NewSize; _Buffer := Ptr; End; Procedure MemoryStream.SetBuffer(BufferSize:Integer;Buffer:PByte); Begin _Size := BufferSize; _Buffer := Buffer; _Pos := 0; End; End.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { Author: Ondrej Pokorny, http://www.kluug.net All Rights Reserved. License: MPL 1.1 / GPLv2 / LGPLv2 / FPC modified LGPLv2 } { OTextReadWrite.pas TOTextReader -> read text from streams with buffer. - very fast thanks to internal string and stream buffer - read from streams with every supported encoding - when reading char-by-char an internal buffer can be used for saving last read keyword etc. TOTextWriter -> write text to a destination stream with buffer. - very fast thanks to internal string buffer - write to streams with every supported encoding } unit Xml.Internal.OTextReadWrite; interface uses System.SysUtils, System.Classes, Xml.Internal.OBufferedStreams; const TEncodingBuffer_FirstElement = 0; type TOTextReader = class(TObject) private fTempString: string; fTempStringPosition: Integer; fTempStringLength: Integer; fTempStringRemain: Integer; fBufferSize: Integer; fStream: TStream; fStreamSize: NativeInt; fStreamPosition: NativeInt; fStreamStartPosition: NativeInt; fOwnsStream: Boolean; fFilePosition: Integer;//current character in file (in character units, not bytes!), 1-based fLinePosition: Integer;//current character in line, 1-based fLine: Integer;//current line in file, 1-based fEncoding: TEncoding; fOwnsEncoding: Boolean; fBOMFound: Boolean; fEOFi: Boolean; //undo support fPreviousChar: Char; fReadFromUndo: Boolean; procedure SetEncoding(const Value: TEncoding); function GetApproxStreamPosition: NativeInt; procedure LoadStringFromStream; protected procedure DoCreate(const aBufferSize: Integer); virtual; procedure DoInit(const aNewStream: TStream; const aNewOwnsStream: Boolean; const aDefaultEncoding: TEncoding); virtual; public //create constructor Create(const aBufferSize: Integer = OBUFFEREDSTREAMS_DEFBUFFERSIZE); overload; //create and init constructor Create(const aStream: TStream; const aDefaultEncoding: TEncoding = nil; const aBufferSize: Integer = OBUFFEREDSTREAMS_DEFBUFFERSIZE); overload; destructor Destroy; override; public //The Init* procedures initialize a document for reading. // Please note that the file/stream/... is locked until the end of the // document is reached or you call ReleaseDocument! //aDefaultEncoding - if no BOM is found, use this encoding, // if BOM is found, always the correct encoding from the BOM is used //load document from file // if aForceEncoding<>nil : enforce encoding (<?xml encoding=".."?> is ignored) procedure InitFile(const aFileName: String; const aDefaultEncoding: TEncoding = nil); //load document from file // if aForceEncoding = nil: in encoding specified by the document // if aForceEncoding<>nil : enforce encoding (<?xml encoding=".."?> is ignored) procedure InitStream(const aStream: TStream; const aDefaultEncoding: TEncoding = nil); //loads XML in default unicode encoding: UTF-16 for DELPHI, UTF-8 for FPC procedure InitString(const aString: string); //load document from TBytes buffer // if aForceEncoding = nil: in encoding specified by the document // if aForceEncoding<>nil : enforce encoding (<?xml encoding=".."?> is ignored) procedure InitBuffer(const aBuffer: TBytes; const aDefaultEncoding: TEncoding = nil); //Release the current document (that was loaded with Init*) procedure ReleaseDocument; public //read char-by-char, returns false if EOF is reached function ReadNextChar(var outChar: Char): Boolean; //read text function ReadString(const aMaxChars: Integer; const aBreakAtNewLine: Boolean = False): string; //get text from temp buffer that has been already read // -> it's not assured that some text can be read, use only as extra information // e.g. for errors etc. function ReadPreviousString(const aMaxChars: Integer; const aBreakAtNewLine: Boolean = False): string; //go back 1 char. only 1 undo operation is supported procedure UndoRead; //if your original stream does not allow seeking and you want to change encoding at some point // (e.g. the encoding is read from the text itself) you have to block the temporary buffer procedure BlockFlushTempBuffer; procedure UnblockFlushTempBuffer; public //encoding of the text that is read from the stream // when changing encoding, the stream is always reset to the starting position // and the stream has to be read again property Encoding: TEncoding read fEncoding write SetEncoding; property OwnsEncoding: Boolean read fOwnsEncoding write fOwnsEncoding; //Returns true if BOM was found in the document property BOMFound: Boolean read fBOMFound; //Returns true if end-of-file is reached property EOFi: Boolean read fEOFi; //Approximate byte position in original read stream // exact position cannot be determined because of variable UTF-8 character lengths property ApproxStreamPosition: NativeInt read GetApproxStreamPosition; //Character position in text // -> in Lazarus, the position is always in UTF-8 characters (no way to go around that since Lazarus uses UTF-8). // -> in Delphi the position is always correct property FilePosition: Integer read fFilePosition;//absolute character position in file, 1-based property LinePosition: Integer read fLinePosition;//current character in line, 1-based property Line: Integer read fLine;//current line, 1-based //size of original stream property StreamSize: NativeInt read fStreamSize; end; TOTextWriter = class(TObject) private fTempString: string; fTempStringPosition: Integer; fTempStringLength: Integer; fStream: TStream; fOwnsStream: Boolean; fEncoding: TEncoding; fOwnsEncoding: Boolean; fWriteBOM: Boolean; fBOMWritten: Boolean; procedure WriteStringToStream(const aString: string; const aMaxLength: Integer); procedure SetEncoding(const Value: TEncoding); protected procedure DoCreate(const aBufferSize: Integer); procedure DoInit(const aNewStream: TStream; const aNewOwnsStream: Boolean; const aEncoding: TEncoding; const aWriteBOM: Boolean); public //create constructor Create(const aCharBufferSize: Integer = OBUFFEREDSTREAMS_DEFCHARBUFFERSIZE); overload; //create and init constructor Create(const aStream: TStream; const aEncoding: TEncoding = nil; const aWriteBOM: Boolean = True; const aCharBufferSize: Integer = OBUFFEREDSTREAMS_DEFCHARBUFFERSIZE); overload; destructor Destroy; override; public //The Init* procedures initialize a document for writing. // Please note that the file/stream/... is locked until you destroy // TOTextWriter or call ReleaseDocument! procedure InitFile(const aFileName: String; const aEncoding: TEncoding = nil; const aWriteBOM: Boolean = True); procedure InitStream(const aStream: TStream; const aEncoding: TEncoding = nil; const aWriteBOM: Boolean = True); //Release the current document (that was loaded with Init*) procedure ReleaseDocument; public //write string procedure WriteString(const aString: string); procedure WriteChar(const aChar: Char); //write the whole temporary buffer to the destination stream procedure EnsureTempStringWritten; public //encoding of the resulting stream //the encoding will be used only for new text, old text (that has already //been written with WriteString()) is written with last used encoding property Encoding: TEncoding read fEncoding write SetEncoding; property OwnsEncoding: Boolean read fOwnsEncoding write fOwnsEncoding; //should BOM be written property WriteBOM: Boolean read fWriteBOM write fWriteBOM; end; EOTextReader = class(Exception); //decide what encoding is used in a stream (BOM markers are searched for) // only UTF-8, UTF-16, UTF-16BE can be recognized function GetEncodingFromStream(const aStream: TStream; var {%H-}ioTempStringPosition: NativeInt; const aLastPosition: NativeInt; const {%H-}aDefaultEncoding: TEncoding): TEncoding; implementation {$ZEROBASEDSTRINGS OFF} resourcestring OTextReadWrite_Undo2Times = 'The aStream parameter must be assigned when creating a buffered stream.'; function GetEncodingFromStream(const aStream: TStream; var ioTempStringPosition: NativeInt; const aLastPosition: NativeInt; const aDefaultEncoding: TEncoding): TEncoding; var xSize: Integer; xBuffer: TBytes; xEncoding: TEncoding; begin if aDefaultEncoding <> nil then Result := aDefaultEncoding else Result := TEncoding.Default; xSize := aLastPosition - aStream.Position; if xSize < 2 then Exit;//BOM must be at least 2 characters if xSize > 4 then xSize := 4;//BOM may be up to 4 characters SetLength(xBuffer, xSize); aStream.ReadBuffer(xBuffer[TEncodingBuffer_FirstElement], xSize); xEncoding := nil; ioTempStringPosition := ioTempStringPosition + //TEncoding.GetEncodingFromBOM(xBuffer, xEncoding, Result); TEncoding.GetBufferEncoding(xBuffer, xEncoding, Result); if xEncoding <> nil then Result := xEncoding; if Result = nil then begin if aDefaultEncoding <> nil then Result := aDefaultEncoding else Result := TEncoding.Default; end; aStream.Position := ioTempStringPosition; end; { TOTextReader } procedure TOTextReader.BlockFlushTempBuffer; begin if fStream is TOBufferedReadStream then TOBufferedReadStream(fStream).BlockFlushTempBuffer; end; constructor TOTextReader.Create(const aStream: TStream; const aDefaultEncoding: TEncoding; const aBufferSize: Integer); begin inherited Create; DoCreate(aBufferSize); InitStream(aStream, aDefaultEncoding); end; constructor TOTextReader.Create(const aBufferSize: Integer); begin inherited Create; DoCreate(aBufferSize); end; destructor TOTextReader.Destroy; begin ReleaseDocument; if fOwnsEncoding then fEncoding.Free; inherited; end; procedure TOTextReader.DoCreate(const aBufferSize: Integer); begin fBufferSize := aBufferSize; end; procedure TOTextReader.DoInit(const aNewStream: TStream; const aNewOwnsStream: Boolean; const aDefaultEncoding: TEncoding); var xStreamPosition: Integer; begin fEOFi := False; ReleaseDocument; fStream := aNewStream; fOwnsStream := aNewOwnsStream; fStreamPosition := fStream.Position; fStreamStartPosition := fStreamPosition; fStreamSize := fStream.Size; BlockFlushTempBuffer;//block because GetEncodingFromStream seeks back in stream! try xStreamPosition := fStreamPosition; fEncoding := GetEncodingFromStream(fStream, fStreamPosition, fStreamSize, aDefaultEncoding); fBOMFound := (xStreamPosition < fStreamPosition);//if BOM was found, fStreamPosition increased finally UnblockFlushTempBuffer; end; fOwnsEncoding := not TEncoding.IsStandardEncoding(fEncoding); fTempStringPosition := 1; fTempStringLength := 0; fTempStringRemain := 0; fPreviousChar := #0; fReadFromUndo := False; fFilePosition := 0; fLinePosition := 0; fLine := 1; end; function TOTextReader.GetApproxStreamPosition: NativeInt; begin //YOU CAN'T KNOW IT EXACTLY!!! (due to Lazarus Unicode->UTF8 or Delphi UTF8->Unicode conversion etc.) //the char lengths may differ from one character to another Result := fStreamPosition - fStreamStartPosition + fTempStringPosition; end; procedure TOTextReader.InitBuffer(const aBuffer: TBytes; const aDefaultEncoding: TEncoding); var xLength: Integer; xNewStream: TStream; begin xNewStream := TMemoryStream.Create; xLength := Length(aBuffer); if xLength > 0 then xNewStream.WriteBuffer(aBuffer[0], xLength); xNewStream.Position := 0; DoInit(xNewStream, True, aDefaultEncoding); end; procedure TOTextReader.InitFile(const aFileName: String; const aDefaultEncoding: TEncoding); begin DoInit( TFileStream.Create(aFileName, fmOpenRead or fmShareDenyNone), True, aDefaultEncoding); end; procedure TOTextReader.InitStream(const aStream: TStream; const aDefaultEncoding: TEncoding); begin if (aStream is TCustomMemoryStream) or (aStream is TFileStream) then begin //no need for buffering on memory stream or file stream // buffering is here just because some (custom) streams may not support seeking // which is needed when reading encoding from xml header DoInit(aStream, False, aDefaultEncoding); end else begin //we need to buffer streams that do not support seeking (zip etc.) DoInit( TOBufferedReadStream.Create(aStream, fBufferSize), True, aDefaultEncoding); end; end; procedure TOTextReader.InitString(const aString: string); var xLength: Integer; xNewStream: TStream; begin xNewStream := TMemoryStream.Create; xLength := Length(aString); if xLength > 0 then xNewStream.WriteBuffer(aString[1], xLength * SizeOf(Char)); xNewStream.Position := 0; DoInit(xNewStream, True, nil); Encoding := TEncoding.Unicode; end; procedure TOTextReader.LoadStringFromStream; var xBuffer: TBytes; xUTF8Inc: Integer; xReadBytes: NativeInt; const BS = TEncodingBuffer_FirstElement; begin xReadBytes := fStreamSize-fStreamPosition; if xReadBytes > fBufferSize then xReadBytes := fBufferSize; if xReadBytes = 0 then Exit; SetLength(xBuffer, xReadBytes+5);//5 is maximum UTF-8 increment fStream.ReadBuffer(xBuffer[BS], xReadBytes); if fEncoding is TUTF8Encoding then begin //check if we did not reach an utf-8 character in the middle if ((Ord(xBuffer[BS+xReadBytes-1]) and $80) = $00) then//last byte is 0....... xUTF8Inc := 0 else if ((xReadBytes > 1) and ((Ord(xBuffer[BS+xReadBytes-1]) and $E0) = $C0)) or//110..... -> double char ((xReadBytes > 2) and ((Ord(xBuffer[BS+xReadBytes-2]) and $F0) = $E0)) or//1110.... -> triple char ((xReadBytes > 3) and ((Ord(xBuffer[BS+xReadBytes-3]) and $F8) = $F0)) or//11110... -> 4 char ((xReadBytes > 4) and ((Ord(xBuffer[BS+xReadBytes-4]) and $FC) = $F8)) or//111110.. -> 5 char ((xReadBytes > 5) and ((Ord(xBuffer[BS+xReadBytes-5]) and $FE) = $FC)) //1111110. -> 6 char then xUTF8Inc := 1 else if ((xReadBytes > 1) and ((Ord(xBuffer[BS+xReadBytes-1]) and $F0) = $E0)) or//1110.... -> triple char ((xReadBytes > 2) and ((Ord(xBuffer[BS+xReadBytes-2]) and $F8) = $F0)) or//11110... -> 4 char ((xReadBytes > 3) and ((Ord(xBuffer[BS+xReadBytes-3]) and $FC) = $F8)) or//111110.. -> 5 char ((xReadBytes > 4) and ((Ord(xBuffer[BS+xReadBytes-4]) and $FE) = $FC)) //1111110. -> 6 char then xUTF8Inc := 2 else if ((xReadBytes > 1) and ((Ord(xBuffer[BS+xReadBytes-1]) and $F8) = $F0)) or//11110... -> 4 char ((xReadBytes > 2) and ((Ord(xBuffer[BS+xReadBytes-2]) and $FC) = $F8)) or//111110.. -> 5 char ((xReadBytes > 3) and ((Ord(xBuffer[BS+xReadBytes-3]) and $FE) = $FC)) //1111110. -> 6 char then xUTF8Inc := 3 else if ((xReadBytes > 1) and ((Ord(xBuffer[BS+xReadBytes-1]) and $FC) = $F8)) or//111110.. -> 5 char ((xReadBytes > 2) and ((Ord(xBuffer[BS+xReadBytes-2]) and $FE) = $FC)) //1111110. -> 6 char then xUTF8Inc := 4 else if ((xReadBytes > 1) and ((Ord(xBuffer[BS+xReadBytes-1]) and $FE) = $FC)) //1111110. -> 6 char then xUTF8Inc := 5 else xUTF8Inc := 0;//ERROR ? if xUTF8Inc > 0 then fStream.ReadBuffer(xBuffer[BS+xReadBytes], xUTF8Inc); end else xUTF8Inc := 0; Inc(fStreamPosition, xReadBytes+xUTF8Inc); SetLength(xBuffer, xReadBytes+xUTF8Inc); fTempString := fEncoding.GetString(xBuffer); fTempStringLength := Length(fTempString); fTempStringRemain := fTempStringLength; fTempStringPosition := 1; end; function TOTextReader.ReadNextChar(var outChar: Char): Boolean; begin if fReadFromUndo then begin outChar := fPreviousChar; fReadFromUndo := False; Result := True; Inc(fLinePosition); Inc(fFilePosition); Exit; end; if fTempStringRemain = 0 then LoadStringFromStream; if fTempStringRemain > 0 then begin outChar := fTempString[fTempStringPosition]; case Ord(outChar) of 10: begin if fPreviousChar <> #13 then Inc(fLine); fLinePosition := 0; end; 13: begin fLinePosition := 0; Inc(fLine); end; else Inc(fLinePosition); end; fPreviousChar := outChar; Inc(fTempStringPosition); Dec(fTempStringRemain); Inc(fFilePosition); Result := True; end else begin fEOFi := True; outChar := #0; ReleaseDocument; Result := False; end; end; function TOTextReader.ReadPreviousString(const aMaxChars: Integer; const aBreakAtNewLine: Boolean): string; var xReadChars: Integer; I: Integer; begin xReadChars := fTempStringPosition-1; if xReadChars > aMaxChars then xReadChars := aMaxChars; if xReadChars > 0 then begin Result := Copy(fTempString, fTempStringPosition-xReadChars, xReadChars); if aBreakAtNewLine then for I := Length(Result) downto 1 do case Result[I] of #13, #10: begin //break at last new line if I = Length(Result) then Result := '' else Result := Copy(Result, I+1, Length(Result)-I); Exit; end; end; end else Result := ''; end; function TOTextReader.ReadString(const aMaxChars: Integer; const aBreakAtNewLine: Boolean): string; var I, R: Integer; xC: Char; const cMaxStartBuffer = OBUFFEREDSTREAMS_DEFCHARBUFFERSIZE; begin if aMaxChars <= 0 then begin Result := ''; Exit; end; R := aMaxChars; if aMaxChars > cMaxStartBuffer then R := cMaxStartBuffer; SetLength(Result, R); I := 0; while (I < aMaxChars) and ReadNextChar({%H-}xC) do begin if aBreakAtNewLine then case xC of #10, #13: begin UndoRead; Break; end; end; Inc(I); if R = 0 then begin R := Length(Result); SetLength(Result, Length(Result) + R); end; Result[I] := xC; Dec(R); end; if I < aMaxChars then SetLength(Result, I); end; procedure TOTextReader.ReleaseDocument; begin if fOwnsStream then fStream.Free; fStream := nil; end; procedure TOTextReader.SetEncoding(const Value: TEncoding); begin if fEncoding <> Value then begin//the condition fEncoding <> Value must be here!!! if fOwnsEncoding then fEncoding.Free; fEncoding := Value; fOwnsEncoding := not TEncoding.IsStandardEncoding(fEncoding); //CLEAR ALREADY READ STRING AND GO BACK fStream.Position := fStreamStartPosition; fStreamPosition := fStreamStartPosition; fTempStringLength := 0; fTempStringPosition := 1; fTempStringRemain := 0; end; end; procedure TOTextReader.UnblockFlushTempBuffer; begin if fStream is TOBufferedReadStream then TOBufferedReadStream(fStream).UnblockFlushTempBuffer; end; procedure TOTextReader.UndoRead; begin if fReadFromUndo then raise EOTextReader.Create(OTextReadWrite_Undo2Times); fReadFromUndo := True; Dec(fLinePosition); Dec(fFilePosition); end; { TOTextWriter } constructor TOTextWriter.Create(const aCharBufferSize: Integer); begin inherited Create; DoCreate(aCharBufferSize) end; constructor TOTextWriter.Create(const aStream: TStream; const aEncoding: TEncoding; const aWriteBOM: Boolean; const aCharBufferSize: Integer); begin inherited Create; DoCreate(aCharBufferSize); InitStream(aStream, aEncoding, aWriteBOM); end; destructor TOTextWriter.Destroy; begin ReleaseDocument; if fOwnsEncoding then fEncoding.Free; inherited; end; procedure TOTextWriter.DoCreate(const aBufferSize: Integer); begin fTempStringLength := aBufferSize; SetLength(fTempString, fTempStringLength); fEncoding := TEncoding.Default; fOwnsEncoding := not TEncoding.IsStandardEncoding(fEncoding); fWriteBOM := True; end; procedure TOTextWriter.DoInit(const aNewStream: TStream; const aNewOwnsStream: Boolean; const aEncoding: TEncoding; const aWriteBOM: Boolean); begin ReleaseDocument; fStream := aNewStream; fOwnsStream := aNewOwnsStream; fTempStringPosition := 1; fBOMWritten := False; if aEncoding <> nil then begin Encoding := aEncoding; WriteBOM := aWriteBOM; end; end; procedure TOTextWriter.EnsureTempStringWritten; begin if fTempStringPosition > 1 then begin if fTempStringLength = fTempStringPosition-1 then begin WriteStringToStream(fTempString, -1); end else begin WriteStringToStream(fTempString, fTempStringPosition-1); end; fTempStringPosition := 1; end; end; procedure TOTextWriter.InitFile(const aFileName: String; const aEncoding: TEncoding; const aWriteBOM: Boolean); begin DoInit(TFileStream.Create(aFileName, fmCreate), True, aEncoding, aWriteBOM); end; procedure TOTextWriter.InitStream(const aStream: TStream; const aEncoding: TEncoding; const aWriteBOM: Boolean); begin DoInit(aStream, False, aEncoding, aWriteBOM); end; procedure TOTextWriter.ReleaseDocument; begin if fStream <> nil then EnsureTempStringWritten; if fOwnsStream then fStream.Free; fStream := nil; end; procedure TOTextWriter.SetEncoding(const Value: TEncoding); begin if fEncoding <> Value then begin EnsureTempStringWritten; if fOwnsEncoding then fEncoding.Free; fEncoding := Value; fOwnsEncoding := not TEncoding.IsStandardEncoding(fEncoding); end; end; procedure TOTextWriter.WriteChar(const aChar: Char); begin if fTempStringPosition > fTempStringLength then begin EnsureTempStringWritten;//WRITE TEMP BUFFER end; fTempString[fTempStringPosition] := aChar; Inc(fTempStringPosition); end; procedure TOTextWriter.WriteString(const aString: string); var xStringLength: Integer; begin xStringLength := Length(aString); if xStringLength = 0 then Exit; if fTempStringPosition-1 + xStringLength > fTempStringLength then begin EnsureTempStringWritten;//WRITE TEMP BUFFER end; if xStringLength > fTempStringLength then begin WriteStringToStream(aString, -1); end else begin Move(aString[1], fTempString[fTempStringPosition], xStringLength*SizeOf(Char)); fTempStringPosition := fTempStringPosition + xStringLength; end; end; procedure TOTextWriter.WriteStringToStream(const aString: string; const aMaxLength: Integer); var xBytes: TBytes; xBytesLength: Integer; xBOM: TBytes; begin if fWriteBOM and not fBOMWritten then begin //WRITE BOM xBOM := fEncoding.GetPreamble; if Length(xBOM) > 0 then fStream.WriteBuffer(xBOM[TEncodingBuffer_FirstElement], Length(xBOM)); end; fBOMWritten := True; if aMaxLength < 0 then begin //write complete string xBytes := fEncoding.GetBytes(aString); xBytesLength := Length(xBytes); end else begin //write part of string xBytes := fEncoding.GetBytes(Copy(aString, 1, aMaxLength)); xBytesLength := Length(xBytes); end; if xBytesLength > 0 then fStream.WriteBuffer(xBytes[TEncodingBuffer_FirstElement], xBytesLength); end; end.
{ Vladimir Klimov 1.0 classes for Postgres data access wintarif@narod.ru } unit PostgresClasses; interface uses Windows, libpq_fe, postgres_ext, SyncObjs; const DEFAULT_PORT = '5432'; DEFAULT_HOST = 'localhost'; type TNotifyEvent = procedure(Sender: TObject) of object; IPostgresQuery = interface; IPostgresStmt = interface; PParams = ^TParam; TParam = record nParams:longint; paramTypes: POid; paramValues: PPChars; paramLengths: PIntegers; paramFormats: PIntegers; resultFormat:longint; end; IPostgres = interface(IInterface) procedure Lock; procedure Unlock; function IsConnected: Boolean; function GetConnection: PPGconn; function GetDatabase: string; function GetError: string; function Connect: Boolean; procedure Disconnect; function ExecQuery(const SQL: String): IPostgresQuery; function ExecQueryParams(const SQL: String; params: PParams): IPostgresQuery; function SendQuery(const SQL: String): boolean; function Prepare(const SQL, StmtName: string; params: PParams): IPostgresStmt; function ExecQueryPrepared(const StmtName: string; params: PParams): IPostgresQuery; function GetLastErrorString: string; property Connection: PPGconn read GetConnection; property LastErrorString: string read GetLastErrorString; end; TPostgres = class(TInterfacedObject, IPostgres) private FConnected: boolean; FConnection: PPGconn; FPort: string; FPassword: string; FDatabase: string; FHost: string; FUser: string; FCS: TCriticalSection; FLastErrorString: string; { IPostgres } function IsConnected: Boolean; function GetConnection: PPGconn; function GetDatabase: string; function GetError: string; function GetLastErrorString: string; public constructor Create(const host, port, database, user, password: string); virtual; destructor Destroy; override; { IPostgres } procedure Lock; procedure Unlock; function Connect: Boolean; virtual; procedure Disconnect; virtual; function ExecQuery(const SQL: String): IPostgresQuery; virtual; function ExecQueryParams(const SQL: String; params: PParams): IPostgresQuery; virtual; function SendQuery(const SQL: String): boolean; virtual; function Prepare(const SQL, StmtName: string; params: PParams): IPostgresStmt; virtual; function ExecQueryPrepared(const StmtName: string; params: PParams): IPostgresQuery; virtual; property Connection: PPGconn read GetConnection; property Database: string read FDatabase; property LastErrorString: string read GetLastErrorString; end; IPostgresQuery = interface(IInterface) function GetQueryStatus: ExecStatusType; function GetQueryStatusStr: string; function GetRecordCount: Integer; function GetFieldCount: Integer; function GetValue(row, field: integer): PChar; function GetValueLen(row, field: integer): integer; function GetFieldIndex(const fname: string): integer; function GetValueIsNull(row, field: integer): boolean; property Status: ExecStatusType read GetQueryStatus; property StatusStr: string read GetQueryStatusStr; property FieldCount: Integer read GetFieldCount; property RecordCount: Integer read GetRecordCount; property Value[row, field: Integer]: PChar read GetValue; property ValueLen[row, field: Integer]: integer read GetValueLen; property FieldIndex[const fname: string]: integer read GetFieldIndex; property ValueIsNull[row, field: Integer]: boolean read GetValueIsNull; end; TPostgresQuery = class(TInterfacedObject, IPostgresQuery) private FPPGresult: PPGresult; FParams: PParams; function GetQueryStatus: ExecStatusType; function GetQueryStatusStr: string; function GetRecordCount: Integer; function GetFieldCount: Integer; function GetValue(row, field: integer): PChar; function GetValueLen(row, field: integer): integer; function GetFieldIndex(const fname: string): integer; function GetValueIsNull(row, field: integer): boolean; public constructor Create(APostgres: IPostgres; res: PPGresult; params: PParams); destructor Destroy; override; property Status: ExecStatusType read GetQueryStatus; property StatusStr: string read GetQueryStatusStr; property FieldCount: Integer read GetFieldCount; property RecordCount: Integer read GetRecordCount; property Value[row, field: Integer]: PChar read GetValue; property ValueLen[row, field: Integer]: integer read GetValueLen; property FieldIndex[const fname: string]: integer read GetFieldIndex; property ValueIsNull[row, field: Integer]: boolean read GetValueIsNull; //property FieldName[Index: Integer]: string read GetFieldName; todo //property ValueByName[const FieldName: string]: string read GetValueByName; todo end; IPostgresStmt = interface(IInterface) function GetQueryStatus: ExecStatusType; function GetQueryStatusStr: string; function GetStmtName: string; property Status: ExecStatusType read GetQueryStatus; property StatusStr: string read GetQueryStatusStr; property StmtName: string read GetStmtName; end; TPostgresStmt = class(TInterfacedObject, IPostgresStmt) private FPPGresult: PPGresult; FParams: PParams; FStmtName: string; function GetQueryStatus: ExecStatusType; function GetQueryStatusStr: string; function GetStmtName: string; public constructor Create(APostgres: IPostgres; const StmtName: string; res: PPGresult; params: PParams); destructor Destroy; override; property Status: ExecStatusType read GetQueryStatus; property StatusStr: string read GetQueryStatusStr; property StmtName: string read GetStmtName; end; implementation { TPostgres } constructor TPostgres.Create(const host, port, database, user, password: string); begin inherited Create; FConnected := false; if length(host) = 0 then FHost := DEFAULT_HOST; if length(port) = 0 then FPort := DEFAULT_PORT; FDatabase:= database; FUser:= user; FPassword:= password; FCS := TCriticalSection.Create; end; destructor TPostgres.Destroy; begin Disconnect; FCS.Free; inherited; end; procedure TPostgres.Lock; begin FCS.Enter; end; procedure TPostgres.Unlock; begin FCS.Leave; end; function TPostgres.Connect: Boolean; begin FConnection := PQsetdbLogin(PChar(FHost), PChar(FPort), nil, nil, PChar(FDatabase), PChar(FUser), PChar(FPassword)); FConnected := PQstatus(FConnection) = CONNECTION_OK; result:= FConnected; if not(FConnected) then begin FLastErrorString:= GetError; Disconnect; end; end; procedure TPostgres.Disconnect; begin if FConnection = nil then exit; FConnected:= false; PQfinish(FConnection); FConnection:= nil; end; function TPostgres.IsConnected: Boolean; begin Result := FConnected; end; function TPostgres.GetDatabase: string; begin Result := FDatabase; end; function TPostgres.GetError: string; begin result:= PQerrorMessage(FConnection); result:= Copy(result, 1, length(result) - 1); end; function TPostgres.GetLastErrorString: string; begin result:= FLastErrorString; end; function TPostgres.GetConnection: PPGconn; begin Result := FConnection; end; function TPostgres.SendQuery(const SQL: String): boolean; begin result:= PQsendQuery(FConnection, PChar(SQL)) <> 0; end; function TPostgres.ExecQuery(const SQL: String): IPostgresQuery; var pr: PPGresult; begin result := nil; if not(FConnected) then exit; pr := PQexec(FConnection, PChar(SQL)); result:= TPostgresQuery.Create(self, pr, nil); end; function TPostgres.ExecQueryParams(const SQL: String; params: PParams): IPostgresQuery; var pr: PPGresult; begin result := nil; if not(FConnected) then exit; pr := PQexecParams(FConnection, PChar(SQL), params.nParams, params.paramTypes, params.paramValues, params.paramLengths, params.paramFormats, params.resultFormat); result:= TPostgresQuery.Create(self, pr, params); end; function TPostgres.Prepare(const SQL, StmtName: string; params: PParams): IPostgresStmt; var pr: PPGresult; begin result := nil; if not(FConnected) then exit; pr := PQprepare(FConnection, PChar(StmtName), PChar(SQL), params.nParams, params.paramTypes); result:= TPostgresStmt.Create(self, StmtName, pr, params); end; function TPostgres.ExecQueryPrepared(const StmtName: string; params: PParams): IPostgresQuery; var pr: PPGresult; begin result := nil; if not(FConnected) then exit; pr := PQexecPrepared(FConnection, PChar(StmtName), params.nParams, params.paramValues, params.paramLengths, params.paramFormats, params.resultFormat); result:= TPostgresQuery.Create(self, pr, params); end; { TPostgresQuery } constructor TPostgresQuery.Create(APostgres: IPostgres; res: PPGresult; params: PParams); begin FPPGresult := res; FParams:= params; end; destructor TPostgresQuery.Destroy; begin PQclear(FPPGresult); inherited; end; function TPostgresQuery.GetQueryStatus: ExecStatusType; begin result := PQresultStatus(FPPGresult); end; function TPostgresQuery.GetQueryStatusStr: string; begin result := PQresStatus(PQresultStatus(FPPGresult)); end; function TPostgresQuery.GetRecordCount: Integer; begin result := PQntuples(FPPGresult); end; function TPostgresQuery.GetFieldCount: Integer; begin result := PQnfields(FPPGresult); end; function TPostgresQuery.GetValue(row, field: integer): PChar; begin result:= PQgetvalue(FPPGresult, row, field); end; function TPostgresQuery.GetValueLen(row, field: integer): integer; begin result:= PQgetlength(FPPGresult, row, field); end; function TPostgresQuery.GetFieldIndex(const fname: string): integer; begin result:= PQfnumber(FPPGresult, PAnsiChar(fname)); end; function TPostgresQuery.GetValueIsNull(row, field: integer): boolean; begin result:= PQgetisnull(FPPGresult, row, field) <> 0; end; { TPostgresStmt } constructor TPostgresStmt.Create(APostgres: IPostgres; const StmtName: string; res: PPGresult; params: PParams); begin FPPGresult := res; FParams:= params; FStmtName:= StmtName; end; destructor TPostgresStmt.Destroy; begin PQclear(FPPGresult); inherited; end; function TPostgresStmt.GetQueryStatus: ExecStatusType; begin result := PQresultStatus(FPPGresult); end; function TPostgresStmt.GetQueryStatusStr: string; begin result := PQresStatus(PQresultStatus(FPPGresult)); end; function TPostgresStmt.GetStmtName: string; begin result:= FStmtName; end; end{$WARNINGS OFF}.
{ ******************************************************************************************************************* SpiderUtils: Contains Request and Response classes for Free Spider web application for lazarus Author: Motaz Abdel Azeem email: motaz@code.sd Home page: http://code.sd License: LGPL Last modifie: 28.Aug.2012 Jul/2010 - Modified by Luiz Américo * Remove LCL dependency * Fix memory leaks ******************************************************************************************************************* } unit SpiderUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TRequestFile = record FileName: string; FieldName: string; FileContent: string; ContentType: string; FileSize: Integer; end; TRequestFiles = array of TRequestFile; { TSpiderRequest } TSpiderRequest = class(TObject) protected fRequestMethod: string; fUserAgent: string; fRemoteAddress: string; fContentType: string; fQueryString: string; fContentLength: string; fQueryFields: TStringList; fContentFields: TStringList; fCookieList: TStringList; fMultiPart: Boolean; fBoundary: string; fFilesCount: Integer; fFiles: TRequestFiles; fPathInfo: string; fReferer: string; fIsCGI: Boolean; fIsApache: Boolean; fURI: string; fHost: string; fWebServerSoftware: string; procedure ReadCookies; virtual; abstract; procedure DecodeMultiPart; virtual; abstract; function ReadContent: string; virtual; abstract; procedure DisplayErrorMessage(Msg: string); virtual; abstract; procedure ReadVariables; virtual; abstract; procedure DecodeRequest(AText: string; var List: TStringList); function GetRootURI: string; function GetHost: string; public constructor Create; destructor Destroy; override; function Query(FieldName: string): string; function Form(FieldName: string): string; function GetCookie(AName: string): string; function ContentNames(Index: Integer): string; function ContentValues(Index: Integer): string; property Queryfields: TStringList read fQueryFields; property ContentFields: TStringList read fContentFields; property RequestMethod: string read fRequestMethod; property UserAgent: string read fUserAgent; property RemoteAddress: string read fRemoteAddress; property ContentType: string read fContentType; property FilesCount: Integer read fFilesCount; property ContentFiles: TRequestFiles read fFiles; property PathInfo: string read fPathInfo; property Referer: string read fReferer; property URI: string read fURI; property RootURI: string read GetRootURI; property WebServerSoftware: string read fWebServerSoftware; property Host: string read GetHost; property IsCGI: Boolean read fIsCGI; property IsApache: Boolean read fIsApache; property Cookies: TStringList read fCookieList; end; { TSpiderResponse } TSpiderResponse = class (TObject) private fCookieList: TStringList; fContent: TStringList; fCustomHeader: TStringList; fContentType: string; fResponseCode: Integer; fResponseString: string; public procedure SetCookie(AName, AValue, APath: string; ExpiresInGMT: TDateTime = -1); procedure DeleteCookie(AName, APath: string); procedure Add(HTMLText: string); property CookieList: TStringList read fCookieList; property Content: TStringList read fContent; property ContentType: string read fContentType write fContentType; property CustomHeader: TStringList read fCustomHeader; procedure SendRedirect(AUrl: string; RedirectionHint: string = 'Redirecting..'); constructor Create; destructor Destroy; override; property ResponseCode:Integer read fResponseCode write fResponseCode; property ResponseString:String read fResponseString write fResponseString; // HTML Tags procedure NewLine(NumOfNewLines: Integer = 1); procedure HR; procedure NewTable(Attr: string = ''); procedure CloseTable; procedure NewTableRow(Attr: string = ''); procedure CloseTableRow; procedure NewTableData(Attr: string = ''); procedure CloseTableData; procedure PutTableData(aData: string; Attr: string = ''); procedure AddBold(aText: string); procedure AddItalic(aText: string); procedure AddListItem(aText: string); procedure AddFont(aText, Attr: string); procedure AddParagraph(aText: string; Attr: string = ''); procedure AddHyperLink(URL, aText: string); procedure NewForm(Method, Action: string; ExtraParams: string = ''); procedure CloseForm; end; TSpiderEvent = procedure(Sender: TObject; Request: TSpiderRequest; var Response: TSpiderResponse) of object; implementation { TRequest } procedure TSpiderRequest.DecodeRequest(AText: string; var List: TStringList); var i: Integer; Hex: string; Dec: Integer; Line: string; begin Line:=''; List.Clear; i:= 1; while i <= Length(AText) do begin if AText[i] = '%' then begin Hex:= Copy(AText, i + 1, 2); i:= i + 2; Dec:= StrToInt('$' + Hex); Line:= Line + Chr(Dec); end else if AText[i] = '+' then Line:= Line + ' ' else if AText[i] = '&' then begin List.Add(Line); Line:= ''; end else Line:= Line + AText[i]; Inc(i); end; if Line <> '' then List.Add(Line); end; constructor TSpiderRequest.Create; begin try ReadVariables; fFilesCount:= 0; fQueryFields:= TStringList.Create; fContentFields:= TStringList.Create; fCookieList:= TStringList.Create; ReadCookies; fMultiPart:= Pos('multipart/form-data', fContentType) > 0; if fMultiPart then fBoundary:= Trim(Copy(fContentType, Pos('boundary=', fContentType) + 10, Length(fContentType))); if LowerCase(fRequestMethod) = 'get' then DecodeRequest(fQueryString, fQueryFields) else if LowerCase(fRequestMethod) = 'post' then begin if fMultiPart then DecodeMultiPart else DecodeRequest(ReadContent, fContentFields); end; // if LowerCase.. except on e: exception do begin DisplayErrorMessage(e.Message); end; end; end; destructor TSpiderRequest.Destroy; begin fQueryFields.Free; fContentFields.Free; fCookieList.Free; inherited Destroy; end; function TSpiderRequest.Query(FieldName: string): string; begin Result:= fQueryFields.Values[FieldName]; end; function TSpiderRequest.Form(FieldName: string): string; begin Result:= fContentFields.Values[FieldName]; end; function TSpiderRequest.GetCookie(AName: string): string; begin Result:= fCookieList.Values[AName]; end; function TSpiderRequest.ContentNames(Index: Integer): string; begin Result:= fContentFields.Names[Index]; end; function TSpiderRequest.ContentValues(Index: Integer): string; begin Result:= fContentFields.ValueFromIndex[Index]; end; function TSpiderRequest.GetRootURI: string; begin if fPathInfo = '/' then Result:= fURI else begin Result:= fURI; if pos('?', Result) > 0 then Result:= Copy(Result, 1, Pos('?', Result) - 1); Result:= Copy(Result, 1, Length(Result) - Length(fPathInfo)); if (Result <> '') and (Result[Length(Result)] = '/') then Delete(Result, Length(Result), 1); end; end; function TSpiderRequest.GetHost: string; begin Result:= fHost; end; { TSpiderResponse } constructor TSpiderResponse.Create; begin fContent:= TStringList.Create; fCookieList:= TStringList.Create; fCustomHeader:= TStringList.Create; fContentType:= 'TEXT/HTML'; fResponseCode := 200; fResponseString := 'OK'; end; destructor TSpiderResponse.Destroy; begin fContent.Free; fCookieList.Free; fCustomHeader.Free; inherited Destroy; end; procedure TSpiderResponse.NewLine(NumOfNewLines: Integer = 1); var i: Integer; begin for i:= 1 to NumOfNewLines do fContent.Add('<br />'); end; procedure TSpiderResponse.HR; begin fContent.Add('<HR>'); end; procedure TSpiderResponse.NewTable(Attr: string); begin fContent.Add('<table ' + Attr + '>'); end; procedure TSpiderResponse.CloseTable; begin fContent.Add('</table>'); end; procedure TSpiderResponse.NewTableRow(Attr: string); begin fContent.Add('<tr ' + Attr + '>'); end; procedure TSpiderResponse.CloseTableRow; begin fContent.Add('</tr>'); end; procedure TSpiderResponse.NewTableData(Attr: string); begin fContent.Add('<td ' + Attr + '>'); end; procedure TSpiderResponse.CloseTableData; begin fContent.Add('</td>'); end; procedure TSpiderResponse.PutTableData(aData: string; Attr: string); begin fContent.Add('<td ' + Attr + '>' + aData + '</td>'); end; procedure TSpiderResponse.AddBold(aText: string); begin fContent.Add('<b>' + aText + '</b>'); end; procedure TSpiderResponse.AddItalic(aText: string); begin fContent.Add('<i>' + aText + '</i>'); end; procedure TSpiderResponse.AddListItem(aText: string); begin fContent.Add('<li>' + aText + '</li>'); end; procedure TSpiderResponse.AddFont(aText, Attr: string); begin fContent.Add('<font ' + Attr + '>' + aText + '</font>'); end; procedure TSpiderResponse.AddParagraph(aText: string; Attr: string); begin fContent.Add('<P ' + Attr + '>' + aText + '</P>'); end; procedure TSpiderResponse.AddHyperLink(URL, aText: string); begin fContent.Add('<a href="' + URL + '">' + aText + '</a>'); end; procedure TSpiderResponse.NewForm(Method, Action: string; ExtraParams: string); begin fContent.Add('<form method="' + Method + '" action="' + Action + '" ' + ExtraParams + '>'); end; procedure TSpiderResponse.CloseForm; begin fContent.Add('</form>'); end; procedure TSpiderResponse.SetCookie(AName, AValue, APath: string; ExpiresInGMT: TDateTime = -1); var Line: string; begin Line:= 'Set-Cookie: ' + Trim(AName) + '=' + AValue + '; path=' + APath; if ExpiresInGMT <> -1 then Line:= Line + '; expires=' + FormatDateTime('ddd, dd-mmm-yyyy hh:nn:ss', ExpiresInGMT) + ' GMT'; fCookieList.Add(Line); end; procedure TSpiderResponse.DeleteCookie(AName, APath: string); begin fCookieList.Add('Set-Cookie: ' + AName + '=; path=' + APath + '; expires=Thu, 01-Jan-1970 00:00:01 GMT'); end; procedure TSpiderResponse.Add(HTMLText: string); begin Content.Add(HTMLText); end; // By: Sammarco Francesco procedure TSpiderResponse.SendRedirect(AUrl: string; RedirectionHint: string = 'Redirecting..'); begin with fContent do begin Clear; Add('<HTML>'); Add('<HEAD>'); Add('<META HTTP-EQUIV="REFRESH" CONTENT="0; URL=' + AUrl + '">'); Add('</HEAD>'); Add('<BODY>'); Add(RedirectionHint); Add('</BODY>'); Add('</HTML>'); end; end; end.
unit ClienteC; interface uses System.SysUtils, ZConnection, ZDataset; type TCliente = class private FConn: TZConnection; FID: Integer; FLogradouro: String; FIbgeUf: String; FCep: String; FNumero: String; FComplemento: String; FNome: String; FCidade: String; FSiglaUf: String; FIbgeCidade: String; public constructor Create(conn: TZConnection); property ID: Integer read FID write FID; property Nome: String read FNome write FNome; property Cep: String read FCep write FCep; property Logradouro: String read FLogradouro write FLogradouro; property Numero: String read FNumero write FNumero; property Complemento: String read FComplemento write FComplemento; property Cidade: String read FCidade write FCidade; property IbgeCidade: String read FIbgeCidade write FIbgeCidade; property SiglaUf: String read FSiglaUf write FSiglaUf; property IbgeUf: String read FIbgeUf write FIbgeUf; function GetCliente(out erro: string): Boolean; end; implementation { TCliente } constructor TCliente.Create(conn: TZConnection); begin FConn := conn; end; function TCliente.GetCliente(out Erro: string): Boolean; var Qry: TZQuery; PNome: String; begin try try Qry := TZQuery.Create(nil); Qry.Connection := FConn; Qry.SQL.Text := 'SELECT * FROM CLIENTE WHERE upper(NOME) LIKE ''%'+Nome+'%'''; Qry.Open; if not Qry.IsEmpty then begin Erro := ''; Result := True; ID := Qry.FieldByName('ID').AsInteger; Nome := Qry.FieldByName('NOME').AsString; Cep := Qry.FieldByName('CEP').AsString; Logradouro := Qry.FieldByName('LOGRADOURO').AsString; Numero := Qry.FieldByName('NUMERO').AsString; Complemento := Qry.FieldByName('COMPLEMENTO').AsString; Cidade := Qry.FieldByName('CIDADE').AsString; IbgeCidade := Qry.FieldByName('IBGE_CIDADE').AsString; SiglaUf := Qry.FieldByName('SIGLA_UF').AsString; IbgeUf := Qry.FieldByName('IBGE_UF').AsString; end else begin erro := 'Usuário NÃO Encontrado'; Result := False; end; except on E: exception do begin erro := 'Erro ao Pesquisar: '+E.Message; Result := False; end; end; finally Qry.Connection := nil; FreeAndNil(Qry); end; end; end.
unit uLicExeCryptor; { ResourceString: Dario 13/03/13 } interface uses SyncObjs, Classes, Windows, EXECryptor, Sysutils; type TTipoChave = (tcTemporaria, tcDefinitiva, tcTeste, tcLocacao, tcInvalida, tcFreePremium, tcFreePro, tcNenhum); TStatusConta = (scSemConta, scAtivar, scFree, scPremium, scPremiumVenc, scOutroHD, scAnt, scBloqueada, scCybermgr, scTipoLicInvalida); TChaveLiberacao = class private FString : String; function GetVencimento: TDateTime; public constructor Create; function FreePremium: Boolean; function Status(const aCodLoja: Integer; var aCodEquip, aSN: String; var aTipo: TTipoChave): TStatusConta; function ChaveValida(const aCodLoja: Integer; var aCodEquip, aSN: String; var aTipo: TTipoChave): Integer; // Resultado: 0 = serial invalido, caso contrário igual numero de máquinas licenciadas function Venceu: Boolean; property AsString: String read FString write FString; property Vencimento: TDateTime read GetVencimento; end; TArrayChaveLiberacao = class private FItems : TList; function GetChaveByIndex(N: Integer): TChaveLiberacao; function GetString: String; procedure SetString(const Value: String); public constructor Create; destructor Destroy; override; function Status(const aCodLoja: Integer; var aCodEquip, aSN: String; var aVenceEm: TDateTime): TStatusConta; procedure Add(const StrChave: String); function Remove(const StrChave: String): Boolean; function Count: Integer; procedure Clear; function Clone: TArrayChaveLiberacao; property Items[N: Integer]: TChaveLiberacao read GetChaveByIndex; Default; property AsString: String read GetString write SetString; end; TRegistro = class private FCacheS : String; FChaves : TArrayChaveLiberacao; FLoja : Integer; FEmail : String; FIDLoja : Cardinal; FIDLojaKey : String; FFalhouSalvar : Boolean; FCS : TCriticalSection; FJafoiPremium : Boolean; FBoletosPendentes : Integer; FTipo : TTipoChave; function GetCodLojaAsString: String; procedure SetCodLojaAsString(const Value: String); function GetStringChaves: String; procedure SetStringChaves(const Value: String); function GetLoja: Integer; procedure SetLoja(const Value: Integer); procedure Lock; procedure Unlock; procedure SetConta(const Value: String); function GetConta: String; function GetBoletosPendentes: Integer; function GetJaFoiPremium: Boolean; procedure SetBoletosPendentes(const Value: Integer); procedure SetJaFoiPremium(const Value: Boolean); function GetIDLoja: Cardinal; protected procedure Clear; public constructor Create; destructor Destroy; override; function Status: TStatusConta; function GetSerialHD: String; function GetCodEquip(Serial: string) : String; procedure LeArq(const aNomeArq: String; const aCreate: Boolean = True; const LeCodLoja: Boolean = False); procedure SalvaArq(const aNomeArq: String); procedure LeArqPadrao(const LeCodLoja: Boolean = False); procedure SalvaArqPadrao; procedure AjustaContaSalva(aConta, aChaves: String); procedure SetIDLoja(aIDLoja: String); procedure SetIDLojaKey(aIDLojaKey : String); function IDLojaKey: String; property Tipo: TTipoChave read FTipo; property IDLoja: Cardinal read GetIDLoja; property Conta: String read GetConta write SetConta; property CodLoja: Integer read GetLoja write SetLoja; property Email: String read FEmail; property CodLojaAsString: String read GetCodLojaAsString write SetCodLojaAsString; property JaFoiPremium: Boolean read GetJaFoiPremium write SetJaFoiPremium; property BoletosPendentes: Integer read GetBoletosPendentes write SetBoletosPendentes; function NumChaves: Integer; function Inexistente: Boolean; procedure CodEquipSerial(var aCE, aSN: String); function RemoveChave(const StrChave: String): Boolean; procedure AddChave(const StrChave: String); class function ChavesOk(S: String): Boolean; function CloneChaves: TArrayChaveLiberacao; function LicencasValidas(aSomarVencidas: Boolean; aCodEquip: String = ''; aSN: String = ''): Integer; property StringChaves: String read GetStringChaves write SetStringChaves; end; function ObtemProxy(var aProxyIP: String; var aProxyPort: Integer): Boolean; function CodLojaOK(S: String): Boolean; function TrimCodLoja(S: String): String; function DateToDateLic(D: TDateTime; aFreePremium: Boolean): String; function DateLicToDate(D: String): TDateTime; function SerialToCodEquip(aSerial: String): String; function StrToCodLoja(S: String): Integer; function CodLojaToStr(I: Integer): String; function getIDLojaKey(aIDLoja, aConta: String): String; overload; function getIDLojaKey(aIDLoja: Cardinal; aConta: String): String; overload; const // Tipo da Licença ectcTemporaria = 0; ectcDefinitiva = 2; ectcTeste = 3; ectcLocacao = 4; ectcFreePremium = 5; ectcFreePro = 6; ChaveCybermgr = '9999-9999-9999-9999-9999'; ChaveBloqueado = '1111-1111-1111-1111-1111'; ChaveAtivar = '2222-2222-2222-2222-2222'; ChaveInexistente = '3333-3333-3333-3333-3333'; TipoChaveStr : Array[TTipoChave] of String = ('Temporaria', 'Definitiva', 'Teste', 'Locação', 'Inválida', 'Free/Premium', 'Free/Pro', 'Nenhum'); var RegistroGlobal : TRegistro = nil; slSer : TStrings; csSer : TCriticalSection; gDTol : Byte = 0; threadvar CEOK, SNOK : String; lastCEOK : String; implementation uses // GetDiskSerial, uScsi, md5, {$ifdef nexcafe} IdeSN, GetDiskSerial, {$else} IdeSN_XE7, uGetSerial, {$endif} Registry, ncDebug, ncSyncLic; // START resource string wizard section resourcestring SArquivoDeLicenças = 'Arquivo de licenças "'; SNãoExiste = '" não existe'; // END resource string wizard section {$ifndef nexcafe} function nexgetserialstr: widestring; stdcall; external 'nexutils.dll' {$endif} function pathlic: String; begin Result := ExtractFilePath(ParamStr(0)); end; procedure GetSerials(sl: TStrings); var {$ifdef nexcafe}ds: TGetDiskSerial;{$endif} I: Integer; ss : wideString; ss2 : WideString; procedure Add(S: String); begin csSer.Enter; try if (S>'') and (slSer.IndexOf(S)=-1) then begin // Debugmsg('GetSerials - Disco '+IntToStr(I)+' = '+S); // do not localize slSer.Add(S); end; finally csSer.Leave; end; end; begin {$I crypt_start.inc} sl.Clear; try {$ifdef nexcafe} try DS := TGetDiskSerial.Create(nil); for I := 0 to 3 do begin try DS.DriveID := I; Add(Trim(DS.SerialNumber)); except on E: Exception do DebugMsg('GetSerials - HD - Erro = '+E.Message); // do not localize end; end; finally DS.Free; end; {$else} I := 100; ss2 := #13#10; ss := nexgetserialstr; repeat I := Pos(ss2, ss); if I>0 then begin Add(Trim(Copy(SS, 1, I-1))); Delete(SS, 1, I+1); end else Add(Trim(ss)); until (I<1); {$endif} I := 100; Add(Trim(GetIdeSN)); I := 101; Add(Trim(GetSCSISerial(pathlic[1]))); I := 102; Add(Trim(IntToStr(GetHardwareID))); except on E: Exception do DebugMsg('GetSerials - HD - Erro = '+E.Message); // do not localize end; csSer.Enter; try sl.Text := slSer.Text; finally csSer.Leave; end; // DebugMsg('uLicExecryptor.GetSerials: ' + sl.Text); {$I crypt_end.inc} end; function GetCodEquips: TStrings; var Serial: String; I: Integer; begin {$I crypt_start.inc} Result := TStringList.Create; GetSerials(Result); for I := 0 to Result.Count - 1 do begin Serial := Result[I]; Serial := Serial + 'n'; Serial := Serial + 'e'; Serial := Serial + 'x'; Serial := Serial + 'c'; Serial := Serial + 'a'; Serial := Serial + 'f'; Serial := Serial + 'e'; Serial := Serial + 'z'; Serial := Serial + 'i'; Serial := Serial + 'z'; Serial := Copy(GetMD5Str(Serial), 9, 16); Result[I] := Copy(Serial, 1, 4)+'-'+ Copy(Serial, 5, 4)+'-'+ Copy(Serial, 9, 4)+'-'+ Copy(Serial, 13, 4); // DebugMsg('GetCodEquips '+IntToStr(I)+': '+Result[I]); // do not localize end; {$I crypt_end.inc} end; function TrimCodLoja(S: String): String; begin while (Length(S)>0) and not (S[Length(S)] in ['0'..'9']) do Delete(S, Length(S), 1); Result := S; end; function FullLicArq: String; begin Result := ExtractFilePath(ParamStr(0))+'LicArq.txt'; // do not localize if not FileExists(Result) then Result := ExtractFilePath(ParamStr(0))+'Lic.txt'; // do not localize end; function SerialToCodEquip(aSerial: String): String; var S: String; begin {$I crypt_start.inc} S := S + 'n'; S := S + 'e'; S := S + 'x'; S := S + 'c'; S := S + 'a'; S := S + 'f'; S := S + 'e'; S := S + 'z'; S := S + 'i'; S := S + 'z'; Result := Copy(GetMD5Str(aSerial+S), 9, 16); Result := Copy(Result, 1, 4)+'-'+ Copy(Result, 5, 4)+'-'+ Copy(Result, 9, 4)+'-'+ Copy(Result, 13, 4); {$I crypt_end.inc} end; function ECTypeToTipoChave(const EC: Byte): TTipoChave; begin // DebugMsg('ECTypeToTipoChave - EC: '+IntToStr(EC)); case EC of ectcTemporaria : begin Result := tcTemporaria; // DebugMsg('ECTypeToTipoChave: Temporária'); end; ectcDefinitiva : begin Result := tcDefinitiva; // DebugMsg('ECTypeToTipoChave: Definitiva'); end; ectcTeste : begin Result := tcTeste; // DebugMsg('ECTypeToTipoChave: Teste'); end; ectcLocacao : begin Result := tcLocacao; // DebugMsg('ECTypeToTipoChave: Locacao'); end; ectcFreePremium : begin Result := tcFreePremium; // DebugMsg('ECTypeToTipoChave: FreePremium'); end; ectcFreePro : begin Result := tcFreePro; // DebugMsg('ECTypeToTipoChave: FreePro'); end; else // DebugMsg('ECTypeToTipoChave: Inválida'); Result := tcInvalida; end; end; function ObtemProxy(var aProxyIP: String; var aProxyPort: Integer): Boolean; var R: TRegistry; begin try Result := False; R := TRegistry.Create; R.RootKey := HKEY_CURRENT_USER; R.Access := KEY_READ; if R.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', False) then begin // do not localize Result := (R.ReadInteger('ProxyEnable')=1); // do not localize aProxyIP := R.ReadString('ProxyServer'); // do not localize aProxyPort := StrToIntDef(Copy(aProxyIP, Pos(':', aProxyIP)+1, 5), 8080); Delete(aProxyIP, Pos(':', aProxyIP), 10); R.CloseKey; end; except Result := False; end; R.Free; end; function ZeroPad(St: String; Len: Integer): String; begin Result := St; while Length(Result)<Len do Result := '0'+Result; end; function NumStr(I, Tam: Integer): String; begin Result := ZeroPad(IntToStr(I), Tam); end; function LimpaTraco(S: String): String; var I : Integer; begin Result := ''; for I := 1 to Length(S) do if S[I] <> '-' then Result := Result + S[I]; end; function Inverte(S: String): String; var I : Integer; begin Result := ''; for I := 1 to Length(S) do Result := S[I] + Result; end; function CodLojaToStr(I: Integer): String; begin if I=0 then Result := '' else begin if I>9999 then Result := IntToStr(I) else Result := NumStr(I, 4); Result := Copy(GetMD5Str(Result+'cyber'), 1 , 4) + '-' + Result; // do not localize end; end; function StrToCodLoja(S: String): Integer; begin S := TrimCodLoja(S); Result := StrToIntDef(TrimCodLoja(Copy(S, 6, 10)), 0); if (Result<>0) and (CodLojaToStr(Result)<>S) then Result := 0; end; function CodLojaOK(S: String): Boolean; begin Result := (StrToCodLoja(S)>0); end; function VolumeSerial(DriveChar: Char): string; var OldErrorMode: Integer; Serial, NotUsed, VolFlags: DWORD; Buf: array [0..MAX_PATH] of Char; begin {$I crypt_start.inc} OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Buf[0] := #$00; if GetVolumeInformation(PChar(DriveChar + ':\'), nil, 0, @Serial, NotUsed, VolFlags, nil, 0) then Result := IntToHex(Integer(Serial), 0) else Result := ''; finally SetErrorMode(OldErrorMode); end; {$I crypt_end.inc} end; function DataBaseLic: TDateTime; begin Result := EncodeDate(2003, 1, 1); end; function IsPremiumDateChar(C: Char): Boolean; begin Result := (C in ['G'..'V']); end; function HexToPremium(C: Char): Char; begin {$I crypt_start.inc} case C of '0': Result := 'G'; '1': Result := 'H'; '2': Result := 'I'; '3': Result := 'J'; '4': Result := 'K'; '5': Result := 'L'; '6': Result := 'M'; '7': Result := 'N'; '8': Result := 'O'; '9': Result := 'P'; 'A': Result := 'Q'; 'B': Result := 'R'; 'C': Result := 'S'; 'D': Result := 'T'; 'E': Result := 'U'; 'F': Result := 'V'; else Result := C; end; {$I crypt_end.inc} end; function PremiumToHex(C: Char): Char; begin {$I crypt_start.inc} case C of 'G': Result := '0'; 'H': Result := '1'; 'I': Result := '2'; 'J': Result := '3'; 'K': Result := '4'; 'L': Result := '5'; 'M': Result := '6'; 'N': Result := '7'; 'O': Result := '8'; 'P': Result := '9'; 'Q': Result := 'A'; 'R': Result := 'B'; 'S': Result := 'C'; 'T': Result := 'D'; 'U': Result := 'E'; 'V': Result := 'F'; else Result := C; end; {$I crypt_end.inc} end; function IsPremiumDate(D: String): Boolean; begin if Length(D)<4 then Result := False else begin D := UpperCase(D); Result := IsPremiumDateChar(D[1]) and IsPremiumDateChar(D[2]) and IsPremiumDateChar(D[3]) and IsPremiumDateChar(D[4]); end; end; function IsFreeDate(D: String): Boolean; begin Result := SameText(Copy(D, 1, 4), 'FREE'); // do not localize end; function IsPremiumOrFree(D: String): Boolean; begin Result := SameText(Copy(D, 1, 4), 'FREE') or IsPremiumDate(D); // do not localize end; function PremiumDateToDateLic(D: String): String; begin if IsPremiumDate(D) then Result := PremiumToHex(D[1]) + PremiumToHex(D[2]) + PremiumToHex(D[3]) + PremiumToHex(D[4]) else Result := D; end; function DateLicToPremiumDate(D: String): String; begin if Length(D)<4 then Result := D else Result := HexToPremium(D[1]) + HexToPremium(D[2]) + HexToPremium(D[3]) + HexToPremium(D[4]); end; function DateLicToDate(D: String): TDateTime; begin if SameText(Copy(D, 1, 4), 'FREE') then // do not localize Result := 0 else Result := DataBaseLic + StrToIntDef('$'+PremiumDateToDateLic(D), 0); end; function DateToDateLic(D: TDateTime; aFreePremium: Boolean): String; begin if D<=DataBaseLic then Result := '0000' // do not localize else Result := IntToHex(Trunc(D-DataBaseLic), 4); if aFreePremium then if (D=0) then Result := 'FREE' else // do not localize Result := DateLicToPremiumDate(Result); end; function TChaveLiberacao.ChaveValida( const aCodLoja: Integer; var aCodEquip, aSN: String; var aTipo: TTipoChave): Integer; var SNI: TSerialNumberInfo; S, S2: String; SaveSep: Char; procedure Checar; var sl : TStrings; I : Integer; begin {$I crypt_start.inc} Result := 0; sl := GetCodEquips; try lastCEOK := ''; for I := 0 to sl.Count-1 do begin S2 := Copy(FString, 6, 30); if DecodeSerialNumber(S, S2, SNI, sl[I]) = vrOK then begin // DebugMsg('ChaveValida.Checar - OK: CodEquip = ' + sl[I] + ' S2: ' + S2 + ' - SNI.UserParam: '+IntToStr(SNI.UserParam)); // do not localize Result := SNI.UserParam; // DebugMsg('ChaveValiuda.Checar - LicType: ' + IntToStr(SNI.LicType)); aTipo := ECTypeToTipoChave(SNI.LicType); if not (aTipo in [tcDefinitiva, tcFreePremium, tcFreePro]) then begin Result := 0; // DebugMsg('ChaveValida.Checar - Tipo Invalido: ' + IntToStr(Integer(aTipo))); // do not localize end else begin lastCEOK := sl[I]; Break; // DebugMsg('ChaveValida.Checar OK!'); // do not localize end; end else begin Result := 0; // DebugMsg('ChaveValida.Checar - FALSE: CodEquip = ' + sl[I] + ' S2: ' + S2); // do not localize aTipo := tcInvalida; end; end; finally sl.Free; end; {$I crypt_end.inc} end; begin {$I crypt_start.inc} SaveSep := {$ifndef nexcafe}FormatSettings.{$endif}DateSeparator; if IsPremiumOrFree(FString) then S := Copy(FString, 1, 4) else begin {$ifndef nexcafe}FormatSettings.{$endif}DateSeparator := '/'; try S := IntToStr(aCodLoja)+'-'+FormatDateTime('dd/mm/yyyy', Vencimento); // do not localize finally {$ifndef nexcafe}FormatSettings.{$endif}DateSeparator := SaveSep; end; end; Checar; if (Result > 0) and (Result<2000) and (aTipo<>tcInvalida) then begin CEOK := aCodEquip; SNOK := aSN; end else if (CEOK>'') and (SNOK>'') and (aCodEquip>'') and (aSN>'') and ((Pos(aSN, SNOK)>0) or (Pos(SNOK, aSN)>0)) then begin aCodEquip := CEOK; aSN := SNOK; Checar; end; {$I crypt_end.inc} end; constructor TChaveLiberacao.Create; begin FString := ''; end; function TChaveLiberacao.FreePremium: Boolean; begin Result := IsPremiumOrFree(Copy(FString, 1, 4)); end; function TChaveLiberacao.GetVencimento: TDateTime; begin Result := DateLicToDate(Copy(FString, 1, 4)); end; function TChaveLiberacao.Status(const aCodLoja: Integer; var aCodEquip, aSN: String; var aTipo: TTipoChave): TStatusConta; var N: Integer; begin {$I crypt_start.inc} if SameText(FString, ChaveBloqueado) then Result := scBloqueada else if SameText(FString, ChaveCybermgr) then Result := scCybermgr else if SameText(FString, ChaveInexistente) then Result := scSemConta else if SameText(FString, ChaveAtivar) then Result := scAtivar else if FreePremium then begin N := ChaveValida(0, aCodEquip, aSN, aTipo); if (N=0) or (aTipo=tcInvalida) then Result := scOutroHD else begin if IsFreeDate(FString) then Result := scFree else begin if Venceu then Result := scPremiumVenc else Result := scPremium; end; end; end else begin N := ChaveValida(aCodLoja, aCodEquip, aSN, aTipo); if aTipo=tcInvalida then Result := scOutroHD else begin if aTipo=tcDefinitiva then Result := scAnt else Result := scTipoLicInvalida; end; end; {$I crypt_end.inc} end; function TChaveLiberacao.Venceu: Boolean; begin {$I crypt_start.inc} if gDTol>9 then gDTol := 9; Result := (Date > (Vencimento+gDTol)); {$I crypt_end.inc} end; { TRegistro } procedure TRegistro.AddChave(const StrChave: String); begin Lock; try FChaves.Add(StrChave); finally Unlock; end; end; procedure TRegistro.AjustaContaSalva(aConta, aChaves: String); begin Lock; try Conta := aConta; StringChaves := aChaves; SalvaArqPadrao; finally Unlock; end; end; class function TRegistro.ChavesOk(S: String): Boolean; var C: String; P: Integer; begin S := Trim(S); while S>'' do begin P := Pos(';', S); if P>0 then begin C := Trim(Copy(S, 1, P-1)); Delete(S, 1, P); end else begin C := Trim(S); S := ''; end; if Length(C)=24 then begin Result := True; Exit; end; end; Result := False; end; procedure TRegistro.Clear; begin FChaves.Clear; end; function TRegistro.CloneChaves: TArrayChaveLiberacao; begin Result := FChaves.Clone; end; constructor TRegistro.Create; begin inherited; try try FCS := TCriticalSection.Create; except on e: exception do DebugMsgEsp('TRegistro.Create - Erro criando CriticalSection: ' + E.Message, False, True); // do not localize end; FEmail := ''; FTipo := tcNenhum; FJaFoiPremium := False; FBoletosPendentes := 0; FCacheS := ''; FChaves := TArrayChaveLiberacao.Create; FFalhouSalvar := False; FLoja := 0; FIDLoja := 0; FIDLojaKey := ''; except on E: Exception do DebugMsgEsp('TRegistro.Create - E.Message: ' + E.Message, False, True); // do not localize end; end; destructor TRegistro.Destroy; begin Clear; FChaves.Free; FCS.Free; inherited; end; function TRegistro.GetCodLojaAsString: String; begin Result := CodLojaToStr(CodLoja); end; function TRegistro.GetConta: String; begin if FLoja>0 then Result := CodLojaAsString else Result := FEmail; end; function TRegistro.GetIDLoja: Cardinal; begin Lock; try if (FIDLoja>0) and SameText(getIDLojaKey(FIDLoja, FEmail), FIDLojaKey) then Result := FIDLoja else Result := 0; finally Unlock; end; end; function TRegistro.IDLojaKey: String; begin Lock; try result := FIDLojaKey; finally Unlock; end; end; function TRegistro.GetJaFoiPremium: Boolean; begin Lock; try Result := FJaFoiPremium; finally Unlock; end; end; function TRegistro.GetLoja: Integer; begin Lock; try Result := FLoja; finally Unlock; end; end; function TRegistro.GetStringChaves: String; begin Lock; try Result := FChaves.AsString; finally Unlock; end; end; function TRegistro.Inexistente: Boolean; begin Lock; try Result := (FChaves.Count>0) and SameText(FChaves[0].AsString, ChaveInexistente); finally Unlock; end; end; procedure TRegistro.CodEquipSerial(var aCE, aSN: String); begin aSN := GetSerialHD; aCE := GetCodEquip(aSN); end; function TRegistro.GetBoletosPendentes: Integer; begin Lock; try Result := FBoletosPendentes; finally Unlock; end; end; function TRegistro.GetCodEquip(Serial: String): String; begin {$I crypt_start.inc} Serial := Serial + 'n'; Serial := Serial + 'e'; Serial := Serial + 'x'; Serial := Serial + 'c'; Serial := Serial + 'a'; Serial := Serial + 'f'; Serial := Serial + 'e'; Serial := Serial + 'z'; Serial := Serial + 'i'; Serial := Serial + 'z'; Result := Copy(GetMD5Str(Serial), 9, 16); Result := Copy(Result, 1, 4)+'-'+ Copy(Result, 5, 4)+'-'+ Copy(Result, 9, 4)+'-'+ Copy(Result, 13, 4); {$I crypt_end.inc} end; procedure TRegistro.LeArq(const aNomeArq: String; const aCreate: Boolean = True; const LeCodLoja: Boolean = False); var SL: TStrings; Existe: Boolean; begin Lock; try Existe := FileExists(aNomeArq); if (not Existe) and (not aCreate) then raise Exception.Create(SArquivoDeLicenças+aNomeArq+SNãoExiste); SL := TStringList.Create; if LeCodLoja then FLoja := 0; Clear; try if Existe then begin SL.LoadFromFile(aNomeArq); if LeCodLoja then Conta := SL.Values['Loja']; // do not localize StringChaves := SL.Values['Chaves']; // do not localize FBoletosPendentes := StrToIntDef(SL.Values['BP'], 0); // do not localize FJaFoiPremium := SameText(SL.Values['JFP'], 'S'); // do not localize SetIDLoja(sl.Values['IDLoja']); SetIDLojaKey(sl.Values['IDLojaToken']); end else begin SL.Values['Loja'] := ''; // do not localize SL.Values['Chaves'] := ''; // do not localize SL.Values['IDLoja'] := ''; SL.Values['IDLojaToken'] := ''; SL.SaveToFile(aNomeArq); end; finally SL.Free; end; finally UnLock; end; end; procedure TRegistro.LeArqPadrao(const LeCodLoja: Boolean = False); begin LeArq(FullLicArq, True, LeCodLoja); end; function TRegistro.LicencasValidas(aSomarVencidas: Boolean; aCodEquip: String = ''; aSN: String = ''): Integer; var I, N : Integer; Tipo : TTipoChave; begin {$I crypt_start.inc} Lock; try Result := 0; if aCodEquip='' then CodEquipSerial(aCodEquip, aSN); for I := 0 to NumChaves - 1 do begin N := FChaves[I].ChaveValida(FLoja, aCodEquip, aSN, Tipo); if N>2000 then N := 0; if (N>0) and (Tipo<>tcDefinitiva) and (Tipo<>tcFreePremium) and (Tipo<>tcFreePro) and FChaves[I].Venceu then N := 0; Result := Result + N; end; finally UnLock; end; {$I crypt_end.inc} end; procedure TRegistro.Lock; begin FCS.Enter; end; function TRegistro.NumChaves: Integer; begin Lock; try Result := FChaves.Count; finally UnLock; end; end; function TRegistro.RemoveChave(const StrChave: String): Boolean; begin Lock; try Result := FChaves.Remove(StrChave); finally UnLock; end; end; procedure TRegistro.SalvaArq(const aNomeArq: String); var SL : TStrings; const SNBool : Array[Boolean] of Char = ('N', 'S'); begin Lock; try SL := TStringList.Create; try SL.Values['Loja'] := Conta; // do not localize SL.Values['Chaves'] := StringChaves; // do not localize SL.Values['BP'] := IntToStr(FBoletosPendentes); // do not localize SL.Values['JFP'] := SNBool[FJaFoiPremium]; // do not localize SL.Values['IDLoja'] := IntToStr(FIDLoja); SL.Values['IDLojaToken'] := FIDLojaKey; if FileIsReadOnly(aNomeArq) then FileSetReadOnly(aNomeArq, False); FileSetAttr(aNomeArq, faArchive); try SL.SaveToFile(aNomeArq); FFalhouSalvar := False; except FFalhouSalvar := True; end; finally SL.Free; end; finally UnLock; end; end; procedure TRegistro.SalvaArqPadrao; begin SalvaArq(FullLicArq); end; function TRegistro.GetSerialHD: String; var sl: TStrings; begin {$I crypt_start.inc} Result := ''; sl := TStringList.Create; try try GetSerials(sl); Result := sl[0]; finally sl.Free; end; except on E: Exception do DebugMsg('GetSerial HD - Erro = '+E.Message); // do not localize end; {$I crypt_end.inc} end; procedure TRegistro.SetBoletosPendentes(const Value: Integer); begin Lock; try FBoletosPendentes := Value; finally Unlock; end; end; procedure TRegistro.SetCodLojaAsString(const Value: String); begin CodLoja := StrToCodLoja(Value); end; procedure TRegistro.SetConta(const Value: String); begin CodLoja := StrToIntDef(Value, 0); if CodLoja=0 then CodLoja := StrToCodLoja(Value); if CodLoja=0 then FEmail := Value; end; function getIDLojaKey(aIDLoja, aConta: String): String; overload; begin Result := getMD5Str('nex'+aIDLoja+'nex'+aConta+'nex'); end; function getIDLojaKey(aIDLoja: Cardinal; aConta: String): String; overload; begin Result := getIDLojaKey(IntToStr(aIDLoja), aConta); end; procedure TRegistro.SetIDLoja(aIDLoja: String); begin FCS.Enter; try FIDLoja := StrToIntDef(aIDLoja, 0); finally FCS.Leave; end; end; procedure TRegistro.SetIDLojaKey(aIDLojaKey: String); begin FCS.Enter; try FIDLojaKey := aIDLojaKey; finally FCS.Leave; end; end; procedure TRegistro.SetJaFoiPremium(const Value: Boolean); begin Lock; try FJaFoiPremium := Value; finally Unlock; end; end; procedure TRegistro.SetLoja(const Value: Integer); begin Lock; try FLoja := Value; if Value>0 then FEmail := ''; finally UnLock; end; end; procedure TRegistro.SetStringChaves(const Value: String); var S, C: String; P: Integer; begin Lock; try Clear; S := Trim(Value); while S>'' do begin P := Pos(';', S); if P>0 then begin C := Trim(Copy(S, 1, P-1)); Delete(S, 1, P); end else begin C := Trim(S); S := ''; end; if Length(C)=24 then AddChave(C); end; finally UnLock; end; end; function TRegistro.Status: TStatusConta; var I : Integer; aCE, aSN : String; aTipo : TTipoChave; begin Lock; try if (Trim(Conta)='') or (NumChaves=0) then Result := scSemConta else for I := 0 to NumChaves - 1 do begin CodEquipSerial(aCE, aSN); Result := FChaves[I].Status(FLoja, aCE, aSN, FTipo); if Result<>scOutroHD then Exit; end; finally Unlock; end; end; procedure TRegistro.Unlock; begin FCS.Leave; end; { TArrayChaveLiberacao } procedure TArrayChaveLiberacao.Add(const StrChave: String); var C: TChaveLiberacao; begin C := TChaveLiberacao.Create; C.AsString := StrChave; FItems.Add(C) end; procedure TArrayChaveLiberacao.Clear; begin while Count>0 do begin TObject(FItems[0]).Free; FItems.Delete(0); end; end; function TArrayChaveLiberacao.Clone: TArrayChaveLiberacao; begin Result := TArrayChaveLiberacao.Create; Result.AsString := AsString; end; function TArrayChaveLiberacao.Count: Integer; begin Result := FItems.Count; end; constructor TArrayChaveLiberacao.Create; begin FItems := TList.Create; end; destructor TArrayChaveLiberacao.Destroy; begin Clear; FItems.Free; inherited; end; function TArrayChaveLiberacao.GetChaveByIndex(N: Integer): TChaveLiberacao; begin Result := TChaveLiberacao(FItems[N]); end; function TArrayChaveLiberacao.GetString: String; var I : Integer; begin Result := ''; for I := 0 to Count - 1 do begin if Result>'' then Result := Result + ';'; Result := Result + Items[I].AsString; end; end; function TArrayChaveLiberacao.Remove(const StrChave: String): Boolean; var I : Integer; begin for I := 0 to Count-1 do if SameText(StrChave, Items[I].AsString) then begin Items[I].Free; FItems.Delete(I); Result := True; Exit; end; Result := False; end; procedure TArrayChaveLiberacao.SetString(const Value: String); var S, C: String; P: Integer; begin Clear; S := Trim(Value); while S>'' do begin P := Pos(';', S); if P>0 then begin C := Trim(Copy(S, 1, P-1)); Delete(S, 1, P); end else begin C := Trim(S); S := ''; end; if Length(C)=24 then Add(C); end; end; function TArrayChaveLiberacao.Status(const aCodLoja: Integer; var aCodEquip, aSN: String; var aVenceEm: TDateTime): TStatusConta; var I : Integer; aTipo : TTipoChave; begin if Count=0 then begin aVenceEm := 0; Result := scOutroHD; end else begin Result := Items[0].Status(aCodLoja, aCodEquip, aSN, aTipo); aVenceEm := Items[0].Vencimento; end; end; initialization gDTol := 0; csSer := TCriticalSection.Create; slSer := TStringList.Create; RegistroGlobal := TRegistro.Create; // RegistroGlobal.LeArqPadrao; finalization RegistroGlobal.Free; slSer.Free; csSer.Free; end.
unit ConverteNumEmExtenso; interface Uses SysUtils, Classes, FolhaFuncs; Function NumeroEmExtenso(crValor: Currency): String; Function Converte(sDesc1,sDesc2,sNum: String): String; implementation Var aUnidades: Array[1..10] of String; aDezenas1: Array[1..9] of String; aDezenas2: Array[2..9] of String; aCentenas: Array[1..9] of String; Function NumeroEmExtenso(crValor: Currency): String; Var sValor: String[12]; sMilhoes, sMilhares: String; Begin Result := ''; aUnidades[1] := 'Um'; aUnidades[2] := 'Dois'; aUnidades[3] := 'Tres'; aUnidades[4] := 'Quatro'; aUnidades[5] := 'Cinco'; aUnidades[6] := 'Seis'; aUnidades[7] := 'Sete'; aUnidades[8] := 'Oito'; aUnidades[9] := 'Nove'; aUnidades[10] := 'Dez'; aDezenas1[1] := 'Onze'; aDezenas1[2] := 'Doze'; aDezenas1[3] := 'Treze'; aDezenas1[4] := 'Quatorze'; aDezenas1[5] := 'Quinze'; aDezenas1[6] := 'Dezeseis'; aDezenas1[7] := 'Dezesete'; aDezenas1[8] := 'Dezoito'; aDezenas1[9] := 'Dezenove'; aDezenas2[2] := 'Vinte'; aDezenas2[3] := 'Trinta'; aDezenas2[4] := 'Quarenta'; aDezenas2[5] := 'Cinquenta'; aDezenas2[6] := 'Sessenta'; aDezenas2[7] := 'Setenta'; aDezenas2[8] := 'Oitenta'; aDezenas2[9] := 'Noventa'; aCentenas[1] := 'Cento'; aCentenas[2] := 'Duzentos'; aCentenas[3] := 'Trezentos'; aCentenas[4] := 'Quatrocentos'; aCentenas[5] := 'Quinhentos'; aCentenas[6] := 'Seiscentos'; aCentenas[7] := 'Setecentos'; aCentenas[8] := 'Oitocentos'; aCentenas[9] := 'Novecentos'; sValor := CurrToStr(Arredonda(crValor,2)); If Pos(',',sValor) = 0 Then sValor := PreencheZeros(sValor,9)+'.00' Else If Length(Copy(sValor,Pos(',',sValor)+1,2)) = 1 Then sValor := PreencheZeros(sValor,11)+'0' Else sValor := PreencheZeros(sValor,12); sMilhoes := Converte('Milhão','Milhões',Copy(sValor,1,3)); Result := sMilhoes; If (crValor>999999.99) And (StrToInt(Copy(sValor,4,6))=0) Then Result := Result + ' de Reais'; // sValor := [000002000,66] // 123456789012 If (StrToInt(Copy(sValor,4,6))=0) And (StrToInt(Copy(sValor,11,2))=0) Then Exit; sMilhares := Converte('Mil','',Copy(sValor,4,3)); Result := Result + ' ' + sMilhares; If (Not Empty(Result)) And (StrToInt(Copy(sValor,7,3)) = 0) Then Result := Result + ' Reais' Else If (Not Empty(Result)) And (StrToInt(Copy(sValor,7,3)) <= 100) Then Result := Result + ' e'; { Else If (StrToInt(Copy(sValor,7,3))=0) Then Result := Result + ' Reais'; } If (StrToInt(Copy(sValor,7,3))=0) And (StrToInt(Copy(sValor,11,2))=0) Then Exit; If StrToInt(Copy(sValor,7,3)) > 0 Then Result := Result + ' '+Converte('Real','Reais',Copy(sValor,7,3)); If (Result <> '') And (StrToInt(Copy(sValor,11,2))>0) Then Result := Result + ' e'; Result := Result + ' '+Converte('Centavo','Centavos',Copy(sValor,11,2)); End; Function Converte(sDesc1,sDesc2,sNum: String): String; Var sDesc: String; sNum2: String[3]; cTeste: Char; Begin { If StrToInt(sNum) = 18 Then cTeste := 'a'; } Result := ''; If StrToInt(sNum) = 0 Then Exit; If Length(RTrim(sNum)) < 3 Then sNum := '0'+ sNum; If sDesc2 = '' Then sDesc := sDesc1 Else sDesc := sDesc2; If StrToInt(sNum) <= 10 Then Result := aUnidades[StrToInt(sNum)] Else If StrToInt(sNum) <= 19 Then Result := aDezenas1[StrToInt(sNum)-10] Else If StrToInt(sNum) <= 99 Then Begin sNum2 := sNum; If StrToInt(Copy(sNum,1,1)) = 0 Then sNum2 := Copy(sNum,2,2); Result := aDezenas2[StrToInt(Copy(sNum2,1,1))]; If StrToInt(_Right(Rtrim(sNum2),1)) > 0 Then Result := Result+' e '+aUnidades[StrToInt(_Right(RTrim(sNum2),1))] End Else Begin If StrToInt(sNum) = 100 Then Begin Result := 'Cem '+sDesc; Exit; End Else Result := aCentenas[StrToInt(Copy(sNum,1,1))]; If StrToInt(_Right(sNum,2)) > 0 Then Begin If StrToInt(_Right(sNum,2)) <= 10 Then Result := Result + ' e '+aUnidades[StrToInt(_Right(sNum,2))] Else If StrToInt(_Right(sNum,2)) <= 19 Then Result := Result + ' e '+aDezenas1[StrToInt(_Right(sNum,2))-10] Else Begin sNum2 := sNum; If StrToInt(Copy(sNum,1,1)) = 0 Then sNum2 := Copy(sNum,2,2); Result := Result +' e '+aDezenas2[StrToInt(Copy(sNum2,2,1))]; If StrToInt(Copy(sNum2,3,1)) > 0 Then Result := Result+' e '+aUnidades[StrToInt(_Right(sNum2,1))]; End; End; End; If StrToInt(sNum) = 1 Then Result := Result + ' ' + sDesc1 Else Result := Result + ' ' +sDesc; End; end.
unit uEmprestimoModel; interface uses uEnumerado, FireDAC.Comp.Client; type TEmprestimoModel = class private FAcao: TAcao; FIdLivro: string; FIdUsuario: string; FInicio: string; FVencimento: string; FCodigo: integer; FRenovacoes: integer; function Buscar: TFDQuery; procedure setAcao(const Value: TAcao); procedure setCodigo(const Value: integer); procedure setInicio(const Value: string); procedure setLivro(const Value: string); procedure setRenovacoes(const Value: integer); procedure setUsuario(const Value: string); procedure setVencimento(const Value: string); public function ObterSelecionadas(Cpf: string): TFDQuery; function Salvar: Boolean; property IdLivro: string read FIdLivro write setLivro; property IdUsuario: string read FIdUsuario write setUsuario; property Inicio: string read FInicio write setInicio; property Vencimento: string read FVencimento write setVencimento; property Renovacoes: integer read FRenovacoes write setRenovacoes; property Codigo: integer read FCodigo write setCodigo; property Acao: TAcao read FAcao write setAcao; end; implementation { TLivro } uses uEmprestimoDao; function TEmprestimoModel.Buscar: TFDQuery; begin end; function TEmprestimoModel.Salvar: Boolean; var Dao: TEmprestimoDao; begin Result := False; Dao := TEmprestimoDao.Create; try case FAcao of uEnumerado.tacIncluir: Result := Dao.Incluir(Self); uEnumerado.tacAlterar: Result := Dao.Renovar(Self); uEnumerado.tacExcluir: Result := Dao.Excluir(Self); end; finally Dao.Free; end; end; procedure TEmprestimoModel.setAcao(const Value: TAcao); begin FAcao := Value; end; procedure TEmprestimoModel.setCodigo(const Value: integer); begin FCodigo := Value; end; procedure TEmprestimoModel.setInicio(const Value: string); begin FInicio := Value; end; procedure TEmprestimoModel.setLivro(const Value: string); begin FIdLivro := Value; end; procedure TEmprestimoModel.setRenovacoes(const Value: integer); begin FRenovacoes := Value; end; procedure TEmprestimoModel.setUsuario(const Value: string); begin FIdUsuario := Value; end; procedure TEmprestimoModel.setVencimento(const Value: string); begin FVencimento := Value; end; function TEmprestimoModel.ObterSelecionadas(Cpf: string): TFDQuery; var Dao: TEmprestimoDao; begin Dao := TEmprestimoDao.Create; try Result := Dao.ObterSelecionadas(Cpf); finally Dao.Free; end; end; end.
unit FIToolkit.Consts; interface uses System.SysUtils, FIToolkit.Types, FIToolkit.Commons.Consts, FIToolkit.CommandLine.Consts, FIToolkit.Localization; const { About } STR_APP_ABOUT_STRIP = '----------------------------------------------------------------------'; STR_APP_COPYRIGHT_HOLDER = 'Xcentric <true.xcentric@gmail.com>'; STR_APP_COPYRIGHT_TEXT = ' Copyright (c) 2017 ' + STR_APP_COPYRIGHT_HOLDER; STR_APP_DESCRIPTION = ' A set of tools for TMS Software(R) FixInsight(TM).'; STR_APP_TITLE = 'FIToolkit'; STR_APP_TITLE_ALIGNED = ' ' + STR_APP_TITLE; { Common consts } ARR_APPCOMMAND_TO_CLIOPTION_MAPPING : array [TApplicationCommand] of String = ( String.Empty, // STR_CLI_OPTION_HELP, STR_CLI_OPTION_VERSION, STR_CLI_OPTION_GENERATE_CONFIG, STR_CLI_OPTION_SET_CONFIG, STR_CLI_OPTION_NO_EXIT, STR_CLI_OPTION_LOG_FILE, // String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, // String.Empty ); ARR_CASE_SENSITIVE_CLI_OPTIONS : TArray<String> = []; ARR_CLIOPTION_PROCESSING_ORDER : TArray<String> = [ // Fixed order. Do not change! STR_CLI_OPTION_NO_EXIT, STR_CLI_OPTION_LOG_FILE, // Changeable order below. STR_CLI_OPTION_HELP, STR_CLI_OPTION_VERSION, STR_CLI_OPTION_GENERATE_CONFIG, STR_CLI_OPTION_SET_CONFIG ]; ARR_INPUT_FILE_TYPE_TO_EXT_MAPPING : array [TInputFileType] of String = ( String.Empty, '.dpr', '.dpk', '.dproj', '.groupproj' // Do not localize! ); ARR_INITIAL_APPSTATES : TArray<TApplicationState> = [asInitial, asNoExitBehaviorSet, asLogFileSet]; SET_FINAL_APPSTATES : set of TApplicationState = [asFinal, asHelpPrinted, asVersionPrinted, asConfigGenerated]; STR_ARCHIVE_FILE_EXT = '.zip'; STR_CMD_LINE_SWITCH_DEBUG = 'debug'; { Exit codes } UINT_EC_NO_ERROR = 0; UINT_EC_ERROR_OCCURRED = 1; UINT_EC_ANALYSIS_MESSAGES_FOUND = 2; { Resources. Do not localize! } STR_RES_HELP = 'HelpOutput'; resourcestring { About } RSApplicationAbout = STR_APP_ABOUT_STRIP + sLineBreak + STR_APP_TITLE_ALIGNED + sDualBreak + STR_APP_DESCRIPTION + sDualBreak + STR_APP_COPYRIGHT_TEXT + sLineBreak + STR_APP_ABOUT_STRIP + sLineBreak; {$IF LANGUAGE = LANG_EN_US} {$INCLUDE 'Locales\en-US.inc'} {$ELSEIF LANGUAGE = LANG_RU_RU} {$INCLUDE 'Locales\ru-RU.inc'} {$ELSE} {$MESSAGE FATAL 'No language defined!'} {$ENDIF} implementation end.
unit uLockBroker; interface // put in seperate unit so it can be shared with PKI package procedure LockBroker; // OK to nest calls as long as always paired with UnlockBroker calls procedure UnlockBroker; implementation uses System.SyncObjs; var uLock: TCriticalSection = nil; procedure LockBroker; // OK to nest calls as long as always paired with UnlockBroker calls begin uLock.Acquire; end; procedure UnlockBroker; begin uLock.Release; end; initialization uLock := TCriticalSection.Create; finalization uLock.Free; end.
unit UMain_Form; 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, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.MultiView, FMX.ListBox, FMX.Layouts, FMX.TabControl, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Objects, FMX.ScrollBox, FMX.Memo, FMX.ListView, FMX.Edit, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMX.EditBox, FMX.NumberBox, Fmx.Bind.Grid, Data.Bind.Grid, FMX.Grid, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, REST.Backend.PushTypes, REST.Backend.MetaTypes, System.JSON, REST.Backend.KinveyServices, REST.Backend.ServiceTypes, REST.Backend.Providers, REST.Backend.ServiceComponents, REST.Backend.KinveyProvider, Data.Bind.ObjectScope, REST.Backend.BindSource, FMXTee.Engine, FMXTee.Series, FMXTee.Procs, FMXTee.Chart, FMX.DateTimeCtrls; type TMain_Form = class(TForm) MultiView1: TMultiView; MultiView_ToolBar: TToolBar; MultiView_Menu_Label: TLabel; Menu_ListBox: TListBox; Lbi_Student: TListBoxItem; Lbi_Teacher: TListBoxItem; Lbi_Alram: TListBoxItem; Lbi_Class: TListBoxItem; ToolBar2: TToolBar; Button1: TButton; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; TabItem5: TTabItem; GridPanelLayout1: TGridPanelLayout; Panel1: TPanel; Panel2: TPanel; ToolBar3: TToolBar; Teacher_Edt_Search: TEdit; Teacher_Btn_Search: TButton; Teacher_ListView: TListView; ToolBar4: TToolBar; Teacher_Btn_New: TButton; Teacher_Btn_Sujung: TButton; Teacher_Btn_Del: TButton; Teacher_Btn_Cancle: TButton; Teacher_Memo_Groupbox: TGroupBox; Teacher_Memo_Memo: TMemo; Teacher_Image_GroupBox: TGroupBox; Teacher_Image: TImage; Teacher_Btn_TakePh: TButton; Teacher_Btn_ImageDel: TButton; Teacher_Info_GroupBox: TGroupBox; ListBox2: TListBox; ListBoxItem5: TListBoxItem; ListBoxItem6: TListBoxItem; ListBoxItem7: TListBoxItem; ListBoxItem8: TListBoxItem; ListBoxItem9: TListBoxItem; ListBoxItem10: TListBoxItem; ListBoxItem11: TListBoxItem; Teacher_Edt_Name: TEdit; Teacher_Edt_Phone: TEdit; Teacher_Edt_Dept: TEdit; Teacher_Edt_Address: TEdit; Image2: TImage; Image3: TImage; Image4: TImage; Image5: TImage; Lbi_Stats: TListBoxItem; Image7: TImage; Teacher_Btn_Save: TButton; Teacher_Edt_Age: TNumberBox; Teacher_Edt_Manegement: TNumberBox; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkListControlToField1: TLinkListControlToField; Teacher_PB_Score: TNumberBox; GridPanelLayout2: TGridPanelLayout; Panel3: TPanel; ToolBar1: TToolBar; Student_Edt_Search: TEdit; Student_Btn_Search: TButton; Student_ListView: TListView; Panel4: TPanel; ToolBar5: TToolBar; Student_Btn_New: TButton; Student_Btn_Sujang: TButton; Student_Btn_Del: TButton; Student_Btn_Cancle: TButton; Student_Btn_Save: TButton; GroupBox1: TGroupBox; Student_Memo: TMemo; GroupBox2: TGroupBox; Student_Image: TImage; Button8: TButton; Button9: TButton; GroupBox3: TGroupBox; ListBox1: TListBox; ListBoxItem1: TListBoxItem; Student_Edt_Name: TEdit; ListBoxItem2: TListBoxItem; Student_Edt_Age: TNumberBox; ListBoxItem3: TListBoxItem; Student_Edt_Address: TEdit; ListBoxItem4: TListBoxItem; Student_Edt_Class: TEdit; ListBoxItem12: TListBoxItem; Student_Edt_PName: TEdit; ListBoxItem13: TListBoxItem; Student_Edt_PAge: TNumberBox; ListBoxItem14: TListBoxItem; lbl_Title: TLabel; Student_Edt_PPhone: TEdit; BindSourceDB2: TBindSourceDB; LinkListControlToField2: TLinkListControlToField; GroupBox4: TGroupBox; ListBox3: TListBox; ListBoxGroupHeader1: TListBoxGroupHeader; log_text: TListBoxItem; ListBoxItem15: TListBoxItem; Log: TLabel; LogMemo: TMemo; TetheringManager1: TTetheringManager; TetheringAppProfile1: TTetheringAppProfile; GroupBox5: TGroupBox; BackendPush1: TBackendPush; KinveyProvider1: TKinveyProvider; BackendUsers1: TBackendUsers; Memo1: TMemo; ToolBar6: TToolBar; Button3: TButton; Button2: TButton; ToolBar7: TToolBar; DateEdit1: TDateEdit; Label1: TLabel; Label2: TLabel; ComboBox1: TComboBox; GroupBox6: TGroupBox; ListView1: TListView; BindSourceDB3: TBindSourceDB; LinkListControlToField3: TLinkListControlToField; Button4: TButton; GridPanelLayout3: TGridPanelLayout; Panel5: TPanel; ToolBar8: TToolBar; ListView2: TListView; Panel6: TPanel; ToolBar9: TToolBar; Button6: TButton; Button11: TButton; Button12: TButton; GroupBox7: TGroupBox; Memo2: TMemo; GroupBox8: TGroupBox; Memo3: TMemo; Label3: TLabel; Label4: TLabel; BindSourceDB4: TBindSourceDB; LinkListControlToField4: TLinkListControlToField; LinkControlToField1: TLinkControlToField; LinkControlToField2: TLinkControlToField; LinkPropertyToFieldText: TLinkPropertyToField; ToolBar10: TToolBar; ToolBar11: TToolBar; Label5: TLabel; Label7: TLabel; Label6: TLabel; Edit1: TEdit; Edit2: TEdit; LinkControlToField3: TLinkControlToField; LinkControlToField4: TLinkControlToField; LinkPropertyToFieldText2: TLinkPropertyToField; StyleBook1: TStyleBook; Image1: TImage; Image6: TImage; Image8: TImage; procedure Menu_ListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure Lbi_TeacherClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Teacher_Btn_SaveClic(Sender: TObject); procedure Teacher_Btn_NewClick(Sender: TObject); procedure Teacher_Btn_DelClick(Sender: TObject); procedure Teacher_ListViewChange(Sender: TObject); procedure Teacher_Clear; procedure Teacher_Btn_SujungClick(Sender: TObject); procedure Teacher_Btn_CancleClick(Sender: TObject); procedure Teacher_Edt_SearchClick(Sender: TObject); procedure Teacher_Btn_SearchClick(Sender: TObject); procedure Lbi_StudentClick(Sender: TObject); procedure Student_Btn_NewClick(Sender: TObject); procedure Student_Btn_CancleClick(Sender: TObject); procedure Student_Btn_SaveClick(Sender: TObject); procedure Student_Btn_SujangClick(Sender: TObject); procedure Student_Btn_DelClick(Sender: TObject); procedure Student_ListViewChange(Sender: TObject); procedure Lbi_AlramClick(Sender: TObject); procedure Log_Show(sLogMes : string); procedure TetheringManager1PairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringManager1RemoteManagerShutdown(const Sender: TObject; const AManagerIdentifier: string); procedure TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Lbi_StatsClick(Sender: TObject); procedure Lbi_ClassClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); procedure Button6Click(Sender: TObject); procedure Button11Click(Sender: TObject); procedure Button12Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main_Form: TMain_Form; TeacherCount : integer; implementation {$R *.fmx} uses UDM; procedure TMain_Form.Button11Click(Sender: TObject); begin DM.CDS_QA.Cancel; Button6.Enabled := True; Button11.Enabled := False; Button12.Enabled := False; end; procedure TMain_Form.Button12Click(Sender: TObject); begin Button6.Enabled := True; Button11.Enabled := False; Button12.Enabled := False; DM.CDS_QA.Post; DM.CDS_QA.ApplyUpdates(0); end; procedure TMain_Form.Button2Click(Sender: TObject); begin DM.CDS_MEMO.FieldByName('M_DATE').AsString := DateToStr(DateEdit1.Date); DM.CDS_MEMO.FieldByName('M_MEMO').AsString := Memo1.Text; DM.CDS_MEMO.FieldByName('M_EDITER').AsString := ComboBox1.Items.Strings[ComboBox1.ItemIndex]; DM.CDS_MEMO.Post; DM.CDS_MEMO.ApplyUpdates(0); // BackendPush1.Message := 'Memo#'+Memo1.Text; // BackendPush1.Push; Memo1.Text:=''; ShowMessage('전송되었습니다.'); Button2.Enabled := False; end; procedure TMain_Form.Button3Click(Sender: TObject); begin Memo1.Text :=''; DM.CDS_MEMO.Cancel; Button4.Enabled:= True; end; procedure TMain_Form.Button4Click(Sender: TObject); begin Memo1.Text:= ''; DateEdit1.Date := Now; ComboBox1.ItemIndex := 0; DM.CDS_MEMO.Insert; Button2.Enabled := True; Button3.Enabled := True; end; procedure TMain_Form.Button6Click(Sender: TObject); begin DM.CDS_QA.Edit; Label7.Text := DateToStr(Now); Button11.Enabled := True; Button12.Enabled := True; Button6.Enabled := False; end; procedure TMain_Form.FormCreate(Sender: TObject); begin TabControl1.ActiveTab := TabItem1; end; procedure TMain_Form.Menu_ListBoxItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin Item.IsSelected := False; MultiView1.HideMaster; end; procedure TMain_Form.Student_Btn_CancleClick(Sender: TObject); begin DM.CDS_Student_Info.Cancel; Student_Btn_Del.Enabled :=True; Student_Btn_Sujang.Enabled :=True; Student_Btn_New.Enabled :=True; Student_Btn_Save.Enabled :=False; Student_Btn_Cancle.Enabled := False; end; procedure TMain_Form.Student_Btn_DelClick(Sender: TObject); begin DM.CDS_Student_Info.Delete; DM.CDS_Student_Info.ApplyUpdates(0); end; procedure TMain_Form.Student_Btn_NewClick(Sender: TObject); begin Student_Edt_Name.Text := ''; Student_Edt_Age.Value:=0; Student_Edt_Class.Text:=''; Student_Edt_Address.Text:=''; Student_Edt_PName.Text:=''; Student_Edt_PAge.Value:=0; Student_Memo.Text:=''; Student_Edt_PPhone.Text:=''; DM.CDS_Student_Info.Last; DM.CDS_Student_Info.Insert; Student_Btn_Del.Enabled :=False; Student_Btn_Sujang.Enabled :=False; Student_Btn_New.Enabled :=False; Student_Btn_Save.Enabled :=True; Student_Btn_Cancle.Enabled := True; end; procedure TMain_Form.Student_Btn_SaveClick(Sender: TObject); begin Student_Btn_Del.Enabled :=True; Student_Btn_Sujang.Enabled :=True; Student_Btn_New.Enabled :=True; Student_Btn_Save.Enabled :=False; Student_Btn_Cancle.Enabled := False; DM.CDS_Student_Info.FieldByName('S_NAME').AsString := Student_Edt_Name.Text; DM.CDS_Student_Info.FieldByName('S_AGE').AsInteger := StrToInt(Student_Edt_Age.Text); DM.CDS_Student_Info.FieldByName('S_CLASS').AsString:= Student_Edt_Class.Text; DM.CDS_Student_Info.FieldByName('S_ADDRESS').AsString := Student_Edt_Address.Text; DM.CDS_Student_Info.FieldByName('P_NAME').AsString := Student_Edt_PName.Text; DM.CDS_Student_Info.FieldByName('P_AGE').AsInteger := StrToInt(Student_Edt_PAge.Text); DM.CDS_Student_Info.FieldByName('P_COMMENT').AsString :=Student_Memo.Text; DM.CDS_Student_Info.Post; DM.CDS_Student_Info.ApplyUpdates(0); Student_Edt_Name.Text := ''; Student_Edt_Age.Value:=0; Student_Edt_Class.Text:=''; Student_Edt_Address.Text:=''; Student_Edt_PName.Text:=''; Student_Edt_PAge.Value:=0; Student_Memo.Text:=''; Student_Edt_PPhone.Text:=''; end; procedure TMain_Form.Student_Btn_SujangClick(Sender: TObject); begin DM.CDS_Student_Info.Edit; Student_Btn_Del.Enabled :=False; Student_Btn_Sujang.Enabled :=False; Student_Btn_New.Enabled :=False; Student_Btn_Save.Enabled :=True; Student_Btn_Cancle.Enabled := True; end; procedure TMain_Form.Student_ListViewChange(Sender: TObject); begin Student_Edt_Name.Text:=DM.CDS_Student_Info.FieldByName('S_NAME').AsString ; Student_Edt_Age.Text:=IntToStr(DM.CDS_Student_Info.FieldByName('S_AGE').AsInteger); Student_Edt_Class.Text:=DM.CDS_Student_Info.FieldByName('S_CLASS').AsString ; Student_Edt_Address.Text:=DM.CDS_Student_Info.FieldByName('S_ADDRESS').AsString; Student_Edt_PName.Text:=DM.CDS_Student_Info.FieldByName('P_NAME').AsString ; Student_Edt_PAge.Text := IntToStr(DM.CDS_Student_Info.FieldByName('P_AGE').AsInteger) ; Student_Memo.Text:=DM.CDS_Student_Info.FieldByName('P_COMMENT').AsString; end; procedure TMain_Form.Teacher_Btn_CancleClick(Sender: TObject); begin DM.CDS_Teacher.Cancel; Teacher_Clear; end; procedure TMain_Form.Teacher_Btn_DelClick(Sender: TObject); begin DM.CDS_Teacher.Delete; DM.CDS_Teacher.ApplyUpdates(-1); Teacher_Clear; end; procedure TMain_Form.Teacher_Btn_NewClick(Sender: TObject); begin Teacher_Edt_Name.Text:=''; Teacher_Edt_Age.Value:=0; Teacher_Edt_Phone.Text:=''; Teacher_Edt_Dept.Text:=''; Teacher_Edt_Address.Text:=''; Teacher_Edt_Manegement.Value:=0; Teacher_PB_Score.Value:=0; Teacher_Memo_Memo.Text:=''; DM.CDS_Teacher.First; DM.CDS_Teacher.Insert; Teacher_Btn_Del.Enabled :=False; Teacher_Btn_Sujung.Enabled :=False; Teacher_Btn_New.Enabled :=False; Teacher_Btn_Save.Enabled :=True; Teacher_Btn_Cancle.Enabled := True; end; procedure TMain_Form.Teacher_Btn_SaveClic(Sender: TObject); begin DM.CDS_Teacher.FieldByName('T_NAME').AsString:=Main_Form.Teacher_Edt_Name.Text; DM.CDS_Teacher.FieldByName('T_AGE').AsInteger:=StrToInt(Main_Form.Teacher_Edt_Age.Text); DM.CDS_Teacher.FieldByName('T_PHONE').AsString:=Main_Form.Teacher_Edt_Phone.Text; DM.CDS_Teacher.FieldByName('T_DEPT').AsString:=Main_Form.Teacher_Edt_Dept.Text; DM.CDS_Teacher.FieldByName('T_ADDRESS').AsString:=Main_Form.Teacher_Edt_Address.Text; DM.CDS_Teacher.FieldByName('T_MANAGEMENT').AsInteger:=StrToInt(Main_Form.Teacher_Edt_Manegement.Text); DM.CDS_Teacher.FieldByName('T_COMMENT').AsString:=Main_Form.Teacher_Memo_Memo.Text; DM.CDS_Teacher.FieldByName('T_SCORE').AsInteger:=StrToInt(Main_Form.Teacher_PB_Score.Text); DM.CDS_Teacher.Post; DM.CDS_Teacher.ApplyUpdates(0); Teacher_Clear; end; procedure TMain_Form.Teacher_Btn_SearchClick(Sender: TObject); var i : integer; begin DM.CDS_Teacher.First; for I := 0 to DM.CDS_Teacher.RecordCount do begin if dm.CDS_Teacher.FieldByName('T_NAME').AsString = Teacher_Edt_Search.Text then Exit else DM.CDS_Teacher.Next; end; end; procedure TMain_Form.Teacher_Btn_SujungClick(Sender: TObject); begin Teacher_Btn_Del.Enabled :=False; Teacher_Btn_Sujung.Enabled :=False; Teacher_Btn_New.Enabled :=False; Teacher_Btn_Save.Enabled :=True; Teacher_Btn_Cancle.Enabled := True; DM.CDS_Teacher.Edit; end; procedure TMain_Form.Teacher_Clear; begin DM.CDS_Teacher.First; Teacher_Btn_Save.Enabled :=False; Teacher_Btn_Cancle.Enabled := False; Teacher_Btn_New.Enabled :=True; Teacher_Btn_Del.Enabled :=True; Teacher_Btn_Sujung.Enabled :=True; end; procedure TMain_Form.Teacher_Edt_SearchClick(Sender: TObject); begin Teacher_Edt_Search.Text := ''; end; procedure TMain_Form.Teacher_ListViewChange(Sender: TObject); begin Main_Form.Teacher_Edt_Name.Text:=DM.CDS_Teacher.FieldByName('T_NAME').AsString; Main_Form.Teacher_Edt_Age.Text := IntToStr(DM.CDS_Teacher.FieldByName('T_AGE').AsInteger); Main_Form.Teacher_Edt_Phone.Text :=DM.CDS_Teacher.FieldByName('T_PHONE').AsString; Main_Form.Teacher_Edt_Dept.Text:= DM.CDS_Teacher.FieldByName('T_DEPT').AsString; Main_Form.Teacher_Edt_Address.Text:=DM.CDS_Teacher.FieldByName('T_ADDRESS').AsString; Main_Form.Teacher_Edt_Manegement.Text:=IntToStr(DM.CDS_Teacher.FieldByName('T_MANAGEMENT').AsInteger); Main_Form.Teacher_Memo_Memo.Text:=DM.CDS_Teacher.FieldByName('T_COMMENT').AsString; Main_Form.Teacher_PB_Score.Text:= IntToStr(DM.CDS_Teacher.FieldByName('T_SCORE').AsInteger); end; procedure TMain_Form.TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin case AResource.ResType of TRemoteResourceType.Data: begin if AResource.Hint = 'CLIENT_STRING' then // AResource.Hint는 보내는쪽 SendStream 이나 SendString의 두번째 파라미터(Description) begin Log_Show( AResource.Value.AsString ); ShowMessage('알림이 전송됩니다.'); BackendPush1.Message := 'Test#'; BackendPush1.Push; end; end; end; end; procedure TMain_Form.TetheringManager1PairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin Log_Show('연결되었습니다.'); Log.Text := '임석진 선생님과 연결중'; end; procedure TMain_Form.TetheringManager1RemoteManagerShutdown( const Sender: TObject; const AManagerIdentifier: string); begin Log_Show('연결 해제됨'); Log.Text := '임석진 선생님과 연결이 종료되었습니다.'; end; procedure TMain_Form.Lbi_AlramClick(Sender: TObject); var i: integer; begin TabControl1.ActiveTab :=TabItem3; lbl_Title.Text := '알림센터'; dm.CDS_Teacher.First; for I := 0 to DM.CDS_Teacher.RecordCount-1 do begin ComboBox1.Items.Add(DM.CDS_Teacher.FieldByName('T_NAME').AsString); DM.CDS_Teacher.Next; end; end; procedure TMain_Form.Lbi_ClassClick(Sender: TObject); begin TabControl1.ActiveTab :=TabItem4; lbl_Title.Text := '질의 응답'; end; procedure TMain_Form.Lbi_StatsClick(Sender: TObject); begin ShowMessage('개발중입니다.'); end; procedure TMain_Form.Lbi_StudentClick(Sender: TObject); begin TabControl1.ActiveTab :=TabItem1; lbl_Title.Text := '원생관리'; end; procedure TMain_Form.Lbi_TeacherClick(Sender: TObject); begin TabControl1.ActiveTab :=TabItem2; lbl_Title.Text := '선생님관리'; end; procedure TMain_Form.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); var i : integer; begin for I := 0 to ComboBox1.Items.Count do begin if DM.CDS_MEMO.FieldByName('M_EDITER').AsString = ComboBox1.Items.Strings[i] then begin ComboBox1.ItemIndex:=i; memo1.Text:=dm.CDS_MEMO.FieldByName('M_MEMO').AsString; Break; end; end; end; procedure TMain_Form.Log_Show(sLogMes: string); begin LogMemo.Lines.Add('임석진선생님:'+sLogMes); LogMemo.ScrollBy(0,-9999999); end; end.
unit guid_1; interface implementation var G1, G2: TGUID; procedure CreateGUID(out GUID: TGUID); external 'system'; procedure Test; begin CreateGUID(G1); G2 := G1; end; initialization Test(); finalization Assert(G1 = G2); end.
unit uWBGoogleMaps; interface uses SysUtils, Forms, Graphics, Windows, Classes, ShDocVw, uWebBrowser; type TWBGoogleMaps = class(TWBWrapper) private fLoadedGoogleMaps: Boolean; public constructor Create(const HostedBrowser: TWebBrowser); procedure LoadDefaultGoogleMapsDocument; property LoadedGoogleMaps: Boolean read fLoadedGoogleMaps; published property OnGetExternal; end; implementation constructor TWBGoogleMaps.Create(const HostedBrowser: TWebBrowser); begin inherited; // my preferred defaults: no border, no scroll bars Show3DBorder := False; ShowScrollBars := False; end; procedure TWBGoogleMaps.LoadDefaultGoogleMapsDocument; const rootDoc: String = '<html>'#13#10 + ' <head>'#13#10 + ' <meta http-equiv="content-type" content="text/html"/>'#13#10 + ' <title>Google Maps JavaScript API Example</title>'#13#10 + ' <script src="http://maps.google.com/maps?file=api&amp;v=2" type="text/javascript"></script>'#13#10 + ' <script type="text/javascript">'#13#10 + ''#13#10 + ' var map;'#13#10 + ' //<![CDATA['#13#10 + ''#13#10 + ' function load() {'#13#10 + ' if (GBrowserIsCompatible()) {'#13#10 + ' map = new GMap2(document.getElementById("map"));'#13#10 + ' map.addControl(new GLargeMapControl());'#13#10 + ' map.addControl(new GMapTypeControl());'#13#10 + ' map.addControl(new GScaleControl());'#13#10 + ' map.enableScrollWheelZoom();'#13#10 + ' map.setCenter(new GLatLng(37.05173494, -122.03160858), 13);'#13#10 + ' }'#13#10 + ' }'#13#10 + ''#13#10 + ' //]]>'#13#10 + ' </script>'#13#10 + ' </head>'#13#10 + ''#13#10 + ' <body onload="load()" onunload="GUnload()" style="margin:0">'#13#10 + ' <div id="map" style="width: 100%; height: 300px"></div>'#13#10 + ' </body>'#13#10 + '</html>'; begin LoadHTML(rootDoc, true); fLoadedGoogleMaps := true; end; end.
unit intensive.view.Editar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, intensive.Controller.Interfaces, intensive.Controller; type TfrmEditar = class(TForm) Panel1: TPanel; Panel3: TPanel; btnSalvar: TButton; btnCancelar: TButton; edtNome: TLabeledEdit; edtTelefone: TLabeledEdit; edtLogradouro: TLabeledEdit; edtCep: TLabeledEdit; edtBairro: TLabeledEdit; edtCidade: TLabeledEdit; edtEstado: TLabeledEdit; grdEnderecos: TDBGrid; dsEndereco: TDataSource; edtId: TLabeledEdit; procedure FormDestroy(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure grdEnderecosCellClick(Column: TColumn); private FEditar : Boolean; FDts : TDataSource; FController : iController; procedure FillFields; public constructor Create(AOwner: TComponent; aDataSource: TDataSource; aEditar: Boolean = true); end; var frmEditar: TfrmEditar; implementation {$R *.dfm} { TfrmEditar } procedure TfrmEditar.btnSalvarClick(Sender: TObject); begin FController.Cliente .Nome(edtNome.Text) .Telefone(edtTelefone.Text) .Build.Inserir; // FController.Endereco // .IdCliente(FController.Cliente.Id) // .Logradouro(edtLogradouro.Text) // .Cep(edtCep.Text) // .Bairro(edtBairro.Text) // .Cidade(edtCidade.Text) // .Estado(edtEstado.Text) // .Build.Inserir; FillFields; end; constructor TfrmEditar.Create(AOwner: TComponent; aDataSource: TDataSource; aEditar: Boolean = true); begin inherited Create(AOwner); FDts := TDataSource.Create(nil); Fdts := aDataSource; FEditar := aEditar; if aEditar then begin edtNome.Text := FDts.DataSet.FieldByName('NOME').AsString; edtTelefone.Text := FDts.DataSet.FieldByName('TELEFONE').AsString; end; FController := TController.New; end; procedure TfrmEditar.grdEnderecosCellClick(Column: TColumn); begin edtLogradouro.Text := dsEndereco.DataSet.FieldByName('LOGRADOURO').AsString; edtCep.Text := dsEndereco.DataSet.FieldByName('CEP').AsString; edtBairro.Text := dsEndereco.DataSet.FieldByName('BAIRRO').AsString; edtCidade.Text := dsEndereco.DataSet.FieldByName('CIDADE').AsString; edtEstado.Text := dsEndereco.DataSet.FieldByName('ESTADO').AsString; end; procedure TfrmEditar.FillFields; begin edtid.Text := FController.Cliente.Id.ToString; edtNome.Text := FController.Cliente.Nome; edtTelefone.Text := FController.Cliente.Telefone; // edtLogradouro.Text := FController.Endereco.Logradouro; // edtCep.Text := FController.Endereco.Cep; // edtBairro.Text := FController.Endereco.Bairro; // edtCidade.Text := FController.Endereco.Cidade; // edtEstado.Text := FController.Endereco.Estado; // // dsEndereco.DataSet := FController.Endereco.Build.Listar; end; procedure TfrmEditar.FormDestroy(Sender: TObject); begin FDts.DisposeOf; end; end.
unit ComponentsGroupUnit2; interface uses BaseComponentsGroupUnit2, System.Classes, NotifyEvents, ComponentsQuery, FamilyQuery, ComponentsCountQuery, EmptyFamilyCountQuery, ComponentsExcelDataModule, System.Generics.Collections, ExcelDataModule, Data.DB, CustomErrorTable, DSWrap; type TAutomaticLoadErrorTableW = class(TCustomErrorTableW) private FCategoryName: TFieldWrap; FDescription: TFieldWrap; FFileName: TFieldWrap; FSheetIndex: TFieldWrap; public constructor Create(AOwner: TComponent); override; procedure LocateOrAppendData(const AFileName: string; ASheetIndex: Variant; ACategoryName: string; const ADescription: string; AError: string); property CategoryName: TFieldWrap read FCategoryName; property Description: TFieldWrap read FDescription; property FileName: TFieldWrap read FFileName; property SheetIndex: TFieldWrap read FSheetIndex; end; TAutomaticLoadErrorTable = class(TCustomErrorTable) private function GetW: TAutomaticLoadErrorTableW; protected function CreateWrap: TCustomErrorTableW; override; public constructor Create(AOwner: TComponent); override; property W: TAutomaticLoadErrorTableW read GetW; end; TFolderLoadEvent = class(TObject) private FAutomaticLoadErrorTable: TAutomaticLoadErrorTable; FCategoryName: string; FExcelDMEvent: TExcelDMEvent; FFileName: string; FProducer: string; public constructor Create(const AFileName: string; const AutomaticLoadErrorTable: TAutomaticLoadErrorTable; const ACategoryName: string; const AExcelDMEvent: TExcelDMEvent; const AProducer: string); property AutomaticLoadErrorTable: TAutomaticLoadErrorTable read FAutomaticLoadErrorTable; property CategoryName: string read FCategoryName; property ExcelDMEvent: TExcelDMEvent read FExcelDMEvent; property FileName: string read FFileName; property Producer: string read FProducer; end; TComponentsGroup2 = class(TBaseComponentsGroup2) private FqComponents: TQueryComponents; FqFamily: TQueryFamily; function GetqComponents: TQueryComponents; function GetqFamily: TQueryFamily; protected procedure DoBeforeDetailPost(Sender: TObject); public constructor Create(AOwner: TComponent); override; procedure DoAfterLoadSheet(e: TFolderLoadEvent); procedure DoOnTotalProgress(e: TFolderLoadEvent); procedure LoadDataFromExcelTable(AComponentsExcelTable : TComponentsExcelTable; const AProducer: string); // TODO: LoadBodyList // procedure LoadBodyList(AExcelTable: TComponentBodyTypesExcelTable); function LoadFromExcelFolder(AFileNames: TList<String>; AutomaticLoadErrorTable: TAutomaticLoadErrorTable; const AProducer: String): Integer; property qComponents: TQueryComponents read GetqComponents; property qFamily: TQueryFamily read GetqFamily; end; implementation uses ProgressInfo, System.SysUtils, Vcl.Forms, System.StrUtils, TreeListQuery, System.IOUtils, System.Variants, FireDAC.Comp.DataSet; { TfrmComponentsMasterDetail } constructor TComponentsGroup2.Create(AOwner: TComponent); begin inherited Create(AOwner); // Сначала будем открывать компоненты, чтобы при открытии семейства знать сколько у него компонент // Компоненты и семейства не связаны как главный-подчинённый главным для них является категория QList.Add(qComponents); QList.Add(qFamily); TNotifyEventWrap.Create(qComponents.W.BeforePost, DoBeforeDetailPost, EventList); end; procedure TComponentsGroup2.DoAfterLoadSheet(e: TFolderLoadEvent); var AExcelTable: TComponentsExcelTable; AWarringCount: Integer; S: string; begin AExcelTable := e.ExcelDMEvent.ExcelTable as TComponentsExcelTable; // if AExcelTable.RecordCount = 0 then Exit; e.AutomaticLoadErrorTable.W.LocateOrAppendData(e.FileName, e.ExcelDMEvent.SheetIndex, e.CategoryName, 'Сохраняем в базе данных ...', ''); try // Приступаем к сохранению в базе данных AExcelTable.Process( procedure(ASender: TObject) begin LoadDataFromExcelTable(AExcelTable, e.Producer); end, procedure(ASender: TObject) Var PI: TProgressInfo; begin PI := ASender as TProgressInfo; e.AutomaticLoadErrorTable.W.LocateOrAppendData(e.FileName, e.ExcelDMEvent.SheetIndex, e.CategoryName, Format('Сохраняем в базе данных (%d%%)', [Round(PI.Position)]), ''); Application.ProcessMessages; end); AWarringCount := AExcelTable.Errors.TotalErrorsAndWarrings; S := IfThen(AWarringCount = 0, 'Успешно', Format('Успешно, предупреждений %d', [AWarringCount])); e.AutomaticLoadErrorTable.W.LocateOrAppendData(e.FileName, e.ExcelDMEvent.SheetIndex, e.CategoryName, S, ''); except on ee: Exception do begin e.AutomaticLoadErrorTable.W.LocateOrAppendData(e.FileName, e.ExcelDMEvent.SheetIndex, e.CategoryName, ee.Message, 'Ошибка'); end; end; end; procedure TComponentsGroup2.DoBeforeDetailPost(Sender: TObject); begin Assert(qFamily.FDQuery.RecordCount > 0); if qComponents.W.ParentProductID.F.IsNull then qComponents.W.ParentProductID.F.Value := qFamily.W.PK.Value; end; procedure TComponentsGroup2.DoOnTotalProgress(e: TFolderLoadEvent); begin e.AutomaticLoadErrorTable.W.LocateOrAppendData(e.FileName, e.ExcelDMEvent.SheetIndex, e.CategoryName, Format('Загружаем данные с листа %d (%d%%)', [e.ExcelDMEvent.SheetIndex, Round(e.ExcelDMEvent.TotalProgress.PIList[e.ExcelDMEvent.SheetIndex - 1] .Position)]), ''); Application.ProcessMessages; end; function TComponentsGroup2.GetqComponents: TQueryComponents; begin if FqComponents = nil then FqComponents := TQueryComponents.Create(Self); Result := FqComponents; end; function TComponentsGroup2.GetqFamily: TQueryFamily; begin if FqFamily = nil then FqFamily := TQueryFamily.Create(Self); Result := FqFamily; end; procedure TComponentsGroup2.LoadDataFromExcelTable(AComponentsExcelTable : TComponentsExcelTable; const AProducer: string); var I: Integer; k: Integer; m: TArray<String>; S: string; begin Assert(not AProducer.IsEmpty); Assert(not qFamily.AutoTransaction); Assert(not qComponents.AutoTransaction); // работать в рамках одной транзакции гораздо быстрее // qFamily.AutoTransaction := True; // qComponents.AutoTransaction := True; k := 0; // Кол-во обновлённых записей try qFamily.FDQuery.DisableControls; qComponents.FDQuery.DisableControls; try // qFamily.SaveBookmark; // qComponents.SaveBookmark; // try AComponentsExcelTable.First; AComponentsExcelTable.CallOnProcessEvent; while not AComponentsExcelTable.Eof do begin // Добавляем семейство в базу данных qFamily.FamilyW.LocateOrAppend (AComponentsExcelTable.FamilyName.AsString, AProducer); // Если в Excel файле указаны дополнительные подгруппы if not AComponentsExcelTable.SubGroup.AsString.IsEmpty then begin // Получаем все коды категорий отдельно m := AComponentsExcelTable.SubGroup.AsString.Replace(' ', '', [rfReplaceAll]).Split([',']); S := ',' + qFamily.W.SubGroup.F.AsString + ','; for I := Low(m) to High(m) do begin // Если такой категории в списке ещё не было if S.IndexOf(',' + m[I] + ',') < 0 then S := S + m[I] + ','; end; m := nil; S := S.Trim([',']); // Если что-то изменилось if qFamily.W.SubGroup.F.AsString <> S then begin qFamily.W.TryEdit; qFamily.W.SubGroup.F.AsString := S; qFamily.W.TryPost end; end; // Добавляем дочерний компонент if not AComponentsExcelTable.ComponentName.AsString.IsEmpty then begin qComponents.ComponentsW.LocateOrAppend(qFamily.W.PK.Value, AComponentsExcelTable.ComponentName.AsString); end; Inc(k); // Уже много записей обновили в рамках одной транзакции if k >= 1000 then begin k := 0; Connection.Commit; Connection.StartTransaction; end; AComponentsExcelTable.Next; AComponentsExcelTable.CallOnProcessEvent; end; // finally // qFamily.RestoreBookmark; // qComponents.RestoreBookmark; // end; finally qComponents.FDQuery.EnableControls; qFamily.FDQuery.EnableControls end; finally Connection.Commit; end; end; function TComponentsGroup2.LoadFromExcelFolder(AFileNames: TList<String>; AutomaticLoadErrorTable: TAutomaticLoadErrorTable; const AProducer: String): Integer; var AComponentsExcelDM: TComponentsExcelDM; AFullFileName: string; AFileName: string; m: TArray<String>; AQueryTreeList: TQueryTreeList; begin Assert(AFileNames <> nil); Assert(AutomaticLoadErrorTable <> nil); Result := 0; if AFileNames.Count = 0 then Exit; Assert(not qFamily.AutoTransaction); Assert(not qComponents.AutoTransaction); AQueryTreeList := TQueryTreeList.Create(Self); try AQueryTreeList.FDQuery.Open; for AFullFileName in AFileNames do begin if not TFile.Exists(AFullFileName) then begin AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, '', 'Файл не найден', 'Ошибка'); Continue; end; AFileName := TPath.GetFileNameWithoutExtension(AFullFileName); AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, '', 'Идёт обработка этого файла...', ''); m := AFileName.Split([' ']); if Length(m) = 0 then begin AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, '', 'Имя файла не содержит идентификатора категории загрузки (или пробела)', 'Ошибка'); Continue; end; try // Проверяем что первая часть содержит целочисленный код категории m[0].ToInteger; except AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, '', 'Имя файла не содержит идентификатора категории загрузки (или пробела)', 'Ошибка'); Continue; end; AQueryTreeList.W.FilterByExternalID(m[0]); if AQueryTreeList.FDQuery.RecordCount = 0 then begin AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, '', Format('Категория %s не найдена', [m[0]]), 'Ошибка'); Continue; end; AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, AQueryTreeList.W.Value.F.AsString, 'Идёт обработка этого файла...', ''); // загружаем компоненты из нужной нам категории qComponents.LoadFromMaster(AQueryTreeList.W.PK.Value); qFamily.LoadFromMaster(AQueryTreeList.W.PK.Value); AComponentsExcelDM := TComponentsExcelDM.Create(Self); try AComponentsExcelDM.ExcelTable.Producer := AProducer; TNotifyEventR.Create(AComponentsExcelDM.BeforeLoadSheet, // Перед загрузкой очередного листа procedure(ASender: TObject) Var e: TExcelDMEvent; begin e := ASender as TExcelDMEvent; AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, e.SheetIndex, AQueryTreeList.W.Value.F.AsString, Format('Загружаем данные с листа %d...', [e.SheetIndex]), ''); end); TNotifyEventR.Create(AComponentsExcelDM.OnTotalProgress, procedure(ASender: TObject) Var e: TFolderLoadEvent; begin e := TFolderLoadEvent.Create(AFileName, AutomaticLoadErrorTable, AQueryTreeList.W.Value.F.AsString, ASender as TExcelDMEvent, AProducer); DoOnTotalProgress(e); FreeAndNil(e); end); TNotifyEventR.Create(AComponentsExcelDM.AfterLoadSheet, // После загрузки очередного листа procedure(ASender: TObject) Var e: TFolderLoadEvent; begin e := TFolderLoadEvent.Create(AFileName, AutomaticLoadErrorTable, AQueryTreeList.W.Value.F.AsString, ASender as TExcelDMEvent, AProducer); DoAfterLoadSheet(e); FreeAndNil(e); end); try // Загружаем даные из Excel файла AComponentsExcelDM.LoadExcelFile2(AFullFileName); qFamily.ApplyUpdates; qComponents.ApplyUpdates; except on e: Exception do begin AutomaticLoadErrorTable.W.LocateOrAppendData(AFileName, NULL, AQueryTreeList.W.Value.F.AsString, e.Message, 'Ошибка'); Continue; end; end; finally FreeAndNil(AComponentsExcelDM); end; end; Result := AQueryTreeList.W.PK.Value; finally FreeAndNil(AQueryTreeList); end; end; constructor TFolderLoadEvent.Create(const AFileName: string; const AutomaticLoadErrorTable: TAutomaticLoadErrorTable; const ACategoryName: string; const AExcelDMEvent: TExcelDMEvent; const AProducer: string); begin inherited Create; FFileName := AFileName; FAutomaticLoadErrorTable := AutomaticLoadErrorTable; FCategoryName := ACategoryName; FExcelDMEvent := AExcelDMEvent; FProducer := AProducer; end; constructor TAutomaticLoadErrorTable.Create(AOwner: TComponent); begin inherited; FieldDefs.Add(W.FileName.FieldName, ftWideString, 100); FieldDefs.Add(W.SheetIndex.FieldName, ftInteger); FieldDefs.Add(W.CategoryName.FieldName, ftWideString, 100); FieldDefs.Add(W.Description.FieldName, ftWideString, 100); FieldDefs.Add(W.Error.FieldName, ftWideString, 20); IndexDefs.Add('idxOrd', Format('%s;%s', [W.FileName.FieldName, W.SheetIndex.FieldName]), []); CreateDataSet; IndexName := 'idxOrd'; Open; end; function TAutomaticLoadErrorTable.CreateWrap: TCustomErrorTableW; begin Result := TAutomaticLoadErrorTableW.Create(Self); end; function TAutomaticLoadErrorTable.GetW: TAutomaticLoadErrorTableW; begin Result := Wrap as TAutomaticLoadErrorTableW; end; constructor TAutomaticLoadErrorTableW.Create(AOwner: TComponent); begin inherited; FCategoryName := TFieldWrap.Create(Self, 'CategoryName', 'Категория'); FDescription := TFieldWrap.Create(Self, 'Description', 'Описание'); FFileName := TFieldWrap.Create(Self, 'FileName', 'Имя файла'); FSheetIndex := TFieldWrap.Create(Self, 'SheetIndex', '№ листа'); end; procedure TAutomaticLoadErrorTableW.LocateOrAppendData(const AFileName: string; ASheetIndex: Variant; ACategoryName: string; const ADescription: string; AError: string); var AFieldNames: string; begin Assert(AFileName <> ''); AFieldNames := Format('%s;%s', [FileName.FieldName, SheetIndex.FieldName]); if not FDDataSet.LocateEx(AFieldNames, VarArrayOf([AFileName, ASheetIndex]), [lxoCaseInsensitive]) then begin if not FDDataSet.LocateEx(AFieldNames, VarArrayOf([AFileName, NULL]), [lxoCaseInsensitive]) then begin TryAppend; FileName.F.AsString := AFileName; end else TryEdit; end else TryEdit; SheetIndex.F.Value := ASheetIndex; CategoryName.F.AsString := ACategoryName; Description.F.AsString := ADescription; Error.F.AsString := AError; TryPost; end; end.
unit FC.Trade.Trader.MACross1; {$I Compiler.inc} interface uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage; type //Пока здесь объявлен. Потом как устоится, вынести в Definitions IStockTraderMACross1 = interface ['{DD4E918D-BAF8-4CF4-B249-F383337079A7}'] end; TStockTraderMACross1 = class (TStockTraderBase,IStockTraderMACross1) private FBarHeightD1 : ISCIndicatorBarHeight; FSMA21_M15,FSMA55_M15, FSMA84_M15, FSMA220_M15: ISCIndicatorMA; FSMA21_M1,FSMA55_M1: ISCIndicatorMA; //FLWMA21_M15,FLWMA55_M15: ISCIndicatorMA; //FMA84_M15,FMA220_M15: ISCIndicatorMA; FLastOpenOrderTime : TDateTime; FPropFullBarsOnly : TPropertyYesNo; FPropMaxPriceAndMAGap : TPropertyInt; protected function CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; function CreateMA(const aChart: IStockChart; aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; //Считает, на какой примерно цене сработает Stop Loss или Trailing Stop function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; //Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; procedure CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); procedure CloseAllOrders(aKind: TSCOrderKind;const aComment: string); function GetRecommendedLots: TStockOrderLots; override; procedure SetTP(const aOrder: IStockOrder; const aTP: TStockRealNumber; const aComment: string); function GetMainTrend(index: integer): TSCRealNumber; function GetFastTrend(index: integer): TSCRealNumber; function GetCross2155(index: integer): integer; function GetCross84_220(index: integer): integer; function GetCrossM1(index: integer): integer; function PriceToPoint(const aPrice: TSCRealNumber): integer; function GetCurrentBid: TSCRealNumber; public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; function OpenOrder(aKind: TStockOrderKind;const aComment: string=''): IStockOrder; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses DateUtils,Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderMACross1 } procedure TStockTraderMACross1.CloseAllOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) then CloseOrder(aOrders[i],aComment); end; end; procedure TStockTraderMACross1.CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string); var i: Integer; aOrders : IStockOrderCollection; begin aOrders:=GetOrders; for i := aOrders.Count- 1 downto 0 do begin if (aOrders[i].GetKind=aKind) and (aOrders[i].GetCurrentProfit>0) then CloseOrder(aOrders[i],aComment); end; end; constructor TStockTraderMACross1.Create; begin inherited Create; FPropFullBarsOnly := TPropertyYesNo.Create('Method','Full Bars Only',self); FPropFullBarsOnly.Value:=true; FPropMaxPriceAndMAGap:=TPropertyInt.Create('Method','Max gap between price and MA level',self); FPropMaxPriceAndMAGap.Value:=200; RegisterProperties([FPropFullBarsOnly,FPropMaxPriceAndMAGap]); //UnRegisterProperties([PropLotDefaultRateSize,PropLotDynamicRate]); end; function TStockTraderMACross1.CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorBarHeight,'BarHeightD1',true, aCreated) as ISCIndicatorBarHeight; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetPeriod(3); Result.SetBarHeight(bhHighLow); end; end; function TStockTraderMACross1.CreateMA(const aChart: IStockChart;aPeriod: integer; aMethod: TSCIndicatorMAMethod): ISCIndicatorMA; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorMA, 'MA'+IntToStr(integer(aMethod))+'_'+IntToStr(aPeriod)+StockTimeIntervalNames[aChart.StockSymbol.TimeInterval], true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin Result.SetMAMethod(aMethod); Result.SetPeriod(aPeriod); end; end; destructor TStockTraderMACross1.Destroy; begin inherited; end; procedure TStockTraderMACross1.Dispose; begin inherited; end; function TStockTraderMACross1.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber; begin result:=aOrder.GetStopLoss; if aOrder.GetState=osOpened then if aOrder.GetKind=okBuy then result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop) else result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop); end; function TStockTraderMACross1.GetFastTrend(index: integer): TSCRealNumber; begin result:=0;//FLWMA21_M15.GetValue(index)-FLWMA55_M15.GetValue(index); end; function TStockTraderMACross1.GetRecommendedLots: TStockOrderLots; var aDayVolatility,aDayVolatilityM,k: TStockRealNumber; begin if not PropLotDynamicRate.Value then exit(inherited GetRecommendedLots); aDayVolatility:=FBarHeightD1.GetValue(FBarHeightD1.GetInputData.Count-1); //Считаем какая волатильность в деньгах у нас была последние дни aDayVolatilityM:=GetBroker.PriceToMoney(GetSymbol,aDayVolatility,1); //Считаем, сколько таких волатильностей вынесет наш баланс k:=(GetBroker.GetEquity/aDayVolatilityM); //Теперь берем допустимый процент result:=RoundTo(k*PropLotDynamicRateSize.Value/100,-2); end; function TStockTraderMACross1.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber; begin if aOrder.GetKind=okBuy then result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder) else result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice; end; procedure TStockTraderMACross1.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin //Создае нужных нам экспертов FBarHeightD1:=CreateBarHeightD1(aValue.GetStockChart(sti1440)); FSMA21_M15:= CreateMA(aValue.GetStockChart(sti15),21,mamSimple); FSMA21_M15.SetColor(clWebDarkGoldenRod); FSMA55_M15:= CreateMA(aValue.GetStockChart(sti15),55,mamSimple); FSMA55_M15.SetColor(clRed); FSMA84_M15:= CreateMA(aValue.GetStockChart(sti15),84,mamSimple); FSMA84_M15.SetColor(clWebSteelBlue); FSMA220_M15:= CreateMA(aValue.GetStockChart(sti15),220,mamSimple); FSMA220_M15.SetColor(clBlue); //M1 FSMA21_M1:= CreateMA(aValue.GetStockChart(sti1),21,mamSimple); FSMA21_M1.SetColor(clWebDarkGoldenRod); FSMA55_M1:= CreateMA(aValue.GetStockChart(sti1),55,mamSimple); FSMA55_M1.SetColor(clRed); end; end; procedure TStockTraderMACross1.SetTP(const aOrder: IStockOrder;const aTP: TStockRealNumber; const aComment: string); var aNew : TStockRealNumber; begin aNew:=GetBroker.RoundPrice(aOrder.GetSymbol,aTP); if not SameValue(aNew,aOrder.GetTakeProfit) then begin if aComment<>'' then GetBroker.AddMessage(aOrder,aComment); aOrder.SetTakeProfit(aNew); end; end; function TStockTraderMACross1.GetMainTrend(index: integer): TSCRealNumber; begin result:=0;//FMA84_M15.GetValue(index)-FMA220_M15.GetValue(index); end; function TStockTraderMACross1.GetCross2155(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FSMA21_M15.GetValue(index)-FSMA55_M15.GetValue(index)); x2:=Sign(FSMA21_M15.GetValue(index-1)-FSMA55_M15.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; function TStockTraderMACross1.GetCross84_220(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FSMA84_M15.GetValue(index)-FSMA220_M15.GetValue(index)); x2:=Sign(FSMA84_M15.GetValue(index-1)-FSMA220_M15.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; function TStockTraderMACross1.GetCrossM1(index: integer): integer; var x1,x2: integer; begin x1:=Sign(FSMA21_M1.GetValue(index)-FSMA55_M1.GetValue(index)); x2:=Sign(FSMA21_M1.GetValue(index-1)-FSMA55_M1.GetValue(index-1)); if x1=x2 then exit(0); result:=x1; end; function TStockTraderMACross1.GetCurrentBid: TSCRealNumber; begin result:=GetBroker.GetCurrentPrice(GetSymbol,bpkBid); end; procedure TStockTraderMACross1.UpdateStep2(const aTime: TDateTime); var idx15,idx1: integer; aInputData : ISCInputDataCollection; aChart : IStockChart; aOpenedOrder: IStockOrder; aOpen : integer; aMaCross84_220 : integer; aMaCross2155 : integer; aMaCrossM1 : integer; aTime15 : TDateTime; aClose : integer; //aFastTrend : TSCRealNumber; //aPrice : TSCRealNumber; j: Integer; aMALevel : TSCRealNumber; aMaxGap : TSCRealNumber; begin if FPropFullBarsOnly.Value then begin if not (MinuteOf(aTime) in [55..59])then exit; end; aTime15:=TStockDataUtils.AlignTimeToLeft(aTime,sti15); if SameTime(FLastOpenOrderTime,aTime15) then exit; //Брокер может закрыть ордера и без нас. У нас в списке они останутся, //но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не //сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы //от эксперта в эту же сторону опять можно отрабатывать RemoveClosedOrders; //Анализируем экcпертные оценки aChart:=GetParentStockChart(FSMA21_M15); aInputData:=aChart.GetInputData; idx15:=aChart.FindBar(aTime); aChart:=GetParentStockChart(FSMA21_M1); aInputData:=aChart.GetInputData; idx1:=aChart.FindBar(aTime); if (idx1<>-1) and (idx15<>-1) and (idx15>=FSMA84_M15.GetPeriod) then begin aOpen:=0; aClose:=0; aMaCrossM1:=GetCrossM1(idx1); if aMaCrossM1<>0 then begin for j:=idx15 downto idx15-12 do begin aMaCross2155:=GetCross2155(j); if aMaCross2155=aMaCrossM1 then begin //Открываем ордер if aMaCross2155>0 then aOpen:=1 else if aMaCross2155<0 then aOpen:=-1; {for i := idx15 downto idx15-40*4 do begin aMaCross84_220:=GetCross84_220(i); if aMaCross84_220=aMaCross2155 then begin //Открываем ордер if aMaCross84_220>0 then aOpen:=1 else if aMaCross84_220<0 then aOpen:=-1; end; if aMaCross84_220<>0 then break; end;} end; if aMaCross2155<>0 then break; end; end; aMaCross84_220:=GetCross84_220(idx15); //Открываем ордер if aMaCross84_220>0 then aClose:=-1 else if aMaCross84_220<0 then aClose:=1; if aOpen<>0 then begin aMaxGap:=aInputData.PointToPrice(FPropMaxPriceAndMAGap.Value); aMALevel:=FSMA21_M15.GetValue(idx15); //aPrice:=aInputData.DirectGetItem_DataClose(idx15); //aFastTrend:=GetFastTrend(i); //BUY if (aOpen=1) {and (aFastTrend>0) }and (LastOrderType<>lotBuy) then begin CloseAllOrders(okSell,('Trader: Open opposite')); //if Abs(PriceToPoint(aPrice-FSMA21_M15.GetValue(idx15)))<100 then if Abs(GetCurrentBid-aMALevel)<aMaxGap then begin aOpenedOrder:=OpenOrder(okBuy); FLastOpenOrderTime:=aTime15; end; end //SELL else if (aOpen=-1) {and (aFastTrend<0) }and (LastOrderType<>lotSell) then begin CloseAllOrders(okBuy,('Trader: Open opposite')); if Abs(GetCurrentBid-aMALevel)<aMaxGap then begin aOpenedOrder:=OpenOrder(okSell); FLastOpenOrderTime:=aTime15; end; end; end; if aClose<0 then CloseAllOrders(okSell,('Trader: Time to close')) else if aClose>0 then CloseAllOrders(okBuy,('Trader: Time to close')); end; end; procedure TStockTraderMACross1.OnBeginWorkSession; begin inherited; FLastOpenOrderTime:=0; end; function TStockTraderMACross1.OpenOrder(aKind: TStockOrderKind; const aComment: string): IStockOrder; begin Result:=inherited OpenOrder(aKind,aComment); end; function TStockTraderMACross1.PriceToPoint(const aPrice: TSCRealNumber): integer; begin result:=GetBroker.PriceToPoint(GetSymbol,aPrice); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','MA Cross 1',TStockTraderMACross1,IStockTraderMACross1); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } {*******************************************************} unit ColorGrd; {$R-} interface uses {$IFDEF LINUX} WinUtils, {$ENDIF} Windows, Messages, Classes, Graphics, Forms, Controls, ExtCtrls; const NumPaletteEntries = 20; type TGridOrdering = (go16x1, go8x2, go4x4, go2x8, go1x16); TColorGrid = class(TCustomControl) private FPaletteEntries: array[0..NumPaletteEntries - 1] of TPaletteEntry; FClickEnablesColor: Boolean; FForegroundIndex: Integer; FBackgroundIndex: Integer; FForegroundEnabled: Boolean; FBackgroundEnabled: Boolean; FSelection: Integer; FCellXSize, FCellYSize: Integer; FNumXSquares, FNumYSquares: Integer; FGridOrdering: TGridOrdering; FHasFocus: Boolean; FOnChange: TNotifyEvent; FButton: TMouseButton; FButtonDown: Boolean; procedure DrawSquare(Which: Integer; ShowSelector: Boolean); procedure DrawFgBg; procedure UpdateCellSizes(DoRepaint: Boolean); procedure SetGridOrdering(Value: TGridOrdering); function GetForegroundColor: TColor; function GetBackgroundColor: TColor; procedure SetForegroundIndex(Value: Integer); procedure SetBackgroundIndex(Value: Integer); procedure SetSelection(Value: Integer); procedure EnableForeground(Value: Boolean); procedure EnableBackground(Value: Boolean); procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; protected procedure KeyDown(var Key: Word; Shift: TShiftState); 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 CreateWnd; override; procedure Paint; override; procedure Change; dynamic; function SquareFromPos(X, Y: Integer): Integer; public constructor Create(AOwner: TComponent); override; function ColorToIndex(AColor: TColor): Integer; property ForegroundColor: TColor read GetForegroundColor; property BackgroundColor: TColor read GetBackgroundColor; published property Anchors; property ClickEnablesColor: Boolean read FClickEnablesColor write FClickEnablesColor default False; property Constraints; property Ctl3D; property DragCursor; property DragMode; property Enabled; property GridOrdering: TGridOrdering read FGridOrdering write SetGridOrdering default go4x4; property ForegroundIndex: Integer read FForegroundIndex write SetForegroundIndex default 0; property BackgroundIndex: Integer read FBackgroundIndex write SetBackgroundIndex default 0; property ForegroundEnabled: Boolean read FForegroundEnabled write EnableForeground default True; property BackgroundEnabled: Boolean read FBackgroundEnabled write EnableBackground default True; property Font; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property Selection: Integer read FSelection write SetSelection default 0; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; implementation uses SysUtils, Consts, StdCtrls; constructor TColorGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque]; FGridOrdering := go4x4; FNumXSquares := 4; FNumYSquares := 4; FForegroundEnabled := True; FBackgroundEnabled := True; Color := clBtnFace; Canvas.Brush.Style := bsSolid; Canvas.Pen.Color := clBlack; SetBounds(0, 0, 100, 100); GetPaletteEntries(GetStockObject(DEFAULT_PALETTE), 0, NumPaletteEntries, FPaletteEntries); end; function TColorGrid.ColorToIndex(AColor: TColor): Integer; var I: Integer; RealColor: TColor; begin Result := 0; I := 0; RealColor := ColorToRGB(AColor); while I < 20 do begin with FPaletteEntries[I] do if RealColor = TColor(RGB(peRed, peGreen, peBlue)) then Exit; if I <> 7 then Inc(I) else Inc(I, 5); Inc(Result); end; Result := -1; end; procedure TColorGrid.CreateWnd; begin inherited CreateWnd; SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) or WS_CLIPSIBLINGS); end; procedure TColorGrid.DrawSquare(Which: Integer; ShowSelector: Boolean); var WinTop, WinLeft: Integer; PalIndex: Integer; CellRect: TRect; begin if (Which >=0) and (Which <= 15) then begin if Which < 8 then PalIndex := Which else PalIndex := Which + 4; WinTop := (Which div FNumXSquares) * FCellYSize; WinLeft := (Which mod FNumXSquares) * FCellXSize; CellRect := Bounds(WinLeft, WinTop, FCellXSize, FCellYSize); if Ctl3D then begin Canvas.Pen.Color := clBtnFace; with CellRect do Canvas.Rectangle(Left, Top, Right, Bottom); InflateRect(CellRect, -1, -1); Frame3D(Canvas, CellRect, clBtnShadow, clBtnHighlight, 2); end else Canvas.Pen.Color := clBlack; with FPaletteEntries[PalIndex] do begin Canvas.Brush.Color := TColor(RGB(peRed, peGreen, peBlue)); if Ctl3D then Canvas.Pen.Color := TColor(RGB(peRed, peGreen, peBlue)); end; if not ShowSelector then with CellRect do Canvas.Rectangle(Left, Top, Right, Bottom) else with CellRect do begin if Ctl3D then begin Canvas.Rectangle(Left, Top, Right, Bottom); InflateRect(CellRect, -1, -1); DrawFocusRect(Canvas.Handle, CellRect); end else with Canvas do begin Pen.Color := clBlack; Pen.Mode := pmNot; Rectangle(Left, Top, Right, Bottom); Pen.Mode := pmCopy; Rectangle(Left + 2, Top + 2, Right - 2, Bottom - 2); end; end; end; end; procedure TColorGrid.DrawFgBg; var TextColor: TPaletteEntry; PalIndex: Integer; TheText: string; OldBkMode: Integer; R: TRect; function TernaryOp(Test: Boolean; ResultTrue, ResultFalse: Integer): Integer; begin if Test then Result := ResultTrue else Result := ResultFalse; end; begin OldBkMode := SetBkMode(Canvas.Handle, TRANSPARENT); if FForegroundEnabled then begin if (FForegroundIndex = FBackgroundIndex) and FBackgroundEnabled then TheText := SFB else TheText := SFG; if FForegroundIndex < 8 then PalIndex := FForegroundIndex else PalIndex := FForegroundIndex + 4; TextColor := FPaletteEntries[PalIndex]; with TextColor do begin peRed := TernaryOp(peRed >= $80, 0, $FF); peGreen := TernaryOp(peGreen >= $80, 0, $FF); peBlue := TernaryOp(peBlue >= $80, 0, $FF); Canvas.Font.Color := TColor(RGB(peRed, peGreen, peBlue)); end; with R do begin left := (FForegroundIndex mod FNumXSquares) * FCellXSize; right := left + FCellXSize; top := (FForegroundIndex div FNumXSquares) * FCellYSize; bottom := top + FCellYSize; end; DrawText(Canvas.Handle, PChar(TheText), -1, R, DT_NOCLIP or DT_SINGLELINE or DT_CENTER or DT_VCENTER); end; if FBackgroundEnabled then begin if (FForegroundIndex = FBackgroundIndex) and FForegroundEnabled then TheText := SFB else TheText := SBG; if FBackgroundIndex < 8 then PalIndex := FBackgroundIndex else PalIndex := FBackgroundIndex + 4; TextColor := FPaletteEntries[PalIndex]; with TextColor do begin peRed := TernaryOp(peRed >= $80, 0, $FF); peGreen := TernaryOp(peGreen >= $80, 0, $FF); peBlue := TernaryOp(peBlue >= $80, 0, $FF); Canvas.Font.Color := TColor(RGB(peRed, peGreen, peBlue)); end; with R do begin left := (FBackgroundIndex mod FNumXSquares) * FCellXSize; right := left + FCellXSize; top := (FBackgroundIndex div FNumXSquares) * FCellYSize; bottom := top + FCellYSize; end; DrawText(Canvas.Handle, PChar(TheText), -1, R, DT_NOCLIP or DT_SINGLELINE or DT_CENTER or DT_VCENTER); end; SetBkMode(Canvas.Handle, OldBkMode); end; procedure TColorGrid.EnableForeground(Value: Boolean); begin if FForegroundEnabled = Value then Exit; FForegroundEnabled := Value; DrawSquare(FForegroundIndex, (FForegroundIndex = FSelection) and FHasFocus); DrawFgBg; end; procedure TColorGrid.EnableBackground(Value: Boolean); begin if FBackgroundEnabled = Value then Exit; FBackgroundEnabled := Value; DrawSquare(FBackgroundIndex, (FBackgroundIndex = FSelection) and FHasFocus); DrawFgBg; end; function TColorGrid.GetForegroundColor: TColor; var PalIndex: Integer; begin if FForegroundIndex < 8 then PalIndex := FForegroundIndex else PalIndex := FForegroundIndex + 4; with FPaletteEntries[PalIndex] do Result := TColor(RGB(peRed, peGreen, peBlue)); end; function TColorGrid.GetBackgroundColor: TColor; var PalIndex: Integer; begin if FBackgroundIndex < 8 then PalIndex := FBackgroundIndex else PalIndex := FBackgroundIndex + 4; with FPaletteEntries[PalIndex] do Result := TColor(RGB(peRed, peGreen, peBlue)); end; procedure TColorGrid.WMSetFocus(var Message: TWMSetFocus); begin FHasFocus := True; DrawSquare(FSelection, True); DrawFgBg; inherited; end; procedure TColorGrid.WMKillFocus(var Message: TWMKillFocus); begin FHasFocus := False; DrawSquare(FSelection, False); DrawFgBg; inherited; end; procedure TColorGrid.KeyDown(var Key: Word; Shift: TShiftState); var NewSelection: Integer; Range: Integer; begin inherited KeyDown(Key, Shift); NewSelection := FSelection; Range := FNumXSquares * FNumYSquares; case Key of $46, $66: begin if not FForegroundEnabled and FClickEnablesColor then begin FForegroundEnabled := True; DrawSquare(FForegroundIndex, (FForegroundIndex = FSelection) and FHasFocus); FForegroundIndex := -1; end; SetForegroundIndex(NewSelection); SetSelection(NewSelection); Click; end; $42, $62: begin if not FBackgroundEnabled and FClickEnablesColor then begin FBackgroundEnabled := True; DrawSquare(FBackgroundIndex, (FBackgroundIndex = FSelection) and FHasFocus); FBackgroundIndex := -1; end; SetBackgroundIndex(NewSelection); SetSelection(NewSelection); Click; end; VK_HOME: NewSelection := 0; VK_UP: if FSelection >= FNumXSquares then NewSelection := FSelection - FNumXSquares else if FSelection <> 0 then NewSelection := Range - FNumXSquares + FSelection - 1 else NewSelection := Range - 1; VK_LEFT: if FSelection <> 0 then NewSelection := FSelection - 1 else NewSelection := Range - 1; VK_DOWN: if FSelection + FNumXSquares < Range then NewSelection := FSelection + FNumXSquares else if FSelection <> Range - 1 then NewSelection := FSelection mod FNumXSquares + 1 else NewSelection := 0; VK_SPACE, VK_RIGHT: if FSelection <> Range - 1 then NewSelection := FSelection + 1 else NewSelection := 0; VK_END: NewSelection := Range - 1; else inherited KeyDown(Key, Shift); Exit; end; Key := 0; if FSelection <> NewSelection then SetSelection(NewSelection); end; procedure TColorGrid.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS + DLGC_WANTCHARS; end; procedure TColorGrid.WMSize(var Message: TWMSize); begin DisableAlign; try inherited; UpdateCellSizes(False); finally EnableAlign; end; end; procedure TColorGrid.CMCtl3DChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure TColorGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Square: Integer; begin inherited MouseDown(Button, Shift, X, Y); FButton := Button; FButtonDown := True; Square := SquareFromPos(X, Y); if Button = mbLeft then begin if not FForegroundEnabled and FClickEnablesColor then begin FForegroundEnabled := True; DrawSquare(FForegroundIndex, (FForegroundIndex = FSelection) and FHasFocus); FForegroundIndex := -1; end; SetForegroundIndex(Square); end else if Button = mbRight then begin MouseCapture := True; if not FBackgroundEnabled and FClickEnablesColor then begin FBackgroundEnabled := True; DrawSquare(FBackgroundIndex, (FBackgroundIndex = FSelection) and FHasFocus); FBackgroundIndex := -1; end; SetBackgroundIndex(Square); end; SetSelection(Square); if TabStop then SetFocus; end; procedure TColorGrid.MouseMove(Shift: TShiftState; X, Y: Integer); var Square: Integer; begin inherited MouseMove(Shift, X, Y); if FButtonDown then begin Square := SquareFromPos(X, Y); if FButton = mbLeft then SetForegroundIndex(Square) else if FButton = mbRight then SetBackgroundIndex(Square); SetSelection(Square); end; end; procedure TColorGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); FButtonDown := False; if FButton = mbRight then begin MouseCapture := False; Click; end; end; procedure TColorGrid.Paint; var Row, Col, wEntryIndex: Integer; begin Canvas.Font := Font; for Row := 0 to FNumYSquares do for Col := 0 to FNumXSquares do begin wEntryIndex := Row * FNumXSquares + Col; DrawSquare(wEntryIndex, False); end; DrawSquare(FSelection, FHasFocus); DrawFgBg; end; procedure TColorGrid.SetBackgroundIndex(Value: Integer); begin if (FBackgroundIndex <> Value) and FBackgroundEnabled then begin DrawSquare(FBackgroundIndex, (FBackgroundIndex = FSelection) and FHasFocus); FBackgroundIndex := Value; if FBackgroundIndex = FForegroundIndex then DrawSquare(FBackgroundIndex, (FBackgroundIndex = FSelection) and FHasFocus); DrawFgBg; Change; end; end; procedure TColorGrid.SetForegroundIndex(Value: Integer); begin if (FForegroundIndex <> Value) and FForegroundEnabled then begin DrawSquare(FForegroundIndex, (FForegroundIndex = FSelection) and FHasFocus); FForegroundIndex := Value; if FForegroundIndex = FBackgroundIndex then DrawSquare(FForegroundIndex, (FForegroundIndex = FSelection) and FHasFocus); DrawFgBg; Change; end; end; procedure TColorGrid.SetGridOrdering(Value: TGridOrdering); begin if FGridOrdering = Value then Exit; FGridOrdering := Value; FNumXSquares := 16 shr Ord(FGridOrdering); FNumYSquares := 1 shl Ord(FGridOrdering); UpdateCellSizes(True); end; procedure TColorGrid.SetSelection(Value: Integer); begin if FSelection = Value then Exit; DrawSquare(FSelection, False); FSelection := Value; DrawSquare(FSelection, FHasFocus); DrawFgBg; end; function TColorGrid.SquareFromPos(X, Y: Integer): Integer; begin if X > Width - 1 then X := Width - 1 else if X < 0 then X := 0; if Y > Height - 1 then Y := Height - 1 else if Y < 0 then Y := 0; Result := (Y div FCellYSize) * FNumXSquares + (X div FCellXSize); end; procedure TColorGrid.UpdateCellSizes(DoRepaint: Boolean); var NewWidth, NewHeight: Integer; begin NewWidth := (Width div FNumXSquares) * FNumXSquares; NewHeight := (Height div FNumYSquares) * FNumYSquares; BoundsRect := Bounds(Left, Top, NewWidth, NewHeight); FCellXSize := Width div FNumXSquares; FCellYSize := Height div FNumYSquares; if DoRepaint then Invalidate; end; procedure TColorGrid.Change; begin Changed; if Assigned(FOnChange) then FOnChange(Self); end; end.
unit testweakintf; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, weakable; type TTestWeakIntf= class(TTestCase) protected procedure SetUp; override; procedure TearDown; override; published procedure Test1; end; implementation var _GentlemanCount, _LadyCount: Integer; procedure ResetCount; begin _GentlemanCount := 0; _LadyCount := 0; end; type IGentleman = interface; ILady = interface ['{EBF25A5B-60F8-48D4-8309-AD0F63C40E84}'] function GetGentleman: IGentleman; procedure SetGentleman(const Value: IGentleman); property Gentleman: IGentleman read GetGentleman write SetGentleman; end; IGentleman = interface ['{00F07C37-2569-4B18-85B4-71D404C4019E}'] function GetLady: ILady; procedure SetLady(const Value: ILady); property Lady: ILady read GetLady write SetLady; end; { TLadyObj } TLadyObj = class(TWeakableInterfaced, ILady) private FGentlemanIntf: IWeakInterface; public constructor Create; destructor Destroy; override; procedure SetGentleman(const Value: IGentleman); function GetGentleman: IGentleman; end; { TGentlemanObj } TGentlemanObj = class(TWeakableInterfaced, IGentleman) private FLadyIntf: IWeakInterface; public constructor Create; destructor Destroy; override; procedure SetLady(const Value: ILady); function GetLady: ILady; end; { TLadyObj } constructor TLadyObj.Create; begin inherited; Inc(_LadyCount); end; destructor TLadyObj.Destroy; begin Dec(_LadyCount); inherited Destroy; end; function TLadyObj.GetGentleman: IGentleman; begin result := FGentlemanIntf.Ref as IGentleman; end; procedure TLadyObj.SetGentleman(const Value: IGentleman); begin FGentlemanIntf := (Value as IWeakable).Weak; end; { TGentlemanObj } constructor TGentlemanObj.Create; begin inherited; Inc(_GentlemanCount); end; destructor TGentlemanObj.Destroy; begin Dec(_GentlemanCount); inherited Destroy; end; function TGentlemanObj.GetLady: ILady; begin result := FLadyIntf.Ref as ILady; end; procedure TGentlemanObj.SetLady(const Value: ILady); begin FLadyIntf := (Value as IWeakable).Weak; end; procedure TTestWeakIntf.Test1; var lady: ILady; gentleman: IGentleman; begin lady := TLadyObj.Create; gentleman := TGentlemanObj.Create; lady.Gentleman := gentleman; gentleman.Lady := lady; lady := nil; gentleman := nil; Self.CheckEquals(0, _GentlemanCount); Self.CheckEquals(0, _LadyCount); end; procedure TTestWeakIntf.SetUp; begin end; procedure TTestWeakIntf.TearDown; begin end; initialization RegisterTest(TTestWeakIntf); end.
PROGRAM Maximum; var x, y, z, out: integer; FUNCTION Max2(x, y: integer): integer; BEGIN (* Max2 *) IF (x < y) THEN BEGIN Max2 := y; END ELSE BEGIN Max2 := x; END; (* IF *) END; (* Max2 *) FUNCTION Max3(x, y, z: integer): integer; BEGIN (* Max3 *) Max3 := Max2(Max2(x, y), z); END; (* Max3 *) BEGIN (* Maximum *) Read(x); Read(y); Read(z); IF (z = 0) THEN BEGIN out := Max2(x, y); END ELSE BEGIN out := Max3(x, y, z); END; (* IF *) Writeln('Maximum: ', out); END. (* Maximum *)
unit Dictionary; interface uses Windows, Classes, Forms, SysUtils, ForestConsts, ForestTypes, Dialogs; type TDictionary = class(TObject) private FDictionaryFile: AnsiString; FCaption: AnsiString; FCatalogArray: TCatalogArr; FDictArray: TDictArr; FForceSkip: Boolean; FDictionaryFormatString: AnsiString; FSQLScript: AnsiString; FDictionaryList: TStringList; procedure ReadSettings; procedure WriteSettings; function Equal(const A: TCatalogRecord; const B: TCatalogRecord): Boolean; procedure PrepareValuesList; // function GetCaption: AnsiString; procedure SetCaption(Value: AnsiString); function GetDictionaryArray: TDictArr; procedure SetDictionaryArray(Value: TDictArr); function GetForceSkip: Boolean; procedure SetForceSkip(Value: Boolean); function GetDictionaryFormatString: AnsiString; procedure SetDictionaryFormatString(Value: AnsiString); function GetSQLScript: AnsiString; procedure SetSQLScript(Value: AnsiString); function GetCatalogFile: AnsiString; function GetCatalogArray: TCatalogArr; procedure SetCatalogArray(Value: TCatalogArr); public function Validate(const AWord: AnsiString; const RelationID: Integer): Integer; function FindRecord(const AWord: AnsiString; const RelationID: Integer; var WordRecord: TCatalogRecord): Boolean; function GetRecordByListItem(const S: AnsiString): TDictRecord; procedure WriteRecord(const WordRecord: TCatalogRecord); procedure Clear; // constructor Create(AFile: AnsiString; DictCaption: AnsiString); destructor Destroy; override; //-- property Caption: AnsiString read GetCaption write SetCaption; property DictionaryArr: TDictArr read GetDictionaryArray write SetDictionaryArray; property CatalogArr: TCatalogArr read GetCatalogArray write SetCatalogArray; property DictionaryList: TStringList read FDictionaryList; property ForceSkip: Boolean read GetForceSkip write SetForceSkip; property DictionaryFormatString: AnsiString read GetDictionaryFormatString write SetDictionaryFormatString; property DictionaryFile: AnsiString read FDictionaryFile; property CatalogFile: AnsiString read GetCatalogFile; property SQLScript: AnsiString read GetSQLScript write SetSQLScript; end; var DictionaryFile: file of TDictRecord; CatalogFile: file of TCatalogRecord; implementation uses IniFiles, NsUtils; //--------------------------------------------------------------------------- { TDictionary } procedure TDictionary.Clear; begin SetLength(FDictArray, 0); end; //--------------------------------------------------------------------------- constructor TDictionary.Create(AFile: AnsiString; DictCaption: AnsiString); var DictFilePath, CatalogFilePath: AnsiString; DictFile: File of TDictRecord; CatalogFile: File of TCatalogRecord; I: Integer; begin FDictionaryFile := AFile; FCaption := DictCaption; FDictionaryList := TStringList.Create(); ReadSettings(); Clear(); CatalogFilePath := Format('%s%s', [GetAppPath, FDictionaryFile]); if FileExists(CatalogFilePath) then begin Assign(CatalogFile, CatalogFilePath); Reset(CatalogFile); while not Eof(CatalogFile) do begin I := Length(FCatalogArray); SetLength(FCatalogArray, I + 1); Read(CatalogFile, FCatalogArray[I]); end; CloseFile(CatalogFile); end; DictFilePath := Format('%s%s%s', [GetAppPath, S_DICT_VALID_PREFIX, FDictionaryFile]); if FileExists(DictFilePath) then begin Assign(DictFile, DictFilePath); Reset(DictFile); while not Eof(DictFile) do begin I := Length(FDictArray); SetLength(FDictArray, I + 1); Read(DictFile, FDictArray[I]); end; CloseFile(DictFile); end; PrepareValuesList(); end; //--------------------------------------------------------------------------- destructor TDictionary.Destroy; var CatalogFilePath, DictFilePath: AnsiString; CatalogFile: File of TCatalogRecord; DictFile: File of TDictRecord; I: Integer; begin CatalogFilePath := Format('%s%s', [GetAppPath, FDictionaryFile]); Assign(CatalogFile, CatalogFilePath); Rewrite(CatalogFile); for I := 0 to (Length(FCatalogArray) - 1) do Write(CatalogFile, FCatalogArray[I]); CloseFile(CatalogFile); DictFilePath := Format('%s%s%s', [GetAppPath, S_DICT_VALID_PREFIX, FDictionaryFile]); Assign(DictFile, DictFilePath); Rewrite(DictFile); for I := 0 to (Length(FDictArray) - 1) do Write(DictFile, FDictArray[I]); CloseFile(DictFile); Clear(); FDictionaryList.Clear(); FDictionaryList.Destroy; WriteSettings(); inherited; end; //--------------------------------------------------------------------------- function TDictionary.Equal(const A: TCatalogRecord; const B: TCatalogRecord): Boolean; begin Result := (A.OldWord = B.OldWord); end; //--------------------------------------------------------------------------- function TDictionary.FindRecord(const AWord: AnsiString; const RelationID: Integer; var WordRecord: TCatalogRecord): Boolean; var I: Integer; begin Result := False; for I := 0 to (Length(FCatalogArray) - 1) do if (FCatalogArray[I].OldWord = AWord) and (FCatalogArray[I].RelationID = RelationID) then begin WordRecord := FCatalogArray[I]; Result := True; Break; end; end; //--------------------------------------------------------------------------- function TDictionary.GetCaption: AnsiString; begin Result := FCaption; end; //--------------------------------------------------------------------------- function TDictionary.GetCatalogArray: TCatalogArr; begin Result := FCatalogArray; end; //--------------------------------------------------------------------------- function TDictionary.GetCatalogFile: AnsiString; begin Result := S_DICT_VALID_PREFIX + FDictionaryFile; end; //--------------------------------------------------------------------------- function TDictionary.GetDictionaryArray: TDictArr; begin Result := FDictArray; end; //--------------------------------------------------------------------------- function TDictionary.GetDictionaryFormatString: AnsiString; begin Result := FDictionaryFormatString; end; //--------------------------------------------------------------------------- function TDictionary.GetForceSkip: Boolean; begin Result := FForceSkip; end; //--------------------------------------------------------------------------- function TDictionary.GetRecordByListItem(const S: AnsiString): TDictRecord; begin Result := FDictArray[FDictionaryList.IndexOf(S)]; end; //--------------------------------------------------------------------------- function TDictionary.GetSQLScript: AnsiString; begin Result := FSQLScript; end; //--------------------------------------------------------------------------- procedure TDictionary.PrepareValuesList; var I: Integer; TmpStr: AnsiString; begin FDictionaryList.Clear(); for I := 0 to Length(FDictArray) - 1 do begin TmpStr := FDictionaryFormatString; TmpStr := StringReplace(TmpStr, S_DICT_NAME_FORMAT, FDictArray[I].WordValue, [rfReplaceAll, rfIgnoreCase]); TmpStr := StringReplace(TmpStr, S_DICT_ID_FORMAT, IntToStr(FDictArray[I].WordIndex), [rfReplaceAll, rfIgnoreCase]); FDictionaryList.Add(TmpStr); end; end; //--------------------------------------------------------------------------- procedure TDictionary.ReadSettings; begin if not FileExists(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME) then Exit; with TIniFile.Create(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME) do try FDictionaryFormatString := ReadString(S_INI_DICT_FORMATS, FDictionaryFile, S_DICT_NAME_FORMAT); finally Free(); end; end; //--------------------------------------------------------------------------- procedure TDictionary.SetCaption(Value: AnsiString); begin if FCaption <> Value then FCaption := Value; end; //--------------------------------------------------------------------------- procedure TDictionary.SetCatalogArray(Value: TCatalogArr); begin if Value <> FCatalogArray then FCatalogArray := Value; end; //--------------------------------------------------------------------------- procedure TDictionary.SetForceSkip(Value: Boolean); begin if Value <> FForceSkip then FForceSkip := Value; end; //--------------------------------------------------------------------------- procedure TDictionary.SetSQLScript(Value: AnsiString); begin if FSQLScript <> Value then FSQLScript := Value; end; //--------------------------------------------------------------------------- procedure TDictionary.SetDictionaryArray(Value: TDictArr); begin if Value <> FDictArray then begin FDictArray := Value; PrepareValuesList(); end; end; //--------------------------------------------------------------------------- procedure TDictionary.SetDictionaryFormatString(Value: AnsiString); begin if Value <> FDictionaryFormatString then begin FDictionaryFormatString := Value; PrepareValuesList(); end; end; //--------------------------------------------------------------------------- function TDictionary.Validate(const AWord: AnsiString; const RelationID: Integer): Integer; var I: Integer; begin Result := -1; for I := 0 to Length(FDictArray) - 1 do if (FDictArray[I].WordValue = AnsiUpperCase(AWord)) and (FDictArray[I].RelationID = RelationID) then begin Result := FDictArray[I].WordIndex; Break; end; end; //--------------------------------------------------------------------------- procedure TDictionary.WriteRecord(const WordRecord: TCatalogRecord); var I: Integer; begin for I := 0 to (Length(FCatalogArray) - 1) do if Equal(FCatalogArray[I], WordRecord) then begin FCatalogArray[I].NewWord := AnsiUpperCase(WordRecord.NewWord); Exit; end; I := Length(FCatalogArray); SetLength(FCatalogArray, I + 1); FCatalogArray[I] := WordRecord; end; //--------------------------------------------------------------------------- procedure TDictionary.WriteSettings; begin with TIniFile.Create(ExtractFilePath(Application.ExeName) + S_SETTINGS_FILE_NAME) do try WriteString(S_INI_DICT_FORMATS, FDictionaryFile, FDictionaryFormatString); finally Free(); end; end; end.
program info(output); procedure WriteHeader; begin writeln('Content-type: text/html'); writeln; writeln('<html>'); writeln('<head>'); writeln('<title>Irie Pascal sample CGI application</title>'); writeln('<h1>CGI environment variables.</h1>'); writeln('</head>') end; procedure WriteBody; procedure DisplayEnvVar(name : string); var value : string; begin value := getenv(name); writeln(name, ' = ', value, '<br>') end; begin writeln('<body>'); DisplayEnvVar('HTTP_ACCEPT'); DisplayEnvVar('HTTP_ACCEPT_ENCODING'); DisplayEnvVar('HTTP_ACCEPT_LANGUAGE'); DisplayEnvVar('HTTP_AUTHORIZATION'); DisplayEnvVar('HTTP_CHARGE_TO'); DisplayEnvVar('HTTP_FROM'); DisplayEnvVar('HTTP_IF_MODIFIED_SINCE'); DisplayEnvVar('HTTP_PRAGMA'); DisplayEnvVar('HTTP_REFERER'); DisplayEnvVar('HTTP_USER_AGENT'); writeln('<hr>'); DisplayEnvVar('AUTH_TYPE'); DisplayEnvVar('CONTENT_LENGTH'); DisplayEnvVar('CONTENT_TYPE'); DisplayEnvVar('GATEWAY_INTERFACE'); DisplayEnvVar('PATH_INFO'); DisplayEnvVar('PATH_TRANSLATED'); DisplayEnvVar('QUERY_STRING'); DisplayEnvVar('REMOTE_ADDR'); DisplayEnvVar('REMOTE_HOST'); DisplayEnvVar('REMOTE_IDENT'); DisplayEnvVar('REMOTE_USER'); DisplayEnvVar('REQUEST_METHOD'); DisplayEnvVar('SCRIPT_NAME'); DisplayEnvVar('SERVER_NAME'); DisplayEnvVar('SERVER_PORT'); DisplayEnvVar('SERVER_PROTOCOL'); DisplayEnvVar('SERVER_SOFTWARE'); writeln('</body>') end; procedure WriteFooter; begin writeln('</html>') end; begin WriteHeader; WriteBody; WriteFooter end.
En una casa viven una abuela y sus N nietos. Además la abuela compró caramelos que quiere convidar entre sus nietos. Inicialmente la abuela deposita en una fuente X caramelos, luego cada nieto intenta comer caramelos de la siguiente manera: si la fuente tiene caramelos el nieto agarra uno de ellos, en el caso de que la fuente esté vacía entonces se le avisa a la abuela quien repone nuevamente X caramelos. Luego se debe permitir que el nieto que no pudo comer sea el primero en hacerlo, es decir, el primer nieto que puede comer nuevamente es el primero que encontró la fuente vacía. NOTA: siempre existen caramelos para reponer. Cada nieto tarda t minutos en comer un caramelo (t no es igual para cada nieto). Puede haber varios nietos comiendo al mismo tiempo. PROGRAM SIETE BEGIN Monitor Fuente BEGIN var int cantidadCaramelos= 0; cond colaAbuela; cond colaNieto; cond colaNietoEsperando; bool primero=true; procedure obtenerCaramelo() BEGIN bool ok = false; while(ok == false) DO if(cantidadCaramelos > 0) THEN cantidadCaramelos --; ok= true; END ELSE IF(primero) THEN primero = false; wait(colaNieto); ok= true; cantidadCaramelos --; singalAll(colaNietoEsperando); END; ELSE THEN // no soy el primero wait(colaNietoEsperando); END; END; END; procedure reponer(int x) BEGIN //si la cantidad de caramelos //es disntinto de 0 //espero a que un nieto pida que la abuela reponga if(cantidadCaramelos != 0) BEGIN wait(colaAbuela); END signal(colaNieto); //re pongo caramelos cantidadCaramelos = x; END; END; Process Abuela[1] BEGIN while(true) BEGIN Fuente.reponer(); END; END; Process Nieto [n=1 to N] BEGIN while (true) BEGIN Fuente.obtenerCaramelo(); //comer caramelo END; END; END;
unit uPerfilUsuarioEdt; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.DBCtrls; type TOperacao = (OpIncluir, OpAlterar, OpExcluir); TfrmPerfilUsuarioEdt = class(TForm) pnlRodape: TPanel; pnlControle: TPanel; btnFechar: TBitBtn; btnOK: TBitBtn; lblDescrição: TLabel; edtDescricao: TEdit; rgPON_ADM_PFL: TRadioGroup; procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure carregarRegistro; procedure MoverDadosFormularios; function testarDados: Boolean; function incluir: Boolean; function alterar: Boolean; function excluir: Boolean; public { Public declarations } Operacao: TOperacao; pPON_PK_SEQ_PFL: Integer; end; var frmPerfilUsuarioEdt: TfrmPerfilUsuarioEdt; implementation {$R *.dfm} uses uDmDados, uConstates, uTipoFeriado, uPerfilUsuario; { TfrmTipoFeriadoEdt } function TfrmPerfilUsuarioEdt.alterar: Boolean; begin carregarRegistro; if not dmDados.cdsPONTBPFL.IsEmpty then begin try dmDados.cdsPONTBPFL.Edit; dmDados.cdsPONTBPFL.FieldByName('PON_DESC_PFL').AsString := edtDescricao.Text; dmDados.cdsPONTBPFL.FieldByName('PON_ADM_PFL').AsBoolean := (rgPON_ADM_PFL.ItemIndex = 1); dmDados.cdsPONTBPFL.Post; dmDados.cdsPONTBPFL.ApplyUpdates(0); frmPerfilUsuario.AtualizaGrid; except on e: Exception do begin ShowMessage('Erro ao o perfil de usuário: ' + e.Message); end; end; end; Result := True; end; procedure TfrmPerfilUsuarioEdt.btnOKClick(Sender: TObject); begin if testarDados then begin if Operacao = OpIncluir then begin if incluir then begin ShowMessage('Registro incluso com sucesso!'); edtDescricao.Text := ''; rgPON_ADM_PFL.ItemIndex := -1; if edtDescricao.CanFocus then edtDescricao.SetFocus; end; end else if Operacao = OpAlterar then begin if alterar then begin ShowMessage('Registro alterado com sucesso!'); ModalResult := mrOk; end; end else begin if MessageDlg('Tem certeza que deseja excluir esse registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin if excluir then begin ShowMessage('Registro excluído com sucesso!'); ModalResult := mrOk; end; end; end; end; end; procedure TfrmPerfilUsuarioEdt.carregarRegistro; begin dmDados.cdsPONTBPFL.Close; dmDados.cdsPONTBPFL.CommandText := ' SELECT * FROM PONTBPFL WHERE PON_PK_SEQ_PFL = ' + QuotedStr(VarToStr(pPON_PK_SEQ_PFL)); dmDados.cdsPONTBPFL.Open; end; function TfrmPerfilUsuarioEdt.excluir: Boolean; begin carregarRegistro; if not dmDados.cdsPONTBPFL.IsEmpty then begin try dmDados.cdsPONTBPFL.Delete; dmDados.cdsPONTBPFL.ApplyUpdates(0); frmPerfilUsuario.AtualizaGrid; except on e: Exception do begin ShowMessage('Erro ao ecluir perfil de usuário: ' + e.Message); end; end; end; Result := True; end; procedure TfrmPerfilUsuarioEdt.FormShow(Sender: TObject); begin if Operacao = OpIncluir then begin Caption := 'Inclusão de perfil de usuário'; edtDescricao.SetFocus; end else if Operacao = OpAlterar then begin Caption := 'Alteração de perfil de usuário'; carregarRegistro; MoverDadosFormularios; frmPerfilUsuario.AtualizaGrid; end else begin Caption := 'Exclusão de perfil de usuário'; carregarRegistro; MoverDadosFormularios; frmPerfilUsuario.AtualizaGrid; pnlControle.Enabled := False; btnOK.SetFocus; end; end; function TfrmPerfilUsuarioEdt.incluir: Boolean; begin try dmDados.cdsPONTBPFL.Insert; dmDados.cdsPONTBPFL.FieldByName('PON_PK_SEQ_PFL').AsInteger := 0; dmDados.cdsPONTBPFL.FieldByName('PON_DESC_PFL').AsString := edtDescricao.Text; dmDados.cdsPONTBPFL.FieldByName('PON_ADM_PFL').AsBoolean := (rgPON_ADM_PFL.ItemIndex = 1); dmDados.cdsPONTBPFL.Post; dmDados.cdsPONTBPFL.ApplyUpdates(0); frmPerfilUsuario.AtualizaGrid; except on e: Exception do begin ShowMessage('Erro ao inserir perfil de usuário: ' + e.Message); end; end; Result := True; end; procedure TfrmPerfilUsuarioEdt.MoverDadosFormularios; begin edtDescricao.Text := dmDados.cdsPONTBPFL.FieldByName('PON_DESC_PFL').AsString; if dmDados.cdsPONTBPFL.FieldByName('PON_ADM_PFL').AsBoolean then begin rgPON_ADM_PFL.ItemIndex := 1; end else begin rgPON_ADM_PFL.ItemIndex := 0; end; end; function TfrmPerfilUsuarioEdt.testarDados: Boolean; begin Result := False; if (Operacao = OpIncluir) or (Operacao = OpAlterar) then begin if edtDescricao.Text = '' then begin ShowMessage('Informe a descrição do perfil do usuário.'); if edtDescricao.CanFocus then edtDescricao.SetFocus; Exit; end; if rgPON_ADM_PFL.ItemIndex = -1 then begin ShowMessage('Informe se o perfil do usuário e administrador ou não.'); if rgPON_ADM_PFL.CanFocus then rgPON_ADM_PFL.SetFocus; Exit; end; end; Result := True; end; end.
unit AProcessaProdutividade; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, ComCtrls, Componentes1, Buttons, ExtCtrls, PainelGradiente, Db, UnOrdemProducao, DBTables, DBClient, Tabela; type TFProcessaProdutividade = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BarraStatus: TStatusBar; Progresso: TProgressBar; BProcessar: TBitBtn; BFechar: TBitBtn; EData: TCalendario; Label1: TLabel; Aux: TSQL; Celulas: TSQL; Produtividade: TSQL; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BProcessarClick(Sender: TObject); procedure BFecharClick(Sender: TObject); private { Private declarations } FunOrdemProducao : TRBFuncoesOrdemProducao; function RQtdCelulas(VpaData: TDateTime):Integer; procedure CorrigeProdutividadeColetas(VpaCodCelula : Integer;VpaData : TDateTime); procedure ProcessaProdutividade; procedure AtualizaStatus(VpaTexto : String); public { Public declarations } end; var FProcessaProdutividade: TFProcessaProdutividade; implementation uses APrincipal, FunSql, Fundata, FunNumeros, FunString; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFProcessaProdutividade.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } EData.DateTime := date; FunOrdemProducao := TRBFuncoesOrdemProducao.cria(FPrincipal.BaseDados); end; { ******************* Quando o formulario e fechado ************************** } procedure TFProcessaProdutividade.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunOrdemProducao.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} function TFProcessaProdutividade.RQtdCelulas(VpaData: TDateTime):Integer; Begin AdicionaSQLAbreTabela(Aux,'select COUNT(DISTINCT(CODCELULA)) QTD from COLETAFRACAOOP '+ ' Where '+SQLTextoDataEntreAAAAMMDD('DATINICIO',VpaDAta,INCDia(VpaData,1),false)); result := Aux.FieldByName('QTD').AsInteger; Aux.Close; end; {******************************************************************************} procedure TFProcessaProdutividade.CorrigeProdutividadeColetas(VpaCodCelula : Integer;VpaData : TDateTime); var VpfQtdIdeal : Double; VpfProdutividade : Integer; begin AdicionaSQLAbreTabela(Produtividade,'select COL.CODFILIAL, COL.SEQORDEM, COL.SEQFRACAO, COL.SEQESTAGIO, COL.SEQCOLETA, '+ ' COL.QTDMINUTOS, COL.QTDCOLETADO, ESP.QTDPRODUCAOHORA '+ ' from COLETAFRACAOOP COL, FRACAOOPESTAGIO FRE, PRODUTOESTAGIO ESP '+ ' where COL.CODCELULA = '+IntToStr(VpaCodCelula)+ SQLTextoDataEntreAAAAMMDD('DATINICIO',VpaDAta,INCDia(VpaData,1),true)+ ' AND COL.CODFILIAL = FRE.CODFILIAL '+ ' AND COL.SEQORDEM = FRE.SEQORDEM '+ ' AND COL.SEQFRACAO = FRE.SEQFRACAO '+ ' AND COL.SEQESTAGIO = FRE.SEQESTAGIO '+ ' AND FRE.SEQPRODUTO = ESP.SEQPRODUTO '+ ' AND FRE.SEQESTAGIO = ESP.SEQESTAGIO'); While not Produtividade.Eof do begin AtualizaStatus('Reprocessando produtividade celula '+IntToStr(VpaCodCelula)+' - Coleta '+Produtividade.FieldByName('SEQCOLETA').AsString); VpfQtdIdeal := (Produtividade.FieldByName('QTDMINUTOS').AsInteger * Produtividade.FieldByName('QTDPRODUCAOHORA').AsFloat)/60; VpfProdutividade := RetornaInteiro((Produtividade.FieldByName('QTDCOLETADO').AsFloat * 100)/VpfQtdIdeal); ExecutaComandoSql(Aux,'Update COLETAFRACAOOP '+ ' SET QTDPRODUCAOIDEAL = '+SubstituiStr(FormatFloat('0.00',VpfQtdIdeal),',','.')+ ' , QTDPRODUCAOHORA = '+SubstituiStr(FormatFloat('0.0000',Produtividade.FieldByName('QTDPRODUCAOHORA').AsFloat),',','.')+ ' , PERPRODUTIVIDADE = '+IntToStr(VpfProdutividade)+ ' Where CODFILIAL = '+Produtividade.FieldByName('CODFILIAL').AsString+ ' AND SEQORDEM = '+Produtividade.FieldByName('SEQORDEM').AsString+ ' AND SEQFRACAO = '+Produtividade.FieldByName('SEQFRACAO').AsString+ ' AND SEQESTAGIO = '+Produtividade.FieldByName('SEQESTAGIO').AsString+ ' AND SEQCOLETA = '+Produtividade.FieldByName('SEQCOLETA').AsString); Produtividade.next; end; Produtividade.close; end; {******************************************************************************} procedure TFProcessaProdutividade.ProcessaProdutividade; begin Progresso.Max := RQtdCelulas(EData.DateTime); Progresso.Position := 0; AdicionaSQLAbreTabela(Celulas,'select DISTINCT(CODCELULA) CELULA from COLETAFRACAOOP '+ 'Where '+SQLTextoDataEntreAAAAMMDD('DATINICIO',EData.DateTime,INCDia(EData.DateTime,1),false)); While not Celulas.Eof do begin CorrigeProdutividadeColetas(Celulas.FieldByName('CELULA').AsInteger,EData.DateTime); AtualizaStatus('Processando produtividade Celula '+Celulas.FieldByName('CELULA').AsString); FunOrdemProducao.ProcessaProdutividadeCelula(Celulas.FieldByName('CELULA').AsInteger,EData.DateTime); Celulas.next; Progresso.Position := Progresso.Position + 1; end; Celulas.Close; AtualizaStatus('Produtividade reprocessada com sucesso.'); end; {******************************************************************************} procedure TFProcessaProdutividade.AtualizaStatus(VpaTexto : String); begin BarraStatus.Panels[0].Text := VpaTexto; end; {******************************************************************************} procedure TFProcessaProdutividade.BProcessarClick(Sender: TObject); begin ProcessaProdutividade; end; {******************************************************************************} procedure TFProcessaProdutividade.BFecharClick(Sender: TObject); begin close; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFProcessaProdutividade]); end.
// ************************************************************************************************** // Delphi Aio Library. // Unit GreenletsImpl // https://github.com/Purik/AIO // The contents of this file are subject to the Apache License 2.0 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // // The Original Code is GreenletsImpl.pas. // // Contributor(s): // Pavel Minenkov // Purik // https://github.com/Purik // // The Initial Developer of the Original Code is Pavel Minenkov [Purik]. // All Rights Reserved. // // ************************************************************************************************** unit GreenletsImpl; {$DEFINE USE_NATIVE_OS_API} interface uses SysUtils, Gevent, Classes, Boost, SyncObjs, GInterfaces, Hub, Greenlets, {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF}, GarbageCollector, PasMP; type // local storage TLocalStorage = class type TValuesArray = array of TObject; strict private {$IFDEF DCC} FStorage: TDictionary<string, TObject>; {$ELSE} FStorage: TFPGMap<string, TObject>; {$ENDIF} protected function ToArray: TValuesArray; procedure Clear; public constructor Create; destructor Destroy; override; procedure SetValue(const Key: string; Value: TObject); function GetValue(const Key: string): TObject; procedure UnsetValue(const Key: string); overload; procedure UnsetValue(Value: TObject); overload; function IsExists(const Key: string): Boolean; overload; function IsExists(Value: TObject): Boolean; overload; function IsEmpty: Boolean; end; TTriggers = record strict private FCollection: array of TThreadMethod; function Find(const Cb: TThreadMethod; out Index: Integer): Boolean; public procedure OnCb(const Cb: TThreadMethod); procedure OffCb(const Cb: TThreadMethod); procedure RaiseAll; end; TRawGreenletImpl = class(TInterfacedObject, IRawGreenlet) type AExit = class(EAbort); ESelfSwitch = class(Exception); const MAX_CALL_PER_THREAD = 1000; strict private // context dependencies FContext: Boost.TContext; FCurrentContext: Boost.TContext; // internal flags FInjectException: Exception; FInjectRoutine: TSymmetricRoutine; // fields FException: Exception; FLS: TLocalStorage; FGC: TGarbageCollector; FOnStateChange: TGevent; FOnTerminate: TGevent; FState: tGreenletState; // FProxy: TObject; FLock: SyncObjs.TCriticalSection; // triggers FKillTriggers: TTriggers; FHubTriggers: TTriggers; // хаб на котором обслуживаемся FHub: TCustomHub; FName: string; FEnviron: TObject; FOrigThread: TThread; FSleepEv: TGevent; FObjArguments: TList; // {$IFDEF USE_NATIVE_OS_API} class procedure EnterProcFiber(Param: Pointer); stdcall; static; {$ELSE} FStack: Pointer; FStackSize: LongWord; function Allocatestack(Size: NativeUInt): Pointer; procedure DeallocateStack(Stack: Pointer; Size: NativeUInt); {$ENDIF} class procedure EnterProc(Param: Pointer); cdecl; static; procedure ContextSetup; inline; procedure SetHub(Value: TCustomHub); function GetHub: TCustomHub; private FForcingKill: Boolean; FBeginThread: TGreenThread; protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; procedure Execute; virtual; abstract; class function GetStackSize: LongWord; virtual; class function IsNativeAPI: Boolean; procedure SetState(const Value: tGreenletState); procedure Lock; inline; procedure Unlock; inline; procedure HubChanging(OldHub, NewHub: TCustomHub); virtual; class function GetCurrent: TRawGreenletImpl; procedure MoveTo(NewHub: THub); overload; procedure MoveTo(Thread: TThread); overload; procedure BeginThread; procedure EndThread; class function GetEnviron: IGreenEnvironment; property KillTriggers: TTriggers read FKillTriggers; property HubTriggers: TTriggers read FHubTriggers; class procedure Switch2RootContext(const aDelayedCall: TThreadMethod=nil); static; class procedure ClearContexts; static; class function GetCallStackIndex: Integer; static; property Hub: TCustomHub read GetHub write SetHub; procedure Sleep(const Timeout: LongWord); property ObjArguments: TList read FObjArguments; public constructor Create; destructor Destroy; override; procedure Switch; procedure Yield; overload; function GetUID: NativeUInt; function GetProxy: IGreenletProxy; procedure Inject(E: Exception); overload; procedure Inject(const Routine: TSymmetricRoutine); overload; procedure Kill; procedure Suspend; procedure Resume; function GetState: tGreenletState; inline; function GetException: Exception; procedure ReraiseException; function GetInstance: TObject; function GetOnStateChanged: TGevent; function GetOnTerminate: TGevent; function GetName: string; procedure SetName(const Value: string); function Context: TLocalStorage; procedure Join(const RaiseErrors: Boolean = False); function GLS: TLocalStorage; function GC: TGarbageCollector; {$IFDEF DEBUG} function RefCount: Integer; {$ENDIF} end; TChannelRefBasket = class(TInterfacedObject) strict private FChannel: IAbstractChannel; FReaderFactor: Integer; FWriterFactor: Integer; public constructor Create(Channel: IAbstractChannel; ReaderFactor, WriterFactor: Integer); destructor Destroy; override; end; // доп прослойка для входных аргументов сопрограмм // может облегчить доп. работу по копированию или // приведению к персистентному виду TArgument<T> = record strict private type PValue = ^T; var FValue: T; FIsObject: Boolean; FObject: TObject; FSmartObj: IGCObject; FIsDynArr: Boolean; FChanBasket: IInterface; public constructor Create(const Value: T; Owner: TRawGreenletImpl = nil); class operator Implicit(const A: TArgument<T>): T; property IsObject: Boolean read FIsObject; property AsObject: TObject read FObject; end; TResult<T> = record strict private type PValue = ^T; var FValue: T; FIsObject: Boolean; FObject: TObject; FSmartObj: IGCObject; public constructor Create(const Value: T; Owner: TRawGreenletImpl); class operator Implicit(const A: TResult<T>): T; end; // implementations TGreenletImpl = class(TRawGreenletImpl, IGreenlet) strict private FRoutine: TSymmetricRoutine; FArgRoutine: TSymmetricArgsRoutine; FArgStaticRoutine: TSymmetricArgsStatic; protected const MAX_ARG_SZ = 20; var FArgs: array[0..MAX_ARG_SZ-1] of TVarRec; FSmartArgs: array[0..MAX_ARG_SZ-1] of IGCObject; FArgsSz: Integer; procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine); overload; constructor Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); overload; constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload; function Switch: tTuple; overload; function Switch(const Args: array of const): tTuple; overload; function Yield: tTuple; overload; function Yield(const A: array of const): tTuple; overload; end; { TGeneratorImpl } TGeneratorImpl<T> = class(TInterfacedObject, IGenerator<T>) type TGenEnumerator = class(GInterfaces.TEnumerator<T>) private FGen: TGeneratorImpl<T>; protected function GetCurrent: T; override; public function MoveNext: Boolean; override; property Current: T read GetCurrent; procedure Reset; override; end; private type TGenGreenletImpl = class(TGreenletImpl) FGen: TGeneratorImpl<T>; end; var FGreenlet: IGreenlet; FCurrent: T; FIsObject: Boolean; FYieldExists: Boolean; FSmartPtr: TSmartPointer<TObject>; function MoveNext: Boolean; dynamic; procedure Reset; procedure CheckMetaInfo; procedure GarbageCollect(const Old, New: T); public constructor Create(const Routine: TSymmetricRoutine); overload; constructor Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); overload; constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload; destructor Destroy; override; procedure Setup(const Args: array of const); function GetEnumerator: GInterfaces.TEnumerator<T>; class function Yield(const Value: T): tTuple; end; TSymmetricImpl = class(TRawGreenletImpl) strict private FRoutine: TSymmetricRoutine; FRoutineStatic: TSymmetricRoutineStatic; protected procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine; Hub: THub=nil); overload; constructor Create(const Routine: TSymmetricRoutineStatic; Hub: THub=nil); overload; end; TSymmetricImpl<T> = class(TRawGreenletImpl) strict private FArg: TArgument<T>; FRoutine: TSymmetricRoutine<T>; FRoutineStatic: TSymmetricRoutineStatic<T>; protected procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine<T>; const Arg: T; Hub: THub=nil); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T>; const Arg: T; Hub: THub=nil); overload; end; TSymmetricImpl<T1, T2> = class(TRawGreenletImpl) strict private FArg1: TArgument<T1>; FArg2: TArgument<T2>; FRoutine: TSymmetricRoutine<T1, T2>; FRoutineStatic: TSymmetricRoutineStatic<T1, T2>; protected procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine<T1, T2>; const Arg1: T1; const Arg2: T2; Hub: THub=nil); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2>; const Arg1: T1; const Arg2: T2; Hub: THub=nil); overload; end; TSymmetricImpl<T1, T2, T3> = class(TRawGreenletImpl) strict private FArg1: TArgument<T1>; FArg2: TArgument<T2>; FArg3: TArgument<T3>; FRoutine: TSymmetricRoutine<T1, T2, T3>; FRoutineStatic: TSymmetricRoutineStatic<T1, T2, T3>; protected procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub=nil); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub=nil); overload; end; TSymmetricImpl<T1, T2, T3, T4> = class(TRawGreenletImpl) strict private FArg1: TArgument<T1>; FArg2: TArgument<T2>; FArg3: TArgument<T3>; FArg4: TArgument<T4>; FRoutine: TSymmetricRoutine<T1, T2, T3, T4>; FRoutineStatic: TSymmetricRoutineStatic<T1, T2, T3, T4>; protected procedure Execute; override; public constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub=nil); overload; constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub=nil); overload; end; TAsymmetricImpl<Y> = class(TRawGreenletImpl, IAsymmetric<Y>) strict private FRoutine: TAsymmetricRoutine<Y>; FRoutineStatic: TAsymmetricRoutineStatic<Y>; FResult: TResult<Y>; protected procedure Execute; override; public constructor Create(const Routine: TAsymmetricRoutine<Y>; Hub: THub=nil); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<Y>; Hub: THub=nil); overload; destructor Destroy; override; function GetResult(const Block: Boolean = True): Y; end; TAsymmetricImpl<T, Y> = class(TRawGreenletImpl, IAsymmetric<Y>) strict private FRoutine: TAsymmetricRoutine<T, Y>; FRoutineStatic: TAsymmetricRoutineStatic<T, Y>; FResult: TResult<Y>; FArg: TArgument<T>; protected procedure Execute; override; public constructor Create(const Routine: TAsymmetricRoutine<T, Y>; const Arg: T; Hub: THub=nil); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T, Y>; const Arg: T; Hub: THub=nil); overload; destructor Destroy; override; function GetResult(const Block: Boolean = True): Y; end; TAsymmetricImpl<T1, T2, Y> = class(TRawGreenletImpl, IAsymmetric<Y>) strict private FRoutine: TAsymmetricRoutine<T1, T2, Y>; FRoutineStatic: TAsymmetricRoutineStatic<T1, T2, Y>; FResult: TResult<Y>; FArg1: TArgument<T1>; FArg2: TArgument<T2>; protected procedure Execute; override; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, Y>; const Arg1: T1; const Arg2: T2; Hub: THub=nil); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const Arg1: T1; const Arg2: T2; Hub: THub=nil); overload; destructor Destroy; override; function GetResult(const Block: Boolean = True): Y; end; TAsymmetricImpl<T1, T2, T3, Y> = class(TRawGreenletImpl, IAsymmetric<Y>) strict private FRoutine: TAsymmetricRoutine<T1, T2, T3, Y>; FRoutineStatic: TAsymmetricRoutineStatic<T1, T2, T3, Y>; FResult: TResult<Y>; FArg1: TArgument<T1>; FArg2: TArgument<T2>; FArg3: TArgument<T3>; protected procedure Execute; override; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub=nil); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub=nil); overload; destructor Destroy; override; function GetResult(const Block: Boolean = True): Y; end; TAsymmetricImpl<T1, T2, T3, T4, Y> = class(TRawGreenletImpl, IAsymmetric<Y>) strict private FRoutine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; FRoutineStatic: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; FResult: TResult<Y>; FArg1: TArgument<T1>; FArg2: TArgument<T2>; FArg3: TArgument<T3>; FArg4: TArgument<T4>; protected procedure Execute; override; public constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub=nil); overload; constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub=nil); overload; destructor Destroy; override; function GetResult(const Block: Boolean = True): Y; end; TGreenGroupImpl<KEY> = class(TInterfacedObject, IGreenGroup<KEY>) strict private {$IFDEF DCC} FMap: TDictionary<KEY, IRawGreenlet>; {$ELSE} FMap: TFPGMap<KEY, IRawGreenlet>; {$ENDIF} FOnUpdated: TGevent; FList: TList; function IsExists(const Key: KEY): Boolean; procedure Append(const Key: KEY; G: IRawGreenlet); procedure Remove(const Key: KEY); procedure SetValue(const Key: KEY; G: IRawGreenlet); function GetValue(const Key: KEY): IRawGreenlet; public constructor Create; destructor Destroy; override; property Item[const Index: KEY]: IRawGreenlet read GetValue write SetValue; default; procedure Clear; procedure KillAll; function IsEmpty: Boolean; function Join(Timeout: LongWord = INFINITE; const RaiseError: Boolean=False): Boolean; function Copy: IGreenGroup<KEY>; function Count: Integer; end; tArrayOfGreenlet = array of IRawGreenlet; tArrayOfGevent = array of TGevent; TJoiner = class strict private FList: TList; FOnUpdate: TGevent; FLock: SyncObjs.TCriticalSection; function Find(G: TRawGreenletImpl; out Index: Integer): Boolean; function GetItem(Index: Integer): TRawGreenletImpl; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Remove(G: TRawGreenletImpl); procedure Append(G: TRawGreenletImpl); procedure Clear; property OnUpdate: TGevent read FOnUpdate; property Count: Integer read GetCount; function GetStateEvents: tArrayOfGevent; function GetAll: tArrayOfGreenlet; function HasExecutions: Boolean; property Item[Index: Integer]: TRawGreenletImpl read GetItem; default; procedure KillAll; end; TGCondVariableImpl = class(TInterfacedObject, IGCondVariable) strict private type TCoDescr = record Thread: TThread; Ctx: NativeUInt; GEv: TGEvent; Cond: PBoolean; IsDestroyed: PBoolean; {$IFDEF FPC} class operator = (a : TCoDescr; b : TCoDescr): Boolean; {$ENDIF} end; TItems = {$IFDEF DCC}TList<TCoDescr>{$ELSE}TFPGList<TCoDescr>{$ENDIF}; var FQueue: TItems; FMutex: TCriticalSection; FExternalMutex: Boolean; FSync: Boolean; procedure Enqueue(const D: TCoDescr; aUnlocking: TCriticalSection; aSpinUnlocking: TPasMPSpinLock); function Dequeue(out D: TCoDescr): Boolean; procedure ForceDequeue(Ctx: NativeUInt; Thread: TThread); procedure WaitInternal(aUnlocking: TCriticalSection; aSpinUnlocking: TPasMPSpinLock; Gevent: TGevent = nil); protected property Queue: TItems read FQueue; procedure SetSync(const Value: Boolean); function GetSync: Boolean; public constructor Create(aExternalMutex: TCriticalSection = nil); destructor Destroy; override; procedure Wait(aUnlocking: TCriticalSection = nil); overload; procedure Wait(aSpinUnlocking: TPasMPSpinLock); overload; procedure Signal; procedure Broadcast; end; TGSemaphoreImpl = class(TInterfacedObject, IGSemaphore) type EInvalidLimit = class(Exception); strict private type TDescr = class strict private FNotify: TGevent; FRecursion: Integer; public constructor Create; destructor Destroy; override; property Notify: TGevent read FNotify; property Recursion: Integer read FRecursion write FRecursion; end; THashTable = {$IFDEF DCC} TDictionary<NativeUInt, TDescr> {$ELSE} TFPGMap<NativeUInt, TDescr> {$ENDIF}; TQueue = TList; var FLock: TCriticalSection; FQueue: TList; FAcqQueue: TList; FValue: LongWord; FLimit: LongWord; FHash: THashTable; procedure Enqueue(const Ctx: NativeUInt); function Dequeue(out Ctx: NativeUInt): Boolean; procedure Lock; inline; procedure Unlock; inline; function GetCurContext: NativeUInt; function AcquireCtx(const Ctx: NativeUint): TDescr; function ReleaseCtx(const Ctx: NativeUint): Boolean; public constructor Create(Limit: LongWord); destructor Destroy; override; procedure Acquire; procedure Release; function Limit: LongWord; function Value: LongWord; end; TGMutexImpl = class(TInterfacedObject, IGMutex) strict private FSem: IGSemaphore; public constructor Create; procedure Acquire; procedure Release; end; TGQueueImpl<T> = class(TInterfacedObject, IGQueue<T>) strict private type TItems = {$IFDEF DCC}TList<T>{$ELSE}TFPGList<T>{$ENDIF}; var FItems: TItems; FLock: TCriticalSection; FCanDequeue: IGCondVariable; FCanEnqueue: IGCondVariable; FOnEnqueue: TGEvent; FOnDequeue: TGEvent; FMaxCount: LongWord; procedure RefreshGEvents; protected property OnEnqueue: TGEvent read FOnEnqueue; property OnDequeue: TGEvent read FOnDequeue; public constructor Create(MaxCount: LongWord = 0); destructor Destroy; override; procedure Enqueue(A: T); procedure Dequeue(out A: T); procedure Clear; function Count: Integer; end; TFutureImpl<RESULT, ERROR> = class(TInterfacedObject, IFuture<RESULT, ERROR>) private FOnFullFilled: TGevent; FOnRejected: TGevent; FResult: TSmartPointer<RESULT>; FErrorCode: TSmartPointer<ERROR>; FDefValue: RESULT; FErrorStr: string; public constructor Create; destructor Destroy; override; function OnFullFilled: TGevent; function OnRejected: TGevent; function GetResult: RESULT; function GetErrorCode: ERROR; function GetErrorStr: string; end; TPromiseImpl<RESULT, ERROR> = class(TInterfacedObject, IPromise<RESULT, ERROR>) strict private FFuture: TFutureImpl<RESULT, ERROR>; FActive: Boolean; public constructor Create(Future: TFutureImpl<RESULT, ERROR>); destructor Destroy; override; procedure SetResult(const A: RESULT); procedure SetErrorCode(Value: ERROR; const ErrorStr: string = ''); end; TCollectionImpl<T> = class(TInterfacedObject, ICollection<T>) type TEnumerator<Y> = class(GInterfaces.TEnumerator<Y>) strict private FCollection: TCollectionImpl<Y>; FCurPos: Integer; protected function GetCurrent: Y; override; public constructor Create(Collection: TCollectionImpl<Y>); function MoveNext: Boolean; override; property Current: Y read GetCurrent; procedure Reset; override; end; private FList: TList<T>; public constructor Create; destructor Destroy; override; procedure Append(const A: T; const IgnoreDuplicates: Boolean); overload; procedure Append(const Other: ICollection<T>; const IgnoreDuplicates: Boolean); overload; procedure Remove(const A: T); function Count: Integer; function Get(Index: Integer): T; function Copy: ICollection<T>; procedure Clear; function GetEnumerator: GInterfaces.TEnumerator<T>; end; TCaseImpl = class(TInterfacedObject, ICase) strict private FIOOperation: TIOOperation; FOnSuccess: TGevent; FOnError: TGevent; FErrorHolder: IErrorHolder<TPendingError>; FWriteValueExists: Boolean; public destructor Destroy; override; function GetOperation: TIOOperation; procedure SetOperation(const Value: TIOOperation); function GetOnSuccess: TGevent; procedure SetOnSuccess(Value: TGevent); function GetOnError: TGevent; procedure SetOnError(Value: TGevent); function GetErrorHolder: IErrorHolder<TPendingError>; procedure SetErrorHolder(Value: IErrorHolder<TPendingError>); function GetWriteValueExists: Boolean; procedure SetWriteValueExists(const Value: Boolean); end; TGeventPImpl = class(TGevent); {$IFDEF DEBUG} var GreenletCounter: Integer; GeventCounter: Integer; procedure DebugString(const S: string); procedure DebugDump(const Prefix: string; const Ptr: Pointer; Size: LongWord; const Sep: Char = ' '); {$ENDIF} function TimeOut2Time(aTimeOut: LongWord): TTime; function Time2TimeOut(aTime: TTime): LongWord; // Преобразование TVarRec function AsString(const Value: TVarRec): string; inline; function AsObject(const Value: TVarRec): TObject; inline; function AsInteger(const Value: TVarRec): Integer; inline; function AsInt64(const Value: TVarRec): Int64; inline; function AsSingle(const Value: TVarRec): Single; inline; function AsDouble(const Value: TVarRec): Double; inline; function AsBoolean(const Value: TVarRec): Boolean; inline; function AsVariant(const Value: TVarRec): Variant; inline; function AsDateTime(const Value: TVarRec): TDateTime; inline; function AsClass(const Value: TVarRec): TClass; inline; function AsPointer(const Value: TVarRec): Pointer; inline; function AsInterface(const Value: TVarRec): IInterface; inline; function AsAnsiString(const Value: TVarRec): AnsiString; inline; // чек типа function IsString(const Value: TVarRec): Boolean; inline; function IsObject(const Value: TVarRec): Boolean; inline; function IsInteger(const Value: TVarRec): Boolean; inline; function IsInt64(const Value: TVarRec): Boolean; inline; function IsSingle(const Value: TVarRec): Boolean; inline; function IsDouble(const Value: TVarRec): Boolean; inline; function IsBoolean(const Value: TVarRec): Boolean; inline; function IsVariant(const Value: TVarRec): Boolean; inline; function IsClass(const Value: TVarRec): Boolean; inline; function IsPointer(const Value: TVarRec): Boolean; inline; function IsInterface(const Value: TVarRec): Boolean; inline; // finalize TVarRec procedure Finalize(var Value: TVarRec); inline; function GetJoiner(Hub: TCustomHub): TJoiner; implementation uses Math, TypInfo, {$IFDEF MSWINDOWS} {$IFDEF DCC}Winapi.Windows{$ELSE}windows{$ENDIF} {$ELSE} // TODO {$ENDIF}; const MAX_TUPLE_SIZE = 20; HUB_JOINER = 'B2F22831-7AF8-4498-B0AE-278B1F2038F7'; GREEN_ENV = 'D1C68A29-4293-43C5-8CA8-D0C5E8B854DF'; ATTRIB_DESCR = '8D627073-9CF8-433D-B268-581D9363E51B'; type ExceptionClass = class of Exception; TGreenletProxyImpl = class(TInterfacedObject, IGreenletProxy) strict private FBase: TRawGreenletImpl; FLock: SyncObjs.TCriticalSection; procedure Lock; inline; procedure Unlock; inline; procedure SetBase(Base: TRawGreenletImpl); function GetBase: TRawGreenletImpl; protected procedure ResumeBase; procedure SwitchBase; procedure SuspendBase; procedure KillBase; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create(Base: TRawGreenletImpl); property Base: TRawGreenletImpl read GetBase write SetBase; destructor Destroy; override; procedure Pulse; procedure DelayedSwitch; procedure Resume; procedure Suspend; procedure Kill; function GetHub: TCustomHub; function GetState: tGreenletState; function GetException: Exception; function GetOnStateChanged: TGevent; function GetOnTerminate: TGevent; function GetUID: NativeUInt; end; TUniValue = class(TPersistent) strict private FStrValue: string; FIntValue: Integer; FFloatValue: Single; FDoubleValue: Double; FInt64Value: Int64; public procedure Assign(Source: TPersistent); override; property StrValue: string read FStrValue write FStrValue; property IntValue: Integer read FIntValue write FIntValue; property FloatValue: Single read FFloatValue write FFloatValue; property DoubleValue: Double read FDoubleValue write FDoubleValue; property Int64Value: Int64 read FInt64Value write FInt64Value; end; TGreenEnvironmentImpl = class(TInterfacedObject, IGreenEnvironment) strict private FStorage: TLocalStorage; FNames: TStrings; function GetUniValue(const Name: string): TUniValue; public constructor Create; destructor Destroy; override; procedure SetValue(const Name: string; Value: TPersistent); procedure UnsetValue(const Name: string); function GetValue(const Name: string): TPersistent; procedure SetIntValue(const Name: string; Value: Integer); procedure SetStrValue(const Name: string; Value: string); procedure SetFloatValue(const Name: string; Value: Single); procedure SetDoubleValue(const Name: string; const Value: Double); procedure SetInt64Value(const Name: string; const Value: Int64); function GetIntValue(const Name: string): Integer; function GetStrValue(const Name: string): string; function GetFloatValue(const Name: string): Single; function GetDoubleValue(const Name: string): Double; function GetInt64Value(const Name: string): Int64; function Copy: TGreenEnvironmentImpl; procedure Clear; end; TKillToken = class(TInterfacedObject) strict private FKilling: TRawGreenletImpl; public constructor Create(Killing: TRawGreenletImpl); destructor Destroy; override; procedure DoIt; end; // Thread Local Storage threadvar Current: TRawGreenletImpl; CurrentYieldSz: Integer; CurrentYield: array[0..MAX_TUPLE_SIZE-1] of TVarRec; CurrentYieldClear: Boolean; CallStack: array[1..TRawGreenletImpl.MAX_CALL_PER_THREAD] of TRawGreenletImpl; CallIndex: Integer; DelayedCall: TThreadMethod; RootContext: Boost.TContext; {$IFDEF USE_NATIVE_OS_API} {$IFDEF FPC} {$I fpc.inc} {$ENDIF} function GetRootContext: Boost.TContext; inline; begin if not Assigned(RootContext) then RootContext := Pointer(ConvertThreadToFiber(nil)); Result := RootContext; end; {$ENDIF} function PushCaller(G: TRawGreenletImpl): Boolean; begin Result := CallIndex < TRawGreenletImpl.MAX_CALL_PER_THREAD; if Result then begin Inc(CallIndex); CallStack[CallIndex] := G; end; end; function PopCaller: TRawGreenletImpl; inline; begin if CallIndex > 0 then begin Result := CallStack[CallIndex]; Dec(CallIndex); end else Result := nil end; function PeekCaller: TRawGreenletImpl; inline; begin if CallIndex > 0 then begin Result := CallStack[CallIndex]; end else Result := nil end; function GetJoiner(Hub: TCustomHub): TJoiner; begin Result := TJoiner(Hub.HLS(HUB_JOINER)); if not Assigned(Result) then begin Result := TJoiner.Create; Hub.HLS(HUB_JOINER, Result) end; end; function GetCurrent: TRawGreenletImpl; begin Result := Current end; function GetCurrentYield: tTuple; inline; begin SetLength(Result, CurrentYieldSz); if CurrentYieldSz > 0 then Move(CurrentYield[0], Result[0], CurrentYieldSz * SizeOf(TVarRec)) end; { TSymmetricImpl<T> } constructor TSymmetricImpl<T>.Create(const Routine: TSymmetricRoutine<T>; const Arg: T; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg := TArgument<T>.Create(Arg); FRoutine := Routine; end; constructor TSymmetricImpl<T>.Create( const Routine:TSymmetricRoutineStatic<T>; const Arg: T; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg := TArgument<T>.Create(Arg); FRoutineStatic := Routine; end; procedure TSymmetricImpl<T>.Execute; begin if Assigned(FRoutine) then FRoutine(FArg) else if Assigned(FRoutineStatic) then FRoutineStatic(FArg) end; function TimeOut2Time(aTimeOut: LongWord): TTime; var H,M,S,MS: Word; Tmp: LongWord; begin if aTimeOut = INFINITE then Exit(Now + 100000); MS := aTimeOut mod 1000; S := Trunc(aTimeOut / 1000) mod 60; // откинули сек и мсек Tmp := LongWord(aTimeOut - 1000*S - MS); if Tmp > 0 then begin // переводим в минуты Tmp := Tmp div (60*1000); M := Tmp mod 60; H := (Tmp - M) div 60; end else begin H := 0; M := 0; end; Result := EncodeTime(H, M, S, MS); end; function Time2TimeOut(aTime: TTime): LongWord; var H,M,S,MS: Word; begin if aTime < 0 then Exit(0); DecodeTime(aTime, H, M, S, MS); Result := MS + S*1000 + M*1000*60 + H*1000*60*60; end; { TLocalStorage } function TLocalStorage.ToArray: TValuesArray; var I: Integer; begin {$IFDEF DCC} SetLength(Result, Length(FStorage.ToArray)); for I := 0 to High(Result) do Result[I] := FStorage.ToArray[I].Value {$ELSE} SetLength(Result, FStorage.Count); for I := 0 to FStorage.Count-1 do Result[I] := FStorage.Data[I]; {$ENDIF} end; procedure TLocalStorage.Clear; var Val: TObject; IntfInst: IInterface; {$IFDEF FPC}I: Integer;{$ENDIF} procedure Finalize(A: TObject); begin if A.GetInterface(IInterface, IntfInst) then IntfInst._Release else A.Free; end; begin {$IFDEF DCC} for Val in FStorage.Values do if Assigned(Val) then begin Finalize(Val); end; {$ELSE} for I := 0 to FStorage.Count-1 do begin Val := FStorage.Data[I]; if Assigned(Val) then Finalize(Val); end; {$ENDIF} FStorage.Clear; end; constructor TLocalStorage.Create; begin {$IFDEF DCC} FStorage := TDictionary<string, TObject>.Create {$ELSE} FStorage := TFPGMap<string, TObject>.Create; {$ENDIF} end; destructor TLocalStorage.Destroy; begin Clear; FStorage.Free; inherited; end; procedure TLocalStorage.SetValue(const Key: string; Value: TObject); var Intf: IInterface; begin if Value.GetInterface(IInterface, Intf) then Intf._AddRef; FStorage.Add(Key, Value) end; function TLocalStorage.GetValue(const Key: string): TObject; {$IFDEF FPC} var Index: Integer; {$ENDIF} begin {$IFDEF DCC} if FStorage.ContainsKey(Key) then Result := FStorage[Key] else Result := nil; {$ELSE} if FStorage.Find(Key, Index) then Result := FStorage.Data[Index] else Result := nil; {$ENDIF} end; procedure TLocalStorage.UnsetValue(const Key: string); begin if IsExists(Key) then FStorage.Remove(Key); end; procedure TLocalStorage.UnsetValue(Value: TObject); var {$IFDEF DCC} KV: TPair<string, TObject>; {$ELSE} Index: Integer; Key: string; {$ENDIF} begin {$IFDEF DCC} if IsExists(Value) then begin for KV in FStorage.ToArray do if KV.Value = Value then begin FStorage.Remove(KV.Key); Break end; end; {$ELSE} Index := FStorage.IndexOfData(Value); if Index >= 0 then begin Key := FStorage.Keys[Index]; FStorage.Remove(Key); end; {$ENDIF} end; function TLocalStorage.IsExists(const Key: string): Boolean; {$IFDEF FPC} var Index: Integer; {$ENDIF} begin {$IFDEF DCC} Result := FStorage.ContainsKey(Key) {$ELSE} Result := FStorage.Find(Key, Index); {$ENDIF} end; function TLocalStorage.IsExists(Value: TObject): Boolean; begin {$IFDEF DCC} Result := FStorage.ContainsValue(Value); {$ELSE} Result:= FStorage.IndexOfData(Value) >= 0; {$ENDIF} end; function TLocalStorage.IsEmpty: Boolean; begin Result := FStorage.Count = 0 end; function IsString_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtString, vtPChar, vtAnsiString, vtUnicodeString, vtPWideChar]; end; function AsString_(const Value: TVarRec): string; inline; begin case Value.VType of vtInteger: Result := IntToStr(Value.VInteger); vtBoolean: Result := BoolToStr(Value.VBoolean, True); vtChar: Result := string(Value.VChar); vtExtended:Result := FloatToStr(Value.VExtended^); vtString: Result := string(Value.VString^); vtPChar: Result := string(Value.VPChar); vtObject: Result := Format('%s instance: %x', [Value.VObject.ClassName, Value.VObject]); vtClass: Result := Value.VClass.ClassName; vtAnsiString: Result := string(Value.VAnsiString); vtUnicodeString: Result := string(Value.VUnicodeString); vtCurrency: Result := CurrToStr(Value.VCurrency^); vtVariant: Result := string(Value.VVariant^); vtInt64: Result := IntToStr(Value.VInt64^); vtPointer: Result := Format('%x', [Value.VPointer]); vtPWideChar: Result := string(Value.VPWideChar); vtWideChar: Result := Value.VWideChar; else Assert(False, 'Can''t convert VarRec to String'); end; end; function AsAnsiString_(const Value: TVarRec): AnsiString; inline; begin if Value.VType in [vtAnsiString] then Result := AnsiString(Value.VAnsiString) else if Value.VType in [vtString] then Result := AnsiString(Value.VString^) else if Value.VType in [vtUnicodeString] then Result := AnsiString(Value.VPWideChar) else Result := ''; end; function IsObject_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType = vtObject end; function AsObject_(const Value: TVarRec): TObject; inline; begin Result := nil; case Value.VType of vtObject: Result := Value.VObject; vtPointer: Result := TObject(Value.VPointer) else Assert(False, 'Can''t convert VarRec to Object'); end; end; function IsInteger_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtInteger] end; function AsInteger_(const Value: TVarRec): Integer; inline; begin Result := 0; case Value.VType of vtInteger: Result := Value.VInteger; vtBoolean: if Value.VBoolean then Result := 1 else Result := 0; vtObject: Result := Integer(Value.VObject); vtInt64: Result := Integer(Value.VInt64^); vtPointer: Result := Integer(Value.VPointer); vtVariant: Result := Value.VVariant^; else Assert(False, 'Can''t convert VarRec to Integer'); end; end; function IsInt64_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtInt64] end; function AsInt64_(const Value: TVarRec): Int64; inline; begin Result := 0; case Value.VType of vtInteger, vtBoolean: Result := aSiNTEGER(Value); vtObject: Result := Int64(Value.VObject); vtInt64: Result := Value.VInt64^; vtVariant: Result := Value.VVariant^; else Assert(False, 'Can''t convert VarRec to Int64'); end; end; function IsSingle_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtExtended] end; function AsSingle_(const Value: TVarRec): Single; inline; begin Result := 0; case Value.VType of vtInteger, vtBoolean: Result := AsInteger(Value); vtExtended:Result := Value.VExtended^; vtCurrency: Result := Value.VCurrency^; vtVariant: Result := Value.VVariant^; vtInt64: Result := Value.VInt64^; else Assert(False, 'Can''t convert VarRec to Single'); end; end; function IsDouble_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtExtended] end; function AsDouble_(const Value: TVarRec): Double; inline; begin Result := 0; case Value.VType of vtInteger, vtBoolean: Result := AsInteger(Value); vtExtended: Result := Value.VExtended^; vtCurrency: Result := Value.VCurrency^; vtVariant: Result := Value.VVariant^; vtInt64: Result := Value.VInt64^; else Assert(False, 'Can''t convert VarRec to Double'); end; end; function IsBoolean_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtBoolean] end; function AsBoolean_(const Value: TVarRec): Boolean; inline; begin Result := False; case Value.VType of vtInteger: Result := AsInteger(Value) <> 0; vtBoolean: Result := Value.VBoolean; vtInt64: Result := AsInt64(Value) <> 0; vtVariant: Result := Value.VVariant^; else Assert(False, 'Can''t convert VarRec to Boolean'); end; end; function IsVariant_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtVariant] end; function AsVariant_(const Value: TVarRec): Variant; inline; begin case Value.VType of vtInteger: Result := AsInteger(Value); vtBoolean: Result := AsBoolean(Value); vtChar, vtString, vtPChar, vtAnsiString, vtUnicodeString: Result := AsString(Value); vtExtended:Result := AsDouble(Value); vtCurrency: Result := Value.VCurrency^; vtVariant: Result := Value.VVariant^; vtInt64: Result := AsInt64(Value); else Assert(False, 'Can''t convert VarRec to Variant'); end; end; function AsDateTime_(const Value: TVarRec): TDateTime; inline; begin Result := 0; case Value.VType of vtExtended: Result := AsDouble(Value); vtVariant: Result := AsVariant(Value); else Assert(False, 'Can''t convert VarRec to TDateTime'); end; end; function IsClass_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtClass] end; function AsClass_(const Value: TVarRec): TClass; inline; begin Result := nil; if Value.VType = vtClass then Result := Value.VClass else Assert(False, 'Can''t convert VarRec to Class'); end; function IsPointer_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtPointer] end; function IsInterface_(const Value: TVarRec): Boolean; inline; begin Result := Value.VType in [vtInterface]; end; procedure Finalize_(var Value: TVarRec); inline; begin case Value.VType of vtExtended: Value.VExtended := nil; vtString: Value.VString^ := ''; vtPChar: Value.VPChar := ''; vtPWideChar: Value.VPWideChar := ''; vtAnsiString: string(Value.VAnsiString) := ''; vtUnicodeString: string(Value.VUnicodeString) := ''; vtCurrency: Dispose(Value.VCurrency); vtVariant: begin // почемуто вылетает ошибка Dispose(Value.VVariant); Value.VVariant^ := 0; end; vtInterface: IInterface(Value.VInterface) := nil; vtWideString: WideString(Value.VWideString) := ''; vtInt64: Dispose(Value.VInt64); vtObject: TObject(Value.VObject) := nil; end; Value.VInteger := 0; Value.VType := vtInteger; end; function AsPointer_(const Value: TVarRec): Pointer; inline; begin Result := nil; case Value.VType of vtObject: Result := Pointer(Value.VObject); vtPointer: Result := Value.VPointer else Assert(False, 'Can''t convert VarRec to Pointer'); end; end; function AsInterface_(const Value: TVarRec): IInterface; inline; begin Result := nil; case Value.VType of vtInterface: Result := IInterface(Value.VInterface); vtObject: begin if not Value.VObject.GetInterface(IInterface, Result) then Result := nil end; end; end; function AsString(const Value: TVarRec): string; begin Result := AsString_(Value) end; function AsObject(const Value: TVarRec): TObject; begin Result := AsObject_(Value) end; function AsInteger(const Value: TVarRec): Integer; begin Result := AsInteger_(Value) end; function AsInt64(const Value: TVarRec): Int64;begin Result := AsInt64_(Value) end; function AsSingle(const Value: TVarRec): Single; begin Result := AsSingle_(Value) end; function AsDouble(const Value: TVarRec): Double; begin Result := AsDouble_(Value) end; function AsBoolean(const Value: TVarRec): Boolean; begin Result := AsBoolean_(Value) end; function AsVariant(const Value: TVarRec): Variant; begin Result := AsVariant_(Value) end; function AsDateTime(const Value: TVarRec): TDateTime; begin Result := AsDateTime_(Value) end; function AsClass(const Value: TVarRec): TClass; begin Result := AsClass_(Value) end; function AsPointer(const Value: TVarRec): Pointer; begin Result := AsPointer_(Value) end; function AsInterface(const Value: TVarRec): IInterface; begin Result := AsInterface_(Value) end; function AsAnsiString(const Value: TVarRec): AnsiString; begin Result := AsAnsiString_(Value); end; function IsString(const Value: TVarRec): Boolean; begin Result := IsString_(Value) end; function IsObject(const Value: TVarRec): Boolean; begin Result := IsObject_(Value) end; function IsInteger(const Value: TVarRec): Boolean; begin Result := IsInteger_(Value) end; function IsInt64(const Value: TVarRec): Boolean; begin Result := IsInt64_(Value) end; function IsSingle(const Value: TVarRec): Boolean; begin Result := IsSingle_(Value) end; function IsDouble(const Value: TVarRec): Boolean; begin Result := IsDouble_(Value) end; function IsBoolean(const Value: TVarRec): Boolean; begin Result := IsBoolean_(Value) end; function IsVariant(const Value: TVarRec): Boolean; begin Result := IsVariant_(Value) end; function IsClass(const Value: TVarRec): Boolean; begin Result := IsClass_(Value) end; function IsPointer(const Value: TVarRec): Boolean; begin Result := IsPointer_(Value) end; function IsInterface(const Value: TVarRec): Boolean; begin Result := IsInterface_(Value) end; procedure Finalize(var Value: TVarRec); begin Finalize_(Value); end; { TRawGreenletImpl } constructor TRawGreenletImpl.Create; var Env: TGreenEnvironmentImpl; begin inherited Create; FLS := TLocalStorage.Create; FGC := TGarbageCollector.Create; FState := gsReady; {$IFDEF USE_NATIVE_OS_API} {$IFDEF DCC} FContext := CreateFiber(GetStackSize, @EnterProcFiber, Self); {$ELSE} FContext := CreateFiber(GetStackSize, TFNFiberStartRoutine(EnterProcFiber), Self); {$ENDIF} {$ELSE} FStack := Allocatestack(GetStackSize); FStackSize := GetStackSize; FContext := Boost.make_fcontext(FStack, FStackSize, EnterProc); {$ENDIF} FCurrentContext := FContext; FOnStateChange := TGevent.Create; TGeventPImpl(FOnStateChange)._AddRef; FOnTerminate := TGevent.Create(True); TGeventPImpl(FOnTerminate)._AddRef; FLock := SyncObjs.TCriticalSection.Create; FProxy := TGreenletProxyImpl.Create(Self); TGreenletProxyImpl(FProxy)._AddRef; SetHub(GetCurrentHub); if Current = nil then begin Env := TGreenEnvironmentImpl(Hub.HLS(GREEN_ENV)); if not Assigned(Env) then begin Env := TGreenEnvironmentImpl.Create; Hub.HLS(GREEN_ENV, Env); end; FEnviron := Env.Copy; end else begin FEnviron := TGreenEnvironmentImpl(Current.FEnviron).Copy; end; TGreenEnvironmentImpl(FEnviron)._AddRef; FObjArguments := TList.Create; end; destructor TRawGreenletImpl.Destroy; begin if FState in [gsExecute, gsSuspended] then Kill; SetHub(nil); if Assigned(FBeginThread) then begin FBeginThread.FreeOnTerminate := True; FBeginThread.Kill(False); end; if Assigned(FInjectException) then FInjectException.Free; if Assigned(FSleepEv) then FSleepEv.Free; TGreenletProxyImpl(FProxy).Base := nil; TGreenletProxyImpl(FProxy)._Release; FLS.Free; FGC.Free; TGreenEnvironmentImpl(FEnviron)._Release; TGeventPImpl(FOnStateChange)._Release; TGeventPImpl(FOnTerminate)._Release; if Assigned(FException) then FException.Free; {$IFDEF USE_NATIVE_OS_API} DeleteFiber(FContext); {$ELSE} DeallocateStack(FStack, FStackSize); FStack := nil; {$ENDIF} {$IFDEF DEBUG} FContext := nil; FCurrentContext := nil; {$ENDIF} FLock.Free; FObjArguments.Free; inherited; end; procedure TRawGreenletImpl.EndThread; begin if FState <> gsExecute then Exit; if Assigned(FBeginThread) then begin if FState = gsExecute then begin if Assigned(FBeginThread) then begin MoveTo(FOrigThread); FBeginThread.Kill(False); FBeginThread := nil; end; end; end; end; class procedure TRawGreenletImpl.EnterProc(Param: Pointer); var Me: TRawGreenletImpl; NewState: tGreenletState; I: Integer; Ref: IGCObject; begin Me := TRawGreenletImpl(Param); Me.SetState(gsExecute); NewState := Me.GetState; try try // регистрируем ссылки сборщика мусора у себя тоже for I := 0 to Me.FObjArguments.Count-1 do begin if TGarbageCollector.ExistsInGlobal(TObject(Me.FObjArguments[I])) then Ref := Me.GC.SetValue(TObject(Me.FObjArguments[I])); end; Ref := nil; Me.ContextSetup; Me.Execute; NewState := gsTerminated; Me.FKillTriggers.RaiseAll; except On e: SysUtils.Exception do begin if e.ClassType <> AExit then begin Me.FException := e; Me.FException.Message := e.Message; Me.FException.HelpContext := e.HelpContext; AcquireExceptionObject; NewState := gsException; end else begin NewState := gsKilled; end; end; end; finally try if Assigned(Me.FBeginThread) then begin Me.FBeginThread.Kill(False); Me.FBeginThread := nil; end; Me.FGC.Clear; Me.SetState(NewState); Me.FOnTerminate.SetEvent; // Hub потеряет ссылку на гринлет //Me.RemoveFromJoiner - нельзя вызывать, т.к хаб теряет ссылку и получим утечку; Me.Yield; except Me.Switch2RootContext end; end; end; {$IFDEF USE_NATIVE_OS_API} class procedure TRawGreenletImpl.EnterProcFiber(Param: Pointer); begin EnterProc(Param) end; {$ELSE} function TRawGreenletImpl.Allocatestack(Size: NativeUInt): Pointer; var Limit: Pointer; begin Limit := AllocMem(Size); Result := Pointer(NativeUInt(Limit) + Size); end; procedure TRawGreenletImpl.DeallocateStack(Stack: Pointer; Size: NativeUInt); var Limit: Pointer; begin if Assigned(Stack) then begin Limit := Pointer(NativeUInt(Stack) - Size); FreeMemory(Limit); end; end; {$ENDIF} function TRawGreenletImpl.GC: TGarbageCollector; begin Result := FGC; end; class function TRawGreenletImpl.GetCallStackIndex: Integer; begin Result := CallIndex end; class function TRawGreenletImpl.GetCurrent: TRawGreenletImpl; begin Result := Current end; procedure TRawGreenletImpl.MoveTo(NewHub: THub); var G: TRawGreenletImpl; begin if NewHub <> nil then begin if GetState = gsExecute then begin SetHub(NewHub); end; G := PopCaller; if Assigned(G) then begin G.GetProxy.DelayedSwitch; end; Switch2RootContext(TGreenletProxyImpl(Self.FProxy).Pulse); end; end; procedure TRawGreenletImpl.MoveTo(Thread: TThread); var NewHub: THub; begin if Assigned(Thread) then begin NewHub := DefHub(Thread); MoveTo(NewHub); end; end; class function TRawGreenletImpl.GetEnviron: IGreenEnvironment; var Impl: TGreenEnvironmentImpl; begin if Current = nil then begin Result := TGreenEnvironmentImpl(GetCurrentHub.HLS(GREEN_ENV)); if not Assigned(Result) then begin Impl := TGreenEnvironmentImpl.Create; GetCurrentHub.HLS(GREEN_ENV, Impl); Result := Impl; end; end else Result := TGreenEnvironmentImpl(Current.FEnviron); end; function TRawGreenletImpl.GetException: Exception; begin Result := FException end; function TRawGreenletImpl.GetHub: TCustomHub; begin FLock.Acquire; Result := FHub; FLock.Release; end; function TRawGreenletImpl.GetInstance: TObject; begin Result := Self; end; function TRawGreenletImpl.GetName: string; begin Lock; Result := FName; Unlock; end; function TRawGreenletImpl.GetOnStateChanged: TGevent; begin Result := FOnStateChange end; function TRawGreenletImpl.GetOnTerminate: TGevent; begin Result := FOnTerminate end; function TRawGreenletImpl.GetProxy: IGreenletProxy; begin Result := TGreenletProxyImpl(FProxy); end; class function TRawGreenletImpl.GetStackSize: LongWord; begin Result := $4000; // при нативных вызовах в Windows можно уменьшить в 10 раз end; function TRawGreenletImpl.GetState: tGreenletState; begin Result := FState end; function TRawGreenletImpl.GetUID: NativeUInt; begin Result := NativeUInt(Self) end; function TRawGreenletImpl.GLS: TLocalStorage; begin Result := FLS; end; procedure TRawGreenletImpl.HubChanging(OldHub, NewHub: TCustomHub); begin if HubInfrasctuctureEnable then begin if Assigned(OldHub) then GetJoiner(OldHub).Remove(Self); if Assigned(NewHub) then GetJoiner(NewHub).Append(Self); end; FHubTriggers.RaiseAll; GetOnStateChanged.SetEvent; if Assigned(FSleepEv) then FreeAndNil(FSleepEv); end; procedure TRawGreenletImpl.Inject(E: Exception); begin FInjectException := E; Switch; end; procedure TRawGreenletImpl.Inject(const Routine: TSymmetricRoutine); begin FInjectRoutine := Routine; Switch; FInjectRoutine := nil; end; class function TRawGreenletImpl.IsNativeAPI: Boolean; begin {$IFDEF USE_NATIVE_OS_API} Result := True; {$ELSE} Result := False; {$ENDIF} end; procedure TRawGreenletImpl.Join(const RaiseErrors: Boolean); begin Greenlets.Join([Self], INFINITE, RaiseErrors) end; procedure TRawGreenletImpl.Kill; var Hub: TCustomHub; begin if (Current.GetInstance = Self) and (FState = gsExecute) then raise AExit.Create('trerminated') else begin Hub := GetHub; if FForcingKill then begin Inject(AExit.Create('termination')) end else if FState in [gsExecute, gsSuspended, gsKilling] then begin FState := gsKilling; if (Hub = GetCurrentHub) or (Hub = nil) then begin Inject(AExit.Create('termination')) end else begin GetProxy.Kill end; end; end; end; procedure TRawGreenletImpl.Lock; begin FLock.Acquire; end; {$IFDEF DEBUG} function TRawGreenletImpl.RefCount: Integer; begin Result := FRefCount end; {$ENDIF} procedure TRawGreenletImpl.ReraiseException; begin if Assigned(FException) then begin raise ExceptionClass(FException.ClassType).Create(FException.Message); end; end; procedure TRawGreenletImpl.Resume; begin if FState = gsSuspended then begin SetState(gsExecute); if GetCurrent <> Self then Switch; end; end; procedure TRawGreenletImpl.SetHub(Value: TCustomHub); begin FLock.Acquire; try if FHub <> Value then begin HubChanging(FHub, Value); FHub := Value; end; finally FLock.Release; end; end; procedure TRawGreenletImpl.SetName(const Value: string); begin Lock; FName := Value; Unlock; end; procedure TRawGreenletImpl.SetState(const Value: tGreenletState); begin Lock; try if FState <> Value then begin FState := Value; FOnStateChange.SetEvent; end; finally Unlock; end; end; procedure TRawGreenletImpl.Sleep(const Timeout: LongWord); var TimeoutHnd: THandle; begin {$IFDEF DEBUG} Assert(Current = Self); Assert(FHub <> nil); {$ENDIF} if Assigned(FSleepEv) then FSleepEv.Free; if Timeout = 0 then begin GetProxy.DelayedSwitch; Self.Yield; end else begin TimeoutHnd := 0; FSleepEv := TGEvent.Create; try FSleepEv.WaitFor(Timeout) finally if Timeout <> 0 then FHub.DestroyTimeout(TimeoutHnd); FreeAndNil(FSleepEv); end; end; end; procedure TRawGreenletImpl.Suspend; begin if FState in [gsReady, gsExecute] then SetState(gsSuspended) end; procedure TRawGreenletImpl.Switch; var Caller: TRawGreenletImpl; GP: IGreenletProxy; begin if not ((GetState in [gsReady, gsExecute]) or Assigned(FInjectException)) then Exit; if Current = Self then raise ESelfSwitch.Create('Self switch denied'); Caller := Current; {$IFDEF USE_NATIVE_OS_API} if Current = nil then begin GetRootContext; CallIndex := 0; end; if Self = PeekCaller then PopCaller; if PushCaller(Current) then begin Current := Self; SwitchToFiber(FCurrentContext); end else begin CallIndex := 0; // боремся с memoryleak при исп аноним функций GP := GetProxy; GP.DelayedSwitch; // в след цикле продолжим работу GP := nil; SwitchToFiber(GetRootContext); end; {$ELSE} if Current = nil then begin CallIndex := 0; end; if Self = PeekCaller then PopCaller; if PushCaller(Current) then begin Current := Self; if Caller = nil then Boost.jump_fcontext(RootContext, FCurrentContext, Self, True) else Boost.jump_fcontext(Caller.FCurrentContext, FCurrentContext, Self, True); end else begin CallIndex := 0; GP := GetProxy; GP.DelayedSwitch; // в след цикле продолжим работу GP := nil; if Caller <> nil then Boost.jump_fcontext(Caller.FCurrentContext, RootContext, Self, True); end; {$ENDIF} Current := Caller; if (Current = nil) and Assigned(DelayedCall) then begin try DelayedCall(); finally DelayedCall := nil; end; end; end; class procedure TRawGreenletImpl.Switch2RootContext(const aDelayedCall: TThreadMethod); begin CallIndex := 0; DelayedCall := aDelayedCall; {$IFDEF USE_NATIVE_OS_API} SwitchToFiber(GetRootContext); {$ELSE} Boost.jump_fcontext(Current.FCurrentContext, RootContext, GetCurrent, True); {$ENDIF} end; procedure TRawGreenletImpl.Unlock; begin FLock.Release; end; procedure TRawGreenletImpl.Yield; var Caller: TRawGreenletImpl; begin repeat Caller := PopCaller; until (Caller = nil) or (Caller.GetState in [gsExecute, gsKilling]); {$IFDEF USE_NATIVE_OS_API} if Caller <> nil then SwitchToFiber(Caller.FCurrentContext) else SwitchToFiber(GetRootContext); {$ELSE} if Caller <> nil then Boost.jump_fcontext(FCurrentContext, Caller.FCurrentContext, Self, True) else Boost.jump_fcontext(FCurrentContext, RootContext, Self, True); {$ENDIF} ContextSetup; end; function TRawGreenletImpl._AddRef: Integer; begin {$IFDEF DCC} Result := AtomicIncrement(FRefCount); {$ELSE} Result := interlockedincrement(FRefCount); {$ENDIF} {$IFDEF DEBUG} AtomicIncrement(GreenletCounter); {$ENDIF} end; function TRawGreenletImpl._Release: Integer; var Hub: TCustomHub; begin {$IFDEF DEBUG} AtomicDecrement(GreenletCounter); {$ENDIF} {$IFDEF DCC} Result := AtomicDecrement(FRefCount); {$ELSE} Result := interlockeddecrement(FRefCount); {$ENDIF} if Result = 0 then begin Lock; Hub := GetHub; if (Hub <> GetCurrentHub) and (Hub <> nil) and (not FForcingKill) then begin Hub.EnqueueTask(TKillToken.Create(Self).DoIt); Result := 1; Unlock; end else begin Unlock; Destroy; end; end; end; procedure TRawGreenletImpl.BeginThread; begin if Assigned(FBeginThread) then Exit; FOrigThread := TThread.CurrentThread; FBeginThread := TGreenThread.Create; FBeginThread.FreeOnTerminate := True; MoveTo(FBeginThread); end; class procedure TRawGreenletImpl.ClearContexts; begin {Current := nil; CallIndex := 0; DelayedCall := nil; CurrentYieldClear := False; } //RootContext := nil; end; function TRawGreenletImpl.Context: TLocalStorage; begin Result := FLS end; procedure TRawGreenletImpl.ContextSetup; var E: Exception; begin if Assigned(FInjectException) then begin E := FInjectException; FInjectException := nil; raise E; end; while Assigned(FInjectRoutine) do begin FInjectRoutine(); FInjectRoutine := nil; Yield; end; end; { TSymmetricImpl<T1, T2> } constructor TSymmetricImpl<T1, T2>.Create( const Routine: TSymmetricRoutine<T1, T2>; const Arg1: T1; const Arg2: T2; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FRoutine := Routine; end; constructor TSymmetricImpl<T1, T2>.Create( const Routine: TSymmetricRoutineStatic<T1, T2>; const Arg1: T1; const Arg2: T2; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FRoutineStatic := Routine; end; procedure TSymmetricImpl<T1, T2>.Execute; begin if Assigned(FRoutine) then FRoutine(FArg1, FArg2) else if Assigned(FRoutineStatic) then FRoutineStatic(FArg1, FArg2) end; { TSymmetricImpl<T1, T2, T3> } constructor TSymmetricImpl<T1, T2, T3>.Create( const Routine: TSymmetricRoutine<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FArg3 := TArgument<T3>.Create(Arg3); FRoutine := Routine; end; constructor TSymmetricImpl<T1, T2, T3>.Create( const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FArg3 := TArgument<T3>.Create(Arg3); FRoutineStatic := Routine; end; procedure TSymmetricImpl<T1, T2, T3>.Execute; begin if Assigned(FRoutine) then FRoutine(FArg1, FArg2, FArg3) else if Assigned(FRoutineStatic) then FRoutineStatic(FArg1, FArg2, FArg3) end; { TSymmetricImpl<T1, T2, T3, T4> } constructor TSymmetricImpl<T1, T2, T3, T4>.Create( const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FArg3 := TArgument<T3>.Create(Arg3); FArg4 := TArgument<T4>.Create(Arg4); FRoutine := Routine; end; constructor TSymmetricImpl<T1, T2, T3, T4>.Create( const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1); FArg2 := TArgument<T2>.Create(Arg2); FArg3 := TArgument<T3>.Create(Arg3); FArg4 := TArgument<T4>.Create(Arg4); FRoutineStatic := Routine; end; procedure TSymmetricImpl<T1, T2, T3, T4>.Execute; begin if Assigned(FRoutine) then FRoutine(FArg1, FArg2, FArg3, FArg4) else if Assigned(FRoutineStatic) then FRoutineStatic(FArg1, FArg2, FArg3, FArg4) end; { TGreenletProxyImpl } constructor TGreenletProxyImpl.Create(Base: TRawGreenletImpl); begin FBase := Base; FLock := SyncObjs.TCriticalSection.Create; end; procedure TGreenletProxyImpl.ResumeBase; var Base: TRawGreenletImpl; begin FLock.Acquire; Base := FBase; FLock.Release; if Assigned(Base) then Base.Resume; end; procedure TGreenletProxyImpl.SwitchBase; var Base: TRawGreenletImpl; begin FLock.Acquire; Base := FBase; FLock.Release; if Assigned(Base) then Base.Switch; end; procedure TGreenletProxyImpl.KillBase; var Base: TRawGreenletImpl; begin FLock.Acquire; Base := FBase; FLock.Release; if Assigned(Base) then Base.Kill; end; procedure TGreenletProxyImpl.SuspendBase; var Base: TRawGreenletImpl; begin FLock.Acquire; Base := FBase; FLock.Release; if Assigned(Base) then Base.Suspend; end; procedure TGreenletProxyImpl.DelayedSwitch; begin FLock.Acquire; try if FBase = nil then Exit; FBase.Lock; try if Assigned(FBase.Hub) and (FBase.GetState in [gsReady, gsExecute, gsKilling]) then begin FBase.Hub.EnqueueTask(Self.SwitchBase); end; finally FBase.Unlock; end; finally FLock.Release end; end; destructor TGreenletProxyImpl.Destroy; begin FLock.Free; inherited; end; function TGreenletProxyImpl.GetBase: TRawGreenletImpl; begin Lock; Result := FBase; Unlock; end; function TGreenletProxyImpl.GetException: Exception; begin Lock; Result := FBase.GetException; Unlock; end; function TGreenletProxyImpl.GetHub: TCustomHub; begin Lock; Result := FBase.Hub; Unlock; end; function TGreenletProxyImpl.GetOnStateChanged: TGevent; begin Lock; Result := FBase.GetOnStateChanged; Unlock; end; function TGreenletProxyImpl.GetOnTerminate: TGevent; begin Lock; Result := FBase.GetOnTerminate; Unlock; end; function TGreenletProxyImpl.GetState: tGreenletState; begin Lock; if FBase = nil then Result := gsTerminated else Result := FBase.GetState; Unlock; end; function TGreenletProxyImpl.GetUID: NativeUInt; begin Lock; Result := FBase.GetUID; Unlock; end; procedure TGreenletProxyImpl.Kill; var SameHub: Boolean; Base: TRawGreenletImpl; begin SameHub := False; FLock.Acquire; try Base := FBase; if Base = nil then Exit; FBase.Lock; try if Assigned(FBase.Hub) then begin SameHub := GetCurrentHub = FBase.Hub; if Assigned(FBase.Hub) then FBase.Hub.EnqueueTask(Self.KillBase); end; finally FBase.Unlock; end; finally FLock.Release end; if SameHub then Base.Kill; end; procedure TGreenletProxyImpl.Lock; begin FLock.Acquire; end; procedure TGreenletProxyImpl.Pulse; var SameHub: Boolean; begin SameHub := False; FLock.Acquire; try if FBase = nil then Exit; FBase.Lock; try if Assigned(FBase.Hub) and (FBase.GetState in [gsReady, gsExecute, gsKilling]) then begin SameHub := FBase.Hub = GetCurrentHub; // если обслуживается в удаленном хабе if not SameHub then FBase.Hub.EnqueueTask(Self.SwitchBase); end; finally FBase.Unlock; end; finally FLock.Release end; // если обслуживается в тек. хабе то смело отдаем процессор прямо сейчас if SameHub then FBase.Switch end; procedure TGreenletProxyImpl.Resume; begin FLock.Acquire; try if not Assigned(FBase) then Exit; if Assigned(FBase.Hub) then begin // пробуждение всегда через хаб FBase.Hub.EnqueueTask(Self.ResumeBase); end; finally FLock.Release; end; end; procedure TGreenletProxyImpl.SetBase(Base: TRawGreenletImpl); begin Lock; try if Base <> FBase then begin FBase := Base; if Assigned(FBase) then GetOnStateChanged.SetEvent; end; finally Unlock; end; end; procedure TGreenletProxyImpl.Suspend; begin FLock.Acquire; try if FBase = nil then Exit; FBase.Lock; try FBase.Hub.EnqueueTask(Self.SuspendBase); finally FBase.Unlock; end; finally FLock.Release end; end; procedure TGreenletProxyImpl.Unlock; begin FLock.Release; end; function TGreenletProxyImpl._AddRef: Integer; begin Result := inherited _AddRef end; function TGreenletProxyImpl._Release: Integer; begin Result := inherited _Release end; { TGreenletImpl } constructor TGreenletImpl.Create(const Routine: TSymmetricRoutine); begin inherited Create; FRoutine := Routine; end; constructor TGreenletImpl.Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); var I: Integer; begin inherited Create; FArgsSz := Min(Length(Args), MAX_ARG_SZ); for I := 0 to FArgsSz-1 do begin FArgs[I] := Args[I]; if (Args[I].VType = vtObject) then begin if TGarbageCollector.ExistsInGlobal(Args[I].VObject) then FSmartArgs[I] := Greenlets.GC(Args[I].VObject); if ObjArguments.IndexOf(Args[I].VObject) = -1 then ObjArguments.Add(Args[I].VObject); end; end; FArgRoutine := Routine; end; constructor TGreenletImpl.Create(const Routine: TSymmetricArgsStatic; const Args: array of const); var I: Integer; begin inherited Create; FArgsSz := Min(Length(Args), MAX_ARG_SZ); for I := 0 to FArgsSz-1 do begin FArgs[I] := Args[I]; if (Args[I].VType = vtObject) then begin if TGarbageCollector.ExistsInGlobal(Args[I].VObject) then FSmartArgs[I] := Greenlets.GC(Args[I].VObject); if ObjArguments.IndexOf(Args[I].VObject) = -1 then ObjArguments.Add(Args[I].VObject); end; end; FArgStaticRoutine := Routine; end; procedure TGreenletImpl.Execute; var SlicedArgs: array of TVarRec; I: Integer; begin SetLength(SlicedArgs, FArgsSz); for I := 0 to FArgsSz-1 do SlicedArgs[I] := FArgs[I]; if Assigned(FRoutine) then FRoutine else if Assigned(FArgRoutine) then FArgRoutine(SlicedArgs) else if Assigned(FArgStaticRoutine) then FArgStaticRoutine(SlicedArgs); end; function TGreenletImpl.Switch(const Args: array of const): tTuple; var I: Integer; begin CurrentYieldSz := Length(Args); for I := 0 to High(Args) do CurrentYield[I] := Args[I]; CurrentYieldClear := False; Result := Self.Switch; end; function TGreenletImpl.Yield: tTuple; begin CurrentYieldClear := True; CurrentYieldSz := 0; if Current <> nil then begin Current.Yield; Result := GetCurrentYield; end; end; function TGreenletImpl.Yield(const A: array of const): tTuple; var I: Integer; begin CurrentYieldClear := True; CurrentYieldSz := Length(A); for I := 0 to High(A) do CurrentYield[I] := A[I]; if Current <> nil then Current.Yield; Result := GetCurrentYield; end; function TGreenletImpl.Switch: tTuple; begin if CurrentYieldClear then CurrentYieldSz := 0; if GetState in [gsReady, gsExecute] then inherited Switch else begin CurrentYieldSz := 0; end; Result := GetCurrentYield; end; { TAsymmetricImpl<T> } constructor TAsymmetricImpl<Y>.Create(const Routine: TAsymmetricRoutine<Y>; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FRoutine := Routine; end; constructor TAsymmetricImpl<Y>.Create( const Routine: TAsymmetricRoutineStatic<Y>; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FRoutinestatic := Routine; end; destructor TAsymmetricImpl<Y>.Destroy; begin //TFinalizer<Y>.Fin(FResult); inherited; end; procedure TAsymmetricImpl<Y>.Execute; begin if Assigned(FRoutine) then FResult := TResult<Y>.Create(FRoutine, Self) else if Assigned(FRoutineStatic) then FResult := TResult<Y>.Create(FRoutineStatic, Self); end; function TAsymmetricImpl<Y>.GetResult(const Block: Boolean): Y; begin if Block then begin Join(True); case GetState of gsTerminated: Result := FResult; gsException: ReraiseException else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end else begin case GetState of gsTerminated: Result := FResult else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end; end; { TAsymmetricImpl<T, Y> } constructor TAsymmetricImpl<T, Y>.Create(const Routine: TAsymmetricRoutine<T, Y>; const Arg: T; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg := TArgument<T>.Create(Arg, Self); FRoutine := Routine; end; constructor TAsymmetricImpl<T, Y>.Create( const Routine: TAsymmetricRoutineStatic<T, Y>; const Arg: T; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg := TArgument<T>.Create(Arg, Self); FRoutineStatic := Routine; end; destructor TAsymmetricImpl<T, Y>.Destroy; begin //TFinalizer<Y>.Fin(FResult); inherited; end; procedure TAsymmetricImpl<T, Y>.Execute; begin if Assigned(FRoutine) then FResult := TResult<Y>.Create(FRoutine(FArg), Self) else if Assigned(FRoutineStatic) then FResult := TResult<Y>.Create(FRoutineStatic(FArg), Self); end; function TAsymmetricImpl<T, Y>.GetResult(const Block: Boolean): Y; begin if Block then begin Join(True); case GetState of gsTerminated: Result := FResult; gsException: ReraiseException else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end else begin case GetState of gsTerminated: Result := FResult else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end; end; { TAsymmetricImpl<T1, T2, Y> } constructor TAsymmetricImpl<T1, T2, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, Y>; const Arg1: T1; const Arg2: T2; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FRoutine := Routine; end; constructor TAsymmetricImpl<T1, T2, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const Arg1: T1; const Arg2: T2; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FRoutineStatic := Routine; end; destructor TAsymmetricImpl<T1, T2, Y>.Destroy; begin //TFinalizer<Y>.Fin(FResult); inherited; end; procedure TAsymmetricImpl<T1, T2, Y>.Execute; begin if Assigned(FRoutine) then FResult := TResult<Y>.Create(FRoutine(FArg1, FArg2), Self) else if Assigned(FRoutineStatic) then FResult := TResult<Y>.Create(FRoutinestatic(FArg1, FArg2), Self); end; function TAsymmetricImpl<T1, T2, Y>.GetResult(const Block: Boolean): Y; begin if Block then begin Join(True); case GetState of gsTerminated: Result := FResult; gsException: ReraiseException else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end else begin case GetState of gsTerminated: Result := FResult else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end; end; { TSymmetricImpl } constructor TSymmetricImpl.Create(const Routine: TSymmetricRoutine; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FRoutine := Routine end; constructor TSymmetricImpl.Create(const Routine: TSymmetricRoutineStatic; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FRoutineStatic := Routine end; procedure TSymmetricImpl.Execute; begin if Assigned(FRoutine) then FRoutine() else if Assigned(FRoutineStatic) then FRoutineStatic(); end; {$IFDEF DEBUG} procedure DebugString(const S: string); var P: PChar; Str: string; begin Str := S; P := PChar(Str); OutputDebugString(P); end; procedure DebugDump(const Prefix: string; const Ptr: Pointer; Size: LongWord; const Sep: Char); var Data: PByteArray; S: TStrings; B: Byte; I: LongWord; AStr: AnsiString; P: PChar; Str: string; begin if (Size = 0) or (Ptr= nil) then Exit; Data := PByteArray(Ptr); S := TStringList.Create; try S.Delimiter := Sep; for I := 0 to Size-1 do begin B := Data[I]; S.Add(IntToStr(B)); end; SetLength(AStr, Size); Move(Ptr^, Pointer(AStr)^, Size); Str := Prefix + S.DelimitedText + ' (' + string(AStr) + ')'; P := pchar(Str); OutputDebugString(P); finally S.Free end; end; {$ENDIF} { TJoiner } procedure TJoiner.Append(G: TRawGreenletImpl); begin FLock.Acquire; try FList.Add(G); finally FLock.Release; FOnUpdate.SetEvent; end; end; procedure TJoiner.Clear; var G: TRawGreenletImpl; I: Integer; begin FLock.Acquire; try for I := 0 to FList.Count-1 do begin G := TRawGreenletImpl(FList[I]); G.Hub := nil; end; FList.Clear; finally FLock.Release; end; FOnUpdate.SetEvent; end; constructor TJoiner.Create; begin FLock := SyncObjs.TCriticalSection.Create; FList := TList.Create; FOnUpdate := TGevent.Create; TGeventPImpl(FOnUpdate)._AddRef; end; destructor TJoiner.Destroy; begin if HubInfrasctuctureEnable then Clear; FList.Free; TGeventPImpl(FOnUpdate)._Release; FLock.Free; inherited; end; function TJoiner.Find(G: TRawGreenletImpl; out Index: Integer): Boolean; var I: Integer; begin Result := False; for I := 0 to FList.Count-1 do if FList[I] = G then begin Index := I; Exit(True); end; end; function TJoiner.GetAll: tArrayOfGreenlet; var I: Integer; begin FLock.Acquire; SetLength(Result, FList.Count); for I := 0 to FList.Count-1 do Result[I] := TRawGreenletImpl(FList[I]); FLock.Release; end; function TJoiner.GetCount: Integer; begin FLock.Acquire; Result := FList.Count; FLock.Release; end; function TJoiner.GetItem(Index: Integer): TRawGreenletImpl; begin FLock.Acquire; if Index < FList.Count then Result := TRawGreenletImpl(FList[Index]) else Result := nil; FLock.Release; end; function TJoiner.GetStateEvents: tArrayOfGevent; var I: Integer; begin FLock.Acquire; SetLength(Result, FList.Count+1); Result[0] := FOnUpdate; for I := 0 to FList.Count-1 do Result[I+1] := TRawGreenletImpl(FList[I]).GetOnStateChanged; FLock.Release; end; function TJoiner.HasExecutions: Boolean; var I: Integer; begin FLock.Acquire; try Result := False; for I := 0 to FList.Count-1 do if Item[I].GetState = gsExecute then Exit(True) finally FLock.Release end; end; procedure TJoiner.KillAll; var G: TRawGreenletImpl; begin FLock.Acquire; try while FList.Count > 0 do begin G := TRawGreenletImpl(FList[0]); FList.Delete(0); G.Kill; G.Hub := nil; end; finally FLock.Release end; end; procedure TJoiner.Remove(G: TRawGreenletImpl); var Index: Integer; begin FLock.Acquire; try if Find(G, Index) then begin FList.Delete(Index); FOnUpdate.SetEvent; end; finally FLock.Release; end; end; { TAsymmetricImpl<T1, T2, T3, Y> } constructor TAsymmetricImpl<T1, T2, T3, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FArg3 := TArgument<T3>.Create(Arg3, Self); FRoutine := Routine; end; constructor TAsymmetricImpl<T1, T2, T3, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FArg3 := TArgument<T3>.Create(Arg3, Self); FRoutineStatic := Routine; end; destructor TAsymmetricImpl<T1, T2, T3, Y>.Destroy; begin //TFinalizer<Y>.Fin(FResult); inherited; end; procedure TAsymmetricImpl<T1, T2, T3, Y>.Execute; begin if Assigned(FRoutine) then FResult := TResult<Y>.Create(FRoutine(FArg1, FArg2, FArg3), Self) else if Assigned(FRoutineStatic) then FResult := TResult<Y>.Create(FRoutinestatic(FArg1, FArg2, FArg3), Self); end; function TAsymmetricImpl<T1, T2, T3, Y>.GetResult(const Block: Boolean): Y; begin if Block then begin Join(True); case GetState of gsTerminated: Result := FResult; gsException: ReraiseException else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end else begin case GetState of gsTerminated: Result := FResult else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end; end; { TAsymmetricImpl<T1, T2, T3, T4, Y> } constructor TAsymmetricImpl<T1, T2, T3, T4, Y>.Create( const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FArg3 := TArgument<T3>.Create(Arg3, Self); FArg4 := TArgument<T4>.Create(Arg4, Self); FRoutine := Routine; end; constructor TAsymmetricImpl<T1, T2, T3, T4, Y>.Create( const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const Arg1: T1; const Arg2: T2; const Arg3: T3; const Arg4: T4; Hub: THub); begin inherited Create; if Assigned(Hub) then Self.Hub := Hub; FArg1 := TArgument<T1>.Create(Arg1, Self); FArg2 := TArgument<T2>.Create(Arg2, Self); FArg3 := TArgument<T3>.Create(Arg3, Self); FArg4 := TArgument<T4>.Create(Arg4, Self); FRoutineStatic := Routine; end; destructor TAsymmetricImpl<T1, T2, T3, T4, Y>.Destroy; begin //TFinalizer<Y>.Fin(FResult); inherited; end; procedure TAsymmetricImpl<T1, T2, T3, T4, Y>.Execute; begin if Assigned(FRoutine) then FResult := TResult<Y>.Create(FRoutine(FArg1, FArg2, FArg3, FArg4), Self) else if Assigned(FRoutineStatic) then FResult := TResult<Y>.Create(FRoutinestatic(FArg1, FArg2, FArg3, FArg4), Self); end; function TAsymmetricImpl<T1, T2, T3, T4, Y>.GetResult(const Block: Boolean): Y; begin if Block then begin Join(True); case GetState of gsTerminated: Result := FResult; gsException: ReraiseException else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end else begin case GetState of gsTerminated: Result := FResult else raise EResultIsEmpty.Create('Result is Empty. Check state of greenlet'); end; end; end; { TGeneratorImpl<T> } constructor TGeneratorImpl<T>.Create(const Routine: TSymmetricRoutine); var Inst: TGenGreenletImpl; begin CheckMetaInfo; Inst := TGenGreenletImpl.Create(Routine); Inst.FGen := Self; FGreenlet := Inst; end; constructor TGeneratorImpl<T>.Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); var Inst: TGenGreenletImpl; begin CheckMetaInfo; Inst := TGenGreenletImpl.Create(Routine, Args); Inst.FGen := Self; FGreenlet := Inst; end; procedure TGeneratorImpl<T>.CheckMetaInfo; var ti: PTypeInfo; ObjValuePtr: PObject; begin ti := TypeInfo(T); if (ti.Kind = tkClass) then begin FIsObject := True; end end; constructor TGeneratorImpl<T>.Create(const Routine: TSymmetricArgsStatic; const Args: array of const); var Inst: TGenGreenletImpl; begin CheckMetaInfo; Inst := TGenGreenletImpl.Create(Routine, Args); Inst.FGen := Self; FGreenlet := Inst; end; destructor TGeneratorImpl<T>.Destroy; begin FGreenlet.Kill; inherited; end; procedure TGeneratorImpl<T>.GarbageCollect(const Old, New: T); var ObjValuePtr: PObject; vOld, vNew: TObject; begin if FIsObject then begin ObjValuePtr := @Old; vOld := ObjValuePtr^; ObjValuePtr := @New; vNew := ObjValuePtr^; FSmartPtr := vNew end; end; function TGeneratorImpl<T>.GetEnumerator: GInterfaces.TEnumerator<T>; var Inst: TGenEnumerator; begin Inst := TGenEnumerator.Create; Inst.FGen := Self; Result := Inst; end; function TGeneratorImpl<T>.MoveNext: Boolean; var Inst: TGreenletImpl; begin // Делаем 1 цикл FGreenlet.Switch; // И смотрим что получилось while True do begin case FGreenlet.GetState of gsExecute: begin if FYieldExists then Exit(True) else Exit(False); end; gsSuspended: begin FGreenlet.GetOnStateChanged.WaitFor end else Exit(False) end; end; end; procedure TGeneratorImpl<T>.Reset; begin FYieldExists := False; FGreenlet.Kill; end; procedure TGeneratorImpl<T>.Setup(const Args: array of const); var G: TGreenletImpl; begin G := TGreenletImpl(FGreenlet.GetInstance); FGreenlet.Switch(Args); end; class function TGeneratorImpl<T>.Yield(const Value: T): tTuple; var Gen: TGeneratorImpl<T>; Greenlet: TGenGreenletImpl; Current: TRawGreenletImpl; begin Current := TRawGreenletImpl.GetCurrent; if Current = nil then Exit; if Current.ClassType = TGenGreenletImpl then begin Greenlet := TGenGreenletImpl(Current); Gen := TGeneratorImpl<T>(Greenlet.FGen) end else Gen := nil; if Assigned(Gen) then begin // Кладем наши данные Gen.FYieldExists := True; Gen.GarbageCollect(Gen.FCurrent, Value); Gen.FCurrent := Value; Result := Greenlet.Yield; // эта строка выполнится уже после след вызова Switch Gen.FYieldExists := False; end else begin Current.Yield; end; end; { TGeneratorImpl<T>.TEnumerator } function TGeneratorImpl<T>.TGenEnumerator.GetCurrent: T; begin Result := FGen.FCurrent end; function TGeneratorImpl<T>.TGenEnumerator.MoveNext: Boolean; begin Result := FGen.MoveNext end; procedure TGeneratorImpl<T>.TGenEnumerator.Reset; begin FGen.Reset end; { TUniValue } procedure TUniValue.Assign(Source: TPersistent); begin if InheritsFrom(Source.ClassType) then begin FStrValue := TUniValue(Source).FStrValue; FIntValue := TUniValue(Source).FIntValue; FFloatValue := TUniValue(Source).FFloatValue; FDoubleValue := TUniValue(Source).FDoubleValue; FInt64Value := TUniValue(Source).FInt64Value; end; end; { TGreenEnvironmentImpl } procedure TGreenEnvironmentImpl.Clear; begin while FNames.Count > 0 do UnsetValue(FNames[0]); end; function TGreenEnvironmentImpl.Copy: TGreenEnvironmentImpl; var I: Integer; CpyValue, Value: TPersistent; begin Result := TGreenEnvironmentImpl.Create; for I := 0 to FNames.Count-1 do begin Value := GetValue(FNames[I]); CpyValue := TPersistentClass(Value.ClassType).Create; CpyValue.Assign(Value); Result.SetValue(FNames[I], CpyValue); end; end; constructor TGreenEnvironmentImpl.Create; begin FStorage := TLocalStorage.Create; FNames := TStringList.Create; end; destructor TGreenEnvironmentImpl.Destroy; var AllNames: array of string; I: Integer; begin SetLength(AllNames, FNames.Count); for I := 0 to FNames.Count-1 do AllNames[I] := FNames[I]; for I := 0 to High(AllNames) do UnsetValue(AllNames[I]); FStorage.Free; FNames.Free; inherited; end; function TGreenEnvironmentImpl.GetDoubleValue(const Name: string): Double; begin Result := GetUniValue(Name).DoubleValue end; function TGreenEnvironmentImpl.GetFloatValue(const Name: string): Single; begin Result := GetUniValue(Name).FloatValue end; function TGreenEnvironmentImpl.GetInt64Value(const Name: string): Int64; begin Result := GetUniValue(Name).Int64Value end; function TGreenEnvironmentImpl.GetIntValue(const Name: string): Integer; begin Result := GetUniValue(Name).IntValue end; function TGreenEnvironmentImpl.GetStrValue(const Name: string): string; begin Result := GetUniValue(Name).StrValue end; function TGreenEnvironmentImpl.GetUniValue(const Name: string): TUniValue; var P: TPersistent; begin P := GetValue(Name); if Assigned(P) then begin if not P.InheritsFrom(TUniValue) then begin UnsetValue(Name); Result := TUniValue(P); end else Result := TUniValue(P); end else begin Result := TUniValue.Create; SetValue(Name, Result); end; end; function TGreenEnvironmentImpl.GetValue(const Name: string): TPersistent; begin Result := TPersistent(FStorage.GetValue(Name)); end; procedure TGreenEnvironmentImpl.SetDoubleValue(const Name: string; const Value: Double); begin GetUniValue(Name).DoubleValue := Value end; procedure TGreenEnvironmentImpl.SetFloatValue(const Name: string; Value: Single); begin GetUniValue(Name).FloatValue := Value end; procedure TGreenEnvironmentImpl.SetInt64Value(const Name: string; const Value: Int64); begin GetUniValue(Name).Int64Value := Value end; procedure TGreenEnvironmentImpl.SetIntValue(const Name: string; Value: Integer); begin GetUniValue(Name).IntValue := Value end; procedure TGreenEnvironmentImpl.SetStrValue(const Name: string; Value: string); begin GetUniValue(Name).StrValue := Value; end; procedure TGreenEnvironmentImpl.SetValue(const Name: string; Value: TPersistent); var OldValue: TPersistent; begin OldValue := TPersistent(FStorage.GetValue(Name)); if Assigned(OldValue) then OldValue.Free else FNames.Add(Name); FStorage.SetValue(Name, Value); end; procedure TGreenEnvironmentImpl.UnsetValue(const Name: string); var Value: TObject; begin Value := FStorage.GetValue(Name); if Assigned(Value) then begin FNames.Delete(FNames.IndexOf(Name)); FStorage.UnsetValue(Value); Value.Free; end end; { TKillToken } constructor TKillToken.Create(Killing: TRawGreenletImpl); begin FKilling := Killing; FKilling._AddRef; end; destructor TKillToken.Destroy; begin if Assigned(FKilling) then DoIt; inherited; end; procedure TKillToken.DoIt; begin FKilling.FForcingKill := True; if FKilling.GetState in [gsExecute, gsSuspended] then begin FKilling.Kill; end; FKilling._Release; FKilling := nil; Self._Release; end; { TTriggers } function TTriggers.Find(const Cb: TThreadMethod; out Index: Integer): Boolean; var I: Integer; begin for I := 0 to High(FCollection) do if @FCollection[I] = @Cb then Exit(True); Result := False; end; procedure TTriggers.OffCb(const Cb: TThreadMethod); var Index: Integer; begin if Find(Cb, Index) then begin if Index = High(FCollection) then SetLength(FCollection, Length(FCollection)-1) else begin Move(FCollection[Index+1], FCollection[Index], Length(FCollection)-Index-1); SetLength(FCollection, Length(FCollection)-1); end end; end; procedure TTriggers.OnCb(const Cb: TThreadMethod); var Index: Integer; begin if not Find(Cb, Index) then begin SetLength(FCollection, Length(FCollection) + 1); FCollection[High(FCollection)] := Cb end; end; procedure TTriggers.RaiseAll; var I: Integer; begin for I := 0 to High(FCollection) do FCollection[I](); end; { IGreenGroup<KEY> } procedure TGreenGroupImpl<KEY>.Append(const Key: KEY; G: IRawGreenlet); var Ptr: Pointer; begin FMap.Add(Key, G); Ptr := Pointer(G); FList.Add(Ptr); G._AddRef; FOnUpdated.SetEvent; end; procedure TGreenGroupImpl<KEY>.Clear; var I: Integer; G: IRawGreenlet; begin FMap.Clear; try for I := 0 to FList.Count-1 do begin G := IRawGreenlet(FList[I]); G._Release; end; finally FList.Clear; end; FOnUpdated.SetEvent; end; function TGreenGroupImpl<KEY>.Copy: IGreenGroup<KEY>; var Cpy: TGreenGroupImpl<KEY>; G: IRawGreenlet; Ptr: Pointer; I: Integer; {$IFDEF DCC} KV: TPair<KEY, IRawGreenlet>; {$ELSE} Index: Integer; Key: KEY; {$ENDIF} begin Cpy := TGreenGroupImpl<KEY>.Create; for I := 0 to Self.FList.Count-1 do begin G := IRawGreenlet(FList[I]); Ptr := Pointer(G); G._AddRef; Cpy.FList.Add(Ptr); end; {$IFDEF DCC} for KV in Self.FMap do Cpy.FMap.Add(KV.Key, KV.Value); {$ELSE} for Index := 0 to Self.FMap.Count-1 do begin Key := Self.FMap.Keys[Index]; Cpy.FMap.Add(Key, Self.FMap[Key]); end; {$ENDIF} Result := Cpy; end; constructor TGreenGroupImpl<KEY>.Create; begin inherited Create; {$IFDEF DCC} FMap := TDictionary<KEY, IRawGreenlet>.Create; {$ELSE} FMap := TFPGMap<KEY, IRawGreenlet>.Create; {$ENDIF} FOnUpdated := TGevent.Create; TGeventPImpl(FOnUpdated)._AddRef; FList := TList.Create; end; destructor TGreenGroupImpl<KEY>.Destroy; begin Clear; FMap.Free; TGeventPImpl(FOnUpdated)._Release; FList.Free; inherited; end; function TGreenGroupImpl<KEY>.Count: Integer; begin Result := FList.Count end; function TGreenGroupImpl<KEY>.GetValue(const Key: KEY): IRawGreenlet; begin if IsExists(Key) then Result := FMap[Key] else Result := nil; end; function TGreenGroupImpl<KEY>.IsEmpty: Boolean; begin Result := FMap.Count = 0 end; function TGreenGroupImpl<KEY>.IsExists(const Key: KEY): Boolean; {$IFDEF FPC} var Index: Integer; {$ENDIF} begin {$IFDEF DCC} Result := FMap.ContainsKey(Key) {$ELSE} Result := FMap.Find(Key, Index); {$ENDIF} end; function TGreenGroupImpl<KEY>.Join(Timeout: LongWord; const RaiseError: Boolean): Boolean; var Workers: array of IRawGreenlet; I: Integer; begin SetLength(Workers, FList.Count); for I := 0 to FList.Count-1 do Workers[I] := IRawGreenlet(FList[I]); Result := Greenlets.Join(Workers, Timeout, RaiseError) end; procedure TGreenGroupImpl<KEY>.KillAll; var I: Integer; G: IRawGreenlet; begin try for I := 0 to FList.Count-1 do begin G := IRawGreenlet(FList[I]); G.Kill; end; finally FList.Clear; end; FOnUpdated.SetEvent; end; procedure TGreenGroupImpl<KEY>.Remove(const Key: KEY); var G: IRawGreenlet; Ptr: Pointer; Index: Integer; begin G := FMap[Key]; Ptr := Pointer(G); Index := FList.IndexOf(Ptr); if Index >= 0 then begin FList.Delete(Index); G._Release; end; FMap.Remove(Key); FOnUpdated.SetEvent; end; procedure TGreenGroupImpl<KEY>.SetValue(const Key: KEY; G: IRawGreenlet); begin if IsExists(Key) then Remove(Key); if Assigned(G) then Append(Key, G); end; { TArgument<T> } constructor TArgument<T>.Create(const Value: T; Owner: TRawGreenletImpl); type TDynArr = TArray<T>; PDynArr = ^TDynArr; PInterface = ^IInterface; var ti: PTypeInfo; td: PTypeData; ValuePtr: PValue; B: TBoundArray; DynLen, DynDim: NativeInt; PArrValueIn, PArrValueOut: PDynArr; // rtti rtype: TRTTIType; fields: TArray<TRttiField>; I: Integer; Intf: IInterface; Chan: IAbstractChannel; PIntf: PInterface; RW: IChannel<T>; R: IReadOnly<T>; W: IWriteOnly<T>; begin FIsObject := False; FIsDynArr := False; ti := TypeInfo(T); if ti.Kind = tkRecord then begin rtype := TRTTIContext.Create.GetType(TypeInfo(T)); fields := rtype.GetFields; for I := 0 to High(fields) do begin if fields[I].FieldType.Handle.Kind = tkInterface then begin Intf := fields[I].GetValue(@Value).AsInterface; if Assigned(Intf) then begin if Intf.QueryInterface(IChannel<T>, RW) = 0 then FChanBasket := TChannelRefBasket.Create(RW, 2, 2) else if Intf.QueryInterface(IReadOnly<T>, R) = 0 then FChanBasket := TChannelRefBasket.Create(R, 2, 0) else if Intf.QueryInterface(IWriteOnly<T>, W) = 0 then FChanBasket := TChannelRefBasket.Create(W, 0, 2) end; end; end; end else if ti.Kind = tkInterface then begin PIntf := PInterface(@Value); Intf := PIntf^; if Assigned(Intf) then begin if Intf.QueryInterface(IChannel<T>, RW) = 0 then FChanBasket := TChannelRefBasket.Create(RW, 2, 2) else if Intf.QueryInterface(IReadOnly<T>, R) = 0 then FChanBasket := TChannelRefBasket.Create(R, 2, 0) else if Intf.QueryInterface(IWriteOnly<T>, W) = 0 then FChanBasket := TChannelRefBasket.Create(W, 0, 2) end; end; if (ti.Kind = tkClass) then begin ValuePtr := @Value; FObject := PObject(ValuePtr)^; FIsObject := True; if Assigned(FObject) and FObject.InheritsFrom(TPersistent) then begin if FObject.InheritsFrom(TComponent) then begin FObject := TComponentClass(FObject.ClassType).Create(nil); end else begin FObject := TPersistentClass(FObject.ClassType).Create; end; TPersistent(FObject).Assign(TPersistent(PObject(ValuePtr)^)); Self.FSmartObj := TGCPointerImpl<TObject>.Create(FObject); end else begin if TGarbageCollector.ExistsInGlobal(FObject) then begin FSmartObj := GC(FObject); end else begin // nothing end; end; ValuePtr := PValue(@FObject); FValue := ValuePtr^; if Assigned(Owner) then if Owner.ObjArguments.IndexOf(FObject) = -1 then begin Owner.ObjArguments.Add(FObject); end; end else if ti.Kind = tkDynArray then begin FIsDynArr := True; td := GetTypeData(ti); if DynArrayDim(ti) = 1 then begin if Assigned(td.elType) and (td.elType^.Kind in [tkString, tkUString, tkLString, tkWString, tkInterface]) then begin FValue := Value; end else begin PArrValueIn := PDynArr(@Value); PArrValueOut := PDynArr(@FValue); DynLen := Length(PArrValueIn^); SetLength(PArrValueOut^, DynLen); Move(PArrValueIn^[0], PArrValueOut^[0], DynLen * td.elSize) end; end else FValue := Value end else FValue := Value; end; class operator TArgument<T>.Implicit(const A: TArgument<T>): T; begin Result := A.FValue end; { TResult<T> } constructor TResult<T>.Create(const Value: T; Owner: TRawGreenletImpl); var ti: PTypeInfo; ValuePtr: PValue; begin FIsObject := False; FValue := Value; ti := TypeInfo(T); if (ti.Kind = tkClass) then begin ValuePtr := @Value; FObject := PObject(ValuePtr)^; FIsObject := True; if (Owner.ObjArguments.IndexOf(FObject) <> -1) and TGarbageCollector.ExistsInGlobal(FObject) then FSmartObj := GC(FObject); end; end; class operator TResult<T>.Implicit(const A: TResult<T>): T; begin Result := A.FValue end; { TChannelRefBasket } constructor TChannelRefBasket.Create(Channel: IAbstractChannel; ReaderFactor, WriterFactor: Integer); begin FChannel := Channel; FReaderFactor := ReaderFactor; FWriterFactor := WriterFactor; FChannel.ReleaseRefs(ReaderFactor, WriterFactor); end; destructor TChannelRefBasket.Destroy; begin if Assigned(FChannel) then FChannel.AccumRefs(FReaderFactor, FWriterFactor); inherited; end; { TGCondVariableImpl } procedure TGCondVariableImpl.Broadcast; var D: TCoDescr; begin while Dequeue(D) do begin D.Cond^ := True; D.GEv.SetEvent(FSync) end; end; constructor TGCondVariableImpl.Create(aExternalMutex: TCriticalSection); begin FQueue := TItems.Create; FExternalMutex := Assigned(aExternalMutex); if FExternalMutex then FMutex := aExternalMutex else FMutex := TCriticalSection.Create; FSync := True; end; function TGCondVariableImpl.Dequeue(out D: TCoDescr): Boolean; begin FMutex.Acquire; try Result := FQueue.Count > 0; if Result then begin D := FQueue[0]; FQueue.Delete(0); end; finally FMutex.Release; end; end; destructor TGCondVariableImpl.Destroy; var I: Integer; begin for I := 0 to FQueue.Count-1 do if Assigned(FQueue[I].IsDestroyed) then FQueue[I].IsDestroyed^ := True; FQueue.Free; if not FExternalMutex then FMutex.Free; inherited; end; procedure TGCondVariableImpl.Enqueue(const D: TCoDescr; aUnlocking: TCriticalSection; aSpinUnlocking: TPasMPSpinLock); begin FMutex.Acquire; try FQueue.Add(D); finally if Assigned(aUnlocking) then aUnlocking.Release; if Assigned(aSpinUnlocking) then aSpinUnlocking.Release; FMutex.Release; end; end; procedure TGCondVariableImpl.ForceDequeue(Ctx: NativeUInt; Thread: TThread); var I: Integer; begin FMutex.Acquire; try I := 0; while I < FQueue.Count do begin if (FQueue[I].Ctx = Ctx) and (FQueue[I].Thread = Thread) then FQueue.Delete(I) else Inc(I) end; finally FMutex.Release; end; end; function TGCondVariableImpl.GetSync: Boolean; begin Result := FSync end; procedure TGCondVariableImpl.SetSync(const Value: Boolean); begin FSync := Value end; procedure TGCondVariableImpl.Signal; var D: TCoDescr; begin if Dequeue(D) then begin D.Cond^ := True; D.GEv.SetEvent(FSync); end; end; procedure TGCondVariableImpl.Wait(aSpinUnlocking: TPasMPSpinLock); begin WaitInternal(nil, aSpinUnlocking) end; procedure TGCondVariableImpl.Wait(aUnlocking: TCriticalSection); begin WaitInternal(aUnlocking, nil); end; procedure TGCondVariableImpl.WaitInternal(aUnlocking: TCriticalSection; aSpinUnlocking: TPasMPSpinLock; Gevent: TGevent); var Cond: Boolean; Descr: TCoDescr; Destroyed: Boolean; begin Cond := False; if Greenlets.GetCurrent <> nil then Descr.Ctx := TRawGreenletImpl(Greenlets.GetCurrent).GetUID else Descr.Ctx := NativeUInt(GetCurrentHub); Descr.Thread := TThread.CurrentThread; Descr.Cond := @Cond; Destroyed := False; Descr.IsDestroyed := @Destroyed; if Greenlets.GetCurrent = nil then begin // Случай если ждет нитка if Assigned(Gevent) then Descr.GEv := Gevent else Descr.GEv := TGEvent.Create(False, False); Enqueue(Descr, aUnlocking, aSpinUnlocking); while not Cond do Descr.GEv.WaitFor(INFINITE); ForceDequeue(Descr.Ctx, Descr.Thread); if not Assigned(Gevent) then Descr.GEv.Free; end else begin // Хитрость - ставим блокировку через переменную выделенную на стеке // мы так можем сделать потому что у сопрограммы свой стек Descr.Cond := @Cond; if Assigned(Gevent) then Descr.GEv := Gevent else Descr.GEv := TGEvent.Create; try Enqueue(Descr, aUnlocking, aSpinUnlocking); while not Cond do Descr.GEv.WaitFor(INFINITE); finally if not Destroyed then ForceDequeue(Descr.Ctx, Descr.Thread); if not Assigned(Gevent) then Descr.GEv.Free; end; end; end; { TGSemaphoreImpl } procedure TGSemaphoreImpl.Acquire; var Descr: TDescr; begin Descr := AcquireCtx(GetCurContext); while True do begin Lock; if (FAcqQueue.Count > 0) and (NativeUint(FAcqQueue[0]) = GetCurContext) then begin FAcqQueue.Delete(0); Break; end; if (FValue < FLimit) and (FAcqQueue.Count = 0) and (FQueue.Count = 0) then Break; Enqueue(GetCurContext); Unlock; if Descr.Notify.WaitFor <> wrSignaled then Exit; end; Inc(FValue); Unlock; end; function TGSemaphoreImpl.AcquireCtx(const Ctx: NativeUint): TDescr; begin Lock; try if FHash.ContainsKey(Ctx) then begin Result := FHash[Ctx]; Result.Recursion := Result.Recursion + 1; end else begin Result := TDescr.Create; Result.Recursion := 1; FHash.Add(Ctx, Result) end; finally Unlock; end; end; constructor TGSemaphoreImpl.Create(Limit: LongWord); begin if Limit = 0 then raise EInvalidLimit.Create('Limit must be greater than 0'); FLimit := Limit; FQueue := TList.Create; FAcqQueue := TList.Create; FHash := THashTable.Create; FLock := TCriticalSection.Create; end; function TGSemaphoreImpl.Dequeue(out Ctx: NativeUInt): Boolean; begin Lock; try Result := FQueue.Count > 0; if Result then begin Ctx := NativeUInt(FQueue[0]); FQueue.Delete(0); end; finally Unlock; end; end; destructor TGSemaphoreImpl.Destroy; begin FHash.Free; FQueue.Free; FAcqQueue.Free; FLock.Free; inherited; end; procedure TGSemaphoreImpl.Enqueue(const Ctx: NativeUInt); begin Lock; try FQueue.Add(Pointer(Ctx)) finally Unlock; end; end; function TGSemaphoreImpl.GetCurContext: NativeUInt; begin if Greenlets.GetCurrent = nil then Result := NativeUInt(GetCurrentHub) else Result := TRawGreenletImpl(Greenlets.GetCurrent).GetUID; end; function TGSemaphoreImpl.Limit: LongWord; begin Result := FLimit end; procedure TGSemaphoreImpl.Lock; begin FLock.Acquire; end; procedure TGSemaphoreImpl.Release; var Ctx: NativeUInt; begin Lock; try if ReleaseCtx(GetCurContext) then begin Dec(FValue); if (FValue < FLimit) and Dequeue(Ctx) then begin FAcqQueue.Add(Pointer(Ctx)); FHash[Ctx].Notify.SetEvent; end; end; finally Unlock; end; end; function TGSemaphoreImpl.ReleaseCtx(const Ctx: NativeUint): Boolean; var Descr: TDescr; begin Result := False; Lock; try if FHash.ContainsKey(Ctx) then begin Descr := FHash[Ctx]; Descr.Recursion := Descr.Recursion - 1; if Descr.Recursion = 0 then begin Descr.Free; FHash.Remove(Ctx); while FQueue.IndexOf(Pointer(Ctx)) <> -1 do FQueue.Delete(FQueue.IndexOf(Pointer(Ctx))); end; Result := True; end; finally Unlock; end; end; procedure TGSemaphoreImpl.Unlock; begin FLock.Release; end; function TGSemaphoreImpl.Value: LongWord; begin Result := FValue end; { TGSemaphoreImpl.TDescr } constructor TGSemaphoreImpl.TDescr.Create; begin FNotify := TGevent.Create; end; destructor TGSemaphoreImpl.TDescr.Destroy; begin FNotify.Free; inherited; end; { TGMutexImpl } procedure TGMutexImpl.Acquire; begin FSem.Acquire end; constructor TGMutexImpl.Create; begin FSem := TGSemaphoreImpl.Create(1); end; procedure TGMutexImpl.Release; begin FSem.Release end; { TGQueueImpl<T> } procedure TGQueueImpl<T>.Clear; var I: Integer; Val: T; begin FLock.Acquire; try for I := 0 to FItems.Count-1 do begin Val := FItems[I]; TFinalizer<T>.Fin(Val); end; FItems.Clear; finally FLock.Release; end; end; function TGQueueImpl<T>.Count: Integer; begin FLock.Acquire; try Result := FItems.Count; finally FLock.Release end; end; constructor TGQueueImpl<T>.Create(MaxCount: LongWord); begin FItems := TItems.Create; FLock := TCriticalSection.Create; FCanDequeue := TGCondVariableImpl.Create(FLock); FCanEnqueue := TGCondVariableImpl.Create(FLock); FOnEnqueue := TGEvent.Create(True, True); TGeventPImpl(FOnEnqueue)._AddRef; FOnDequeue := TGEvent.Create(True, False); TGeventPImpl(FOnDequeue)._AddRef; if MaxCount = 0 then FMaxCount := INFINITE else FMaxCount := MaxCount; end; procedure TGQueueImpl<T>.Dequeue(out A: T); var OK: Boolean; ti: PTypeInfo; begin FOnDequeue.SetEvent; repeat FLock.Acquire; // Comment: из-за вызова Cond.Wait(FLock) // можно получить состояние полупредиката если в A := FItems[0]; FItems.Delete(0); // вылетит исключение, но лучшего способа для сохранения // целостности состояния не нашел OK := FItems.Count > 0; if OK then begin A := FItems[0]; FItems.Delete(0); RefreshGEvents; FLock.Release; end else begin FCanDequeue.Wait(FLock); end; until OK; FCanEnqueue.Signal; end; destructor TGQueueImpl<T>.Destroy; begin Clear; FItems.Free; FLock.Free; TGeventPImpl(FOnEnqueue)._Release; TGeventPImpl(FOnDequeue)._Release; inherited; end; procedure TGQueueImpl<T>.Enqueue(A: T); var OK: Boolean; begin // Писать может кто угодно - и сопрограмма и нитка repeat FLock.Acquire; OK := LongWord(FItems.Count) < FMaxCount; if OK then begin FItems.Add(A); RefreshGEvents; FLock.Release; end else begin FCanEnqueue.Wait(FLock); end; until OK; FCanDequeue.Signal; end; procedure TGQueueImpl<T>.RefreshGEvents; begin FLock.Acquire; try if FItems.Count > 0 then FOnDequeue.SetEvent else FOnDequeue.ResetEvent; if LongWord(FItems.Count) < FMaxCount then FOnEnqueue.SetEvent else FOnEnqueue.ResetEvent finally FLock.Release; end; end; { TFutureImpl<RESULT, ERROR> } constructor TFutureImpl<RESULT, ERROR>.Create; begin FOnFullFilled := TGevent.Create(True); TGeventPImpl(FOnFullFilled)._AddRef; FOnRejected := TGevent.Create(True); TGeventPImpl(FOnRejected)._AddRef; FResult := FDefValue; end; destructor TFutureImpl<RESULT, ERROR>.Destroy; begin TGeventPImpl(FOnFullFilled)._Release; TGeventPImpl(FOnRejected)._Release; inherited; end; function TFutureImpl<RESULT, ERROR>.GetErrorCode: ERROR; begin Result := FErrorCode end; function TFutureImpl<RESULT, ERROR>.GetErrorStr: string; begin Result := FErrorStr end; function TFutureImpl<RESULT, ERROR>.GetResult: RESULT; begin Result := FResult end; function TFutureImpl<RESULT, ERROR>.OnRejected: TGevent; begin Result := FOnRejected; end; function TFutureImpl<RESULT, ERROR>.OnFullFilled: TGevent; begin Result := FOnFullFilled end; { TPromiseImpl<T> } constructor TPromiseImpl<RESULT, ERROR>.Create(Future: TFutureImpl<RESULT, ERROR>); begin FFuture := Future; FFuture._AddRef; FActive := True; end; destructor TPromiseImpl<RESULT, ERROR>.Destroy; begin FFuture._Release; inherited; end; procedure TPromiseImpl<RESULT, ERROR>.SetErrorCode(Value: ERROR; const ErrorStr: string); begin if not FActive then Exit; FActive := False; FFuture.FErrorCode := Value; FFuture.FOnRejected.SetEvent; FFuture.FErrorStr := ErrorStr; end; procedure TPromiseImpl<RESULT, ERROR>.SetResult(const A: RESULT); begin if not FActive then Exit; FActive := False; FFuture.FResult := A; FFuture.FOnFullFilled.SetEvent; end; { TCollectionImpl<T> } procedure TCollectionImpl<T>.Append(const A: T; const IgnoreDuplicates: Boolean); var Succ: Boolean; begin if IgnoreDuplicates then Succ := not FList.Contains(A) else Succ := True; if Succ then FList.Add(A); end; procedure TCollectionImpl<T>.Append(const Other: ICollection<T>; const IgnoreDuplicates: Boolean); var I: T; begin for I in Other do Self.Append(I, IgnoreDuplicates) end; procedure TCollectionImpl<T>.Clear; begin FList.Clear; end; function TCollectionImpl<T>.Copy: ICollection<T>; begin Result := TCollectionImpl<T>.Create; Result.Append(Self, True); end; function TCollectionImpl<T>.Count: Integer; begin Result := FList.Count end; constructor TCollectionImpl<T>.Create; begin FList := TList<T>.Create end; destructor TCollectionImpl<T>.Destroy; begin FList.Free; inherited; end; function TCollectionImpl<T>.Get(Index: Integer): T; begin Result := FList[Index] end; function TCollectionImpl<T>.GetEnumerator: GInterfaces.TEnumerator<T>; begin Result := TEnumerator<T>.Create(Self) end; procedure TCollectionImpl<T>.Remove(const A: T); begin if FList.Contains(A) then FList.Remove(A); end; { TCollectionImpl<T>.TEnumerator<T> } constructor TCollectionImpl<T>.TEnumerator<Y>.Create( Collection: TCollectionImpl<Y>); begin FCollection := Collection; FCurPos := -1; end; function TCollectionImpl<T>.TEnumerator<Y>.GetCurrent: Y; begin Result := FCollection.FList[FCurPos]; end; function TCollectionImpl<T>.TEnumerator<Y>.MoveNext: Boolean; begin Result := (FCurPos + 1) < FCollection.FList.Count; if Result then Inc(FCurPos) end; procedure TCollectionImpl<T>.TEnumerator<Y>.Reset; begin FCurPos := -1; end; { TCaseImpl } destructor TCaseImpl.Destroy; begin if Assigned(FOnSuccess) then TGeventPImpl(FOnSuccess)._Release; if Assigned(FOnError) then TGeventPImpl(FOnError)._Release; inherited; end; function TCaseImpl.GetErrorHolder: IErrorHolder<TPendingError>; begin Result := FErrorHolder end; function TCaseImpl.GetOnError: TGevent; begin Result := FOnError end; function TCaseImpl.GetOnSuccess: TGevent; begin Result := FOnSuccess end; function TCaseImpl.GetOperation: TIOOperation; begin Result := FIOOperation; end; function TCaseImpl.GetWriteValueExists: Boolean; begin Result := FWriteValueExists end; procedure TCaseImpl.SetErrorHolder(Value: IErrorHolder<TPendingError>); begin FErrorHolder := Value end; procedure TCaseImpl.SetOnError(Value: TGevent); begin if Value <> FOnError then begin if Assigned(FOnError) then TGeventPImpl(FOnError)._Release; FOnError := Value; if Assigned(FOnError) then TGeventPImpl(FOnError)._AddRef; end; end; procedure TCaseImpl.SetOnSuccess(Value: TGevent); begin if Value <> FOnSuccess then begin if Assigned(FOnSuccess) then TGeventPImpl(FOnSuccess)._Release; FOnSuccess := Value; if Assigned(FOnSuccess) then TGeventPImpl(FOnSuccess)._AddRef; end; end; procedure TCaseImpl.SetOperation(const Value: TIOOperation); begin if Value = ioNotSet then raise EArgumentException.Create('set io operation'); FIOOperation := Value end; procedure TCaseImpl.SetWriteValueExists(const Value: Boolean); begin FWriteValueExists := Value end; end.
{$mode objfpc} {$m+} program Queue; const MAX_SIZE = 5; type ArrayQueue = class private arr : array[0..MAX_SIZE] of integer; first : 0..MAX_SIZE; last : 0..MAX_SIZE; count : 0..MAX_SIZE; public constructor create(); procedure pushLeft(i : integer); procedure pushRight(i : integer); function popLeft() : integer; function popRight() : integer; end; Node = record val : integer; prev : ^Node; next : ^Node; end; LinkedListQueue = class private first : ^Node; last : ^Node; public function popLeft(): integer; function popRight(): integer; procedure pushRight(i : integer); procedure pushLeft(i : integer); end; constructor ArrayQueue.Create(); begin first := 0; last := MAX_SIZE; count := 0; end; procedure ArrayQueue.pushLeft(i : integer); begin if count < MAX_SIZE then begin if first -1 < 0 then first := MAX_SIZE else first := first - 1; writeln('pushing ', i); arr[first] := i; count := count + 1; end else writeln('queue is full'); end; procedure ArrayQueue.pushRight(i : integer); begin if count < MAX_SIZE then begin writeln('pushing ', i); count := count + 1; last := (last + 1) mod MAX_SIZE; arr[last] := i; end else writeln('queue is full'); end; function ArrayQueue.popLeft() : integer; begin if count <= 0 then begin popLeft := -1; writeln('nothing left in queue'); end else begin count := count - 1; writeln('poping ', arr[first]); popLeft := arr[first]; arr[first] := 0; first := (first + 1) mod MAX_SIZE; end; end; function ArrayQueue.popRight() : integer; begin if count <= 0 then begin popRight := -1; writeln('nothing left in queue'); end else begin count := count - 1; writeln('poping ', arr[last]); popRight := arr[last]; arr[last] := 0; if last -1 < 0 then last := MAX_SIZE else last := last - 1; end; end; function LinkedListQueue.popLeft() : integer; begin if first <> nil then begin writeln('poping ', first^.val); popLeft := first^.val; first := first^.next; end else begin popLeft := -1; writeln('nothing left in queue'); end; end; function LinkedListQueue.popRight() : integer; begin if last <> nil then begin writeln('poping ', last^.val); popRight := last^.val; last := last^.prev; end else begin popRight := -1; writeln('nothing left in queue'); end; end; procedure LinkedListQueue.pushLeft(i : integer); var A : ^Node; begin writeln('pushing ', i); new(A); A^.val := i; if first = nil then last := A else begin A^.next := first; first^.prev := A; first := A; end; first := A end; procedure LinkedListQueue.pushRight(i : integer); var A : ^Node; begin writeln('pushing ', i); new(A); A^.val := i; if first = nil then first := A else begin last^.next := A; A^.prev := last; end; last := A; end; var Q : ArrayQueue; L : LinkedListQueue; begin writeln('--ArrayQueue--'); Q := ArrayQueue.Create(); Q.pushLeft(1); Q.pushLeft(2); Q.pushLeft(3); Q.pushLeft(4); Q.popLeft(); Q.popLeft(); Q.popRight(); Q.popRight(); Q.pushRight(1); Q.pushRight(2); Q.pushRight(3); Q.pushRight(4); Q.popLeft(); Q.popLeft(); Q.popRight(); Q.popRight(); writeln('--LinkedListQueue--'); L := LinkedListQueue.Create(); L.pushLeft(1); L.pushLeft(2); L.pushLeft(3); L.pushLeft(4); L.popLeft(); L.popLeft(); L.popRight(); L.popRight(); Q.pushRight(1); Q.pushRight(2); Q.pushRight(3); Q.pushRight(4); Q.popLeft(); Q.popLeft(); Q.popRight(); Q.popRight(); end.
unit FinInfoDetail; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, Vcl.StdCtrls, Vcl.Mask, RzEdit, RzDBEdit, Vcl.DBCtrls, RzDBCmbo, RzButton, RzTabs, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, DB; type TfrmFinInfoDetail = class(TfrmBasePopupDetail) dbluCompany: TRzDBLookupComboBox; edMonthly: TRzDBNumericEdit; edBalance: TRzDBNumericEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } protected procedure Save; override; procedure Cancel; override; procedure BindToObject; override; function ValidEntry: boolean; override; end; var frmFinInfoDetail: TfrmFinInfoDetail; implementation {$R *.dfm} uses LoanData, LoansAuxData, FormsUtil, Loan, FinInfo, IFinanceDialogs; procedure TfrmFinInfoDetail.FormCreate(Sender: TObject); begin inherited; OpenDropdownDataSources(tsDetail); end; procedure TfrmFinInfoDetail.FormShow(Sender: TObject); begin inherited; // disable company on editing dbluCompany.Enabled := dbluCompany.DataSource.DataSet.State = dsInsert; end; procedure TfrmFinInfoDetail.Save; var compId, compName, balance, monthly: string; begin with dmLoan.dstFinInfo do begin if State in [dsInsert,dsEdit] then Post; compId := FieldByName('comp_id').AsString; compName := dbluCompany.Text; balance := edBalance.Text; monthly := edMonthly.Text; ln.AddFinancialInfo(TFinInfo.Create(compId,compName,monthly,balance),true); end; end; procedure TfrmFinInfoDetail.BindToObject; begin inherited; end; procedure TfrmFinInfoDetail.Cancel; begin with dmLoan.dstFinInfo do if State in [dsInsert,dsEdit] then Cancel; end; function TfrmFinInfoDetail.ValidEntry: boolean; var error: string; begin with dmLoan.dstFinInfo do begin if Trim(dbluCompany.Text) = '' then error := 'Please select a company.' else if Trim(edMonthly.Text) = '' then error := 'Please enter monthly due.' else if Trim(edBalance.Text) = '' then error := 'Please enter balance.' else if (State = dsInsert) and (ln.FinancialInfoExists(dbluCompany.GetKeyValue)) then error := 'Financial information already exists.'; end; Result := error = ''; if not Result then ShowErrorBox(error); end; end.
{------------------------------------------------------------------------------- PROGRAM-NAME : 사우회 신규회원 추출/갱신 SYSTEM-NAME : 종합인사정보시스템 SUBSYSTEM-NAME : 복리후생(사우회) PROGRAMMER : 차정훈 VERSION : 1.00 DATE : 1997.10.31 UPDATE CONTENTS 1.00 97.10.31 차정훈 신규프로그램개발 상세처리명세서 -------------------------------------------------------------------------------} unit Psa10101; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Mask, numedit, DBClient, Db, quickrpt, qrprntr, DBTables, MemDS, DBAccess, Ora, Pass, Func; type TFpsa10101 = class(TForm) Panel19: TPanel; Shape7: TShape; Phelpmsg: TPanel; Panel8: TPanel; Lempno: TLabel; Lsysdate: TLabel; Panel9: TPanel; BBRun: TBitBtn; BBclose: TBitBtn; Panel11: TPanel; Panel12: TPanel; Panel13: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Panel14: TPanel; Panel15: TPanel; CBUpdate: TCheckBox; CBprint: TCheckBox; Panel1: TPanel; RBmoniter: TRadioButton; RBprinter: TRadioButton; Bevel1: TBevel; Bevel2: TBevel; PrintDialog1: TPrintDialog; SetDateOf: TPanel; OraQuery1: TOraQuery; procedure FormCreate(Sender: TObject); procedure BBcloseClick(Sender: TObject); procedure CBUpdateClick(Sender: TObject); procedure CBprintClick(Sender: TObject); procedure BBRunClick(Sender: TObject); procedure RBprinterClick(Sender: TObject); procedure RBmoniterClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } StartUp : Boolean; GSempno, GSkorname, GSpass, GSgrade, userid, word : String; SetDateW, SetToday, SelectPrint : String; procedure QueryOfComm(Parameter : String); end; var Fpsa10101: TFpsa10101; CodeCodeString: TStringList; CodeDataString: TStringList; sqlstr : WideString; implementation uses Psa10102; //InsaDll, {$R *.DFM} procedure TFpsa10101.FormCreate(Sender: TObject); begin Phelpmsg.Caption := ' 초기화 설정중입니다 잠시만 기다려 주세요.'; //SB_Help.Panels[1].Text := Application.ProcessMessages; OraConnect; Lempno.Caption := Pkorname + '(' + Pempno+')'; Lsysdate.Caption := fn_GetDateStr; SetToday := Copy(Fn_GetDateTimeStr, 1, 8); Pgrade := copy(Pgrade,3,1); end; procedure TFpsa10101.FormShow(Sender: TObject); var qq : TOraQuery; i : Integer; begin qq := TOraQuery.Create(nil); qq.Session := Ora_Session; try with qq do begin Close; SQL.Clear; SQL.Add('select max(substr(writetime,1,8)) d'); SQL.Add(' from pscman '); SQL.Add(' where retdate is null '); Open; SetDateW := Fields[0].AsString; end; finally qq.Free; end; if SetDateW = '' then SetDateOf.Caption := ' 년 월 일' else begin SetDateOf.Caption := Copy(SetDateW, 1, 4) + '년'; if Length(Trim(Copy(SetDateW, 5, 2))) = 1 then SetDateOf.Caption := SetDateOf.Caption + '0' + Trim(Copy(SetDateW, 5, 2)) + '월' else SetDateOf.Caption := SetDateOf.Caption + Copy(SetDateW, 5, 2) + '월'; if Length(Trim(Copy(SetDateW, 7, 2))) = 1 then SetDateOf.Caption := SetDateOf.Caption + '0' + Trim(Copy(SetDateW, 7, 2)) + '일' else SetDateOf.Caption := SetDateOf.Caption + Copy(SetDateW, 7, 2) + '일'; end; SelectPrint := '0'; Phelpmsg.Caption := ' 신규회원 추출/갱신작업을 하세요.'; RBmoniter.Enabled := False; RBprinter.Enabled := False; end; procedure TFpsa10101.BBcloseClick(Sender: TObject); begin CodeCodeString.Free; CodeDataString.Free; Close; end; procedure TFpsa10101.CBUpdateClick(Sender: TObject); begin if CBprint.Checked then begin RBmoniter.Enabled := True; RBprinter.Enabled := True; end else begin RBmoniter.Enabled := False; RBprinter.Enabled := False; end; end; procedure TFpsa10101.CBprintClick(Sender: TObject); begin CBUpdateClick(Sender); end; procedure TFpsa10101.BBRunClick(Sender: TObject); var StringOfCode : String; qq : TOraQuery; begin with PrintDialog1 do begin Copies := 0; FromPage := 0; MinPage := 0; PrintRange := prAllPages; end; if (not CBupdate.Checked) and (not CBprint.Checked) then begin MessageBeep(0); Phelpmsg.Caption := ' 작업선택을 하세요.'; Exit; end; if CBupdate.Checked then begin Phelpmsg.Caption := ' 신규 사우회원 추출/갱신 작업중입니다.'; Application.ProcessMessages; qq := TOraQuery.Create(nil); qq.Session := Ora_Session; try with qq do begin Close; SQL.Clear; SQL.Add('insert into pscman '); SQL.Add(' (empno, korname, begindate, '); SQL.Add(' prodate, writeman, writetime ) '); SQL.Add('select empno, korname, empdate, '); SQL.Add(' to_char(sysdate,''yyyymmdd''), '); SQL.Add(' :Pempno, '); SQL.Add(' to_char(sysdate,''yyyymmddhh24missd'') '); SQL.Add(' from pimpmas '); SQL.Add(' where empno not like ''Y''||''%'' '); SQL.Add(' and empno not like ''I''||''%'' '); //2007.06.20 I사번 추출 제외 추가/// SQL.Add(' and payra <> ''A11'' '); // 고문제외 SQL.Add(' and empno not in (select empno from pscman) '); ParamByName('Pempno').AsString := Pempno; ExecSql; //// 인사 테이블에서 퇴사일을 가져온다 /////////////////////////////// /// /나중에 배당프로그램에서 처리하므로 다음번에 업데이트는 제외된다./ SQL.Clear; SQL.Add('update pscman a '); SQL.Add(' set retdate = (select b.retdate '); SQL.Add(' from pimpmas b '); SQL.Add(' where a.empno = b.empno), '); SQL.Add(' writeman = :Pempno, '); SQL.Add(' writetime = to_char(sysdate,''yyyymmddhh24missd'') '); SQL.Add(' where retdate is null '); SQL.Add(' and empno in (select empno from pimpmas where retdate is not null)'); ParamByName('Pempno').AsString := Pempno; ExecSql; end; finally qq.Free; end; if CBprint.Checked then begin Phelpmsg.Caption := ' 갱신된 자료 출력작업중입니다.'; Application.ProcessMessages; QueryOfComm(SetToday); if RBmoniter.Checked then begin Fpsa10102.QuickReport1.Preview; Phelpmsg.Caption := ' 출력작업이 완료되었습니다.'; end; end else if RBprinter.Checked then begin if PrintDialog1.Execute then begin Fpsa10102.QuickReport1.Print; Phelpmsg.Caption := ' 출력작업이 완료되었습니다.'; end else Phelpmsg.Caption := ' 출력작업이 취소되었습니다.'; QRPrinter.Cleanup; end else Phelpmsg.Caption := ' 신규 사우회원 추출/갱신 완료되었습니다.'; end else if CBprint.Checked then begin Phelpmsg.Caption := ' 추출/출력 작업중입니다.'; Application.ProcessMessages; QueryOfComm(SetToday); if RBmoniter.Checked then begin Fpsa10102.QuickReport1.Preview; Phelpmsg.Caption := ' 출력작업이 완료되었습니다.'; end else if RBprinter.Checked then begin if PrintDialog1.Execute then begin Fpsa10102.QuickReport1.Print; Phelpmsg.Caption := ' 출력작업이 완료되었습니다.'; end else Phelpmsg.Caption := ' 출력작업이 취소되었습니다.'; QRPrinter.Cleanup; end; end; end; procedure TFpsa10101.QueryOfComm(Parameter : String); begin OraQuery1.Session := Ora_Session; with OraQuery1 do begin Close; SQL.Clear; Sql.Add('select a.empno, a.korname, '); Sql.Add(' a.begindate, nvl(a.retdate,'' '') retdate, '); Sql.Add(' b.orgnum, b.deptcode, b.payra, '); Sql.Add(' (select deptabbr from pycdept '); Sql.Add(' where b.orgnum = orgnum '); Sql.Add(' and b.deptcode = deptcode) deptabbr '); Sql.Add(' from pscman a, pimpmas b '); Sql.Add(' where a.empno = b.empno '); Sql.Add(' and (a.prodate = :pDate or substr(a.writetime,1,8) = :Pdate)'); Sql.Add(' order by retdate, empno, begindate '); ParamByName('pDate').AsString := parameter; Open; end; end; procedure TFpsa10101.RBprinterClick(Sender: TObject); begin SelectPrint := '1'; end; procedure TFpsa10101.RBmoniterClick(Sender: TObject); begin SelectPrint := '0'; end; end.
{******************************************} { } { vtk GridReport library } { } { Copyright (c) 2003 by vtkTools } { } {******************************************} {Contains @link(TvgrControlBar) and @link(TvgrControlBarManager) - components for managing the layout of toolbar components. TvgrControlBar manages the layout of toolbar components. TvgrControlBarManager provides a mechanism to store information about toolbars layout to a TvgrIniStorage or ini file. See also: vgr_FontComboBox,vgr_ColorButton,vgr_Label } unit vgr_ControlBar; {$I vtk.inc} interface uses commctrl, messages, SysUtils, Windows, Classes, forms, Controls, Graphics, comctrls, math, vgr_IniStorage; type TvgrCBBand = class; TvgrControlBar = class; ///////////////////////////////////////////////// // // TvgrCBRow // ///////////////////////////////////////////////// { Internal class, used to store information about row in control bar. Each row consists from several bands. Each band linked to child control of TvgrControlBar. } TvgrCBRow = class(TObject) private FControlBar: TvgrControlBar; FBands: TList; FLoadedMin: Integer; function GetBand(I: integer) : TvgrCBBand; function GetMin: Integer; function GetMax: Integer; function GetSize: Integer; function GetVisible: Boolean; function GetBandsCount: Integer; function GetVisibleBandsCount: Integer; procedure AddBand(Band: TvgrCBBand); procedure DeleteBand(Band: TvgrCBBand); procedure AlignBands; property ControlBar: TvgrControlBar read FControlBar; property Visible: Boolean read GetVisible; property Min: Integer read GetMin; property Max: Integer read GetMax; property Size: Integer read GetSize; property Bands[I: integer]: TvgrCBBand read GetBand; property BandsCount: Integer read GetBandsCount; property VisibleBandsCount: Integer read GetVisibleBandsCount; public {Creates a instance of TvgrCBRow class.} constructor Create(AControlBar: TvgrControlbar); {Destroys an instance of TvgrCBRow. Do not call Destroy directly in an application. Instead, call Free.} destructor Destroy; override; end; ///////////////////////////////////////////////// // // TvgrCBBand // ///////////////////////////////////////////////// { Internal class, used to store information about child control in TvgrControlBar. Each TvgrCBBand object linked to child control of TvgrControlBar. } TvgrCBBand = class(TObject) private FControl: TControl; FMin: Integer; FHeight: Integer; FWidth: Integer; FRow: TvgrCBRow; FVisible: Boolean; FLoadedControlName: string; FLoadedVisible: Boolean; procedure SetRow(Value: TvgrCBRow); procedure SetVisible(Value: Boolean); procedure SetMin(Value: Integer); procedure SetWidth(Value: Integer); procedure SetHeight(Value: Integer); function GetRect: TRect; function GetSize: Integer; procedure DoAlignRowBands; property Row: TvgrCBRow read FRow write SetRow; property Control: TControl read FControl write FControl; property Min: Integer read FMin write SetMin; property Width: Integer read FWidth write SetWidth; property Height: Integer read FHeight write SetHeight; property Visible: Boolean read FVisible write SetVisible; property Rect: TRect read GetRect; property Size: Integer read GetSize; public {Creates a instance of class.} constructor Create(ARow: TvgrCBRow; AControl: TControl; AWidth: Integer; AHeight: Integer; AMin: Integer); overload; {Creates a instance of class.} constructor Create; overload; end; { Position of the TvgrControlBar object within parent control. Syntax: TvgrControlBarSide = (prcbsLeft, prcbsTop, prcbsRight, prcbsBottom); Items: prcbsLeft - Left prcbsTop - Top prcbsRight - Right prcbsBottom - Bottom } TvgrControlBarSide = (prcbsLeft, prcbsTop, prcbsRight, prcbsBottom); ///////////////////////////////////////////////// // // TvgrControlBar // ///////////////////////////////////////////////// { TvgrControlBar manages the layout of toolbar components. Use TvgrControlBar as a docking site for toolbar components. Control bars contain child controls (usually TToolBar objects) that can be moved and resized independently. } TvgrControlBar = class(TCustomControl) private FUpdateCount: Integer; FRows: TList; FDownBand: TvgrCBBand; FSide: TvgrControlBarSide; FDownMousePos: TPoint; FFirstCallAfterLoad: Boolean; procedure SetSide(Value : TvgrControlBarSide); function GetRow(i : integer) : TvgrCBRow; function GetRowsCount : integer; function GetSize : integer; procedure SetSize(Value : integer); procedure CMDesignHitTest(var Msg : TCMDesignHitTest); message CM_DESIGNHITTEST; procedure CMControlListChange(var Msg : TCMControlListChange); message CM_CONTROLLISTCHANGE; function GetEnableUpdate: Boolean; protected procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; procedure ClearRows; function IsControlVisible(Control: TControl) : boolean; function FindControlBand(Control: TControl) : TvgrCBBand; function IsVertical: boolean; function GetControlRowCoord(Control: TControl) : integer; function GetControlBandCoord(Control: TControl) : integer; function FindRow(RowCoord: Integer): TvgrCBRow; function GetLastRowMax: Integer; procedure DeleteRow(Row: TvgrCBRow); procedure DeleteControl(Control: TControl); procedure GetBandSizes(ARow: TvgrCBRow; AControl: TControl; var AWidth, AHeight: Integer); procedure InternalAlignControls; function IsAllControlsCreated: Boolean; procedure AlignControls(Control: TControl; var ARect: TRect); override; procedure UpdateSize; procedure GetPointInfoAt(X,Y : integer; var band : TvgrCBBand); 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 PositionDockRect(DragDockObject: TDragDockObject); override; procedure SetControlVisible(Control: TControl; Visible : boolean); procedure BeginUpdate; procedure EndUpdate; procedure SetupControlProperties(AControl: TControl); procedure NotifyDesigner; procedure InternalBuildAfterLoad; procedure InternalCalculateBandsAfterLoad; procedure DefineProperties(Filer: TFiler); override; procedure ReadLayout(Stream: TStream); procedure WriteLayout(Stream: TStream); procedure Notification(AComponent: TComponent; AOperation: TOperation); override; procedure Loaded; override; property EnableUpdate: Boolean read GetEnableUpdate; property Rows[I: Integer] : TvgrCBRow read GetRow; property RowsCount: Integer read GetRowsCount; public { Calling Create constructs and initializes an instance of TvgrControlBar.} constructor Create(AOwner: TComponent); override; {Destroys an instance of TvgrControlBar. Do not call Destroy directly in an application. Instead, call Free.} destructor Destroy; override; { If Position equals prcbsLeft or prcbsRight - Size property returns and sets Width of TvgrControlBar object. If Position property equals prcbsTop or prcbsBottom - Size property returns and sets Height of TvgrControlBar object. } property Size: integer read GetSize write SetSize; published { Specifies place of the TvgrControlBar object within parent control. } property Side: TvgrControlBarSide read FSide write SetSide default prcbsTop; property Anchors; property Color; property Enabled; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; { TvgrOnGetToolbarsList is the type for event handlers that supply list of toolbars to a TvgrControlBarManager. Syntax: TvgrOnGetToolbarsList = procedure(Sender : TObject; L : TList) of object; Parameters: Sender is the TvgrControlBarManager object L is a list that you can fill with toolbars, which should managed by TvgrControlBarManager object. } TvgrOnGetToolbarsList = procedure(Sender : TObject; L : TList) of object; ///////////////////////////////////////////////// // // TvgrControlBarManager // ///////////////////////////////////////////////// { TvgrControlBarManager provides a mechanism to store information about toolbars layout to a TvgrIniStorage or ini file. Use LeftCB, TopCB, RightCB and BottomCB properties to specify TvgrControlBar objects which aligned to appropriate sides of the form. } TvgrControlBarManager = class(TComponent) private FLeftCB : TvgrControlBar; FTopCB : TvgrControlBar; FRightCB : TvgrControlBar; FBottomCB : TvgrControlBar; FOnGetToolbarsList : TvgrOnGetToolbarsList; FToolbarsList : TList; FOldOnFormShow : TNotifyEvent; FRestoredToolbars : TList; procedure GetToolbarsList; function GetToolbar(i : integer) : TToolbar; function GetToolbarsCount : integer; procedure OnFormShow(Sender : TObject); protected property Toolbars[i : integer] : TToolBar read GetToolbar; property ToolbarsCount : integer read GetToolbarsCount; procedure WriteToolbar(Toolbar: TToolbar; AStorage: TvgrIniStorage; const SectionName : string); procedure WriteControlBar(AControlBar: TvgrControlBar; AStorage: TvgrIniStorage; const SectionName: string); procedure ReadToolbar(Toolbar : TToolbar; AStorage: TvgrIniStorage; const SectionName: string); procedure ReadControlBar(AControlBar: TvgrControlBar; AStorage: TvgrIniStorage; const SectionName: string); procedure Notification(AComponent : TComponent; AOperation : TOperation); override; procedure Loaded; override; public {Calling Create constructs and initializes an instance of TvgrControlBarManager.} constructor Create(AOwner : TComponent); override; {Destroys an instance of TvgrControlBarManager. Do not call Destroy directly in an application. Instead, call Free. Free verifies that the object is not nil before it calls Destroy.} destructor Destroy; override; {Call this method to store information about toolbars layout to an ini file. You can call this method in any time, for example in TForm.OnClose event, or TForm.OnDestroy event. Parameters: AIniFileName is a full name of ini file SectionNamePrefix prefix which are added to a name of sections in ini file, created while writing. } procedure WriteToIni(const AIniFileName: string; const SectionNamePrefix : string); { Call this method to read information about toolbars layout from an ini file. You can call this method only then all toolbars and control bars on the form are created and has valid Handles, therefore you can`t use this method in TForm.OnCreate method, use TForm.OnShow or TForm.OnActivate events instead. Parameters: AIniFileName is a full name of ini file SectionNamePrefix prefix which are added to a name of sections in ini file. Example: procedure TForm1.FormShow(Sender: TObject); begin if not FSettingsRestored then begin ControlBarManager.ReadFromIni('c:\windows\gr.ini', 'ControlBarManager'); FSettingsRestored := True; end; end; } procedure ReadFromIni(const AIniFileName: string; const SectionNamePrefix : string); { Call this method to store information about toolbars layout to an TvgrIniStorage object. You can call this method in any time, for example in TForm.OnClose event, or TForm.OnDestroy event. Parameters: AStorage - TvgrIniStorage object SectionNamePrefix - prefix which are added to a name of sections in ini file, created while writing.} procedure WriteToStorage(AStorage: TvgrIniStorage; const SectionNamePrefix: string); { Call this method to read information about toolbars layout from an TvgrIniStorage object. You can call this method only then all toolbars and control bars on the form are created and has valid Handles, therefore you can`t use this method in TForm.OnCreate method, use TForm.OnShow or TForm.OnActivate events instead. Parameters: AStorage - TvgrIniStorage object SectionNamePrefix - prefix which are added to a name of sections in ini file. Example: procedure TForm1.FormShow(Sender: TObject); var AStorage: TvgrIniFileStorage; begin if not FSettingsRestored then begin AStorage := TvgrIniFileStorage.Create('c:\windows\prog.ini'); vgrControlBarManager1.ReadFromStorage(AStorage, 'Form1'); AStorage.Free; end; end;} procedure ReadFromStorage(AStorage: TvgrIniStorage; const SectionNamePrefix: string); { Call this method to hide or show toolbar, which are managed by TvgrControlBarManagerObject. Parameters: ToolBar - TToolBar object Visible - true shows toolbar, false hides. } procedure ShowHideToolBar(ToolBar: TToolBar; Visible: Boolean); published { Specify TvgrControlBar object which aligned to the left side of the form. } property LeftCB: TvgrControlBar read FLeftCB write FLeftCB; { Specify TvgrControlBar object which aligned to the top side of the form. } property TopCB: TvgrControlBar read FTopCB write FTopCB; { Specify TvgrControlBar object which aligned to the right side of the form. } property RightCB: TvgrControlBar read FRightCB write FRightCB; { Specify TvgrControlBar object which aligned to the bottom side of the form. } property BottomCB: TvgrControlBar read FBottomCB write FBottomCB; { Use this event to provide list of toolbars, which are manged by TvgrControlBarManager object. If this event handler not defined TvgrControlBarManager operates all toolbars on the form. } property OnGetToolbarsList: TvgrOnGetToolbarsList read FOnGetToolbarsList write FOnGetToolbarsList; end; implementation uses vgr_Functions; const CaptionOffs = 7; BorderOffs = 2; aAlignArray: Array [TvgrControlBarSide] of TAlign = (alLeft, alTop, alRight, alBottom); type ///////////////////////////////////////////////// // // TToolBarAccess // ///////////////////////////////////////////////// TToolBarAccess = class(TToolBar) end; ///////////////////////////////////////////////// // // TToolButtonAccess // ///////////////////////////////////////////////// TToolButtonAccess = class(TToolButton) end; ///////////////////////////////////////////////// // // TWinControlAccess // ///////////////////////////////////////////////// TWinControlAccess = class(TWinControl) end; ///////////////////////////////////////////////// // // TvgrCBBand // ///////////////////////////////////////////////// constructor TvgrCBBand.Create; begin inherited Create; end; constructor TvgrCBBand.Create(ARow: TvgrCBRow; AControl: TControl; AWidth: Integer; AHeight: Integer; AMin: Integer); begin Create; FVisible := True; FWidth := AWidth; FHeight := AHeight; FMin := AMin; FControl := AControl; Row := ARow; end; procedure TvgrCBBand.SetRow(Value : TvgrCBRow); begin if FRow <> Value then begin if FRow <> nil then FRow.DeleteBand(Self); FRow := Value; if FRow <> nil then FRow.AddBand(Self); end; end; procedure TvgrCBBand.DoAlignRowBands; begin if FRow<>nil then FRow.AlignBands; end; procedure TvgrCBBand.SetVisible(Value : boolean); begin FVisible := Value; DoAlignRowBands; end; procedure TvgrCBBand.SetMin(Value : integer); begin if FMin <> Value then begin FMin := Value; DoAlignRowBands; end; end; procedure TvgrCBBand.SetWidth(Value: Integer); begin if FWidth <> Value then begin FWidth := Value; DoAlignRowBands; end; end; procedure TvgrCBBand.SetHeight(Value: Integer); begin if FHeight <> Value then begin FHeight := Value; DoAlignRowBands; end; end; function TvgrCBBand.GetRect : TRect; begin if Row.ControlBar.IsVertical then Result := Classes.Rect(Row.Min, Min, Row.Max, Min + Height) else Result := Classes.Rect(Min, Row.Min, Min + Width, Row.Max); end; function TvgrCBBand.GetSize: Integer; begin if Row.ControlBar.IsVertical then Result := Height else Result := Width; end; ///////////////////////////////////////////////// // // TvgrCBRow // ///////////////////////////////////////////////// constructor TvgrCBRow.Create(AControlBar: TvgrControlBar); begin inherited Create; FControlBar := AControlBar; FBands := TList.Create; end; destructor TvgrCBRow.Destroy; begin FreeListItems(FBands); FBands.Free; inherited; end; function TvgrCBRow.GetBand(I: integer) : TvgrCBBand; begin Result := TvgrCBBand(FBands[I]); end; function TvgrCBRow.GetBandsCount : integer; begin Result := FBands.Count; end; function TvgrCBRow.GetVisibleBandsCount : integer; var I: integer; begin Result := 0; for I := 0 to BandsCount - 1 do if Bands[I].Visible then Inc(Result); end; function TvgrCBRow.GetVisible : boolean; var I: integer; begin for I := 0 to BandsCount - 1 do if Bands[I].Visible then begin Result := True; exit; end; Result := False; end; function TvgrCBRow.GetMin : integer; var I: integer; begin Result := 0; for I := 0 to ControlBar.RowsCount - 1 do if ControlBar.Rows[I] = Self then exit else Result := Result + ControlBar.Rows[I].Size; end; function TvgrCBRow.GetSize : integer; var I: integer; begin Result := 0; if ControlBar.IsVertical then begin for I := 0 to BandsCount - 1 do if Bands[I].Visible then if Bands[I].Width > Result then Result := Bands[I].Width; end else begin for I := 0 to BandsCount - 1 do if Bands[I].Visible then if Bands[I].Height > Result then Result := Bands[I].Height; end; end; function TvgrCBRow.GetMax : integer; begin Result := GetMin + GetSize; end; procedure TvgrCBRow.AddBand(Band : TvgrCBBand); begin FBands.Add(Band); AlignBands; end; procedure TvgrCBRow.DeleteBand(Band : TvgrCBBand); begin FBands.Remove(Band); if BandsCount = 0 then ControlBar.DeleteRow(Self) else AlignBands; end; function BandsSorTvgroc(it1,it2 : pointer) : integer; begin Result := TvgrCBBand(it1).Min - TvgrCBBand(it2).Min; end; procedure TvgrCBRow.AlignBands; var I: integer; PriorBand : TvgrCBBand; begin FBands.Sort(BandsSorTvgroc); PriorBand := nil; for I := 0 to BandsCount - 1 do if Bands[I].Visible then begin if PriorBand <> nil then Bands[I].FMin := PriorBand.Min + PriorBand.Size else Bands[I].FMin := math.Max(0, Bands[I].FMin); PriorBand := Bands[I]; end; end; ///////////////////////////////////////////////// // // TvgrControlBar // ///////////////////////////////////////////////// constructor TvgrControlBar.Create(AOwner : TComponent); begin inherited; {$IFDEF VGR_DEMO} ShowDemoWarning; {$ENDIF} ControlStyle := [csDesignInteractive, csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks, csOpaque]; FRows := TList.Create; DockSite := true; Side := prcbsTop; Size := 100; FFirstCallAfterLoad := True; end; destructor TvgrControlBar.Destroy; begin ClearRows; FRows.Free; inherited; end; procedure TvgrControlBar.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Layout', ReadLayout, WriteLayout, RowsCount > 0); end; procedure TvgrControlBar.ReadLayout(Stream: TStream); var I, J, N, K: Integer; ARow: TvgrCBRow; ABand: TvgrCBBand; begin FreeListItems(FRows); FRows.Clear; Stream.Read(N, 4); for I := 0 to N - 1 do begin ARow := TvgrCBRow.Create(Self); Stream.Read(ARow.FLoadedMin, 4); Stream.Read(K, 4); for J := 0 to K - 1 do begin ABand := TvgrCBBand.Create; ABand.FRow := ARow; ABand.FLoadedControlName := ReadString(Stream); ABand.FLoadedVisible := ReadBoolean(Stream); ARow.FBands.Add(ABand); end; FRows.Add(ARow); end; end; procedure TvgrControlBar.WriteLayout(Stream: TStream); var I, J, N: Integer; begin I := RowsCount; Stream.Write(I, 4); for I := 0 to RowsCount - 1 do begin N := Rows[I].Bands[0].Min; Stream.Write(N, 4); N := Rows[I].BandsCount; Stream.Write(N, 4); for J := 0 to N - 1 do begin WriteString(Stream, Rows[I].Bands[J].Control.Name); WriteBoolean(Stream, Rows[I].Bands[J].Visible); end; end; end; procedure TvgrControlBar.Notification(AComponent: TComponent; AOperation: TOperation); begin inherited; if (AComponent is TControl) and (AOperation = opRemove) then DeleteControl(TControl(AComponent)); end; procedure TvgrControlBar.Loaded; begin inherited; InternalBuildAfterLoad; if csDesigning in ComponentState then begin InternalCalculateBandsAfterLoad; InternalAlignControls; end end; procedure TvgrControlBar.InternalBuildAfterLoad; var I, J: Integer; AControl: TControl; ABand: TvgrCBBand; begin for I := 0 to RowsCount - 1 do begin for J := 0 to Rows[I].BandsCount - 1 do begin ABand := Rows[I].Bands[J]; AControl := TControl(Owner.FindComponent(ABand.FLoadedControlName)); if (AControl <> nil) and (AControl is TControl) then begin ABand.FControl := AControl; ABand.FVisible := ABand.FLoadedVisible; end; end; end; end; procedure TvgrControlBar.InternalCalculateBandsAfterLoad; var I, J, AMin, AWidth, AHeight: Integer; ABand: TvgrCBBand; begin for I := 0 to RowsCount - 1 do begin AMin := Rows[I].FLoadedMin; for J := 0 to Rows[I].BandsCount - 1 do begin ABand := Rows[I].Bands[J]; GetBandSizes(Rows[I], ABand.Control, AWidth, AHeight); ABand.FWidth := AWidth; ABand.FHeight := AHeight; ABand.FMin := AMin; if IsVertical then AMin := ABand.FMin + AHeight else AMin := ABand.FMin + AWidth; end; Rows[I].AlignBands; end; end; function TvgrControlBar.GetControlRowCoord(Control : TControl) : integer; begin if IsVertical then Result := Control.Left else Result := Control.Top; end; function TvgrControlBar.GetControlBandCoord(Control : TControl) : integer; begin if IsVertical then Result := Control.Top else Result := Control.Left; end; function TvgrControlBar.FindRow(RowCoord : integer) : TvgrCBRow; var i : integer; begin for i:=0 to RowsCount-1 do if Rows[i].Visible and (RowCoord>=Rows[i].Min) and (RowCoord<=Rows[i].Max) then begin Result := Rows[i]; exit; end; Result := nil; end; function TvgrControlBar.FindControlBand(Control :TControl) : TvgrCBBand; var I, J: integer; begin for I := 0 to RowsCount - 1 do for J := 0 to Rows[I].BandsCount - 1 do if Rows[I].Bands[J].Control = Control then begin Result := Rows[I].Bands[J]; exit; end; Result := nil; end; function TvgrControlBar.GetLastRowMax : integer; begin if RowsCount<=0 then Result := 0 else Result := Rows[RowsCount-1].Max; end; procedure TvgrControlBar.DeleteRow(Row : TvgrCBRow); begin FRows.Remove(Row); Row.Free; end; procedure TvgrControlBar.DeleteControl(Control: TControl); var Band: TvgrCBBand; begin Band := FindControlBand(Control); if band <> nil then begin band.Row := nil; band.Free; end; end; function TvgrControlBar.IsControlVisible(Control : TControl) : boolean; begin Result := (csDesigning in ComponentState) or Control.Visible; end; procedure TvgrControlBar.BeginUpdate; begin Inc(FUpdateCount); end; procedure TvgrControlBar.EndUpdate; begin Dec(FUpdateCount); end; procedure TvgrControlBar.SetupControlProperties(AControl: TControl); begin if AControl is TToolBar then with TToolBar(AControl) do begin DragKind := dkDock; DragMode := dmAutomatic; EdgeBorders := []; Flat := True; AutoSize := True; Align := alNone; end; end; function TvgrControlBar.GetEnableUpdate: Boolean; begin Result := FUpdateCount = 0; end; function WrapButtons(AToolBar: TToolBarAccess; AVertical: Boolean; var NewWidth, NewHeight: Integer): Boolean; var Index, NcX, NcY: Integer; WrapStates: TBits; procedure CalcSize(var CX, CY: Integer); var IsWrapped: Boolean; I, Tmp, X, Y, HeightChange: Integer; Control: TControl; begin CX := 0; CY := 0; X := AToolBar.Indent; Y := 0; for I := 0 to AToolBar.ButtonCount - 1 do begin Control := TControl(AToolBar.Buttons[I]); if (csDesigning in AToolBar.ComponentState) or Control.Visible then begin if (Control is TToolButton) and (I < AToolBar.ButtonCount - 1) then if WrapStates <> nil then IsWrapped := WrapStates[I] else IsWrapped := TToolButton(Control).Wrap else IsWrapped := False; if Control is TToolButton and (TToolButton(Control).Style in [tbsSeparator, tbsDivider]) then begin { Store the change in height, from the current row to the next row after wrapping, in HeightChange. THe IE4 version of comctl32 considers this height to be the width the last separator on the current row - prior versions of comctl32 consider this height to be 2/3 the width the last separator. } HeightChange := Control.Width; if (GetComCtlVersion < ComCtlVersionIE4) or not AToolBar.Flat and (GetComCtlVersion >= ComCtlVersionIE401) then HeightChange := HeightChange * 2 div 3; if IsWrapped and (I < AToolBar.ButtonCount - 1) then begin Tmp := Y + AToolBar.ButtonHeight + HeightChange; if Tmp > CY then CY := Tmp; end else begin Tmp := X + Control.Width; if Tmp > CX then CX := Tmp; end; if IsWrapped then Inc(Y, HeightChange); end else begin Tmp := X + Control.Width; if Tmp > CX then CX := Tmp; Tmp := Y + AToolBar.ButtonHeight; if Tmp > CY then CY := Tmp; end; if IsWrapped then begin X := AToolBar.Indent; Inc(Y, AToolBar.ButtonHeight); end else Inc(X, Control.Width); end; end; { Adjust for 2 pixel top margin when not flat style buttons } if (CY > 0) and not AToolBar.Flat then Inc(CY, 2); end; function WrapHorz(CX: Integer): Integer; var I, J, X: Integer; Control: TControl; Found: Boolean; begin Result := 1; X := AToolBar.Indent; I := 0; while I < AToolBar.ButtonCount do begin Control := TControl(AToolBar.Buttons[I]); if Control is TToolButton then WrapStates[I] := False; if (csDesigning in AToolBar.ComponentState) or Control.Visible then begin if (X + Control.Width > CX) and (not (Control is TToolButton) or not (TToolButton(Control).Style in [tbsDivider, tbsSeparator])) then begin Found := False; for J := I downto 0 do if TControl(AToolBar.Buttons[J]) is TToolButton then with TToolButton(AToolBar.Buttons[J]) do if ((csDesigning in ComponentState) or Visible) and (Style in [tbsSeparator, tbsDivider]) then begin if not WrapStates[J] then begin Found := True; I := J; X := AToolBar.Indent; WrapStates[J] := True; Inc(Result); end; Break; end; if not Found then begin for J := I - 1 downto 0 do if TControl(AToolBar.Buttons[J]) is TToolButton then with TToolButton(AToolBar.Buttons[J]) do if (csDesigning in ComponentState) or Visible then begin if not WrapStates[J] then begin Found := True; I := J; X := AToolBar.Indent; WrapStates[J] := True; Inc(Result); end; Break; end; if not Found then Inc(X, Control.Width); end; end else Inc(X, Control.Width); end; Inc(I); end; end; function InternalButtonCount: Integer; begin Result := AToolBar.Perform(TB_BUTTONCOUNT, 0, 0); end; begin Result := True; if AToolBar.HandleAllocated then begin Index := InternalButtonCount - 1; if (Index >= 0) or not (csDesigning in AToolBar.ComponentState) then begin WrapStates := TBits.Create; try NcX := AToolBar.Width - AToolBar.ClientWidth; NcY := AToolBar.Height - AToolBar.ClientHeight; WrapHorz(NewWidth); CalcSize(NewWidth, NewHeight); if AVertical then begin for Index := 0 to WrapStates.Size - 1 do if TControl(AToolBar.Buttons[Index]) is TToolButton then TToolButton(AToolBar.Buttons[Index]).Wrap := WrapStates[Index]; end; NewWidth := NewWidth + NcX; NewHeight := NewHeight + NcY; finally WrapStates.Free; end; end; end; end; procedure TvgrControlBar.GetBandSizes(ARow: TvgrCBRow; AControl: TControl; var AWidth, AHeight: Integer); var I, ASize, ATempWidth, ATempHeight: Integer; begin if AControl is TToolBar then begin if (csDesigning in ComponentState) and (TToolBar(AControl).ButtonCount = 0) then begin if IsVertical then begin AWidth := 30; AHeight := 100; end else begin AWidth := 100; AHeight := 30; end; end else begin ASize := 0; if (ARow <> nil) and IsVertical then begin for I := 0 to ARow.BandsCount - 1 do begin if (ARow.Bands[I].Control <> AControl) and (ARow.Bands[I].Control is TToolBar) then begin ATempWidth := 0; ATempHeight := MaxInt; WrapButtons(TToolBarAccess(ARow.Bands[I].Control), True, ATempWidth, ATempHeight); ATempWidth := ATempWidth - BorderOffs - BorderOffs; if ATempWidth > ASize then ASize := ATempWidth; end; end; end; if IsVertical then begin AWidth := ASize; AHeight := MaxInt; end else begin AWidth := MaxInt; AHeight := ASize; end; WrapButtons(TToolBarAccess(AControl), IsVertical, AWidth, AHeight); end; end else with AControl do begin AWidth := Width; AHeight := Height; end; if IsVertical then begin AWidth := AWidth + BorderOffs + BorderOffs; AHeight := AHeight + CaptionOffs + BorderOffs + BorderOffs; end else begin AWidth := AWidth + CaptionOffs + BorderOffs + BorderOffs; AHeight := AHeight + BorderOffs + BorderOffs; end; end; procedure TvgrControlBar.InternalAlignControls; var I, J : integer; AControl: TControl; begin BeginUpdate; try for I := 0 to RowsCount - 1 do if Rows[I].Visible then for J := 0 to Rows[I].BandsCount - 1 do if Rows[I].Bands[J].Visible then begin AControl := Rows[I].Bands[J].Control; if IsVertical then begin AControl.SetBounds(Rows[I].Min + BorderOffs, Rows[I].Bands[J].Min + BorderOffs + CaptionOffs, Rows[I].Size - BorderOffs - BorderOffs, Rows[I].Bands[J].Size - CaptionOffs - BorderOffs - BorderOffs); with Rows[I].Bands[J] do begin Width := Control.Width + BorderOffs + BorderOffs; Height := Control.Height + CaptionOffs + BorderOffs + BorderOffs; end; end else begin AControl.SetBounds(Rows[I].Bands[j].Min + CaptionOffs + BorderOffs, Rows[I].Min + BorderOffs, Rows[I].Bands[J].Size - CaptionOffs - BorderOffs - BorderOffs, Rows[I].Size - BorderOffs - BorderOffs); with Rows[I].Bands[J] do begin Width := Control.Width + CaptionOffs + BorderOffs + BorderOffs; Height := Control.Height + BorderOffs + BorderOffs; end; end; end; if not (csDesigning in ComponentState) then UpdateSize; Repaint; finally EndUpdate; end; end; function TvgrControlBar.IsAllControlsCreated: Boolean; var I, J: Integer; begin for I := 0 to RowsCount - 1 do for J := 0 to Rows[I].BandsCount - 1 do if (Rows[I].Bands[J].Control = nil) or ((Rows[I].Bands[J].Control is TWinControl) and not (TWinControlAccess(Rows[I].Bands[J].Control).HandleAllocated)) then begin Result := False; exit; end; Result := True; end; procedure TvgrControlBar.AlignControls(Control: TControl; var ARect: TRect); var I, AWidth, AHeight: integer; ABand: TvgrCBBand; ARow: TvgrCBRow; AControl: TControl; ANeedRepeat: Boolean; begin if EnableUpdate and not (csLoading in ComponentState) and IsAllControlsCreated then begin BeginUpdate; try if FFirstCallAfterLoad and not (csDesigning in ComponentState) then begin InternalCalculateBandsAfterLoad; FFirstCallAfterLoad := False; end else begin ANeedRepeat := False; repeat for I := 0 to ControlCount - 1 do begin AControl := Controls[I]; ABand := FindControlBand(AControl); if ABand = nil then begin // new control added // 1. find row for control ARow := FindRow(GetControlRowCoord(aControl) + BorderOffs); if ARow = nil then begin // row not found create new ARow := TvgrCBRow.Create(Self); FRows.Add(ARow); end; // 2. create band GetBandSizes(ARow, AControl, AWidth, AHeight); TvgrCBBand.Create(ARow, AControl, AWidth, AHeight, GetControlBandCoord(AControl) - BorderOffs - CaptionOffs); end else if IsControlVisible(Controls[I]) and not ABand.Visible then begin // show control FindControlBand(AControl).Visible := True; end else if not IsControlVisible(Controls[I]) and ABand.Visible then begin // hide control FindControlBand(AControl).Visible := False; end else if IsControlVisible(Controls[I]) then begin // control position is changed ABand := FindControlBand(AControl); ARow := FindRow(GetControlRowCoord(AControl)); if ARow = nil then begin // row not found create new ARow := TvgrCBRow.Create(Self); FRows.Add(ARow); ANeedRepeat := not ANeedRepeat; end; ABand.Row := ARow; GetBandSizes(ARow, AControl, AWidth, AHeight); ABand.Width := AWidth; ABand.Height := AHeight; end; end; until not ANeedRepeat; end; InternalAlignControls; finally EndUpdate; end; end; end; procedure TvgrControlbar.UpdateSize; begin Size := GetLastRowMax; end; function TvgrControlBar.IsVertical : boolean; begin Result := FSide in [prcbsLeft,prcbsRight]; end; function TvgrControlBar.GetRow(i : integer) : TvgrCBRow; begin Result := TvgrCBRow(FRows[i]); end; function TvgrControlBar.GetRowsCount : integer; begin Result := FRows.Count; end; procedure TvgrControlBar.ClearRows; var i : integer; begin for i:=0 to FRows.Count-1 do Rows[i].Free; FRows.Clear; end; procedure TvgrControlBar.CreateParams(var Params: TCreateParams); begin inherited; with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TvgrControlBar.Paint; var r : TRect; i,j : integer; begin with Canvas do begin if csDesigning in ComponentState then begin Pen.Color := clBlack; Brush.Color := clBtnFace; Rectangle(0,0,ClientWidth,ClientHeight); end else begin Brush.Color := clBtnFace; FillRect(Rect(0,0,ClientWidth,ClientHeight)); end; // Draw bands for i:=0 to RowsCount-1 do for j:=0 to Rows[i].BandsCount-1 do if Rows[i].Bands[j].Visible then begin r := Rows[i].Bands[j].Rect; DrawEdge(Handle,r,BDR_RAISEDINNER,BF_RECT); if IsVertical then begin r := Rect(r.Left+2,r.Top+2,r.Right-2,r.Top+4); DrawEdge(Handle,r,BDR_RAISEDINNER,BF_RECT); OffsetRect(r,0,3); DrawEdge(Handle,r,BDR_RAISEDINNER,BF_RECT); end else begin r := Rect(r.Left+2,r.Top+2,r.Left+4,r.Bottom-2); DrawEdge(Handle,r,BDR_RAISEDINNER,BF_RECT); OffsetRect(r,3,0); DrawEdge(Handle,r,BDR_RAISEDINNER,BF_RECT); end; end; end; end; procedure TvgrControlBar.SetSide(Value : TvgrControlBarSide); begin if FSide=Value then exit; FSide := Value; Align := aAlignArray[FSide]; end; function TvgrControlBar.GetSize : integer; begin if IsVertical then Result := Width else Result := Height; end; procedure TvgrControlBar.SetSize(Value : integer); begin if GetSize=Value then exit; if IsVertical then Width := Value else Height := Value; end; procedure TvgrControlBar.GetPointInfoAt(X,Y : integer; var band : TvgrCBBand); var i,j : integer; begin band := nil; for i:=0 to RowsCount-1 do for j:=0 to Rows[i].BandsCount-1 do if Rows[i].Bands[j].Visible and PtInRect(Rows[i].Bands[j].Rect,Point(X,Y)) then begin band := Rows[i].Bands[j]; exit; end; end; procedure TvgrControlBar.NotifyDesigner; begin if (Owner is TForm) and (TForm(Owner).Designer <> nil) then TForm(Owner).Designer.Modified; end; procedure TvgrControlBar.MouseDown(Button : TMouseButton; Shift : TShiftState; X,Y: integer); begin GetPointInfoAt(X,Y,FDownBand); FDownMousePos := Point(X, Y); end; procedure TvgrControlBar.MouseMove(Shift : TShiftState; X,Y : Integer); var AOldRow, Row: TvgrCBRow; I, RowCoord, BandCoord, AWidth, AHeight: Integer; begin if (FDownBand = nil) or (not (FDownBand.Control is TToolBar)) or (TToolBar(FDownBand.Control).DragKind <> dkDock) or ((FDownMousePos.X = X) and (FDownMousePos.Y = Y)) then exit; FDownMousePos := Point(X, Y); if IsVertical then begin RowCoord := X; BandCoord := Y; end else begin RowCoord := Y; BandCoord := X; end; if ((RowCoord < 0) or (RowCoord > GetLastRowMax)) and (FDownBand.Row.VisibleBandsCount = 1) then begin if not (csDesigning in ComponentState) then begin // start drag operation FDownBand.Control.BeginDrag(true); DeleteControl(FDownBand.Control); FDownBand := nil; end; end else begin // find new band position if FDownBand.Row.BandsCount > 1 then AOldRow := FDownBand.Row else AOldRow := nil; Row := FindRow(RowCoord); if Row = nil then begin Row := TvgrCBRow.Create(Self); if RowCoord < 0 then FRows.Insert(0, Row) else FRows.Add(Row); end; FDownBand.Row := Row; FDownBand.Min := BandCoord; GetBandSizes(Row, FDownBand.Control, AWidth, AHeight); FDownBand.Width := AWidth; FDownBand.Height := AHeight; // realign old FDownBand row if AOldRow <> nil then for I := 0 to AOldRow.BandsCount - 1 do begin if AOldRow.Bands[I].Control <> nil then begin GetBandSizes(AOldRow, AOldRow.Bands[I].Control, AWidth, AHeight); AOldRow.Bands[I].Width := AWidth; AOldRow.Bands[I].Height := AHeight; end; end; InternalAlignControls; NotifyDesigner; end; end; procedure TvgrControlBar.MouseUp(Button : TMouseButton; Shift : TShiftState; X,Y: Integer); begin FDownBand := nil; end; procedure TvgrControlBar.PositionDockRect(DragDockObject: TDragDockObject); var r: TRect; AWidth, AHeight: Integer; begin inherited; if DragDockObject.Control <> nil then begin GetBandSizes(nil, DragDockObject.Control, AWidth, AHeight); r.Left := Mouse.CurSorPos.x; //DragDockObject.DockRect.Left; r.Top := Mouse.CurSorPos.y; //DragDockObject.DockRect.Top; r.Right := r.Left + AWidth; r.Bottom := r.Top + AHeight; DragDockObject.DockRect := r; end; end; procedure TvgrControlBar.CMDesignHitTest(var Msg : TCMDesignHitTest); var band: TvgrCBBand; begin GetPointInfoAt(Msg.XPos,Msg.YPos,band); Msg.Result := Ord((FDownBand <> nil) or (band <> nil)); end; procedure TvgrControlBar.CMControlListChange(var Msg : TCMControlListChange); begin inherited; if Msg.Control <> nil then begin if Msg.Inserting then begin // Setup default control properties for better if ((csDesigning in ComponentState) or (csDesigning in Msg.Control.ComponentState)) and not (csLoading in ComponentState) and not (csLoading in Msg.Control.ComponentState) then SetupControlProperties(Msg.Control); end else // if EnableUpdate then DeleteControl(Msg.Control); end; end; procedure TvgrControlBar.SetControlVisible(Control : TControl; Visible : boolean); var Band: TvgrCBBand; begin Band := FindControlBand(Control); if Band <> nil then begin BeginUpdate; try band.Visible := Visible; band.Control.Visible := Visible; InternalAlignControls; finally EndUpdate; end; end; end; ///////////////////////////////////////////////// // // TvgrControlBarManager // ///////////////////////////////////////////////// constructor TvgrControlBarManager.Create(AOwner : TComponent); begin inherited; {$IFDEF VGR_DEMO} ShowDemoWarning; {$ENDIF} FToolbarsList := TList.Create; FRestoredToolbars := TList.Create; end; destructor TvgrControlBarManager.Destroy; begin if Owner is TForm then TForm(Owner).OnShow := FOldOnFormShow; FToolbarsList.Free; FRestoredToolbars.Free; inherited; end; procedure TvgrControlBarManager.Notification(AComponent: TComponent; AOperation: TOperation); begin inherited; if AOperation = opRemove then begin if AComponent = FLeftCB then FLeftCB := nil; if AComponent = FTopCB then FTopCB := nil; if AComponent = FRightCB then FRightCB := nil; if AComponent = FBottomCB then FBottomCB := nil; end; end; procedure TvgrControlBarManager.Loaded; var fLoading: Boolean; begin fLoading := csLoading in ComponentState; inherited; if not (csDesigning in ComponentState) and fLoading then begin if Owner is TForm then begin FOldOnFormShow := TForm(Owner).OnShow; TForm(Owner).OnShow := OnFormShow; end; end; end; procedure TvgrControlBarManager.OnFormShow(Sender : TObject); var I: integer; begin for I := 0 to FRestoredToolbars.Count - 1 do with TToolbar(FRestoredToolbars[I]) do begin EnableWindow(Parent.Handle, True); SetWindowPos(Parent.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOZORDER); SetWindowLong(Parent.Handle, GWL_HWNDPARENT, Longint(TForm(Owner).Handle)); end; FRestoredToolbars.Clear; if Assigned(FOldOnFormShow) then FOldOnFormShow(Owner); end; procedure TvgrControlBarManager.GetToolbarsList; var I: integer; begin FToolbarsList.Clear; if Assigned(FOnGetToolbarsList) then FOnGetToolbarsList(Self, FToolbarsList) else for I := 0 to Owner.ComponentCount - 1 do if Owner.Components[I] is TToolBar then FToolbarsList.Add(Owner.Components[I]); end; function TvgrControlBarManager.GetToolbar(I: integer) : TToolbar; begin Result := TToolBar(FToolbarsList[i]); end; function TvgrControlBarManager.GetToolbarsCount : integer; begin Result := FToolbarsList.Count; end; procedure TvgrControlBarManager.WriteToolbar(Toolbar: TToolbar; AStorage: TvgrIniStorage; const SectionName: string); var ADockSide: Integer; begin AStorage.EraseSection(SectionName); AStorage.WriteBool(SectionName, 'Visible', ToolBar.Visible); if not Toolbar.Floating and (ToolBar.Parent is TvgrControlBar) then begin if Toolbar.Parent = LeftCB then ADockSide := 0 else if Toolbar.Parent = RightCB then ADockSide := 1 else if Toolbar.Parent = TopCB then ADockSide := 2 else if Toolbar.Parent = BottomCB then ADockSide := 3 else ADockSide := -1; if ADockSide <> -1 then begin AStorage.WriteBool(SectionName, 'Floating', False); AStorage.WriteInteger(SectionName, 'DockSide', ADockSide); exit; end; end; AStorage.WriteBool(SectionName, 'Floating', True); with ToolBar.Parent.BoundsRect do begin AStorage.WriteInteger(SectionName, 'Left', Left); AStorage.WriteInteger(SectionName, 'Top', Top); AStorage.WriteInteger(SectionName, 'Right', Right); AStorage.WriteInteger(SectionName, 'Bottom', Bottom); end; end; procedure TvgrControlBarManager.WriteControlBar(AControlBar: TvgrControlBar; AStorage: TvgrIniStorage; const SectionName: string); var I, J: Integer; S, S2: string; ARow: TvgrCBRow; begin AStorage.EraseSection(SectionName); AStorage.WriteInteger(SectionName, 'RowsCount', AControlBar.RowsCount); for I := 0 to AControlBar.RowsCount - 1 do begin S := 'Row' + IntToStr(I); ARow := AControlBar.Rows[I]; AStorage.WriteInteger(SectionName, S + '_Min', ARow.Bands[0].Min); AStorage.WriteInteger(SectionName, S + '_Count', ARow.BandsCount); for J := 0 to ARow.BandsCount - 1 do begin S2 := S + '_Band' + IntToStr(J); AStorage.WriteString(SectionName, S2 + '_Control', ARow.Bands[J].Control.Name); AStorage.WriteBool(SectionName, S2 + '_Visible', ARow.Bands[J].Visible); end; end; end; procedure TvgrControlBarManager.WriteToStorage(AStorage: TvgrIniStorage; const SectionNamePrefix: string); var I: integer; begin if LeftCB <> nil then WriteControlBar(LeftCB, AStorage, SectionNamePrefix + 'LeftControlBar'); if RightCB <> nil then WriteControlBar(RightCB, AStorage, SectionNamePrefix + 'RightControlBar'); if TopCB <> nil then WriteControlBar(TopCB, AStorage, SectionNamePrefix + 'TopControlBar'); if BottomCB <> nil then WriteControlBar(BottomCB, AStorage, SectionNamePrefix + 'BottomControlBar'); GetToolbarsList; for I := 0 to ToolbarsCount - 1 do WriteToolbar(Toolbars[I], AStorage, SectionNamePrefix + Toolbars[I].Name); end; procedure TvgrControlBarManager.ReadFromStorage(AStorage: TvgrIniStorage; const SectionNamePrefix: string); var I: integer; procedure EndReadControlBar(AControlBar: TvgrControlBar); begin if AControlBar <> nil then begin AControlBar.InternalCalculateBandsAfterLoad; AControlBar.InternalAlignControls; AControlBar.EndUpdate; end; end; begin if LeftCB <> nil then LeftCB.BeginUpdate; if TopCB <> nil then TopCB.BeginUpdate; if RightCB <> nil then RightCB.BeginUpdate; if BottomCB <> nil then BottomCB.BeginUpdate; try GetToolbarsList; for I := 0 to ToolbarsCount - 1 do ReadToolBar(ToolBars[I], AStorage, SectionNamePrefix + ToolBars[I].Name); if LeftCB <> nil then ReadControlBar(LeftCB, AStorage, SectionNamePrefix + 'LeftControlBar'); if RightCB <> nil then ReadControlBar(RightCB, AStorage, SectionNamePrefix + 'RightControlBar'); if TopCB <> nil then ReadControlBar(TopCB, AStorage, SectionNamePrefix + 'TopControlBar'); if BottomCB <> nil then ReadControlBar(BottomCB, AStorage, SectionNamePrefix + 'BottomControlBar'); finally EndReadControlBar(LeftCB); EndReadControlBar(TopCB); EndReadControlBar(RightCB); EndReadControlBar(BottomCB); end; end; procedure TvgrControlBarManager.ReadToolbar(Toolbar: TToolbar; AStorage: TvgrIniStorage; const SectionName: string); var ADockSide: integer; AFloating: Boolean; ADockControlBar: TvgrControlBar; begin if not AStorage.SectionExists(SectionName) then exit; ADockSide := AStorage.ReadInteger(SectionName, 'DockSide', -1); AFloating := AStorage.ReadBool(SectionName, 'Floating', True); case ADockSide of 0: ADockControlBar := LeftCB; 1: ADockControlBar := RightCB; 2: ADockControlBar := TopCB; 3: ADockControlBar := BottomCB; else ADockControlBar := nil; end; if (ADockControlBar <> nil) and not AFloating then begin if ToolBar.Parent <> ADockControlBar then begin if ToolBar.Parent is TvgrControlBar then TvgrControlBar(Toolbar.Parent).DeleteControl(Toolbar); Toolbar.Parent := ADockControlBar; end; end else begin if ToolBar.Parent is TvgrControlBar then TvgrControlBar(ToolBar.Parent).DeleteControl(ToolBar); ToolBar.ManualFloat(Rect(AStorage.ReadInteger(SectionName, 'Left', 0), AStorage.ReadInteger(SectionName, 'Top', 0), AStorage.ReadInteger(SectionName, 'Right', ToolBar.Width), AStorage.ReadInteger(SectionName, 'Bottom', ToolBar.Height))); FRestoredToolbars.Add(ToolBar); end; ToolBar.Visible := AStorage.ReadBool(SectionName, 'Visible', true); end; procedure TvgrControlBarManager.ReadControlBar(AControlBar: TvgrControlBar; AStorage: TvgrIniStorage; const SectionName: string); var I, J, N, K: Integer; ARow: TvgrCBRow; ABand: TvgrCBBand; S, S2, AControlName: string; AControl: TComponent; begin if not AStorage.SectionExists(SectionName) then exit; FreeListItems(AControlBar.FRows); AControlBar.FRows.Clear; N := AStorage.ReadInteger(SectionName, 'RowsCount', 0); for I := 0 to N - 1 do begin S := 'Row' + IntToStr(I); ARow := TvgrCBRow.Create(AControlBar); ARow.FLoadedMin := AStorage.ReadInteger(SectionName, S + '_Min', 0); K := AStorage.ReadInteger(SectionName, S + '_Count', 0); for J := 0 to K - 1 do begin S2 := S + '_Band' + IntToStr(J); AControlName := AStorage.ReadString(SectionName, S2 + '_Control', ''); AControl := Owner.FindComponent(AControlName); if AControl is TControl then begin ABand := TvgrCBBand.Create; ABand.FRow := ARow; ABand.FControl := TControl(AControl); ABand.FVisible := AStorage.ReadBool(SectionName, S2 + '_Visible', True); ARow.FBands.Add(ABand); end; end; if ARow.BandsCount > 0 then AControlBar.FRows.Add(ARow) else ARow.Free; end; end; procedure TvgrControlBarManager.WriteToIni(const AIniFileName: string; const SectionNamePrefix : string); var AIniFile: TvgrIniFileStorage; begin AIniFile := TvgrIniFileStorage.Create(AIniFileName); try WriteToStorage(AIniFile, SectionNamePrefix); finally AIniFile.Free; end; end; procedure TvgrControlBarManager.ReadFromIni(const AIniFileName: string; const SectionNamePrefix : string); var AIniFile: TvgrIniFileStorage; begin AIniFile := TvgrIniFileStorage.Create(AIniFileName); try ReadFromStorage(AIniFile, SectionNamePrefix); finally AIniFile.Free; end; end; procedure TvgrControlBarManager.ShowHideToolBar(ToolBar: TToolBar; Visible: Boolean); begin GetToolBarsList; if FToolBarsList.IndexOf(ToolBar) = -1 then exit; if ToolBar.Floating then ToolBar.Visible := Visible else if ToolBar.Parent is TvgrControlBar then TvgrControlBar(ToolBar.Parent).SetControlVisible(ToolBar, Visible); end; end.
unit Main; interface uses SysUtils, Classes, Controls, Forms, Dialogs, Graphics, StdCtrls, ScktComp, ExtCtrls, ClientsList, Client, RoomsList, Room, Error, CommonUtils; type TSimpleChatServer = class(TForm) ServerSocket: TServerSocket; Panel1: TPanel; RoomsListBox: TListBox; ClientsListBox: TListBox; LogListPanel: TPanel; LogListBox: TListBox; Label1: TLabel; RoomsListPanel: TPanel; Label2: TLabel; ClientsListPanel: TPanel; Label3: TLabel; Splitter3: TSplitter; Panel2: TPanel; Panel3: TPanel; StartButton: TButton; StopButton: TButton; Panel4: TPanel; Label4: TLabel; PortEdit: TEdit; Splitter2: TSplitter; procedure StartButtonClick(Sender: TObject); procedure StopButtonClick(Sender: TObject); procedure ServerSocketClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure ServerSocketClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure FormCreate(Sender: TObject); procedure PortEditChange(Sender: TObject); procedure ServerSocketListen(Sender: TObject; Socket: TCustomWinSocket); private // Обработка входящих данных procedure Processing(cmd: string; Socket: TCustomWinSocket); procedure ProcessU(params: TStringList; Socket: TCustomWinSocket); procedure ProcessJ(params: TStringList; Socket: TCustomWinSocket); procedure ProcessM(params: TStringList; Socket: TCustomWinSocket); procedure ProcessP(params: TStringList; Socket: TCustomWinSocket); procedure ProcessI(params: TStringList; Socket: TCustomWinSocket); public // Журналирование событий procedure Log(Text: string); end; var SimpleChatServer: TSimpleChatServer; ClientsList: TClientsList; RoomsList: TRoomsList; implementation {$R *.dfm} procedure TSimpleChatServer.StartButtonClick(Sender: TObject); var port: integer; begin if ValidatePort(PortEdit.Text) then begin ServerSocket.Port := StrToInt(PortEdit.Text); ServerSocket.Open; PortEdit.Color := clWindow; end else PortEdit.Color := clRed; end; procedure TSimpleChatServer.StopButtonClick(Sender: TObject); begin ClientsListBox.Clear; if ServerSocket.Active then begin ServerSocket.Close; Log('Сервер остановлен'); StartButton.Enabled := True; StopButton.Enabled := False; end; ClientsList.Clear; RoomsList.Clear; end; procedure TSimpleChatServer.ServerSocketClientRead(Sender: TObject; Socket: TCustomWinSocket); var params: TStringList; para: string; recv: string; i: integer; begin recv := Socket.ReceiveText; params := TStringList.Create; params.Text := recv; for i := 0 to params.Count - 1 do Processing(params[i], Socket); end; procedure TSimpleChatServer.Processing(cmd: string; Socket: TCustomWinSocket); var command: string; params: TStringList; begin params := TStringList.Create; params.Delimiter := ' '; params.DelimitedText := cmd; if params.Count = 0 then Exit; command := params[0]; if command = '$u' then ProcessU(params, Socket) else if command = '$j' then ProcessJ(params, Socket) else if command = '$m' then ProcessM(params, Socket) else if command = '$p' then ProcessP(params, Socket) else if command = '$i' then ProcessI(params, Socket) else TError.EmitError(TError.ErrorCode.UnknownCommand, Socket, command); end; procedure TSimpleChatServer.ProcessU(params: TStringList; Socket: TCustomWinSocket); var Client: TClient; begin if params.Count >= 2 then try Client := ClientsList.AddClient(Socket.SocketHandle, Socket, params[1]); if params.Count >= 3 then Client.dAge := StrToInt(params[2]); if params.Count >= 4 then Client.dEmail := params[3]; Log('Клиент подключился: ' + params[1]); except on ENickInUse do TError.EmitError(TError.ErrorCode.NickNameIsInUse, Socket, params[1]); on EIncorrectNick do TError.EmitError(TError.ErrorCode.IncorrectNickName, Socket, params[1]); end else TError.EmitError(TError.ErrorCode.InvalidCommandFormat, Socket, '$u'); end; procedure TSimpleChatServer.ProcessJ(params: TStringList; Socket: TCustomWinSocket); var client: TClient; begin client := ClientsList.GetClientByHandle(Socket.SocketHandle); if client <> nil then begin if params.Count = 2 then if ValidateRoomName(params[1]) then begin if not RoomsList.IsRoomExists(params[1]) then begin RoomsList.AddRoom(params[1]); Log('Создана комната: ' + params[1]); end; with RoomsList.GetRoomByName(params[1]) do try AddUser(client); NotifyUsers(client.NickName); Socket.SendText('$l ' + params[1] + ' ' + GetListOfUsers + #13#10); Log('Пользователь ' + client.NickName + ' вошел в комнату ' + params[1]); except on EAlreadyInChannel do TError.EmitError(TError.ErrorCode.AlreadyInChannel, Socket, params[1]) end; end else TError.EmitError(TError.ErrorCode.IncorrectRoomName, Socket, params[1]) else TError.EmitError(TError.ErrorCode.InvalidCommandFormat, Socket, '$j'); end; end; procedure TSimpleChatServer.ProcessM(params: TStringList; Socket: TCustomWinSocket); var receiver: string; room: TRoom; client, client2: TClient; begin receiver := params[1]; params.Delimiter := ' '; if receiver[1] = '#' then begin room := RoomsList.GetRoomByName(receiver); client := ClientsList.GetClientByHandle(Socket.SocketHandle); if Assigned(room) then begin params.Delete(0); params.Delete(0); room.SendText(client.NickName, params.DelimitedText); end; end else begin client := ClientsList.GetClientByHandle(Socket.SocketHandle); client2 := ClientsList.GetClientByNick(receiver); if Assigned(client) AND Assigned(client2) then begin params.Delete(0); params.Delete(0); client2.dSocket.SendText('$m ' + client.NickName + ' ' + params.DelimitedText + #13#10); client.dSocket.SendText('$m ' + client.NickName + ' ' + params.DelimitedText + #13#10); end; end; end; procedure TSimpleChatServer.ProcessP(params: TStringList; Socket: TCustomWinSocket); var room: TRoom; client: TClient; begin client := ClientsList.GetClientByHandle(Socket.SocketHandle); if params.Count = 2 then if ValidateRoomName(params[1]) then begin room := nil; room := RoomsList.GetRoomByName(params[1]); if Assigned(room) AND room.IsUserInRoom(client) then begin room.RemoveUser(client); Log('Пользователь ' + client.NickName + ' покинул комнату ' + room.dRoomName); if RoomsList.RemoveEmpty(room) then Log('Комната удалена: ' + params[1]); end; end else TError.EmitError(TError.ErrorCode.IncorrectRoomName, Socket, params[1]) else TError.EmitError(TError.ErrorCode.InvalidCommandFormat, Socket, '$p'); end; procedure TSimpleChatServer.ProcessI(params: TStringList; Socket: TCustomWinSocket); var client, client2: TClient; begin if params.Count = 2 then begin client := ClientsList.GetClientByNick(params[1]); client2 := ClientsList.GetClientByHandle(Socket.SocketHandle); if Assigned(client) AND Assigned(client2) then begin client2.dSocket.SendText('$i ' + client.NickName + ' ' + IntToStr(client.dAge) + ' ' + client.dEmail + #13#10); end; end else TError.EmitError(TError.ErrorCode.InvalidCommandFormat, Socket, '$p'); end; procedure TSimpleChatServer.ServerSocketListen(Sender: TObject; Socket: TCustomWinSocket); begin Log('Сервер запущен'); StartButton.Enabled := False; StopButton.Enabled := True; end; procedure TSimpleChatServer.FormCreate(Sender: TObject); begin ClientsList := TClientsList.Create; ClientsList.SetView(ClientsListBox); RoomsList := TRoomsList.Create; RoomsList.SetView(RoomsListBox); end; procedure TSimpleChatServer.PortEditChange(Sender: TObject); begin PortEdit.Color := clWindow; end; procedure TSimpleChatServer.ServerSocketClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); var Client: TClient; Room: TRoom; i: integer; begin Client := ClientsList.GetClientByHandle(Socket.SocketHandle); if Client <> nil then begin for i := RoomsList.Count - 1 downto 0 do begin Room := RoomsList.Items[i] as TRoom; Room.RemoveUser(Client); RoomsList.RemoveEmpty(Room); end; Log('Клиент отключился: ' + Client.NickName); end else Log('Клиент отключился.'); ClientsList.RemoveClient(Socket.SocketHandle); end; procedure TSimpleChatServer.Log(Text: string); begin LogListBox.Items.Append(Text); LogListBox.TopIndex := -1 + LogListBox.Items.Count; end; end.
unit SpectrumControls; {$mode objfpc}{$H+} interface uses Classes, Controls, ComCtrls, ExtCtrls, Buttons, FGL, Graphics, ImgList; type TNotebookTab = class; TNotebookTabList = specialize TFPGList<TNotebookTab>; TNotebookTabPosition = (ntpTop, ntpBottom); TNotebookTabs = class(TCustomPanel) private FTabs: TNotebookTabList; FNotebook: TNotebook; FImages: TCustomImageList; FTabsPosition: TNotebookTabPosition; FOnTabActivated: TNotifyEvent; function GetActiveTab: TNotebookTab; function GetTab(Index: Integer): TNotebookTab; procedure InvalidateTabs; procedure SetTabsPosition(Value: TNotebookTabPosition); protected procedure Paint; override; public constructor Create(ANotebook: TNotebook); reintroduce; destructor Destroy; override; property TabsPosition: TNotebookTabPosition read FTabsPosition write SetTabsPosition; property ActiveTab: TNotebookTab read GetActiveTab; function AddTab(const Title: String; Index: Integer): TNotebookTab; overload; procedure AddTab(const Title: String; Index: Integer; Feature: TObject); overload; procedure RenameTab(const Title: String; Feature: TObject); procedure ShowTab(Index: Integer); property OnTabActivated: TNotifyEvent read FOnTabActivated write FOnTabActivated; property Images: TCustomImageList read FImages write FImages; property Tabs[Index: Integer]: TNotebookTab read GetTab; end; TNotebookTab = class(TCustomSpeedButton) private FOwner: TNotebookTabs; FTitle: String; FChecked: Boolean; FFeature: TObject; FTabIndex: Integer; FImageIndex: Integer; FPadding: Integer; procedure SetChecked(Value: Boolean); procedure UpdateBorderSpacing; procedure SetTitle(const Value: String); procedure SetImageIndex(Index: Integer); procedure SetPadding(Value: Integer); protected procedure PaintBackground(var PaintRect: TRect); override; function DrawGlyph(ACanvas: TCanvas; const AClient: TRect; const AOffset: TPoint; AState: TButtonState; ATransparent: Boolean; BiDiFlags: Longint): TRect; override; public constructor Create(AOwner: TNotebookTabs); reintroduce; procedure Click; override; procedure GetPreferredSize(var PreferredWidth, PreferredHeight: integer; Raw: Boolean = False; WithThemeSpace: Boolean = True); override; property Checked: Boolean read FChecked write SetChecked; property Feature: TObject read FFeature; property TabIndex: Integer read FTabIndex; property Title: String read FTitle write SetTitle; property ImageIndex: Integer read FImageIndex write SetImageIndex; property Padding: Integer read FPadding write SetPadding; end; TSpectrumStatusBar = class(TStatusBar) private FPanelGraphSource: TStatusPanel; FPanelGraphsCount: TStatusPanel; FPanelPointsCount: TStatusPanel; FPanelModified: TStatusPanel; FPanelFactorX: TStatusPanel; FPanelFactorY: TStatusPanel; procedure SetPanel(APanel: TStatusPanel; const AText: String); public constructor Create(AOwner: TWinControl); reintroduce; procedure ShowModified(Value: Boolean); procedure ShowGraphCount(TotalCount, VisibleCount: Integer); end; TToolPanelHeader = class(TCustomPanel) private const ImageMargin = 2; TextIndent = 2; ButtonMargin = 1; private FCloseButton: TSpeedButton; FImages: TCustomImageList; FImageIndex: Integer; FImageMargin: Integer; FButtonMargin: Integer; FTextIndent: Integer; procedure SetImages(Value: TCustomImageList); procedure SetImageIndex(Value: Integer); protected procedure Paint; override; procedure AdjustSize; override; public constructor Create(AOwner: TWinControl); reintroduce; destructor Destroy; override; property Images: TCustomImageList read FImages write SetImages; property ImageIndex: Integer read FImageIndex write SetImageIndex; end; implementation uses SysUtils, RtlConsts, OriStrings, OriGraphics, SpectrumStrings; const SourceDPI = 96; function CanPaintImage(AImages: TCustomImageList; AImageIndex: Integer): Boolean; begin Result := Assigned(AImages) and (AImageIndex > -1) and (AImageIndex < AImages.Count) end; {%region TNotebookTabs} constructor TNotebookTabs.Create(ANotebook: TNotebook); var I: Integer; S: String; begin inherited Create(ANotebook.Owner); FNotebook := ANotebook; FTabs := TNotebookTabList.Create; Color := cl3DHiLight; BevelOuter := bvNone; BorderSpacing.InnerBorder := ScaleX(3, SourceDPI); for I := 0 to FNotebook.PageCount-1 do begin S := FNotebook.Page[I].Name; if StartsWith(S, 'Page') then S := Copy(S, 5, MaxInt); AddTab(S, I); end; if FTabs.Count > 0 then ShowTab(0); AutoSize := True; end; destructor TNotebookTabs.Destroy; begin FTabs.Free; inherited; end; procedure TNotebookTabs.SetTabsPosition(Value: TNotebookTabPosition); var Tab: TNotebookTab; begin if Value <> FTabsPosition then begin FTabsPosition := Value; for Tab in FTabs do Tab.UpdateBorderSpacing; Invalidate; InvalidateTabs; end; end; procedure TNotebookTabs.InvalidateTabs; var Tab: TNotebookTab; begin for Tab in FTabs do Tab.Invalidate; end; function TNotebookTabs.AddTab(const Title: String; Index: Integer): TNotebookTab; var X: Integer = 0; Tab: TNotebookTab; begin for Tab in FTabs do if Tab.Left > Left then X := Tab.Left + Tab.Width; Result := TNotebookTab.Create(Self); Result.Title := Title; Result.Left := X + 1; Result.Parent := Self; Result.FTabIndex := Index; FTabs.Add(Result); end; procedure TNotebookTabs.AddTab(const Title: String; Index: Integer; Feature: TObject); var Tab: TNotebookTab; begin Tab := AddTab(Title, Index); Tab.FFeature := Feature; ShowTab(Index); end; procedure TNotebookTabs.ShowTab(Index: Integer); var I: Integer; begin for I := 0 to FTabs.Count-1 do if FTabs[I].TabIndex = Index then begin FTabs[I].Checked := True; FNotebook.PageIndex := I; if Assigned(FOnTabActivated) then FOnTabActivated(Self); end else FTabs[I].Checked := False; Invalidate; end; procedure TNotebookTabs.RenameTab(const Title: String; Feature: TObject); var Tab: TNotebookTab; begin for Tab in FTabs do if Tab.Feature = Feature then begin Tab.Title := Title; exit; end; end; procedure TNotebookTabs.Paint; var Y: Integer; begin inherited; if TabsPosition = ntpBottom then Y := 0 else Y := Height-1; Canvas.Pen.Color := cl3DShadow; Canvas.Line(0, Y, Width, Y); end; function TNotebookTabs.GetActiveTab: TNotebookTab; begin for Result in FTabs do if Result.Checked then Exit; Result := nil; end; function TNotebookTabs.GetTab(Index: Integer): TNotebookTab; begin if (Index < 0) or (Index >= FTabs.Count) then raise EListError.CreateFmt(SListIndexError, [Index]); Result := FTabs[Index]; end; {%endregion} {%region TNotebookTab} constructor TNotebookTab.Create(AOwner: TNotebookTabs); begin inherited Create(AOwner); FOwner := AOwner; FImageIndex := -1; FPadding := 12; AutoSize := True; Align := alLeft; UpdateBorderSpacing; end; procedure TNotebookTab.UpdateBorderSpacing; var MarginY: Integer; begin MarginY := ScaleY(6, SourceDPI); if FOwner.TabsPosition = ntpBottom then begin BorderSpacing.Top := 0; BorderSpacing.Bottom := MarginY end else begin BorderSpacing.Top := MarginY; BorderSpacing.Bottom := 0; end; BorderSpacing.Left := ScaleX(6, SourceDPI); end; procedure TNotebookTab.Click; begin FOwner.ShowTab(TabIndex); end; procedure TNotebookTab.GetPreferredSize(var PreferredWidth, PreferredHeight: integer; Raw: Boolean = False; WithThemeSpace: Boolean = True); begin inherited GetPreferredSize(PreferredWidth, PreferredHeight, Raw, WithThemeSpace); Inc(PreferredWidth, FPadding + FPadding); end; procedure TNotebookTab.PaintBackground(var PaintRect: TRect); begin if FChecked then Canvas.Brush.Color := cl3DFace else Canvas.Brush.Color := cl3DHiLight; Canvas.FillRect(PaintRect); Canvas.Pen.Color := cl3DShadow; if FChecked then begin if FOwner.TabsPosition = ntpBottom then begin Canvas.MoveTo(0, 0); Canvas.LineTo(0, PaintRect.Bottom-1); Canvas.LineTo(PaintRect.Right-1, PaintRect.Bottom-1); Canvas.LineTo(PaintRect.Right-1, -1); end else begin Canvas.MoveTo(0, PaintRect.Bottom); Canvas.LineTo(0, 0); Canvas.LineTo(PaintRect.Right-1, 0); Canvas.LineTo(PaintRect.Right-1, PaintRect.Bottom); end; end else begin if FOwner.TabsPosition = ntpBottom then Canvas.Line(0, 0, PaintRect.Right, 0) else Canvas.Line(0, PaintRect.Bottom-1, PaintRect.Right, PaintRect.Bottom-1); end; end; function TNotebookTab.DrawGlyph(ACanvas: TCanvas; const AClient: TRect; const AOffset: TPoint; AState: TButtonState; ATransparent: Boolean; BiDiFlags: Longint): TRect; var Offset: TPoint; begin if CanPaintImage(FOwner.Images, FImageIndex) then begin Offset := AOffset; if FTitle = '' then begin Offset.X := (AClient.Right - AClient.Left - FOwner.Images.Width) div 2; end; Result := inherited DrawGlyph(ACanvas, AClient, Offset, AState, ATransparent, BiDiFlags); end; end; procedure TNotebookTab.SetChecked(Value: Boolean); begin if FChecked <> Value then begin FChecked := Value; Invalidate; end; end; procedure TNotebookTab.SetTitle(const Value: String); begin FTitle := Value; Caption := Value; InvalidatePreferredSize; AdjustSize; end; procedure TNotebookTab.SetPadding(Value: Integer); begin if FPadding <> Value then begin FPadding := Value; InvalidatePreferredSize; AdjustSize; Invalidate; end; end; procedure TNotebookTab.SetImageIndex(Index: Integer); begin FImageIndex := Index; if CanPaintImage(FOwner.Images, Index) then FOwner.Images.GetBitmap(Index, Glyph); end; {%endregion} {%region TSpectrumStatusBar} constructor TSpectrumStatusBar.Create(AOwner: TWinControl); begin inherited Create(AOwner); Parent := AOwner; SimplePanel := False; FPanelGraphsCount := Panels.Add; FPanelModified := Panels.Add; FPanelPointsCount := Panels.Add; FPanelFactorX := Panels.Add; FPanelFactorY := Panels.Add; FPanelGraphSource := Panels.Add; FPanelGraphsCount.Alignment := taCenter; FPanelPointsCount.Alignment := taCenter; FPanelModified.Alignment := taCenter; FPanelFactorX.Alignment := taCenter; FPanelFactorY.Alignment := taCenter; end; procedure TSpectrumStatusBar.ShowModified(Value: Boolean); begin if Value then SetPanel(FPanelModified, Status_Modified) else SetPanel(FPanelModified, ''); end; procedure TSpectrumStatusBar.ShowGraphCount(TotalCount, VisibleCount: Integer); begin if TotalCount <> VisibleCount then SetPanel(FPanelGraphsCount, Format('%s: %d (%d)', [Status_Graphs, VisibleCount, TotalCount])) else SetPanel(FPanelGraphsCount, Format('%s: %d', [Status_Graphs, TotalCount])); end; procedure TSpectrumStatusBar.SetPanel(APanel: TStatusPanel; const AText: String); begin APanel.Text := AText; APanel.Width := Canvas.TextWidth(' ' + AText + ' '); Invalidate; end; {%endregion} {%region TToolPanelHeader} constructor TToolPanelHeader.Create(AOwner: TWinControl); begin inherited Create(AOwner); FImageMargin := ScaleX(ImageMargin, SourceDPI); FButtonMargin := ScaleX(ButtonMargin, SourceDPI); FTextIndent := ScaleX(TextIndent, SourceDPI); Align := alTop; Parent := AOwner; BorderSpacing.Left := ScaleX(3, SourceDPI); BorderSpacing.Right := BorderSpacing.Left; Alignment := taLeftJustify; BevelInner := bvNone; BevelOuter := bvNone; FCloseButton := TSpeedButton.Create(Self); FCloseButton.Parent := Self; FCloseButton.Align := alRight; FCloseButton.Flat := True; FCloseButton.Glyph.LoadFromLazarusResource('close'); FCloseButton.BorderSpacing.Around := 1; AutoSize := True; end; destructor TToolPanelHeader.Destroy; begin FCloseButton.Free; inherited; end; procedure TToolPanelHeader.Paint; var R: TRect; TS: TTextStyle; begin R := ClientRect; Canvas.Pen.Color := cl3DShadow; Canvas.Brush.Color := clBtnFace; Canvas.Rectangle(R); if Assigned(FCloseButton) then Dec(R.Right, FCloseButton.Width + FButtonMargin*2); if CanPaintImage(FImages, FImageIndex) then begin FImages.Draw(Canvas, FImageMargin, FImageMargin, FImageIndex); Inc(R.Left, FImages.Width + FImageMargin); end; if Caption <> '' then begin Inc(R.Left, FTextIndent); TS := Canvas.TextStyle; TS.Alignment := BidiFlipAlignment(Self.Alignment, UseRightToLeftAlignment); if BiDiMode <> bdLeftToRight then TS.RightToLeft := True; TS.Layout := tlCenter; TS.Opaque := False; TS.Clipping := False; TS.SystemFont := Canvas.Font.IsDefault; Canvas.Font.Color := Font.Color; Canvas.TextRect(R, R.Left, R.Top, Caption, TS); end; end; procedure TToolPanelHeader.SetImages(Value: TCustomImageList); begin FImages := Value; Constraints.MinHeight := FImages.Height + FImageMargin*2; AdjustSize; Invalidate; end; procedure TToolPanelHeader.SetImageIndex(Value: Integer); begin if FImageIndex <> Value then begin FImageIndex := Value; Invalidate; end; end; procedure TToolPanelHeader.AdjustSize; begin inherited; if Assigned(FCloseButton) then FCloseButton.Width := FCloseButton.Height; end; end.
unit UNewOrgName; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, cxGroupBox, UFrameSave, Vcl.StdCtrls, Data.DB, DBAccess, Uni, MemDS, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, UFrameUniName, dxSkinDevExpressStyle, dxSkinXmas2008Blue; type TFNewOrgName = class(TForm) FrameSave1: TFrameSave; Group1: TcxGroupBox; lblOrg: TLabel; edtOrg: TcxLookupComboBox; QueryOrg: TUniQuery; dsOrg: TUniDataSource; FrameUniName1: TFrameUniName; procedure FormShow(Sender: TObject); procedure FrameSave1btnSaveClick(Sender: TObject); procedure edtOrgPropertiesEditValueChanged(Sender: TObject); procedure FrameUniName1edtNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FrameUniName1edtUniNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FrameUniName1edtUniNamePropertiesEditValueChanged (Sender: TObject); procedure FrameUniName1edtNamePropertiesEditValueChanged(Sender: TObject); procedure FrameUniName1edtRegNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FrameUniName1edtRegNamePropertiesEditValueChanged (Sender: TObject); private { Private declarations } public s_id_org: Integer; procedure EnableSave; procedure ShowOrg; { Public declarations } end; var FNewOrgName: TFNewOrgName; implementation {$R *.dfm} uses UPasswd; procedure TFNewOrgName.edtOrgPropertiesEditValueChanged(Sender: TObject); begin EnableSave; end; procedure TFNewOrgName.EnableSave; begin if (FrameUniName1.edtUniName.Text <> '') and (FrameUniName1.edtName.Text <> '') and (FrameUniName1.edtRegName.Text <> '') and (edtOrg.Text <> '') then FrameSave1.btnSave.Enabled := True else FrameSave1.btnSave.Enabled := false; end; procedure TFNewOrgName.FormShow(Sender: TObject); begin FrameUniName1.SetLang; FrameUniName1.edtUniName.SetFocus; EnableSave; end; procedure TFNewOrgName.FrameSave1btnSaveClick(Sender: TObject); begin FrameSave1.btnSaveClick(Sender); Close; end; procedure TFNewOrgName.FrameUniName1edtNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin EnableSave; end; procedure TFNewOrgName.FrameUniName1edtNamePropertiesEditValueChanged (Sender: TObject); begin EnableSave; end; procedure TFNewOrgName.FrameUniName1edtRegNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin EnableSave; end; procedure TFNewOrgName.FrameUniName1edtRegNamePropertiesEditValueChanged (Sender: TObject); begin EnableSave; end; procedure TFNewOrgName.FrameUniName1edtUniNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin EnableSave; end; procedure TFNewOrgName.FrameUniName1edtUniNamePropertiesEditValueChanged (Sender: TObject); begin EnableSave; end; procedure TFNewOrgName.ShowOrg; begin with QueryOrg do begin Close; Open; edtOrg.EditValue := s_id_org; end; end; end.
{*******************************************************} { } { FMX UI 组件注册单元 } { } { 版权所有 (C) 2016 YangYxd } { } {*******************************************************} unit UI.Reg; interface const PageName = 'FMX UI'; procedure Register; implementation uses UI.Debug, System.SysUtils, System.Actions, UI.Base, UI.Standard, UI.Edit, UI.Dialog, UI.Calendar, UI.Grid, UI.Design.GridColumns, UI.ListView, // UI.ListViewEx, UI.Toast, UI.Design.Bounds, UI.Design.Accessory, UI.Utils.SVGImage, UI.Design.SVGImage, UI.Design.ImageIndex, UI.Frame, {$IFDEF MSWINDOWS} Windows, Registry, {$ENDIF} ComponentDesigner, DesignIntf, DesignEditors, DesignerTypes, PropertyCategories, VCLEditors, System.Classes, System.Types, System.TypInfo, System.UITypes, System.Generics.Collections, System.RTLConsts, ActionEditors, FMX.ActnList, FMX.ImgList, Vcl.ComCtrls, Vcl.Graphics, FMX.Graphics, FMX.Ani, FMX.Types, FMX.Styles, FMX.Controls, FMX.StdCtrls, FMX.Edit; resourcestring sFMXUICategoryName = 'FMXUI'; sTouchCategoryName = 'Touch'; type TViewControlEditor = class(TDefaultEditor) private FCmdIndex: TArray<Integer>; protected procedure DesignerModified; public function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; TPatchBoundsProperty = class(TClassProperty) private protected procedure Edit; override; public function GetAttributes: TPropertyAttributes; override; end; TViewAccessoryProperty = class(TClassProperty) private protected procedure Edit; override; public function GetAttributes: TPropertyAttributes; override; end; TGridColumnsSettingsProperty = class(TClassProperty) private protected procedure Edit; override; public function GetAttributes: TPropertyAttributes; override; end; TSVGImageProperty = class(TClassProperty) private protected procedure Edit; override; public function GetAttributes: TPropertyAttributes; override; end; // TImageIndexExProperty = class(TIntegerProperty, ICustomPropertyDrawing, // ICustomPropertyListDrawing, ICustomPropertyDrawing80) // private // LI: IGlyph; // public // function GetAttributes: TPropertyAttributes; override; // procedure GetProperties(Proc: TGetPropProc); override; // function GetValue: string; override; // procedure GetValues(Proc: TGetStrProc); override; // procedure SetValue(const Value: string); override; // { ICustomPropertyListDrawing } // procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; // var AHeight: Integer); // procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; // var AWidth: Integer); // procedure ListDrawValue(const Value: string; ACanvas: TCanvas; // const ARect: TRect; ASelected: Boolean); // { ICustomPropertyDrawing } // procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; // ASelected: Boolean); // procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; // ASelected: Boolean); // { ICustomPropertyDrawing80 } // function PropDrawNameRect(const ARect: TRect): TRect; // function PropDrawValueRect(const ARect: TRect): TRect; // { IProperty160 } // procedure SetPropertyPath(const Value: string); // end; TLayoutComponentProperty = class(TComponentProperty) protected public procedure GetValues(Proc: TGetStrProc); override; end; {$IFDEF MSWINDOWS} var [Weak] FCopyBackground: TObject = nil; [Weak] FCopyDrawable: TObject = nil; {$ENDIF} {$IFDEF MSWINDOWS} // 设置环境变量 procedure SetEnvPath(const sName, sValue: string); var reg : TRegistry; sLMKey : string; begin sLMKey := 'System/CurrentControlSet/Control/Session Manager/Environment'; reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKey(sLMKey,False) then begin reg.WriteString(sName, sValue); reg.CloseKey; SetEnvironmentVariable(PChar(sName), PChar(sValue));//更新当前进程的环境变量 end; except end; reg.Free; end; {$ENDIF} procedure Register; begin RegisterComponents(PageName, [TView, TViewGroup, TLinearLayout, TRelativeLayout, TGridsLayout]); RegisterComponents(PageName, [TImageView]); RegisterComponents(PageName, [TImageViewerEx]); RegisterComponents(PageName, [TTextView]); RegisterComponents(PageName, [TEditView]); RegisterComponents(PageName, [TButtonView]); RegisterComponents(PageName, [TBadgeView]); RegisterComponents(PageName, [TProgressView]); RegisterComponents(PageName, [TRingView]); RegisterComponents(PageName, [TMultiPathView]); RegisterComponents(PageName, [TCameraViewer]); RegisterComponents(PageName, [THorzScrollView]); RegisterComponents(PageName, [TVertScrollView]); RegisterComponents(PageName, [TListViewEx]); RegisterComponents(PageName, [TGridView]); RegisterComponents(PageName, [TDBGridView]); RegisterComponents(PageName, [TStringGridView]); RegisterComponents(PageName, [TCalendarView]); RegisterComponents(PageName, [TDateView]); RegisterComponents(PageName, [TTimeView]); RegisterComponents(PageName, [TCalendarLanguage_CN]); RegisterComponents(PageName, [TCalendarLanguage_EN]); RegisterComponents(PageName, [TDialogStyleManager]); RegisterComponents(PageName, [TToastManager]); RegisterComponents(PageName, [TDrawableBrush]); RegisterComponentEditor(TView, TViewControlEditor); RegisterPropertyEditor(TypeInfo(TPatchBounds), TPersistent, '', TPatchBoundsProperty); RegisterPropertyEditor(TypeInfo(TGridColumnsSetting), TGridBase, '', TGridColumnsSettingsProperty); RegisterPropertyEditor(TypeInfo(TControl), TViewLayout, '', TLayoutComponentProperty); RegisterPropertyEditor(TypeInfo(TViewAccessory), TPersistent, '', TViewAccessoryProperty); RegisterPropertyEditor(TypeInfo(TSVGImage), TPersistent, '', TSVGImageProperty); RegisterPropertyEditor(TypeInfo(TImageIndex), TViewImagesBrush, '', TImageIndexProperty); //RegisterPropertyEditor(TypeInfo(TCustomImageList), TPersistent, '', TShareImageListProperty); //RegisterPropertyEditor(TypeInfo(TImageIndex), TViewImagesBrush, '', TAlphaColorProperty); //RegisterSelectionEditor(TView, TLayoutFilter); //RegisterComponentEditor(TCustomButton, TViewControlEditor); //RegisterComponentEditor(TCustomEdit, TViewControlEditor); //RegisterPropertyEditor(TypeInfo(WideString), TADOTable, 'TableName', TTableNameProperty); //RegisterPropertyEditor(TypeInfo(TBrushKind), TStrokeBrush, '', TBrushKindProperty); //RegisterComponentEditor(TCustomBindingsList, TBindCompListEditor); //RegisterSelectionEditor(TBaseLinkingBindSource, TBindCompFactorySelectionEditor); RegisterPropertiesInCategory(sFMXUICategoryName, [ { TView } 'AdjustViewBounds', 'Brush', 'Background', 'Clickable', 'Checked', 'Enabled', 'Layout', 'Padding', 'Paddings', 'Margin', 'Margins', 'InVisible', 'WidthSize', 'HeightSize', 'MinWidth', 'MinHeight', 'MaxWidth', 'MaxHeight', 'Gravity', 'Weight', 'CaptureDragForm', 'Orientation', 'OnClick', 'OnPaint', 'OnResize', { TScrollView } 'ShowScrollBars', 'ScrollBars', 'DragScroll', 'DragOneWay', 'ScrollSmallChangeFraction', 'ScrollStretchGlowColor', 'ScrollbarWidth', { TGridsLayout } 'ColumnCount', 'ColumnWidth', 'ColumnHeight', 'Divider', 'SpacingHorizontal', 'SpacingVertical', 'SpacingBorder', 'StretchMode', 'ForceColumnSize', { TImageView } 'Image', 'ScaleType', 'Stretch', 'Zoom', 'OnZoom', { TListViewEx} 'AllowItemClickEx', 'DividerHeight', 'EnablePullRefresh', 'EnablePullLoad', 'OnPullRefresh', 'OnPullLoad', 'OnInitFooter', 'OnInitHeader', 'OnItemClick', 'OnItemClickEx', 'OnScrollChange', 'OnItemMeasureHeight', { TEditView} 'KeyboardType', 'ReturnKeyType', 'Password', 'ReadOnly', 'MaxLength', 'FilterChar', 'ImeMode', 'Caret', 'KillFocusByReturn', 'CheckSpelling', 'SelectionFill', 'OnValidating', 'OnTyping', { TTextView } 'HtmlText', 'Drawable', 'GroupIndex', 'OnDrawBackgroud', { TProgressView } 'Min', 'Max', 'Value', 'ForeGround', 'StartAngle', 'Kind', 'SolidForeGround', 'PaddingBorder', 'OnValueChange', { TRingView } 'StyleOuter', 'StyleInner', 'Distance', 'AngleStart', 'AngleEnd', 'ClickInPath', { TBadgeView } 'AutoSize', 'TargetView', 'BadgeCount', 'TextColor', 'Style', 'MaxValue', 'Icon', 'ValueOutTail', { TMultiPathView } 'Paths', 'ActiveIndex', { GridView } 'RowHeight', 'DrawableCells', 'Options', 'FixedSettings', 'FooterStyle', 'MinRowCount', 'DataSource', 'ShowCheck', 'ColCount', 'RowCount', 'ShowColIndex', 'ColumnsSettings', { CalendarView } 'DateTime', 'DaysOfWeekDisabled', 'DaysOfWeekHighlighted', 'StartDate', 'EndDate', 'Language', 'RowHeight', 'RowLunarHeight', 'RowLunarPadding', 'RowPadding', 'TextSettingsOfLunar', 'TextSettingsOfTitle', 'TextSettingsOfWeeks', 'ViewModeMax', 'ViewModeMin', 'ViewModeStart', 'WeekStart', 'WeeksWidth', 'OnOwnerDrawCalendar', 'OnOwnerLunarData', 'OnClickView', 'OnTitleClick', 'OnColumnMoved', 'OnFixedCellClick', 'OnCellClick', 'OnCellEnter', 'OnCellLeave', 'OnCellCheck', 'OnCellEditDone', 'OnItemIndexChange', 'OnRowSelChange', 'OnDrawFixedColText', 'OnDrawFixedCellsText', 'OnDrawCells', 'OnDrawFooterCells', { Text } 'Text', 'TextHint', 'TextSettings', 'OnDrawText', 'OnTextChange' ]); RegisterPropertiesInCategory(sTouchCategoryName, [ 'Touch', 'TouchTargetExpansion', 'OnGesture' ]); RegisterPropertiesInCategory(sLayoutCategoryName, [ 'Layout', 'Padding', 'Paddings', 'Margin', 'Margins', 'WidthSize', 'HeightSize', 'MinWidth', 'MinHeight', 'MaxWidth', 'MaxHeight', 'Gravity', 'Weight', 'Orientation', 'ColumnCount', 'ColumnWidth', 'ColumnHeight', 'Divider', 'SpacingHorizontal', 'SpacingVertical', 'SpacingBorder', 'StretchMode', 'ForceColumnSize' ]); end; procedure RegisterAliases; begin AddEnumElementAliases(TypeInfo(TLayoutGravity), ['None', 'LeftTop', 'LeftBottom', 'RightTop', 'RightBottom', 'CenterVertical', 'CenterHorizontal', 'CenterHBottom', 'CenterVRight', 'Center']); AddEnumElementAliases(TypeInfo(TViewSize), ['CustomSize', 'WrapContent', 'FillParent']); AddEnumElementAliases(TypeInfo(TDrawablePosition), ['Left', 'Right', 'Top', 'Bottom', 'Center']); AddEnumElementAliases(TypeInfo(TDrawableKind), ['None', 'Circle', 'Ellipse']); AddEnumElementAliases(TypeInfo(TViewBorderStyle), ['None', 'RectBorder', 'RectBitmap', 'CircleBorder', 'EllipseBorder', 'LineEdit', 'LineTop', 'LineBottom', 'LineLeft', 'LineRight', 'Lines']); AddEnumElementAliases(TypeInfo(TViewBrushKind), ['None', 'Solid', 'Gradient', 'Bitmap', 'Resource', 'Patch9Bitmap', 'AccessoryBitmap', 'SVGImage']); AddEnumElementAliases(TypeInfo(TViewScroll), ['None', 'Horizontal', 'Vertical', 'Both']); AddEnumElementAliases(TypeInfo(TViewStretchMode), ['None', 'SpacingWidth', 'ColumnWidth', 'SpacingWidthUniform']); AddEnumElementAliases(TypeInfo(TProgressKind), ['Horizontal', 'Vertical', 'CircleRing']); AddEnumElementAliases(TypeInfo(TImageScaleType), ['None', 'Matrix', 'Center', 'CenterCrop', 'CenterInside', 'FitCenter', 'FitStart', 'FitEnd']); AddEnumElementAliases(TypeInfo(TBadgeStyle), ['EmptyText', 'NumberText', 'NewText', 'HotText', 'Icon']); AddEnumElementAliases(TypeInfo(TRingViewStyle), ['Rectangle', 'Circle', 'Ellipse']); AddEnumElementAliases(TypeInfo(TGridDataType), ['PlanText', 'CheckBox', 'RadioButton', 'Image', 'ProgressBar', 'CustomDraw']); AddEnumElementAliases(TypeInfo(TGridFooterStyle), ['None', 'DoSum', 'DoAvg', 'DoMin', 'DoMax', 'DoCount']); AddEnumElementAliases(TypeInfo(TGridRecStatus), ['RecNone', 'RecADD', 'RecMod', 'RecDel']); AddEnumElementAliases(TypeInfo(TViewAccessoryStyle), ['Accessory', 'Path']); AddEnumElementAliases(TypeInfo(TViewAccessoryType), ['None', 'More', 'Checkmark', 'Detail', 'Ellipses', 'Flag', 'Back', 'Refresh', 'Action', 'Play','Rewind', 'Forwards', 'Pause', 'Stop', 'Add', 'Prior', 'Next', 'BackWard', 'ForwardGo', 'ArrowUp', 'ArrowDown', 'ArrowLeft','ArrowRight', 'Reply', 'Search', 'Bookmarks', 'Trash', 'Organize', 'Camera', 'Compose', 'Info', 'Pagecurl', 'Details', 'RadioButton', 'RadioButtonChecked', 'CheckBox', 'CheckBoxChecked', 'User', 'Password', 'Down', 'Exit', 'Finish', 'Calendar', 'Cross', 'Menu', 'About', 'Share', 'UserMsg', 'Cart', 'Setting', 'Edit', 'Home', 'Heart', 'Comment', 'Collection', 'Fabulous', 'Image', 'Help', 'VCode', 'Time', 'UserReg', 'Scan', 'Circle', 'Location', 'UserDefined1', 'UserDefined2', 'UserDefined3' ]); AddEnumElementAliases(TypeInfo(TCalendarViewType), ['Days', 'Months', 'Years', 'Decades', 'Centuries']); end; procedure UnregisterAliases; begin RemoveEnumElementAliases(TypeInfo(TLayoutGravity)); RemoveEnumElementAliases(TypeInfo(TViewSize)); RemoveEnumElementAliases(TypeInfo(TDrawablePosition)); RemoveEnumElementAliases(TypeInfo(TDrawableKind)); RemoveEnumElementAliases(TypeInfo(TViewBorderStyle)); RemoveEnumElementAliases(TypeInfo(TViewBrushKind)); RemoveEnumElementAliases(TypeInfo(TViewScroll)); RemoveEnumElementAliases(TypeInfo(TViewStretchMode)); RemoveEnumElementAliases(TypeInfo(TProgressKind)); RemoveEnumElementAliases(TypeInfo(TImageScaleType)); RemoveEnumElementAliases(TypeInfo(TBadgeStyle)); RemoveEnumElementAliases(TypeInfo(TRingViewStyle)); RemoveEnumElementAliases(TypeInfo(TGridDataType)); RemoveEnumElementAliases(TypeInfo(TGridRecStatus)); RemoveEnumElementAliases(TypeInfo(TGridFooterStyle)); RemoveEnumElementAliases(TypeInfo(TViewAccessoryStyle)); RemoveEnumElementAliases(TypeInfo(TViewAccessoryType)); RemoveEnumElementAliases(TypeInfo(TCalendarViewType)); end; { TViewControlEditor } type TViewPri = class(TView); procedure TViewControlEditor.DesignerModified; begin if Designer <> nil then Designer.Modified; end; procedure TViewControlEditor.ExecuteVerb(Index: Integer); var O: TDrawableBase; begin if not (Component is TControl) then Exit; case FCmdIndex[Index] of 0: begin if TControl(Component).Index > 0 then TControl(Component).Index := TControl(Component).Index - 1; end; 1: begin if TControl(Component).Index < TControl(Component).Parent.ChildrenCount - 1 then TControl(Component).Index := TControl(Component).Index + 1; end; 2: begin TControl(Component).Index := 0; end; 3: begin TControl(Component).Index := TControl(Component).Parent.ChildrenCount - 1; end; 4: begin FCopyBackground := TViewPri(Component).FBackground; end; 5: begin try TView(Component).Background := TDrawable(FCopyBackground); except MessageBox(0, PChar(Exception(ExceptObject).Message), 'Error', 48); end; end; 6: begin if TView.ExistRttiValue(Component, 'Drawable') then FCopyDrawable := TView.GetRttiObject(Component, 'Drawable') else FCopyDrawable := TView.GetRttiObject(Component, 'FDrawable'); end; 7: begin try if Component is TTextView then begin TTextView(Component).Drawable := TDrawableIcon(FCopyDrawable) end else if Component is TCustomEditView then begin TCustomEditView(Component).Drawable := TDrawableIcon(FCopyDrawable) end else TView.InvokeMethod(Component, 'SetDrawable', [TDrawableIcon(FCopyDrawable)]); except MessageBox(0, PChar(Exception(ExceptObject).Message), 'Error', 48); end; end; end; Designer.SelectComponent(Component); DesignerModified; end; function TViewControlEditor.GetVerb(Index: Integer): string; const CmdNames: TArray<string> = ['前移', '后移', '移至最前', '移至最后', 'Copy Background', 'Paste Background', 'Copy Drawable', 'Paste Drawable']; begin Result := CmdNames[FCmdIndex[Index]]; end; function TViewControlEditor.GetVerbCount: Integer; var O: TObject; begin SetLength(FCmdIndex, 20); if (Component is TControl) and ((TControl(Component).Parent is TLinearLayout) or (TControl(Component).Parent is TGridsLayout)) then begin Result := 4; FCmdIndex[0] := 0; FCmdIndex[1] := 1; FCmdIndex[2] := 2; FCmdIndex[3] := 3; end else Result := 0; if (Component is TView) then begin FCmdIndex[Result] := 4; Inc(Result); if Assigned(FCopyBackground) then begin FCmdIndex[Result] := 5; Inc(Result); end; O := TView.GetRttiObject(Component, 'Drawable'); if not Assigned(O) then O := TView.GetRttiObject(Component, 'FDrawable'); if Assigned(O) and (O is TDrawableBase) then begin FCmdIndex[Result] := 6; Inc(Result); if Assigned(FCopyDrawable) then begin FCmdIndex[Result] := 7; Inc(Result); end; end; end; end; { TPatchBoundsProperty } procedure TPatchBoundsProperty.Edit; var Component: TObject; Dialog: TBoundsDesigner; begin Component := GetComponent(0); if not (Component is TPatch9Bitmap) then Exit; Dialog := TBoundsDesigner.Create(nil); try Dialog.Caption := '9宫格绘图编辑器'; Dialog.Bitmap := TPatch9Bitmap(Component).Bitmap; Dialog.Bounds := TPatch9Bitmap(Component).Bounds.Rect; if Dialog.ShowModal = mrOK then begin TPatch9Bitmap(Component).Bounds.Rect := Dialog.Bounds; end; finally Dialog.Free; end; end; function TPatchBoundsProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly, paDialog]; end; { TLayoutComponentProperty } procedure TLayoutComponentProperty.GetValues(Proc: TGetStrProc); var I, J: Integer; P: TComponent; Item: TFmxObject; IsSel: Boolean; Selects: IDesignerSelections; begin if Assigned(Designer.CurrentParent) then begin P := Designer.CurrentParent; Selects := GetSelections; for I := 0 to TControl(P).ChildrenCount - 1 do begin Item := TControl(P).Children.Items[I]; if (Item is TControl) and (Item.Name <> '') then begin IsSel := False; if Assigned(Selects) and (Selects.Count > 0) then begin for j := 0 to Selects.Count - 1 do if Item = Selects.Items[J] then begin IsSel := True; Break; end; end; if not IsSel then Proc(Item.Name); end; end; end; end; //{ TShareImageListProperty } // //function TShareImageListProperty.GetValue: string; //begin // Result := Designer.GetComponentName(GetComponentReference); //end; // //procedure TShareImageListProperty.GetValues(Proc: TGetStrProc); //var // I: Integer; // AList: TList<TShareImageList>; //begin // Designer.GetComponentNames(GetTypeData(GetPropType), Proc); // AList := TShareImageList.GetShareImageList; // if Assigned(AList) then begin // for I := 0 to AList.Count - 1 do // if Assigned(AList[I].Owner) then // Proc(AList[I].Owner.ClassName + ':' + AList[I].Name); // end; //end; // //procedure TShareImageListProperty.SetValue(const Value: string); //var // Component: TComponent; // I: Integer; // AList: TList<TShareImageList>; // V: string; //begin // AList := TShareImageList.GetShareImageList; // Component := nil; // if Value <> '' then begin // if Assigned(AList) and (Pos(':', Value) > 0) then begin // for I := 0 to AList.Count - 1 do begin // if Assigned(AList[I].Owner) then // V := LowerCase(AList[I].Owner.ClassName + ':' + AList[I].Name) // else // V := ''; // if V = LowerCase(Value) then begin // Component := AList[I]; // Break; // end; // end; // end; // // if Component = nil then // Component := Designer.GetComponent(Value); // if not (Component is GetTypeData(GetPropType)^.ClassType) then // raise EDesignPropertyError.CreateRes(@SInvalidPropertyValue); // end; // SetOrdValue(LongInt(Component)); //end; { TGridColumnsSettingsProperty } procedure TGridColumnsSettingsProperty.Edit; var Component: TObject; Dialog: TGridColumnsDesigner; begin Component := GetComponent(0); if not (Component is TGridView) then Exit; Dialog := TGridColumnsDesigner.Create(nil); try Dialog.Caption := 'GridView 列设计器 (隐藏的列请通过点击“上一项”或“下一项”切换)'; Dialog.Columns := TGridView(Component).Columns; if Dialog.ShowModal = mrOK then TGridView(Component).Columns.Assign(Dialog.Columns); finally Dialog.Free; end; end; function TGridColumnsSettingsProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly, paDialog]; end; { TSVGImageProperty } procedure TSVGImageProperty.Edit; var Component: TObject; Dialog: TFrmDesignSVGImage; begin Component := GetComponent(0); if not (Component is TViewBrushBase) then Exit; Dialog := TFrmDesignSVGImage.Create(nil); try Dialog.Caption := 'SVG Image'; Dialog.LoadImage(TViewBrushBase(Component).SVGImage); if Dialog.ShowModal = mrOK then TViewBrushBase(Component).SVGImage := Dialog.Bmp; finally Dialog.Free; end; end; function TSVGImageProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly, paDialog]; end; { TViewAccessoryProperty } procedure TViewAccessoryProperty.Edit; var Component: TObject; Dialog: TAccessoryDesigner; begin Component := GetComponent(0); if not (Component is TViewBrushBase) then Exit; Dialog := TAccessoryDesigner.Create(nil); try Dialog.Caption := 'Accessory Designer'; Dialog.Accessory := TViewBrushBase(Component).Accessory; if Dialog.ShowModal = mrOK then begin TViewBrushBase(Component).Accessory := Dialog.Accessory; end; finally Dialog.Free; end; end; function TViewAccessoryProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly, paDialog]; end; initialization RegisterAliases; RegisterFmxClasses([TView, TLinearLayout, TRelativeLayout, TGridView, TTextView, TButtonView, TEditView, TAlertDialog, TDialogStyleManager]); finalization UnregisterAliases; {$IFDEF MSWINDOWS} FCopyBackground := nil; FCopyDrawable := nil; {$ENDIF} end.
unit UsersFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, TB2Item, TBX, TB2Dock, TB2Toolbar, ExtCtrls, RzPanel, StdCtrls, RzLabel, DB, DBAccess, MSAccess, MemDS, Grids, DBGridEh, UpUsersForm, RzLstBox, RzChkLst, GridsEh, DBGridEhGrouping; type TFmeUsers = class(TFrame) RzLabel9: TRzLabel; RzPanel1: TRzPanel; TBXDock1: TTBXDock; TBXToolbar2: TTBXToolbar; Filter: TTBXItem; DelFilter: TTBXItem; TBXItem1: TTBXItem; TBXItem2: TTBXItem; MQuery: TMSSQL; RzPanel2: TRzPanel; dbgError: TDBGridEh; RzPanel3: TRzPanel; chkListRoleAll: TRzCheckList; RzPanel4: TRzPanel; chkListRole: TRzCheckList; TBXItem3: TTBXItem; TBXSeparatorItem1: TTBXSeparatorItem; TBXSeparatorItem2: TTBXSeparatorItem; procedure FilterClick(Sender: TObject); procedure TBXItem2Click(Sender: TObject); procedure DelFilterClick(Sender: TObject); procedure TBXItem1Click(Sender: TObject); procedure dbgErrorCellClick(Column: TColumnEh); procedure dbgErrorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TBXItem3Click(Sender: TObject); private FU:TFrmUpUsers; public procedure Init; procedure GetRole(uid:Integer; List: TStrings); procedure CheckAll(List:TRzCheckList); end; implementation uses DataModule, MainForm; {$R *.dfm} { TFmeUsers } procedure TFmeUsers.Init; begin with dm.qryUsers do begin if Active then Close; try Open; GetRole(dm.qryUsers['uid'], chkListRole.Items); CheckAll(chkListRole); GetRole(-1, chkListRoleAll.Items); except ShowMessage('Извините, не удалось получить информацию о пользователях'); end; end; end; procedure TFmeUsers.FilterClick(Sender: TObject); begin FU:=TFrmUpUsers.Create(Application); try FrmMain.CurRec:=0; FU.ShowModal; if FrmMain.CurRec1 = 1 then begin with MQuery do begin SQL.Clear; SQL.Add('EXEC sp_addlogin :login, :pass, :db'); ParamByName('login').AsString:=FU.edtUsers.Text; ParamByName('pass').AsString:=FU.edtPassword.Text; ParamByName('db').AsString:='Teplosnab'; Execute; SQL.Clear; SQL.Add('EXEC sp_grantdbaccess :login'); ParamByName('login').AsString:=FU.edtUsers.Text; Execute; dm.qryUsers.Refresh; end; end; finally FU.Free end; end; procedure TFmeUsers.TBXItem2Click(Sender: TObject); begin FU:=TFrmUpUsers.Create(Application); try FrmMain.CurRec:=1; FU.ShowModal; if FrmMain.CurRec1 = 1 then begin with MQuery do begin SQL.Clear; SQL.Add('EXEC sp_password :pass, :newpass, :login'); ParamByName('login').AsString:=FU.edtUsers.Text; ParamByName('pass').AsString:=FU.edtPassword.Text; ParamByName('newpass').AsString:=FU.edtConfirm.Text; Execute; end; end; finally FU.Free end; end; procedure TFmeUsers.DelFilterClick(Sender: TObject); begin if Application.MessageBox( PChar('Вы хотите удалить пользователя '+dm.qryUsers.FieldByName('name').AsString+'?'), 'Предупреждение',mb_YesNo or mb_TaskModal or mb_IconQuestion)=idYes then begin with MQuery do begin SQL.Clear; SQL.Add('EXEC sp_dropuser :login'); ParamByName('login').AsString:=dm.qryUsers.FieldByName('name').AsString; Execute; SQL.Clear; SQL.Add('EXEC sp_droplogin :login'); ParamByName('login').AsString:=dm.qryUsers.FieldByName('name').AsString; Execute; dm.qryUsers.Refresh; end; end; end; procedure TFmeUsers.TBXItem1Click(Sender: TObject); begin {Выход} FrmMain.pgcWork.ActivePage:=FrmMain.TabWelcome; end; procedure TFmeUsers.GetRole(uid: Integer; List: TStrings); begin {Роли} List.Clear; with dm.qryRole do begin if Active then Close; try if uid <> -1 then FilterSQL:='u.uid='+IntToStr(uid); Open; while Not Eof do begin List.Add(dm.qryRole.FieldByName('DbRole').AsString); Next; end; except ShowMessage('Нет доступа к данным...'); end; end; end; procedure TFmeUsers.CheckAll(List: TRzCheckList); begin with List do List.CheckAll; end; procedure TFmeUsers.dbgErrorCellClick(Column: TColumnEh); begin GetRole(dm.qryUsers['uid'], chkListRole.Items); CheckAll(chkListRole); end; procedure TFmeUsers.dbgErrorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin GetRole(dm.qryUsers['uid'], chkListRole.Items); CheckAll(chkListRole); end; procedure TFmeUsers.TBXItem3Click(Sender: TObject); Var i:integer; begin with chkListRoleAll do begin for i:=0 to Count-1 do begin if ItemChecked[i] = True then begin with MQuery do begin SQL.clear; SQL.Add('EXEC sp_addrolemember :role,:login'); ParamByName('role').AsString:=ItemCaption(i); ParamByName('login').AsString:=dm.qryUsers['name']; Execute; end; end; end; end; Init; end; end.
{*******************************************************} { VCL helpers/hacks for C++Builder } { } { $Revision: 1.0.1.0 $ } { $Date: 21 Sep 1999 12:54:52 $ } {*******************************************************} unit Vclhlpr; interface uses Windows, Messages, ActiveX, SysUtils, ComObj, Classes, Graphics, Controls, Forms, ExtCtrls, StdVcl, Axctrls; type TVarDispProc = procedure(Result: PVariant; const Instance: Variant; CallDesc: PCallDesc // NOTE: Here there may be other parameters pushed on the stack (for arguments) // See _DispInvoke in SYSTEM.PAS for more information. ); cdecl; TPropertyPageImplHack = class(TPropertyPageImpl, IUnknown) { IUnknown methods for other interfaces } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; // Helper routines use by C++Builder // procedure VariantCpy(const src: Variant; var dst: Variant); procedure VariantAdd(const src: Variant; var dst: Variant); procedure VariantSub(const src: Variant; var dst: Variant); procedure VariantMul(const src: Variant; var dst: Variant); procedure VariantDiv(const src: Variant; var dst: Variant); procedure VariantMod(const src: Variant; var dst: Variant); procedure VariantAnd(const src: Variant; var dst: Variant); procedure VariantOr (const src: Variant; var dst: Variant); procedure VariantXor(const src: Variant; var dst: Variant); procedure VariantShl(const src: Variant; var dst: Variant); procedure VariantShr(const src: Variant; var dst: Variant); function VariantCmp(const v1: Variant; const V2: Variant): Boolean; function VariantLT (const V1: Variant; const V2: Variant): Boolean; function VariantGT (const V1: Variant; const V2: Variant): Boolean; function VariantAdd2(const V1: Variant; const V2: Variant): Variant; function VariantSub2(const V1: Variant; const V2: Variant): Variant; function VariantMul2(const V1: Variant; const V2: Variant): Variant; function VariantDiv2(const V1: Variant; const V2: Variant): Variant; function VariantMod2(const V1: Variant; const V2: Variant): Variant; function VariantAnd2(const V1: Variant; const V2: Variant): Variant; function VariantOr2 (const V1: Variant; const V2: Variant): Variant; function VariantXor2(const V1: Variant; const V2: Variant): Variant; function VariantShl2(const V1: Variant; const V2: Variant): Variant; function VariantShr2(const V1: Variant; const V2: Variant): Variant; function VariantNot (const V1: Variant): Variant; function VariantNeg (const V1: Variant): Variant; function VariantGetElement(const V: Variant; i1: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload; // Raise an instance of EVariantError using the CreateRes constructor. // This function is necessary to avoid attempts to export EVariantError // from variant.cpp, which is not permitted by the linker when building // a package. procedure VariantRaiseError(Ident: Integer); implementation procedure VariantCpy(const src: Variant; var dst: Variant); begin dst := src; end; procedure VariantAdd(const src: Variant; var dst: Variant); begin dst := dst + src; end; procedure VariantSub(const src: Variant; var dst: Variant); begin dst := dst - src; end; procedure VariantMul(const src: Variant; var dst: Variant); begin dst := dst * src; end; procedure VariantDiv(const src: Variant; var dst: Variant); begin dst := dst / src; end; procedure VariantMod(const src: Variant; var dst: Variant); begin dst := dst mod src; end; procedure VariantAnd(const src: Variant; var dst: Variant); begin dst := dst and src; end; procedure VariantOr (const src: Variant; var dst: Variant); begin dst := dst or src; end; procedure VariantXor(const src: Variant; var dst: Variant); begin dst := dst xor src; end; procedure VariantShl(const src: Variant; var dst: Variant); begin dst := dst shl src; end; procedure VariantShr(const src: Variant; var dst: Variant); begin dst := dst shr src; end; function VariantCmp(const v1: Variant; const V2: Variant): Boolean; begin Result := v1 = v2; end; function VariantLT (const V1: Variant; const V2: Variant): Boolean; begin Result := V1 < V2; end; function VariantGT (const V1: Variant; const V2: Variant): Boolean; begin Result := V1 > V2; end; function VariantAdd2(const V1: Variant; const V2: Variant): Variant; begin Result := v1 + V2; end; function VariantSub2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 - V2; end; function VariantMul2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 * V2; end; function VariantDiv2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 / V2; end; function VariantMod2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 mod V2; end; function VariantAnd2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 and V2; end; function VariantOr2 (const V1: Variant; const V2: Variant): Variant; begin Result := V1 or V2; end; function VariantXor2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 xor V2; end; function VariantShl2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 shl V2; end; function VariantShr2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 shr V2; end; function VariantNot (const V1: Variant): Variant; begin Result := not V1; end; function VariantNeg (const V1: Variant): Variant; begin Result := -V1; end; function VariantGetElement(const V: Variant; i1: integer): Variant; overload; begin Result := V[i1]; end; function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload; begin Result := V[i1, i2]; end; function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload; begin Result := V[I1, i2, i3]; end; function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload; begin Result := V[i1, i2, i3, i4]; end; function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload; begin Result := V[i1, i2, i3, i4, i5]; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload; begin V[i1] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload; begin V[i1, i2] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload; begin V[i1, i2, i3] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload; begin V[i1, i2, i3, i4] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload; begin V[i1, i2, i3, i4, i5] := data; end; procedure VariantRaiseError(Ident: Integer); begin raise EVariantError.CreateRes(Ident); end; function TPropertyPageImplHack.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := inherited QueryInterface(IID, Obj); end; function TPropertyPageImplHack._AddRef: Integer; begin Result := inherited _AddRef; end; function TPropertyPageImplHack._Release: Integer; begin Result := inherited _Release; end; end.
unit ncTran; { ResourceString: Dario 13/03/13 } interface uses SysUtils, DB, MD5, Classes, Windows, ClasseCS, ncClassesBase; type TncTransacao = class public trID : Integer; trDataHora : TDateTime; trTipo : Byte; trCancelado : Boolean; trCanceladoPor : String; trCanceladoEm : TDateTime; trFunc : String; trDescr : String; trTotal : Currency; trDesconto : Currency; trPago : Currency; private procedure SetString(const Value: String); function GetString: String; public constructor Create; procedure Limpa; function Igual(Tran: TncTransacao): Boolean; procedure LoadFromDataset(D: TDataset); procedure SaveToDataset(D: TDataset); property AsString: String read GetString write SetString; end; TncTransacoes = class private FItens: TList; function GetItem(I: Integer): TncTransacao; function GetString: String; procedure SetString(Value: String); function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Limpa; function Remove(Tran: TncTransacao): Integer; procedure Delete(Index: Integer); procedure RemoveByID(const aID: Integer); function NewTran: TncTransacao; property Itens[I: Integer]: TncTransacao read GetItem; default; property AsString: String read GetString write SetString; property Count: Integer read GetCount; function TranByID(const aID: Integer): TncTransacao; procedure Totaliza(var aValor, aDesc, aPago: Currency); function TotalPendente(aTipoTran: Integer): Currency; function Total(aTipoTran: Integer): Currency; end; implementation { TncTransacoes } constructor TncTransacoes.Create; begin FItens := TList.Create; end; procedure TncTransacoes.Delete(Index: Integer); begin FItens.Delete(Index); end; destructor TncTransacoes.Destroy; begin Limpa; FItens.Free; inherited; end; function TncTransacoes.GetCount: Integer; begin Result := FItens.Count; end; function TncTransacoes.GetItem(I: Integer): TncTransacao; begin Result := TncTransacao(FItens[I]); end; function TncTransacoes.GetString: String; var I : Integer; begin Result := ''; for I := 0 to Count - 1 do Result := Result + Itens[I].AsString + sListaDelim(classid_TncTransacoes); end; procedure TncTransacoes.Limpa; begin while Count>0 do begin Itens[0].Free; FItens.Delete(0); end; end; function TncTransacoes.NewTran: TncTransacao; begin Result := TncTransacao.Create; FItens.Add(Result) end; function TncTransacoes.Remove(Tran: TncTransacao): Integer; begin Result := FItens.Remove(Tran); end; procedure TncTransacoes.RemoveByID(const aID: Integer); var T: TncTransacao; begin T := TranByID(aID); if T<>nil then Remove(T); end; procedure TncTransacoes.SetString(Value: String); var S: String; begin Limpa; while GetNextListItem(Value, S, classid_TncTransacoes) do NewTran.AsString := S; end; function TncTransacoes.Total(aTipoTran: Integer): Currency; var I : Integer; begin Result := 0; for I := 0 to Count - 1 do with Itens[I] do if ((aTipoTran=-1) or (trTipo=aTipoTran)) and (not trCancelado) then Result := Result + (trTotal-trDesconto); end; procedure TncTransacoes.Totaliza(var aValor, aDesc, aPago: Currency); var I : Integer; begin aValor := 0; aDesc := 0; aPago := 0; for I := 0 to Count - 1 do begin aValor := aValor + Itens[I].trTotal; aDesc := aDesc + Itens[I].trDesconto; aPago := aPago + Itens[I].trPago; end; end; function TncTransacoes.TotalPendente(aTipoTran: Integer): Currency; var I : Integer; begin Result := 0; for I := 0 to Count - 1 do with Itens[I] do if ((aTipoTran=-1) or (trTipo=aTipoTran)) and (not trCancelado) then Result := Result + (trTotal-trDesconto-trPago); end; function TncTransacoes.TranByID(const aID: Integer): TncTransacao; var I : Integer; begin Result := nil; for I := 0 to Count-1 do if Itens[I].trID=aID then begin Result := Itens[I]; Exit; end; end; { TncTransacao } constructor TncTransacao.Create; begin Limpa; end; function TncTransacao.GetString: String; begin Result := IntToStr(trID) + sFldDelim(classid_TncTransacao) + GetDTStr(trDataHora) + sFldDelim(classid_TncTransacao) + IntToStr(trTipo) + sFldDelim(classid_TncTransacao) + BoolStr[trCancelado] + sFldDelim(classid_TncTransacao) + trCanceladoPor + sFldDelim(classid_TncTransacao) + GetDTStr(trCanceladoEm) + sFldDelim(classid_TncTransacao) + trFunc + sFldDelim(classid_TncTransacao) + trDescr + sFldDelim(classid_TncTransacao) + FloatParaStr(trTotal) + sFldDelim(classid_TncTransacao) + FloatParaStr(trDesconto) + sFldDelim(classid_TncTransacao) + FloatParaStr(trPago) + sFldDelim(classid_TncTransacao); end; function TncTransacao.Igual(Tran: TncTransacao): Boolean; begin Result := False; if trID <> Tran.trID then Exit; if trDataHora <> Tran.trDataHora then Exit; if trTipo <> Tran.trTipo then Exit; if trCancelado <> Tran.trCancelado then Exit; if trCanceladoPor <> Tran.trCanceladoPor then Exit; if trCanceladoEm <> Tran.trCanceladoEm then Exit; if trFunc <> Tran.trFunc then Exit; if trDescr <> Tran.trDescr then Exit; if trTotal <> Tran.trTotal then Exit; if trDesconto <> Tran.trDesconto then Exit; if trPago <> Tran.trPago then Exit; Result := True; end; procedure TncTransacao.Limpa; begin trID := -1; trDataHora := 0; trTipo := 0; trCancelado := False; trCanceladoPor := ''; trCanceladoEm := 0; trFunc := ''; trDescr := ''; trTotal := 0; trDesconto := 0; trPago := 0; end; procedure TncTransacao.LoadFromDataset(D: TDataset); var S: String; begin trID := D.FieldByName('ID').AsInteger; // do not localize trDataHora := D.FieldByName('DataHora').AsDateTime; // do not localize trTipo := D.FieldByName('Tipo').AsInteger; // do not localize trCancelado := D.FieldByName('Cancelado').AsBoolean; // do not localize trCanceladoPor := D.FieldByName('CanceladoPor').AsString; // do not localize trCanceladoEm := D.FieldByName('CanceladoEm').AsDateTime; // do not localize trFunc := D.FieldByName('Func').AsString; // do not localize trDescr := D.FieldByName('Descr').AsString; // do not localize trTotal := D.FieldByName('Total').AsCurrency; // do not localize trDesconto := D.FieldByName('Desconto').AsCurrency; // do not localize trPago := D.FieldByName('Pago').AsCurrency; // do not localize end; procedure TncTransacao.SaveToDataset(D: TDataset); begin if trID=-1 then D.FieldByname('ID').Clear else // do not localize D.FieldByName('ID').AsInteger := trID; // do not localize D.FieldByName('DataHora').AsDateTime := trDataHora; // do not localize D.FieldByName('Tipo').AsInteger := trTipo; // do not localize D.FieldByName('Cancelado').AsBoolean := trCancelado; // do not localize D.FieldByName('CanceladoPor').AsString := trCanceladoPor; // do not localize D.FieldByName('CanceladoEm').AsDateTime := trCanceladoEm; // do not localize D.FieldByName('Func').AsString := trFunc; // do not localize D.FieldByName('Descr').AsString := trDescr; // do not localize D.FieldByName('Total').AsCurrency := trTotal; // do not localize D.FieldByName('Desconto').AsCurrency := trDesconto; // do not localize D.FieldByName('Pago').AsCurrency := trPago; // do not localize end; procedure TncTransacao.SetString(const Value: String); var S: String; function _NextField: String; begin Result := GetNextStrDelim(S, classid_TncTransacao); end; begin S := Value; trID := StrToIntDef(_NextField, -1); trDataHora := DTFromStr(_NextField); trTipo := StrToIntDef(_NextField, 0); trCancelado := (_NextField = BoolStr[True]); trCanceladoPor := _NextField; trCanceladoEm := DTFromStr(_NextField); trFunc := _NextField; trDescr := _NextField; trTotal := StrParaFloat(_NextField); trDesconto := StrParaFloat(_NextField); trPago := StrParaFloat(_NextField); end; end.
unit ACadPaises; { Autor: Douglas Thomas Jacobsen Data Criação: 19/10/1999; Função: Cadastrar um novo Caixa Data Alteração: Alterado por: Motivo alteração: } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro, Constantes, StdCtrls, Buttons, Db, DBTables, Tabela, Mask, DBCtrls, Grids, DBGrids, DBKeyViolation, Localizacao, DBClient; type TFCadPaises = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; MoveBasico1: TMoveBasico; BotaoCadastrar1: TBotaoCadastrar; BAlterar: TBotaoAlterar; BotaoExcluir1: TBotaoExcluir; BotaoGravar1: TBotaoGravar; BotaoCancelar1: TBotaoCancelar; DATAPAISES: TDataSource; Label3: TLabel; ESiglaPais: TDBEditColor; Bevel1: TBevel; Label1: TLabel; EConsulta: TLocalizaEdit; CADPAISES: TSQL; BFechar: TBitBtn; GGrid: TGridIndice; ValidaGravacao: TValidaGravacao; Label4: TLabel; DBEditColor1: TDBEditColor; CADPAISESCOD_PAIS: TWideStringField; CADPAISESDES_PAIS: TWideStringField; CADPAISESDAT_ULTIMA_ALTERACAO: TSQLTimeStampField; CADPAISESCOD_IBGE: TFMTBCDField; DBEditColor2: TDBEditColor; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CADPAISESAfterInsert(DataSet: TDataSet); procedure CADPAISESAfterPost(DataSet: TDataSet); procedure CADPAISESAfterEdit(DataSet: TDataSet); procedure BFecharClick(Sender: TObject); procedure CADPAISESAfterCancel(DataSet: TDataSet); procedure GGridOrdem(Ordem: String); procedure PaisChange(Sender: TObject); procedure CADPAISESBeforePost(DataSet: TDataSet); private procedure ConfiguraConsulta( acao : Boolean); public { Public declarations } end; var FCadPaises: TFCadPaises; implementation uses APrincipal, UnSistema; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFCadPaises.FormCreate(Sender: TObject); begin CadPaises.open; end; { ******************* Quando o formulario e fechado ************************** } procedure TFCadPaises.FormClose(Sender: TObject; var Action: TCloseAction); begin CadPaises.Close; { fecha tabelas } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações da Tabela )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {***********************Gera o proximo codigo disponível***********************} procedure TFCadPaises.CADPAISESAfterInsert(DataSet: TDataSet); begin ESiglaPais.ReadOnly := False; ConfiguraConsulta(False); end; {******************************Atualiza a tabela*******************************} procedure TFCadPaises.CADPAISESAfterPost(DataSet: TDataSet); begin EConsulta.AtualizaTabela; ConfiguraConsulta(True); Sistema.MarcaTabelaParaImportar('CAD_PAISES'); end; {*********************Coloca o campo chave em read-only************************} procedure TFCadPaises.CADPAISESAfterEdit(DataSet: TDataSet); begin ESiglaPais.ReadOnly := true; ConfiguraConsulta(False); end; { ********************* quando cancela a operacao *************************** } procedure TFCadPaises.CADPAISESAfterCancel(DataSet: TDataSet); begin ConfiguraConsulta(True); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {****************************Fecha o Formulario corrente***********************} procedure TFCadPaises.BFecharClick(Sender: TObject); begin Close; end; {****** configura a consulta, caso edit ou insert enabled = false *********** } procedure TFCadPaises.ConfiguraConsulta( acao : Boolean); begin Label1.Enabled := acao; EConsulta.Enabled := acao; GGrid.Enabled := acao; end; procedure TFCadPaises.GGridOrdem(Ordem: String); begin EConsulta.AOrdem := ordem; end; procedure TFCadPaises.PaisChange(Sender: TObject); begin if (CadPaises.State in [dsInsert, dsEdit]) then ValidaGravacao.Execute; end; {******************** antes de gravar a alteracao *****************************} procedure TFCadPaises.CADPAISESBeforePost(DataSet: TDataSet); begin //atualiza a data de alteracao para poder exportar CADPAISESDAT_ULTIMA_ALTERACAO.AsDateTime := Sistema.RDataServidor; end; Initialization RegisterClasses([TFCadPaises]); end.
unit Perimeter; interface {$DEFINE HARDCORE_MODE} type TExternalChecking = record ProcPtr: function: LongWord; stdcall; DebuggerResult: LongWord; end; type TPerimeterInputData = record ResistanceType: LongWord; CheckingsType: LongWord; ExtProcOnChecking: TExternalChecking; ExtProcOnEliminating: procedure; MainFormHandle: THandle; Interval: integer; end; // Контрольные суммы основных функций: var ValidInitCRC: LongWord = $D5B7E6EF; ValidStopCRC: LongWord = $CC957F0F; ValidMainCRC: LongWord = $F25875E2; // Константы названий процессов для уничтожения: const Debuggers: array [0..1] of string = ( 'ollydbg.exe', 'idaq.exe' ); AdditionalProcesses: array [0..1] of string = ( 'java.exe', 'javaw.exe' ); SystemProcesses: array [0..3] of string = ( 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe' ); // Константы механизма противодействия: const Nothing = 0; ExternalEliminating = 1; // Внешняя процедура при ликвидации угрозы ShutdownProcess = 2; KillProcesses = 4; Notify = 8; BlockIO = 16; ShutdownPrimary = 32; ShutdownSecondary = 64; GenerateBSOD = 128; HardBSOD = 256; {$IFDEF HARDCORE_MODE} DestroyMBR = 512; {$ENDIF} // Константы-идентификаторы проверок: const ExternalChecking = 1; // Внешняя процедура при проверке LazyROM = 2; ROM = 4; PreventiveFlag = 8; ASM_A = 16; ASM_B = 32; IDP = 64; WINAPI_BP = 128; ZwSIT = 256; ZwQIP = 512; procedure InitPerimeter(const PerimeterInputData: TPerimeterInputData); procedure StopPerimeter; procedure DirectCall(Code: LongWord); procedure Emulate(Debugger: boolean; Breakpoint: boolean); procedure ChangeParameters(ResistanceType: LongWord; CheckingType: LongWord); procedure ChangeExternalProcedures(OnCheckingProc: pointer; DebuggerValue: LongWord; OnEliminatingProc: pointer); // Структуры с отладочной информацией type TFunctionInfo = record Address: pointer; Size: LongWord; Checksum: LongWord; ValidChecksum: LongWord; end; TFunctions = record Main: TFunctionInfo; Init: TFunctionInfo; Stop: TFunctionInfo; end; TASMInfo = record Value: LongWord; IsDebuggerExists: boolean; end; TDebugInfo = record ROMFailure: boolean; PrivilegesActivated: boolean; PreventiveProcessesExists: boolean; IsDebuggerPresent: boolean; Asm_A: TASMInfo; Asm_B: TASMInfo; ZwQIP: TASMInfo; ExternalChecking: TASMInfo; end; type TPerimeterInfo = record Functions: TFunctions; Debug: TDebugInfo; end; var PerimeterInfo: TPerimeterInfo; implementation {$R SOUNDS.RES} {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { WINDOWS } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} const ntdll = 'ntdll.dll'; kernel32 = 'kernel32.dll'; user32 = 'user32.dll'; winmm = 'winmm.dll'; advapi32 = 'advapi32.dll'; const VER_PLATFORM_WIN32_NT = 2; TOKEN_ADJUST_PRIVILEGES = $0020; TOKEN_QUERY = $0008; SE_PRIVILEGE_ENABLED = $00000002; ERROR_SUCCESS = 0; MB_ICONERROR = $00000010; STANDARD_RIGHTS_REQUIRED = $000F0000; SYNCHRONIZE = $00100000; PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $FFF); THREAD_PRIORITY_TIME_CRITICAL = 15; PROCESS_TERMINATE = $0001; type HWND = LongWord; WPARAM = Longint; LPARAM = Longint; UINT = LongWord; BOOL = LongBool; TLargeInteger = Int64; LPCSTR = PAnsiChar; FARPROC = Pointer; PULONG = ^Cardinal; _LUID_AND_ATTRIBUTES = packed record Luid: Int64; Attributes: LongWord; end; TLUIDAndAttributes = _LUID_AND_ATTRIBUTES; _TOKEN_PRIVILEGES = record PrivilegeCount: LongWord; Privileges: array [0..0] of TLUIDAndAttributes; end; TTokenPrivileges = _TOKEN_PRIVILEGES; TOKEN_PRIVILEGES = _TOKEN_PRIVILEGES; function TerminateProcess(Handle: LongWord; ExitCode: LongWord): LongWord; stdcall; external kernel32 name 'TerminateProcess'; function OpenProcess(dwDesiredAccess: LongWord; bInheritHandle: BOOL; dwProcessId: LongWord): THandle; stdcall; external kernel32 name 'OpenProcess'; function OpenProcessToken(ProcessHandle: THandle; DesiredAccess: LongWord; var TokenHandle: THandle): BOOL; stdcall; external advapi32 name 'OpenProcessToken'; function GetCurrentProcess: THandle; stdcall; external kernel32 name 'GetCurrentProcess'; function CloseHandle(hObject: THandle): BOOL; stdcall; external kernel32 name 'CloseHandle'; function LookupPrivilegeValue(lpSystemName, lpName: PChar; var lpLuid: Int64): BOOL; stdcall; external advapi32 name 'LookupPrivilegeValueA'; function AdjustTokenPrivileges(TokenHandle: THandle; DisableAllPrivileges: BOOL; const NewState: TTokenPrivileges; BufferLength: LongWord; var PreviousState: TTokenPrivileges; var ReturnLength: LongWord): BOOL; stdcall; external advapi32 name 'AdjustTokenPrivileges'; function GetCurrentThreadId: LongWord; stdcall; external kernel32 name 'GetCurrentThreadId'; function SetThreadAffinityMask(hThread: THandle; dwThreadAffinityMask: LongWord): LongWord; stdcall; external kernel32 name 'SetThreadAffinityMask'; function SetThreadPriority(hThread: THandle; nPriority: Integer): BOOL; stdcall; external kernel32 name 'SetThreadPriority'; function ReadProcessMemory(hProcess: THandle; const lpBaseAddress: Pointer; lpBuffer: Pointer; nSize: LongWord; var lpNumberOfBytesRead: LongWord): BOOL; stdcall; external kernel32 name 'ReadProcessMemory'; function GetModuleHandle(lpModuleName: PChar): HMODULE; stdcall; external kernel32 name 'GetModuleHandleA'; function LoadLibrary(lpLibFileName: PChar): HMODULE; stdcall; external kernel32 name 'LoadLibraryA'; function GetProcAddress(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall; external kernel32 name 'GetProcAddress'; function GetWindowThreadProcessId(hWnd: HWND; dwProcessId: pointer): LongWord; stdcall; external user32 name 'GetWindowThreadProcessId'; function GetCurrentThread: THandle; stdcall; external kernel32 name 'GetCurrentThread'; function GetCurrentProcessId: LongWord; stdcall; external kernel32 name 'GetCurrentProcessId'; {$IFDEF HARDCORE_MODE} var hDrive: LongWord; Data: pointer; WrittenBytes: LongWord; const GENERIC_ALL = $10000000; FILE_SHARE_READ = $00000001; FILE_SHARE_WRITE = $00000002; OPEN_EXISTING = 3; FILE_ATTRIBUTE_NORMAL = $00000080; type PSecurityAttributes = ^_SECURITY_ATTRIBUTES; _SECURITY_ATTRIBUTES = record nLength: LongWord; lpSecurityDescriptor: Pointer; bInheritHandle: LongBool; end; POverlapped = ^_OVERLAPPED; _OVERLAPPED = record Internal: LongWord; InternalHigh: LongWord; Offset: LongWord; OffsetHigh: LongWord; hEvent: THandle; end; var CreateFile: function( lpFileName: PAnsiChar; dwDesiredAccess, dwShareMode: LongWord; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: LongWord; hTemplateFile: THandle ): THandle; stdcall; WriteFile: function( hFile: THandle; const Buffer; nNumberOfBytesToWrite: LongWord; var lpNumberOfBytesWritten: LongWord; lpOverlapped: POverlapped ): LongBool; stdcall; {$ENDIF} {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { END OF WINDOWS } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { TLHELP32 } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} const TH32CS_SNAPPROCESS = $00000002; MAX_PATH = 260; type tagPROCESSENTRY32 = packed record dwSize: LongWord; cntUsage: LongWord; th32ProcessID: LongWord; th32DefaultHeapID: LongWord; th32ModuleID: LongWord; cntThreads: LongWord; th32ParentProcessID: LongWord; pcPriClassBase: Longint; dwFlags: LongWord; szExeFile: array[0..MAX_PATH - 1] of Char; end; TProcessEntry32 = tagPROCESSENTRY32; function CreateToolhelp32Snapshot(dwFlags, th32ProcessID: LongWord): THandle; stdcall; external kernel32 name 'CreateToolhelp32Snapshot'; function Process32First(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external kernel32 name 'Process32First'; function Process32Next(hSnapshot: THandle; var lppe: TProcessEntry32): BOOL; stdcall; external kernel32 name 'Process32Next'; {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { END OF TLHELP32 } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { SYSUTILS } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} // Переписанный и упрощённый ExtractFileName: function ExtractFileName(const FileName: string): string; var I: integer; Len: integer; DelimiterPos: integer; begin Result := ''; Len := Length(FileName); if FileName[1] = '\' then DelimiterPos := 1 else DelimiterPos := 0; for I := Len downto 1 do begin if FileName[I] = '\' then begin DelimiterPos := I; Break; end; end; inc(DelimiterPos); if DelimiterPos = 1 then begin Result := FileName; end else begin for I := DelimiterPos to Len do begin Result := Result + FileName[I]; end; end; end; // Оригинальный UpperCase от FastCode с комментариями: function UpperCase(const S: string): string; asm {Size = 134 Bytes} push ebx push edi push esi test eax, eax {Test for S = NIL} mov esi, eax {@S} mov edi, edx {@Result} mov eax, edx {@Result} jz @@Null {S = NIL} mov edx, [esi-4] {Length(S)} test edx, edx je @@Null {Length(S) = 0} mov ebx, edx call system.@LStrSetLength {Create Result String} mov edi, [edi] {@Result} mov eax, [esi+ebx-4] {Convert the Last 4 Characters of String} mov ecx, eax {4 Original Bytes} or eax, $80808080 {Set High Bit of each Byte} mov edx, eax {Comments Below apply to each Byte...} sub eax, $7B7B7B7B {Set High Bit if Original <= Ord('z')} xor edx, ecx {80h if Original < 128 else 00h} or eax, $80808080 {Set High Bit} sub eax, $66666666 {Set High Bit if Original >= Ord('a')} and eax, edx {80h if Orig in 'a'..'z' else 00h} shr eax, 2 {80h > 20h ('a'-'A')} sub ecx, eax {Clear Bit 5 if Original in 'a'..'z'} mov [edi+ebx-4], ecx sub ebx, 1 and ebx, -4 jmp @@CheckDone @@Null: pop esi pop edi pop ebx jmp System.@LStrClr @@Loop: {Loop converting 4 Character per Loop} mov eax, [esi+ebx] mov ecx, eax {4 Original Bytes} or eax, $80808080 {Set High Bit of each Byte} mov edx, eax {Comments Below apply to each Byte...} sub eax, $7B7B7B7B {Set High Bit if Original <= Ord('z')} xor edx, ecx {80h if Original < 128 else 00h} or eax, $80808080 {Set High Bit} sub eax, $66666666 {Set High Bit if Original >= Ord('a')} and eax, edx {80h if Orig in 'a'..'z' else 00h} shr eax, 2 {80h > 20h ('a'-'A')} sub ecx, eax {Clear Bit 5 if Original in 'a'..'z'} mov [edi+ebx], ecx @@CheckDone: sub ebx, 4 jnc @@Loop pop esi pop edi pop ebx end; {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { END OF SYSUTILS } {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} const Delta: single = 0.5; // Допуск по времени const SE_SHUTDOWN_NAME = 'SeShutdownPrivilege'; // привилегия, необходимая для // выполнения функций BSOD и // отключения питания SE_DEBUG_NAME = 'SeDebugPrivilege'; // Список параметров для первого способа выключения питания type SHUTDOWN_ACTION = ( ShutdownNoReboot, ShutdownReboot, ShutdownPowerOff ); // Список ВХОДНЫХ опций для функции BSOD'a: для генерации синего экрана // нужна последняя (OptionShutdownSystem). Если в вызове функции указать не её, а другую - // будет сгенерирован MessageBox с сообщением об ошибке, код которой // будет указан первым параметром этой функции. type HARDERROR_RESPONSE_OPTION = ( OptionAbortRetryIgnore, OptionOk, OptionOkCancel, OptionRetryCancel, OptionYesNo, OptionYesNoCancel, OptionShutdownSystem ); // Список ВЫХОДНЫХ опций для функции BSOD'a: type HARDERROR_RESPONSE = ( ResponseReturnToCaller, ResponseNotHandled, ResponseAbort, ResponseCancel, ResponseIgnore, ResponseNo, ResponseOk, ResponseRetry, ResponseYes ); type PSYSTEM_HANDLE_INFORMATION = ^SYSTEM_HANDLE_INFORMATION; SYSTEM_HANDLE_INFORMATION = packed record ProcessId: LongWord; ObjectTypeNumber: Byte; Flags: Byte; Handle: Word; pObject: Pointer; GrantedAccess: LongWord; end; type PSYSTEM_HANDLE_INFORMATION_EX = ^SYSTEM_HANDLE_INFORMATION_EX; SYSTEM_HANDLE_INFORMATION_EX = packed record NumberOfHandles: LongWord; Information: array [0..0] of SYSTEM_HANDLE_INFORMATION; end; type // Объявление типов из NTDDK POWER_ACTION = integer; SYSTEM_POWER_STATE = integer; ULONG = cardinal; NTStatus = LongWord; PVoid = pointer; const // Номера ошибок, с которыми вызывается синий экран. TRUST_FAILURE = $C0000250; LOGON_FAILURE = $C000006C; HOST_DOWN = $C0000350; FAILED_DRIVER_ENTRY = $C0000365; NT_SERVER_UNAVAILABLE = $C0020017; NT_CALL_FAILED = $C002001B; CLUSTER_POISONED = $C0130017; FATAL_UNHANDLED_HARD_ERROR = $0000004C; STATUS_SYSTEM_PROCESS_TERMINATED = $C000021A; const // Создаём массив из кодов ошибок чтобы удобнее было ими оперировать ErrorCode: array [0..8] of LongWord = ( TRUST_FAILURE, LOGON_FAILURE, HOST_DOWN, FAILED_DRIVER_ENTRY, NT_SERVER_UNAVAILABLE, NT_CALL_FAILED, CLUSTER_POISONED, FATAL_UNHANDLED_HARD_ERROR, STATUS_SYSTEM_PROCESS_TERMINATED ); // Делаем заготовки для импортируемых функций и пишем вспомогательные переменные: var // 1й способ отключения питания: ZwShutdownSystem: procedure (Action: SHUTDOWN_ACTION); stdcall; // 2й способ отключения питания: ZwInitiatePowerAction: procedure ( SystemAction: POWER_ACTION; MinSystemState: SYSTEM_POWER_STATE; Flags: ULONG; Asynchronous: BOOL ); stdcall; // BSOD: HR: HARDERROR_RESPONSE; ZwRaiseHardError: procedure ( ErrorStatus: NTStatus; NumberOfParameters: ULong; UnicodeStringParameterMask: PChar; Parameters: PVoid; ResponseOption: HARDERROR_RESPONSE_OPTION; PHardError_Response: pointer ); stdcall; // Завершение процесса из ядра LdrShutdownProcess: procedure; stdcall; ZwTerminateProcess: function(Handle: LongWord; ExitStatus: LongWord): NTStatus; stdcall; //LdrShutdownThread: procedure; stdcall; // Отключение клавиатуры и мыши: BlockInput: function (Block: BOOL): BOOL; stdcall; // Проверка наличия отладчика: IsDebuggerPresent: function: boolean; stdcall; ZwQueryInformationProcess: function (ProcessHandle: THANDLE; ProcessInformationClass: LongWord; ProcessInformation: pointer; ProcessInformationLength: ULONG; ReturnLength: PULONG): NTStatus; stdcall; ZwSetInformationThread: procedure; stdcall; // Маскируем стандартные функции, используем "ручной" вызов: MsgBox: procedure (hWnd: HWND; lpText: PAnsiChar; lpCaption: PAnsiChar; uType: Cardinal); stdcall; PlaySound: procedure (pszSound: string; hMod: HModule; fdwSound: LongWord); stdcall; QueryPerformanceFrequency: procedure (var lpFrequency: Int64); stdcall; QueryPerformanceCounter: procedure (var lpPerformanceCount: Int64); stdcall; SendMessage: procedure (hWnd: HWND; Msg: LongWord; wParam: WPARAM; lParam: LPARAM); stdcall; Sleep: procedure (SuspendTime: LongWord); stdcall; OpenThread: function (dwDesiredAccess: LongWord; bInheritHandle: boolean; dwThreadId: LongWord): THandle; stdcall; // Имена библиотек и вызываемых функций: const // Из ntdll: sZwRaiseHardError: PAnsiChar = 'ZwRaiseHardError'; sZwShutdownSystem: PAnsiChar = 'ZwShutdownSystem'; sZwInitiatePowerAction: PAnsiChar = 'ZwInitiatePowerAction'; sLdrShutdownProcess: PAnsiChar = 'LdrShutdownProcess'; sZwSetInformationThread: PAnsiChar = 'ZwSetInformationThread'; sZwQueryInformationProcess: PAnsiChar = 'ZwQueryInformationProcess'; sZwTerminateProcess: PAnsiChar = 'ZwTerminateProcess'; //sLdrShutdownThread: PAnsiChar = 'LdrShutdownThread'; // Из kernel32: sIsDebuggerPresent: PAnsiChar = 'IsDebuggerPresent'; sQueryPerformanceFrequency: PAnsiChar = 'QueryPerformanceFrequency'; sQueryPerformanceCounter: PAnsiChar = 'QueryPerformanceCounter'; sSleep: PAnsiChar = 'Sleep'; sOutputDebugStringA: PAnsiChar = 'OutputDebugStringA'; sOpenThread: PAnsiChar = 'OpenThread'; {$IFDEF HARDCORE_MODE} sCreateFileA: PAnsiChar = 'CreateFileA'; sWriteFile: PAnsiChar = 'WriteFile'; {$ENDIF} // Из user32: sMessageBox: PAnsiChar = 'MessageBoxA'; sBlockInput: PAnsiChar = 'BlockInput'; sSendMessage: PAnsiChar = 'SendMessageA'; // Из winmm: sPlaySound: PAnsiChar = 'PlaySoundA'; SND_RESOURCE = $00040004; SND_LOOP = $0008; SND_ASYNC = $0001; // Тип внешних проверок: type TExternalGuard = record OnChecking: TExternalChecking; OnEliminating: procedure; end; var ExternalGuard: TExternalGuard; // Рабочие переменные var GlobalInitState: boolean = false; TypeOfResistance: LongWord; TypeOfChecking: LongWord; ThreadID: LongWord; ThreadHandle: integer; FormHandle: THandle; // Хэндл формы, которой будут посылаться сообщения Active: boolean = false; Delay: integer; // Переменные эмуляции отладчика и брейкпоинта: EmuDebugger: boolean = false; EmuBreakpoint: boolean = false; // Переменные сканирования памяти: Process: THandle; InitAddress, StopAddress, MainAddress: pointer; InitSize, StopSize, MainSize: integer; var CRCtable: array[0..255] of cardinal; function CRC32(InitCRC32: cardinal; StPtr: pointer; StLen: integer): cardinal; asm test edx,edx; jz @ret; neg ecx; jz @ret; sub edx,ecx; push ebx; mov ebx,0; @next: mov bl,al; xor bl,byte [edx+ecx]; shr eax,8; xor eax,cardinal [CRCtable+ebx*4]; inc ecx; jnz @next; pop ebx; xor eax, $FFFFFFFF @ret: end; procedure CRCInit; var c: cardinal; i, j: integer; begin for i := 0 to 255 do begin c := i; for j := 1 to 8 do if odd(c) then c := (c shr 1) xor $EDB88320 else c := (c shr 1); CRCtable[i] := c; end; end; {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} function IsProcLaunched(ProcessName: string): boolean; var hSnap: THandle; PE: TProcessEntry32; begin Result := false; PE.dwSize := SizeOf(PE); hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if Process32First(hSnap, PE) then begin if PE.szExeFile = ProcessName then begin Result := true; end else begin while Process32Next(hSnap, PE) do begin if PE.szExeFile = ProcessName then begin Result := true; Break; end; end; end; end; end; // Функция, убивающая процесс по его имени: function KillTask(ExeFileName: string): integer; var Co: BOOL; FS: THandle; FP: TProcessEntry32; begin result := 0; FS := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); FP.dwSize := Sizeof(FP); Co := Process32First(FS,FP); while integer(Co) <> 0 do begin if ((UpperCase(ExtractFileName(FP.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FP.szExeFile) = UpperCase(ExeFileName))) then Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), FP.th32ProcessID), 0)); Co := Process32Next(FS, FP); end; CloseHandle(FS); end; // Установка привилегий function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean; var hToken: THandle; TokenPriv: TOKEN_PRIVILEGES; PrevTokenPriv: TOKEN_PRIVILEGES; ReturnLength: Cardinal; begin if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin if LookupPrivilegeValue(nil, PChar(sPrivilege), TokenPriv.Privileges[0].Luid) then begin TokenPriv.PrivilegeCount := 1; case bEnabled of True: TokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; False: TokenPriv.Privileges[0].Attributes := 0; end; ReturnLength := 0; PrevTokenPriv := TokenPriv; AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv), PrevTokenPriv, ReturnLength); end; CloseHandle(hToken); end; Result := GetLastError = ERROR_SUCCESS; end; procedure InitFunctions; var hUser32: THandle; hKernel32: THandle; hNtdll: THandle; hWinMM: THandle; begin // Присваиваем процессу привилегию SE_SHUTDOWN_NAME: PerimeterInfo.Debug.PrivilegesActivated := NTSetPrivilege(SE_SHUTDOWN_NAME, true) and NTSetPrivilege(SE_DEBUG_NAME, true); // Получаем хэндлы библиотек: hUser32 := LoadLibrary(user32); hKernel32 := LoadLibrary(kernel32); hNtdll := GetModuleHandle(ntdll); hWinMM := LoadLibrary(winmm); // Получаем адреса функций в библиотеках: // kernel32: IsDebuggerPresent := GetProcAddress(hKernel32, sIsDebuggerPresent); QueryPerformanceFrequency := GetProcAddress(hKernel32, sQueryPerformanceFrequency); QueryPerformanceCounter := GetProcAddress(hKernel32, sQueryPerformanceCounter); Sleep := GetProcAddress(hKernel32, sSleep); OpenThread := GetProcAddress(hKernel32, sOpenThread); {$IFDEF HARDCORE_MODE} CreateFile := GetProcAddress(hKernel32, sCreateFileA); WriteFile := GetProcAddress(hKernel32, sWriteFile); {$ENDIF} // user32: BlockInput := GetProcAddress(hUser32, sBlockInput); MsgBox := GetProcAddress(hUser32, sMessageBox); SendMessage := GetProcAddress(hUser32, sSendMessage); // winmm: PlaySound := GetProcAddress(hWinMM, sPlaySound); // ntdll: ZwRaiseHardError := GetProcAddress(hNtdll, sZwRaiseHardError); ZwShutdownSystem := GetProcAddress(hNtdll, sZwShutdownSystem); ZwInitiatePowerAction := GetProcAddress(hNtdll, sZwInitiatePowerAction); LdrShutdownProcess := GetProcAddress(hNtdll, sLdrShutdownProcess); ZwSetInformationThread := GetProcAddress(hNtdll, sZwSetInformationThread); ZwQueryInformationProcess := GetProcAddress(hNtdll, sZwQueryInformationProcess); ZwTerminateProcess := GetProcAddress(hNtdll, sZwTerminateProcess); // LdrShutdownThread := GetProcAddress(hNtdll, sLdrShutdownThread); GlobalInitState := true; end; procedure DirectCall(Code: LongWord); var I: byte; ProcLength, AdditionalLength: byte; begin if not GlobalInitState then InitFunctions; case Code of Nothing: Exit; ShutdownProcess: begin LdrShutdownProcess; ZwTerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), GetCurrentProcessId), 0); end; KillProcesses: begin ProcLength := Length(Debuggers) - 1; for I := 0 to ProcLength do begin KillTask(Debuggers[I]); end; AdditionalLength := Length(AdditionalProcesses); Dec(AdditionalLength); for I := 0 to AdditionalLength do begin KillTask(AdditionalProcesses[I]); end; end; Notify: begin PlaySound('ALERT', 0, SND_RESOURCE or SND_ASYNC or SND_LOOP); MsgBox(FormHandle, 'Внутренняя ошибка! Продолжение невозможно!', 'Угроза внутренней безопасности!', MB_ICONERROR); LdrShutdownProcess; ZwTerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), GetCurrentProcessId), 0); end; BlockIO: BlockInput(true); ShutdownPrimary: ZwShutdownSystem(SHUTDOWN_ACTION(0)); ShutdownSecondary: ZwInitiatePowerAction(4, 6, 0, true); GenerateBSOD: ZwRaiseHardError(ErrorCode[2], 0, nil, nil, HARDERROR_RESPONSE_OPTION(6), @HR); HardBSOD: begin ProcLength := Length(SystemProcesses) - 1; for I := 0 to ProcLength do begin KillTask(SystemProcesses[I]); end; end; {$IFDEF HARDCORE_MODE} DestroyMBR: begin hDrive := CreateFile('\\.\PhysicalDrive0', GENERIC_ALL, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); GetMem(Data, 512); FillChar(Data^, 512, #0); WriteFile(hDrive, Data^, 512, WrittenBytes, nil); CloseHandle(hDrive); FreeMem(Data); end; {$ENDIF} end; end; // Основной поток: проверка на наличие отладчика, проверка на брейкпоинты procedure MainThread; const DebuggerMsg: byte = 0; BreakpointMsg: byte = 1; var MessageType: byte; // Тип текста в оповещении: // 0 = Отладчик // 1 = Брейкпоинт // 2 = Несовпадение контрольных сумм ProcLength: byte; procedure EliminateThreat; var NotifyMessage: PAnsiChar; CaptionMessage: PAnsiChar; BSODErrorCode: byte; I: byte; AdditionalLength: byte; begin // Исполняем внешнюю процедуру уничтожения угрозы: if (TypeOfResistance and ExternalEliminating) = ExternalEliminating then begin ExternalGuard.OnEliminating end; // Убиваем свой процесс из ядра: if (TypeOfResistance and ShutdownProcess) = ShutdownProcess then begin LdrShutdownProcess; ZwTerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), GetCurrentProcessId), 0); end; // Убиваем процессы: if (TypeOfResistance and KillProcesses) = KillProcesses then begin for I := 0 to ProcLength do begin KillTask(Debuggers[I]); end; AdditionalLength := Length(AdditionalProcesses); Dec(AdditionalLength); for I := 0 to AdditionalLength do begin KillTask(AdditionalProcesses[I]); end; end; // Выводим сообщение и закрываем программу: if (TypeOfResistance and Notify) = Notify then begin PlaySound('ALERT', 0, SND_RESOURCE or SND_ASYNC or SND_LOOP); CaptionMessage := 'Угроза внутренней безопасности!'; NotifyMessage := 'Внутренняя ошибка! Продолжение невозможно!'; case MessageType of 0: NotifyMessage := 'Обнаружен отладчик! Продолжение невозможно!'; 1: NotifyMessage := 'Обнаружен брейкпоинт! Продолжение невозможно!'; 2: begin NotifyMessage := 'ROM damaged!'; CaptionMessage := 'System Failure'; end; end; MsgBox(FormHandle, NotifyMessage, CaptionMessage, MB_ICONERROR); LdrShutdownProcess; ZwTerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), GetCurrentProcessId), 0); end; // Блокируем клавиатуру и мышь: if (TypeOfResistance and BlockIO) = BlockIO then begin BlockInput(true); end; // Выключаем питание первым способом: if (TypeOfResistance and ShutdownPrimary) = ShutdownPrimary then begin ZwShutdownSystem(SHUTDOWN_ACTION(0)); end; // Выключаем питание вторым способом: if (TypeOfResistance and ShutdownSecondary) = ShutdownSecondary then begin ZwInitiatePowerAction(4, 6, 0, true); end; // Выводим BSOD: if (TypeOfResistance and GenerateBSOD) = GenerateBSOD then begin BSODErrorCode := Random(6); ZwRaiseHardError(ErrorCode[BSODErrorCode], 0, nil, nil, HARDERROR_RESPONSE_OPTION(6), @HR); end; // Тяжёлый BSOD - убиваем csrss.exe и smss.exe if (TypeOfResistance and HardBSOD) = HardBSOD then begin ProcLength := Length(SystemProcesses) - 1; for I := 0 to ProcLength do begin KillTask(SystemProcesses[I]); end; end; {$IFDEF HARDCORE_MODE} if (TypeOfResistance and DestroyMBR) = DestroyMBR then begin hDrive := CreateFile('\\.\PhysicalDrive0', GENERIC_ALL, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); GetMem(Data, 512); FillChar(Data^, 512, #0); WriteFile(hDrive, Data^, 512, WrittenBytes, nil); CloseHandle(hDrive); FreeMem(Data); end; {$ENDIF} end; procedure ReStruct; var PrivilegesState: boolean; begin with PerimeterInfo do begin PrivilegesState := Debug.PrivilegesActivated; FillChar(Debug, SizeOf(Debug), #0); Debug.PrivilegesActivated := PrivilegesState; Functions.Main.Checksum := 0; Functions.Init.Checksum := 0; Functions.Stop.Checksum := 0; end; end; var iCounterPerSec: TLargeInteger; T1, T2: TLargeInteger; ElapsedTime: single; DebuggerState, BreakpointState: byte; // Для проверки памяти: Buffer: pointer; ByteReaded: Cardinal; // Список процессов: IsProcExists: boolean; I: byte; // Отладочные переменные: FullState: boolean; // Перенос на отдельное ядро: ThreadID: LongWord; ThreadHandle: THandle; begin PerimeterInfo.Debug.PrivilegesActivated := NTSetPrivilege(SE_SHUTDOWN_NAME, true) and NTSetPrivilege(SE_DEBUG_NAME, true); // Выполняем на нулевом ядре: ThreadID := GetCurrentThreadId; ThreadHandle := OpenThread(PROCESS_ALL_ACCESS, false, ThreadId); SetThreadAffinityMask(ThreadHandle, 1); CloseHandle(ThreadHandle); // Задаём максимальный приоритет потока: SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL); QueryPerformanceFrequency(iCounterPerSec); ProcLength := Length(Debuggers) - 1; // DebuggerState := $0D // не инициализируем, т.к. он инициализируется в первом условии BreakpointState := $0B; IsProcExists := false; while Active do begin ReStruct; FullState := false; if (TypeOfChecking and WINAPI_BP) = WINAPI_BP then begin QueryPerformanceCounter(T1); end; if (TypeOfChecking and PreventiveFlag) = PreventiveFlag then begin IsProcExists := false; for I := 0 to ProcLength do begin IsProcExists := IsProcExists or IsProcLaunched(Debuggers[I]); end; PerimeterInfo.Debug.PreventiveProcessesExists := IsProcExists; end; if (TypeOfChecking and ROM) = ROM then begin GetMem(Buffer, InitSize); ReadProcessMemory(Process, InitAddress, Buffer, InitSize, ByteReaded); PerimeterInfo.Functions.Init.Checksum := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); GetMem(Buffer, StopSize); ReadProcessMemory(Process, StopAddress, Buffer, StopSize, ByteReaded); PerimeterInfo.Functions.Stop.Checksum := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); GetMem(Buffer, MainSize); ReadProcessMemory(Process, MainAddress, Buffer, MainSize, ByteReaded); PerimeterInfo.Functions.Main.Checksum := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); if (PerimeterInfo.Functions.Main.Checksum <> ValidMainCRC) or (PerimeterInfo.Functions.Init.Checksum <> ValidInitCRC) or (PerimeterInfo.Functions.Stop.Checksum <> ValidStopCRC) then begin PerimeterInfo.Debug.ROMFailure := true; end else begin PerimeterInfo.Debug.ROMFailure := false; end; end; if (TypeOfChecking and ExternalChecking) = ExternalChecking then begin PerimeterInfo.Debug.ExternalChecking.Value := ExternalGuard.OnChecking.ProcPtr; if PerimeterInfo.Debug.ExternalChecking.Value = ExternalGuard.OnChecking.DebuggerResult then begin PerimeterInfo.Debug.ExternalChecking.IsDebuggerExists := true; FullState := true; end; end; asm mov eax, TypeOfChecking mov ecx, ASM_A and eax, ecx cmp eax, ecx jne @Continue_A // Anti-Debugging A: mov eax, fs:[30h] mov eax, [eax+2] add eax, 65536 mov PerimeterInfo.Debug.Asm_A.Value, eax test eax, eax jnz @A_Debugger mov PerimeterInfo.Debug.Asm_A.IsDebuggerExists, false jmp @Continue_A @A_Debugger: mov PerimeterInfo.Debug.Asm_A.IsDebuggerExists, true @Continue_A: mov eax, TypeOfChecking mov ecx, ASM_B and eax, ecx cmp eax, ecx jne @Continue_B // Anti-Debugging B: mov eax, fs:[30h] mov eax, [eax+68h] mov PerimeterInfo.Debug.Asm_B.Value, eax and eax, 70h test eax, eax jnz @B_Debugger mov PerimeterInfo.Debug.Asm_B.IsDebuggerExists, false jmp @Continue_B @B_Debugger: mov PerimeterInfo.Debug.Asm_B.IsDebuggerExists, true @Continue_B: mov eax, TypeOfChecking mov ecx, ZwSIT and eax, ecx cmp eax, ecx jne @Pass_ZwSIT push 0 push 0 push 11h push -2 call ZwSetInformationThread // будем отключены от отладчика @Pass_ZwSIT: // Финальный аккорд - используем ZwQueryInformationProcess mov eax, TypeOfChecking mov ecx, ZwQIP and eax, ecx cmp eax, ecx jne @Pass_ZwQIP push eax mov eax, esp push 0 push 4 // ProcessInformationLength push eax push 1fh // ProcessDebugFlags push -1 // GetCurrentProcess() call ZwQueryInformationProcess pop eax test eax, eax je @ZwQIP_Debugger // Первый способ провалился? Не беда! Используем второй! :D // Однако этот способ может не работать в новых Windows NT! push eax mov eax, esp push 0 push 2 // ProcessInformationLength push eax // SystemKernelDebuggerInformation push 23h push -1 // GetCurrentProcess() call ZwQueryInformationProcess pop eax test ah, ah mov PerimeterInfo.Debug.ZwQIP.Value, eax jnz @ZwQIP_Debugger // Не нашли отладчик?? О_о Бывает и такое... mov PerimeterInfo.Debug.ZwQIP.IsDebuggerExists, false jmp @Pass_ZwQIP @ZwQIP_Debugger: mov PerimeterInfo.Debug.ZwQIP.IsDebuggerExists, true @Pass_ZwQIP: end; with PerimeterInfo.Debug do begin FullState := FullState or Asm_A.IsDebuggerExists or Asm_B.IsDebuggerExists or ZwQIP.IsDebuggerExists; end; if (TypeOfChecking and IDP) = IDP then begin PerimeterInfo.Debug.IsDebuggerPresent := IsDebuggerPresent; end; if (PerimeterInfo.Debug.IsDebuggerPresent = true) or (EmuDebugger = true) or ((IsProcExists = true) and ((TypeOfChecking and PreventiveFlag) = PreventiveFlag)) or (FullState = true) or (PerimeterInfo.Debug.ROMFailure = true) then begin if EmuDebugger = false then begin DebuggerState := $FD; end else begin DebuggerState := $ED; end; SendMessage(FormHandle, $FFF, DebuggerState, BreakpointState); if PerimeterInfo.Debug.ROMFailure = true then MessageType := 2 else MessageType := 0; EliminateThreat; end else begin DebuggerState := $0D; SendMessage(FormHandle, $FFF, DebuggerState, BreakpointState); end; sleep(Delay); if (TypeOfChecking and WINAPI_BP) = WINAPI_BP then begin QueryPerformanceCounter(T2); ElapsedTime := (T2 - T1) / iCounterPerSec; if (ElapsedTime > Delay + Delta) or (EmuBreakpoint = true) or (ElapsedTime <= 0) then begin if EmuBreakpoint = false then begin BreakpointState := $FB; end else begin BreakpointState := $EB; end; SendMessage(FormHandle, $FFF, DebuggerState, BreakpointState); MessageType := 1; EliminateThreat end else begin BreakpointState := $0B; SendMessage(FormHandle, $FFF, DebuggerState, BreakpointState); end; end else begin // Если проверка на брейкпоинты отключена, // то отправляем сообщение об их отсутствии: BreakpointState := $0B; SendMessage(FormHandle, $FFF, DebuggerState, BreakpointState); end; end; // Посылаем сообщение о завершении работы: SendMessage(FormHandle, $FFF, $00, $00); // Чистим память от адресов функций: asm xor eax, eax mov IsDebuggerPresent, eax; mov BlockInput, eax; mov ZwRaiseHardError, eax; mov ZwShutdownSystem, eax; mov ZwInitiatePowerAction, eax; mov LdrShutdownProcess, eax; mov ZwSetInformationThread, eax; mov OpenThread, eax; mov MsgBox, eax; mov QueryPerformanceCounter, eax; mov QueryPerformanceFrequency, eax; mov PlaySound, eax; mov Sleep, eax; mov SendMessage, eax; end; GlobalInitState := false; EndThread(0); end; procedure InitPerimeter(const PerimeterInputData: TPerimeterInputData); var // Переменные для инициализации основного процесса: ProcessID: LongWord; InitInt, StopInt, EmulateInt, MainInt: integer; EmulateAddress: pointer; // Для "ленивой" проверки памяти: Buffer: pointer; ByteReaded: LongWord; begin CRCInit; if not GlobalInitState then InitFunctions; with PerimeterInputData do begin // Инициализируем наш процесс для возможности чтения памяти: GetWindowThreadProcessID(MainFormHandle, @ProcessID); Process := OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessID); // Получаем адреса и размеры функций: InitAddress := @InitPerimeter; StopAddress := @StopPerimeter; EmulateAddress := @Emulate; MainAddress := @IsProcLaunched; InitInt := Integer(InitAddress); StopInt := Integer(StopAddress); EmulateInt := Integer(EmulateAddress); MainInt := Integer(MainAddress); InitSize := StopInt - InitInt; StopSize := EmulateInt - StopInt; MainSize := InitInt - MainInt; PerimeterInfo.Functions.Main.Address := MainAddress; PerimeterInfo.Functions.Main.Size := MainSize; PerimeterInfo.Functions.Main.ValidChecksum := ValidMainCRC; PerimeterInfo.Functions.Init.Address := InitAddress; PerimeterInfo.Functions.Init.Size := InitSize; PerimeterInfo.Functions.Init.ValidChecksum := ValidInitCRC; PerimeterInfo.Functions.Stop.Address := StopAddress; PerimeterInfo.Functions.Stop.Size := StopSize; PerimeterInfo.Functions.Stop.ValidChecksum := ValidStopCRC; if (CheckingsType and LazyROM) = LazyROM then begin //************************************************************************** GetMem(Buffer, InitSize); ReadProcessMemory(Process, InitAddress, Buffer, InitSize, ByteReaded); ValidInitCRC := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); GetMem(Buffer, StopSize); ReadProcessMemory(Process, StopAddress, Buffer, StopSize, ByteReaded); ValidStopCRC := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); GetMem(Buffer, MainSize); ReadProcessMemory(Process, MainAddress, Buffer, MainSize, ByteReaded); ValidMainCRC := CRC32($FFFFFFFF, Buffer, ByteReaded); FreeMem(Buffer); //************************************************************************** end; // Сбрасываем генератор псевдослучайных чисел: Randomize; // Получаем директивы противодействия: TypeOfResistance := ResistanceType; // Получаем интервал между сканированием: Delay := Interval; // Получаем включение и адреса внешних процедур: ExternalGuard.OnChecking.ProcPtr := ExtProcOnChecking.ProcPtr; ExternalGuard.OnChecking.DebuggerResult := ExtProcOnChecking.DebuggerResult; ExternalGuard.OnEliminating := ExtProcOnEliminating; // Запускаем защиту: Active := true; FormHandle := MainFormHandle; // Убеждаемся в выключении эмуляции: //EmuDebugger := false; //EmuBreakpoint := false; TypeOfChecking := CheckingsType; ThreadHandle := BeginThread(nil, 0, Addr(MainThread), nil, 0, ThreadID); CloseHandle(ThreadHandle); end; // Посылаем сообщение об успешном запуске: SendMessage(FormHandle, $FFF, $FF, $FF); end; procedure StopPerimeter; begin Active := false; // Сигнал к завершению основного потока // Очистка адресов функций перенесена в MainThread // Выключаем эмуляцию отладчика и брейкпоинта: //EmuDebugger := false; //EmuBreakpoint := false; end; procedure Emulate(Debugger: boolean; Breakpoint: boolean); begin EmuDebugger := Debugger; EmuBreakpoint := Breakpoint; end; procedure ChangeParameters(ResistanceType: LongWord; CheckingType: LongWord); begin TypeOfResistance := ResistanceType; TypeOfChecking := CheckingType; end; procedure ChangeExternalProcedures(OnCheckingProc: pointer; DebuggerValue: LongWord; OnEliminatingProc: pointer); begin ExternalGuard.OnChecking.ProcPtr := OnCheckingProc; ExternalGuard.OnChecking.DebuggerResult := DebuggerValue; ExternalGuard.OnEliminating := OnEliminatingProc; end; end.
unit Persistence.CodeGenerator.IBX; interface uses System.Classes, IBX.IBDatabase, IBX.IBCustomDataSet, Persistence.CodeGenerator.Abstract, Spring.Persistence.Mapping.CodeGenerator.Abstract; {$M+} type TCodeGeneratorIBX = class(TCodeGenerator<TIBDataBase>) private const StatementForAllPrimaryKey = 'SELECT ' + ' RC.RDB$RELATION_NAME AS TABLENAME, ' + ' SG.RDB$FIELD_NAME AS FIELDNAME, ' + ' IX.RDB$INDEX_NAME AS INDEXNAME ' + 'FROM ' + ' RDB$INDICES IX ' + ' LEFT JOIN RDB$INDEX_SEGMENTS SG ON IX.RDB$INDEX_NAME = SG.RDB$INDEX_NAME ' + ' LEFT JOIN RDB$RELATION_CONSTRAINTS RC ON RC.RDB$INDEX_NAME = IX.RDB$INDEX_NAME ' + 'WHERE ' + ' RC.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'''; private const StatementForFields = 'SELECT ' + ' R.RDB$FIELD_NAME, ' + ' F.RDB$FIELD_LENGTH, ' + ' F.RDB$FIELD_SCALE, ' + ' F.RDB$FIELD_TYPE, ' + ' CASE F.RDB$FIELD_TYPE ' + ' WHEN ''7'' THEN ''SMALLINT'' ' + ' WHEN ''8'' THEN ''INTEGER'' ' + ' WHEN ''10'' THEN ''FLOAT'' ' + ' WHEN ''12'' THEN ''DATE'' ' + ' WHEN ''13'' THEN ''TIME'' ' + ' WHEN ''14'' THEN ''CHAR'' ' + ' WHEN ''16'' THEN ''BIGINT'' ' + ' WHEN ''27'' THEN ''DOUBLE PRECISION'' ' + ' WHEN ''35'' THEN ''TIMESTAMP'' ' + ' WHEN ''37'' THEN ''VARCHAR'' ' + ' WHEN ''261'' THEN ''BLOB'' ' + ' ELSE F.RDB$FIELD_TYPE ' + ' END FieldTypDescription ' + 'FROM ' + ' RDB$RELATION_FIELDS R ' + ' LEFT JOIN RDB$FIELDS F ON F.RDB$FIELD_NAME = R.RDB$FIELD_SOURCE ' + ' LEFT JOIN RDB$TYPES T ON T.RDB$TYPE = F.RDB$FIELD_TYPE ' + 'WHERE ' + ' R.RDB$RELATION_NAME = ''CUSTOMER'' AND T.RDB$FIELD_NAME = ''RDB$FIELD_TYPE'' ' + 'ORDER BY ' + ' R.RDB$FIELD_POSITION; '; strict private FPrimaryKeys: TStringList; private function GetIBDataSet(const AStatement: string): TIBDataSet; procedure GeneratorColumns(const ATablename: string; const AEntityData: TEntityModelData); procedure FindAllAllPrimaryKeys(); procedure InnerGenerator(); public constructor Create; destructor Destroy; override; procedure Generate(); override; end; {$M-} implementation uses System.SysUtils, Spring.Persistence.Mapping.CodeGenerator; { TCodeGeneratorIBX<TIBDataBase> } constructor TCodeGeneratorIBX.Create; begin inherited; FPrimaryKeys := TStringList.Create; end; destructor TCodeGeneratorIBX.Destroy; begin FPrimaryKeys.Free; inherited; end; procedure TCodeGeneratorIBX.Generate(); begin inherited; FindAllAllPrimaryKeys; InnerGenerator; end; procedure TCodeGeneratorIBX.GeneratorColumns; var LDataSet: TIBDataSet; LColumn: TColumnData; begin LDataSet := GetIBDataSet(Format(StatementForFields, [ATablename])); try while not LDataSet.Eof do begin LColumn := TColumnData.Create; LColumn.ColumnName := LDataSet.Fields[0].AsString.Trim; LColumn.ColumnTypeName := LDataSet.Fields[4].AsString.Trim; if (LDataSet.Fields[3].AsInteger = 14) or (LDataSet.Fields[3].AsInteger = 37) then LColumn.ColumnLength := LDataSet.Fields[1].AsInteger; if (FPrimaryKeys.IndexOf(ATablename + LDataSet.Fields[0].AsString.Trim) > 0) then begin // Only my variant, has to be adapted if necessary... LColumn.IsAutogenerated := True; LColumn.IsPrimaryKey := True; LColumn.IsRequired := True; LColumn.NotNull := True; end; AEntityData.Columns.Add(LColumn); LDataSet.Next; end; finally LDataSet.Free(); end; end; function TCodeGeneratorIBX.GetIBDataSet(const AStatement: string): TIBDataSet; begin Result := TIBDataSet.Create(nil); Result.Database := Database; Result.Transaction := Database.Transactions[Database.TransactionCount - 1]; Result.SelectSQL.Text := AStatement; Result.Open(); Result.First; end; procedure TCodeGeneratorIBX.FindAllAllPrimaryKeys; var LDataSet: TIBDataSet; begin LDataSet := GetIBDataSet(StatementForAllPrimaryKey); try while not LDataSet.Eof do begin FPrimaryKeys.Add(LDataSet.Fields[0].AsString.Trim + LDataSet.Fields[1].AsString.Trim); LDataSet.Next; end; finally LDataSet.Free(); end; end; procedure TCodeGeneratorIBX.InnerGenerator; var LEachTable: string; LTables: TStringList; LEntityData: TEntityModelData; LGenerator: TDelphiUnitCodeGenerator; begin LGenerator := TDelphiUnitCodeGenerator.Create; LTables := TStringList.Create; try Database.GetTableNames(LTables); for LEachTable in LTables do begin LEntityData := TEntityModelData.Create; try LEntityData.TableName := LEachTable; GeneratorColumns(LEachTable, LEntityData); TablesWithField.Add(LEachTable, LGenerator.Generate(LEntityData)); finally LEntityData.Free; end; end; finally LGenerator.Free; LTables.Free; end; end; end.
// // Created by the DataSnap proxy generator. // 2017-06-09 ¿ÀÀü 10:27:09 // unit UClientClass; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FCheckLoginCommand: TDBXCommand; FDuplicatedIDCommand: TDBXCommand; FCheckSeatCommand: TDBXCommand; FDuplicatednumCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function CheckLogin(AID: string; APW: string): Boolean; function DuplicatedID(AID: string): Boolean; function CheckSeat(ADATE: TDateTime; ALIBSEQ: Integer): Boolean; function Duplicatednum(ADATE: TDateTime; ALIBSEQ: Integer; ARent_SeatNum: Integer): Boolean; end; implementation function TServerMethods1Client.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.CheckLogin(AID: string; APW: string): Boolean; begin if FCheckLoginCommand = nil then begin FCheckLoginCommand := FDBXConnection.CreateCommand; FCheckLoginCommand.CommandType := TDBXCommandTypes.DSServerMethod; FCheckLoginCommand.Text := 'TServerMethods1.CheckLogin'; FCheckLoginCommand.Prepare; end; FCheckLoginCommand.Parameters[0].Value.SetWideString(AID); FCheckLoginCommand.Parameters[1].Value.SetWideString(APW); FCheckLoginCommand.ExecuteUpdate; Result := FCheckLoginCommand.Parameters[2].Value.GetBoolean; end; function TServerMethods1Client.DuplicatedID(AID: string): Boolean; begin if FDuplicatedIDCommand = nil then begin FDuplicatedIDCommand := FDBXConnection.CreateCommand; FDuplicatedIDCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDuplicatedIDCommand.Text := 'TServerMethods1.DuplicatedID'; FDuplicatedIDCommand.Prepare; end; FDuplicatedIDCommand.Parameters[0].Value.SetWideString(AID); FDuplicatedIDCommand.ExecuteUpdate; Result := FDuplicatedIDCommand.Parameters[1].Value.GetBoolean; end; function TServerMethods1Client.CheckSeat(ADATE: TDateTime; ALIBSEQ: Integer): Boolean; begin if FCheckSeatCommand = nil then begin FCheckSeatCommand := FDBXConnection.CreateCommand; FCheckSeatCommand.CommandType := TDBXCommandTypes.DSServerMethod; FCheckSeatCommand.Text := 'TServerMethods1.CheckSeat'; FCheckSeatCommand.Prepare; end; FCheckSeatCommand.Parameters[0].Value.AsDateTime := ADATE; FCheckSeatCommand.Parameters[1].Value.SetInt32(ALIBSEQ); FCheckSeatCommand.ExecuteUpdate; Result := FCheckSeatCommand.Parameters[2].Value.GetBoolean; end; function TServerMethods1Client.Duplicatednum(ADATE: TDateTime; ALIBSEQ: Integer; ARent_SeatNum: Integer): Boolean; begin if FDuplicatednumCommand = nil then begin FDuplicatednumCommand := FDBXConnection.CreateCommand; FDuplicatednumCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDuplicatednumCommand.Text := 'TServerMethods1.Duplicatednum'; FDuplicatednumCommand.Prepare; end; FDuplicatednumCommand.Parameters[0].Value.AsDateTime := ADATE; FDuplicatednumCommand.Parameters[1].Value.SetInt32(ALIBSEQ); FDuplicatednumCommand.Parameters[2].Value.SetInt32(ARent_SeatNum); FDuplicatednumCommand.ExecuteUpdate; Result := FDuplicatednumCommand.Parameters[3].Value.GetBoolean; end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FCheckLoginCommand.DisposeOf; FDuplicatedIDCommand.DisposeOf; FCheckSeatCommand.DisposeOf; FDuplicatednumCommand.DisposeOf; inherited; end; end.
unit cStack; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TCompareMode = (Text, Binary); type TMyStack = class private //Hold stack size and stack position. Stack_size, StackPtr: integer; //This hold items for our stack //Stack items T_Items: array of variant; //Compare mode. CmpMode: TCompareMode; //Set compare mode. procedure SetCompare(Value: TCompareMode); //get compare mode. function GetCompare(): TCompareMode; public //To create the stack constructor Create(Size: CARDINAL); //Return stack count property Count: integer read Stack_size; property Compare: TCompareMode read GetCompare write SetCompare; //Push items onto stack procedure Push(Item: variant); //Pop items of stack function Pop(): variant; //Peek at the first item. function Peek(): variant; //Tells us if stack id full. function IsFull(): boolean; //Tells us if stack empry. function IsEmpty(): boolean; //Check for item in stack. function Contains(Item: variant): boolean; procedure Free; end; implementation constructor TMyStack.Create(Size: CARDINAL); begin StackPtr := 0; Stack_size := Size; //Set size of stack SetLength(T_Items, Stack_size); end; function TMyStack.GetCompare(): TCompareMode; begin //Set compare mode. Result := CmpMode; end; procedure TMyStack.SetCompare(Value: TCompareMode); begin //Get compare mode. CmpMode := Value; end; procedure TMyStack.Push(Item: variant); begin if not IsFull then begin //Push items on the stack. T_Items[StackPtr + 1] := Item; StackPtr := StackPtr + 1; end; end; function TMyStack.Pop(): variant; begin if not IsEmpty then begin //Return item from stack. Result := T_Items[StackPtr]; StackPtr := StackPtr - 1; end; end; function TMyStack.Peek(): variant; begin Peek := T_Items[StackPtr + 1]; end; function TMyStack.IsFull(): boolean; begin IsFull := (StackPtr = Stack_size); end; function TMyStack.IsEmpty(): boolean; begin Result := (StackPtr = 0); end; function TMyStack.Contains(Item: variant): boolean; var X: integer; Found: boolean; sItem1, sItem2: variant; begin Found := False; //Look for item in stack. for X := low(T_Items) to high(T_Items) do begin //Compare mode for text. if (cmpMode = TCompareMode.Text) then begin sItem1 := LowerCase(T_Items[x]); sItem2 := LowerCase(Item); end; //Compare mode for binary. if (cmpMode = TcompareMode.Binary) then begin sItem1 := T_Items[X]; sItem2 := Item; end; //Check for item in stack. if (sItem1 = sItem2) then begin Found := True; break; end; end; Contains := Found; end; procedure TMyStack.Free(); begin Stack_size := 0; StackPtr := 0; SetLength(T_Items, 0); end; end.
unit uFrmDataDict; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmRoot, ImgList, ActnList, dxSkinsCore, dxSkinsdxBarPainter, dxSkinsDefaultPainters, cxClasses, dxBar, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxTLdxBarBuiltInMenu, dxSkinscxPCPainter, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxSplitter, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxInplaceContainer, cxTLData, cxDBTL, ADODB, DBClient, cxTextEdit, cxMaskEdit; type TFrmDataDict = class(TFrmRoot) dxbrmngr1: TdxBarManager; dxbrmngr1Bar1: TdxBar; lst1: TcxDBTreeList; grdbtblvwField: TcxGridDBTableView; grdlvlField: TcxGridLevel; grdField: TcxGrid; cxspltr1: TcxSplitter; QryTable: TADOQuery; dsTable: TDataSource; dsField: TDataSource; cdsField: TClientDataSet; dxbrpmn1: TdxBarPopupMenu; btnNewDir: TdxBarButton; btnTable: TdxBarButton; actNewDir: TAction; actNewTable: TAction; actDel: TAction; actEditDict: TAction; btnEditDict: TdxBarButton; btnDelDict: TdxBarButton; actNewChildDir: TAction; btnNewChildDir: TdxBarButton; clnTABLENAME: TcxDBTreeListColumn; procedure FormCreate(Sender: TObject); procedure actDelExecute(Sender: TObject); procedure actNewDirExecute(Sender: TObject); procedure actNewTableExecute(Sender: TObject); procedure actEditDictExecute(Sender: TObject); procedure actlst1Update(Action: TBasicAction; var Handled: Boolean); procedure QryTableNewRecord(DataSet: TDataSet); procedure actNewChildDirExecute(Sender: TObject); private public end; var FrmDataDict: TFrmDataDict; implementation uses dxForms, uFrmTableEdit, uFrmMsg, uDBAccess, uPubFunLib, uConst; {$R *.dfm} procedure TFrmDataDict.actDelExecute(Sender: TObject); begin inherited; if not ShowConfirm('确认要删除当前选择节点吗?') then Exit; QryTable.Delete; end; procedure TFrmDataDict.actEditDictExecute(Sender: TObject); begin inherited; TFrmTableEdit.Execute(QryTable, okUpdate); end; procedure TFrmDataDict.actlst1Update(Action: TBasicAction; var Handled: Boolean); begin inherited; actNewDir.Enabled := QryTable.Active; actNewChildDir.Enabled := QryTable.Active and (lst1.FocusedNode <> nil) and (QryTable.FindField('KIND').AsString <> '1'); actNewTable.Enabled := actNewChildDir.Enabled; actEditDict.Enabled := QryTable.Active and (lst1.FocusedNode <> nil); actDel.Enabled := QryTable.Active and (lst1.FocusedNode <> nil); end; procedure TFrmDataDict.actNewChildDirExecute(Sender: TObject); var lGuid: string; begin inherited; lGuid := QryTable.FindField('GUID').AsString; TFrmTableEdit.Execute(QryTable, okInsert, 0, lGuid); end; procedure TFrmDataDict.actNewDirExecute(Sender: TObject); var lGuid: string; begin inherited; if (lst1.FocusedNode <> nil) and (lst1.FocusedNode.Parent <> nil) then lGuid := QryTable.FindField('PARENTGUID').AsString else lGuid := '-1'; TFrmTableEdit.Execute(QryTable, okInsert, 0, lGuid); end; procedure TFrmDataDict.actNewTableExecute(Sender: TObject); var lGuid: string; begin inherited; lGuid := QryTable.FindField('GUID').AsString; TFrmTableEdit.Execute(QryTable, okInsert, 1, lGuid); end; procedure TFrmDataDict.QryTableNewRecord(DataSet: TDataSet); begin inherited; with DataSet do begin FindField('GUID').AsString := CreateGuid; FindField('STATUS').AsInteger := 0; end; end; procedure TFrmDataDict.FormCreate(Sender: TObject); begin inherited; QryTable.Open; end; initialization dxFormManager.RegisterForm(TFrmDataDict); end.
unit uFLDThread; interface uses Classes, Windows, SysUtils, SyncObjs; type TFLDThread = class(TThread) private { Private declarations } mEvent: TEvent; protected procedure Execute; override; public constructor Create; procedure Terminate; end; implementation uses Mainform; constructor TFLDThread.Create; begin inherited Create(False); mEvent := TEvent.Create(nil, True, False, ''); end; { TFLDThread.Create } procedure TFLDThread.Execute; var dwBytesReturned: Cardinal; i: Integer; StartTime: Cardinal; FLDResult: Boolean; begin try for i := FLDIndStart to High(VolumesInfo) do begin if VolumesInfo[i].FirstDrv <> DoFDThread then Continue; FLDAreaProblem := -1; if FDLSkipTo < 0 then begin FLDAreaProblem := 0; try VolumesInfo[i].Handle := CreateFile(VolumesInfo[i].Name, GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); LastError := GetLastError; except VolumesInfo[i].Handle := INVALID_HANDLE_VALUE; end; if VolumesInfo[i].Handle = INVALID_HANDLE_VALUE then begin FLDFailedInd := i; Break; end; try FlushFileBuffers(VolumesInfo[i].Handle); except end; if FlushWaitTime > 0 then mEvent.WaitFor(FlushWaitTime); end; if Terminated then Break; if FDLSkipTo < 1 then begin if LockVolumes and (not DisableLockAndDismount) then begin FLDAreaProblem := 1; StartTime := GetTickCount; repeat begin try FLDResult := DeviceIoControl(VolumesInfo[i].Handle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0, dwBytesReturned, nil); LastError := GetLastError; except FLDResult := False; end; if FLDResult then Break; if (GetTickCount - StartTime) >= 10000 then Break; mEvent.WaitFor(50); if (GetTickCount - StartTime) >= 10000 then Break; end; until Terminated; if not FLDResult then begin FLDFailedInd := i; Break; end; end; end; if not DisableLockAndDismount then begin FLDAreaProblem := 2; StartTime := GetTickCount; repeat begin try FLDResult := DeviceIoControl(VolumesInfo[i].Handle, FSCTL_DISMOUNT_VOLUME, nil, 0, nil, 0, dwBytesReturned, nil); LastError := GetLastError; except FLDResult := False; end; if FLDResult then Break; if (GetTickCount - StartTime) >= 5000 then Break; mEvent.WaitFor(50); if (GetTickCount - StartTime) >= 5000 then Break; end; until Terminated; if not FLDResult then begin FLDFailedInd := i; Break; end; end; FDLSkipTo := -1; end; finally FLDJobDone := True; end; end; { TFLDThread.Execute } procedure TFLDThread.Terminate; begin TThread(Self).Terminate; mEvent.SetEvent; while not FLDJobDone do Sleep(1); mEvent.Free; end; end.
unit eSocial.Controllers.Factory; interface uses eSocial.Controllers.Interfaces, eSocial.Controllers.Competencia, eSocial.Controllers.Operacao, eSocial.Controllers.Configuracao; type TControllerFactory = class private public class function Competencia : IControllerCompetencia; class function Operacao : IControllerOperacao; class function Configuracao : IControllerConfiguracao; end; implementation { TControllerFactory } class function TControllerFactory.Competencia: IControllerCompetencia; begin Result := TControllerCompetencia.GetInstance; end; class function TControllerFactory.Operacao: IControllerOperacao; begin Result := TControllerOperacao.GetInstance; end; class function TControllerFactory.Configuracao: IControllerConfiguracao; begin Result := TControllerConfiguracao.GetInstance; end; end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit shipment; {$mode objfpc}{$H+} interface uses Classes, SysUtils, xmlobject, LP_base_types_v2, AbstractSerializationObjects; type { Forward declarations } Tshipment = class; Tshipment_element = class; Tshipment_products_list = class; Tshipment_products_list_product = class; { Generic classes for collections } TshipmentList = specialize GXMLSerializationObjectList<Tshipment>; Tshipment_elementList = specialize GXMLSerializationObjectList<Tshipment_element>; Tshipment_products_listList = specialize GXMLSerializationObjectList<Tshipment_products_list>; Tshipment_products_list_productList = specialize GXMLSerializationObjectList<Tshipment_products_list_product>; { Tshipment } //Отгрузка Tshipment = class(TXmlSerializationObject) private Ftrade_participant_inn_sender:Tinn_type; Ftrade_participant_inn_receiver:Tinn_type; Ftrade_participant_inn_owner:Tinn_type; Ftransfer_date:Tdate_type; Fmove_document_number:Tstring255_type; Fmove_document_date:Tdate_type; Fturnover_type:Tturnover_enum_type; Fwithdrawal_type:Twithdrawal_shipment_type; Fwithdrawal_date:Tdate_type; Fst_contract_id:Tstring255_type; Fto_not_participant:Boolean; Fproducts_list:Tshipment_products_list; Faction_id:Longint; Fversion:Double; procedure Settrade_participant_inn_sender( AValue:Tinn_type); procedure Settrade_participant_inn_receiver( AValue:Tinn_type); procedure Settrade_participant_inn_owner( AValue:Tinn_type); procedure Settransfer_date( AValue:Tdate_type); procedure Setmove_document_number( AValue:Tstring255_type); procedure Setmove_document_date( AValue:Tdate_type); procedure Setturnover_type( AValue:Tturnover_enum_type); procedure Setwithdrawal_type( AValue:Twithdrawal_shipment_type); procedure Setwithdrawal_date( AValue:Tdate_type); procedure Setst_contract_id( AValue:Tstring255_type); procedure Setto_not_participant( AValue:Boolean); procedure Setaction_id( AValue:Longint); procedure Setversion( AValue:Double); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public constructor Create; destructor Destroy; override; published //ИНН отправителя property trade_participant_inn_sender:Tinn_type read Ftrade_participant_inn_sender write Settrade_participant_inn_sender; //ИНН получателя property trade_participant_inn_receiver:Tinn_type read Ftrade_participant_inn_receiver write Settrade_participant_inn_receiver; //ИНН собственника property trade_participant_inn_owner:Tinn_type read Ftrade_participant_inn_owner write Settrade_participant_inn_owner; //Дата передачи товара property transfer_date:Tdate_type read Ftransfer_date write Settransfer_date; //Номер первичного документа property move_document_number:Tstring255_type read Fmove_document_number write Setmove_document_number; //Дата первичного документа property move_document_date:Tdate_type read Fmove_document_date write Setmove_document_date; //Вид оборота товаров property turnover_type:Tturnover_enum_type read Fturnover_type write Setturnover_type; //Причина вывода из оборота property withdrawal_type:Twithdrawal_shipment_type read Fwithdrawal_type write Setwithdrawal_type; //Дата вывода из оборота property withdrawal_date:Tdate_type read Fwithdrawal_date write Setwithdrawal_date; //Идентификатор гос.контракта property st_contract_id:Tstring255_type read Fst_contract_id write Setst_contract_id; //Отгрузка не участнику property to_not_participant:Boolean read Fto_not_participant write Setto_not_participant; //Параметры товаров property products_list:Tshipment_products_list read Fproducts_list; property action_id:Longint read Faction_id write Setaction_id; property version:Double read Fversion write Setversion; end; { Tshipment_element } Tshipment_element = class(Tshipment) private protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; function RootNodeName:string; override; public constructor Create; destructor Destroy; override; published end; { Tshipment_products_list } Tshipment_products_list = class(TXmlSerializationObject) private Fproduct:Tshipment_products_list_productList; protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public constructor Create; destructor Destroy; override; published //Параметры товара property product:Tshipment_products_list_productList read Fproduct; end; { Tshipment_products_list_product } Tshipment_products_list_product = class(TXmlSerializationObject) private Fkit:Tkit_type; Fkitu:Tkitu_type; Fcost:Tprice_type; Fvat_value:Tprice_type; procedure Setkit( AValue:Tkit_type); procedure Setkitu( AValue:Tkitu_type); procedure Setcost( AValue:Tprice_type); procedure Setvat_value( AValue:Tprice_type); protected procedure InternalRegisterPropertys; override; procedure InternalInitChilds; override; public constructor Create; destructor Destroy; override; published //КИТ property kit:Tkit_type read Fkit write Setkit; //КИТУ property kitu:Tkitu_type read Fkitu write Setkitu; //Цена за единицу property cost:Tprice_type read Fcost write Setcost; //Сумма НДС property vat_value:Tprice_type read Fvat_value write Setvat_value; end; implementation { Tshipment } procedure Tshipment.Settrade_participant_inn_sender(AValue: Tinn_type); begin CheckStrMinSize('trade_participant_inn_sender', AValue); CheckStrMaxSize('trade_participant_inn_sender', AValue); Ftrade_participant_inn_sender:=AValue; ModifiedProperty('trade_participant_inn_sender'); end; procedure Tshipment.Settrade_participant_inn_receiver(AValue: Tinn_type); begin CheckStrMinSize('trade_participant_inn_receiver', AValue); CheckStrMaxSize('trade_participant_inn_receiver', AValue); Ftrade_participant_inn_receiver:=AValue; ModifiedProperty('trade_participant_inn_receiver'); end; procedure Tshipment.Settrade_participant_inn_owner(AValue: Tinn_type); begin CheckStrMinSize('trade_participant_inn_owner', AValue); CheckStrMaxSize('trade_participant_inn_owner', AValue); Ftrade_participant_inn_owner:=AValue; ModifiedProperty('trade_participant_inn_owner'); end; procedure Tshipment.Settransfer_date(AValue: Tdate_type); begin CheckStrMinSize('transfer_date', AValue); CheckStrMaxSize('transfer_date', AValue); Ftransfer_date:=AValue; ModifiedProperty('transfer_date'); end; procedure Tshipment.Setmove_document_number(AValue: Tstring255_type); begin CheckStrMinSize('move_document_number', AValue); CheckStrMaxSize('move_document_number', AValue); Fmove_document_number:=AValue; ModifiedProperty('move_document_number'); end; procedure Tshipment.Setmove_document_date(AValue: Tdate_type); begin CheckStrMinSize('move_document_date', AValue); CheckStrMaxSize('move_document_date', AValue); Fmove_document_date:=AValue; ModifiedProperty('move_document_date'); end; procedure Tshipment.Setturnover_type(AValue: Tturnover_enum_type); begin CheckLockupValue('turnover_type', AValue); Fturnover_type:=AValue; ModifiedProperty('turnover_type'); end; procedure Tshipment.Setwithdrawal_type(AValue: Twithdrawal_shipment_type); begin CheckLockupValue('withdrawal_type', AValue); Fwithdrawal_type:=AValue; ModifiedProperty('withdrawal_type'); end; procedure Tshipment.Setwithdrawal_date(AValue: Tdate_type); begin CheckStrMinSize('withdrawal_date', AValue); CheckStrMaxSize('withdrawal_date', AValue); Fwithdrawal_date:=AValue; ModifiedProperty('withdrawal_date'); end; procedure Tshipment.Setst_contract_id(AValue: Tstring255_type); begin CheckStrMinSize('st_contract_id', AValue); CheckStrMaxSize('st_contract_id', AValue); Fst_contract_id:=AValue; ModifiedProperty('st_contract_id'); end; procedure Tshipment.Setto_not_participant(AValue: Boolean); begin Fto_not_participant:=AValue; ModifiedProperty('to_not_participant'); end; procedure Tshipment.Setaction_id(AValue: Longint); begin CheckFixedValue('action_id', AValue); Faction_id:=AValue; ModifiedProperty('action_id'); end; procedure Tshipment.Setversion(AValue: Double); begin CheckFixedValue('version', AValue); Fversion:=AValue; ModifiedProperty('version'); end; procedure Tshipment.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; P:=RegisterProperty('trade_participant_inn_sender', 'trade_participant_inn_sender', [xsaSimpleObject], '', 9, 12); P:=RegisterProperty('trade_participant_inn_receiver', 'trade_participant_inn_receiver', [xsaSimpleObject], '', 9, 12); P:=RegisterProperty('trade_participant_inn_owner', 'trade_participant_inn_owner', [xsaSimpleObject], '', 9, 12); P:=RegisterProperty('transfer_date', 'transfer_date', [xsaSimpleObject], '', 10, 10); P:=RegisterProperty('move_document_number', 'move_document_number', [xsaSimpleObject], '', 1, 255); P:=RegisterProperty('move_document_date', 'move_document_date', [xsaSimpleObject], '', 10, 10); P:=RegisterProperty('turnover_type', 'turnover_type', [xsaSimpleObject], '', -1, -1); P.ValidList.Add('SELLING'); P.ValidList.Add('COMMISSION'); P.ValidList.Add('AGENT'); P.ValidList.Add('COMMISSIONAIRE_SALE'); P.ValidList.Add('CONTRACT'); P:=RegisterProperty('withdrawal_type', 'withdrawal_type', [xsaSimpleObject], '', -1, -1); P.ValidList.Add('DONATION'); P.ValidList.Add('STATE_ENTERPRISE'); P.ValidList.Add('NO_RETAIL_USE'); P:=RegisterProperty('withdrawal_date', 'withdrawal_date', [xsaSimpleObject], '', 10, 10); P:=RegisterProperty('st_contract_id', 'st_contract_id', [xsaSimpleObject], '', 1, 255); P:=RegisterProperty('to_not_participant', 'to_not_participant', [xsaSimpleObject], '', -1, -1); P:=RegisterProperty('products_list', 'products_list', [], '', -1, -1); P:=RegisterProperty('action_id', 'action_id', [xsaRequared], '', -1, -1); P.DefaultValue:='10'; P:=RegisterProperty('version', 'version', [xsaRequared], '', -1, -1); P.DefaultValue:='3'; end; procedure Tshipment.InternalInitChilds; begin inherited InternalInitChilds; Fproducts_list:=Tshipment_products_list.Create; end; destructor Tshipment.Destroy; begin Fproducts_list.Free; inherited Destroy; end; constructor Tshipment.Create; begin inherited Create; action_id:=10; version:=3; end; { Tshipment_element } procedure Tshipment_element.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; end; procedure Tshipment_element.InternalInitChilds; begin inherited InternalInitChilds; end; destructor Tshipment_element.Destroy; begin inherited Destroy; end; function Tshipment_element.RootNodeName:string; begin Result:='shipment'; end; constructor Tshipment_element.Create; begin inherited Create; end; { Tshipment_products_list } procedure Tshipment_products_list.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; P:=RegisterProperty('product', 'product', [], '', -1, -1); end; procedure Tshipment_products_list.InternalInitChilds; begin inherited InternalInitChilds; Fproduct:=Tshipment_products_list_productList.Create; end; destructor Tshipment_products_list.Destroy; begin Fproduct.Free; inherited Destroy; end; constructor Tshipment_products_list.Create; begin inherited Create; end; { Tshipment_products_list_product } procedure Tshipment_products_list_product.Setkit(AValue: Tkit_type); begin CheckStrMinSize('kit', AValue); CheckStrMaxSize('kit', AValue); Fkit:=AValue; ModifiedProperty('kit'); end; procedure Tshipment_products_list_product.Setkitu(AValue: Tkitu_type); begin CheckStrMinSize('kitu', AValue); CheckStrMaxSize('kitu', AValue); Fkitu:=AValue; ModifiedProperty('kitu'); end; procedure Tshipment_products_list_product.Setcost(AValue: Tprice_type); begin CheckMinInclusiveValue('cost', AValue); Fcost:=AValue; ModifiedProperty('cost'); end; procedure Tshipment_products_list_product.Setvat_value(AValue: Tprice_type); begin CheckMinInclusiveValue('vat_value', AValue); Fvat_value:=AValue; ModifiedProperty('vat_value'); end; procedure Tshipment_products_list_product.InternalRegisterPropertys; var P: TPropertyDef; begin inherited InternalRegisterPropertys; P:=RegisterProperty('kit', 'kit', [xsaSimpleObject], '', 25, 45); P:=RegisterProperty('kitu', 'kitu', [xsaSimpleObject], '', 18, 18); P:=RegisterProperty('cost', 'cost', [xsaSimpleObject], '', -1, -1); P.TotalDigits := 19; P.FractionDigits := 2; P.minInclusiveFloat:=0; P:=RegisterProperty('vat_value', 'vat_value', [xsaSimpleObject], '', -1, -1); P.TotalDigits := 19; P.FractionDigits := 2; P.minInclusiveFloat:=0; end; procedure Tshipment_products_list_product.InternalInitChilds; begin inherited InternalInitChilds; end; destructor Tshipment_products_list_product.Destroy; begin inherited Destroy; end; constructor Tshipment_products_list_product.Create; begin inherited Create; end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT nodes m_type = related to node's uptime , the lower the higher the uptime , 4 = possibly stale node m_tcpport and udpport are the same on the Ares DHT implementation m_distance is relative con us (DHTMe) } unit dhtcontact; interface uses classes,classes2,int128,windows,sysutils; type TContact=class(TObject) m_clientID:CU_Int128; m_distance:CU_Int128; m_ip:cardinal; m_tcpPort:word; m_udpPort:word; m_type:byte; m_lastTypeSet:cardinal; m_expires:cardinal; m_inUse:cardinal; m_created:cardinal; m_rtt:cardinal; m_outhellotime:cardinal; procedure Init(const clientID:pCU_Int128; ip:cardinal; udpPort:word; tcpPort:word; const target:pCU_Int128); constructor create; // Common var initialization goes here procedure checkingType; procedure updateType; destructor destroy; override; end; Procedure sortCloserContacts(list:Tmylist; FromTarget:pCU_INT128); Procedure sortFarestContacts(list:Tmylist; FromTarget:pCU_INT128); implementation uses helpeR_datetime,vars_global; Procedure sortCloserContacts(list:Tmylist; FromTarget:pCU_INT128); function SCompare(item1,item2:pointer):integer; var c1,c2:TContact; begin c1:=TContact(item1); c2:=TContact(item2); result:=(c1.m_clientid[0] xor FromTarget[0]) - (c2.m_clientid[0] xor FromTarget[0]); //smaller distance first if result<>0 then exit; result:=(c1.m_clientid[1] xor FromTarget[1]) - (c2.m_clientid[1] xor FromTarget[1]); //smaller distance first if result<>0 then exit; result:=(c1.m_clientid[2] xor FromTarget[2]) - (c2.m_clientid[2] xor FromTarget[2]); //smaller distance first if result<>0 then exit; result:=(c1.m_clientid[3] xor FromTarget[3]) - (c2.m_clientid[3] xor FromTarget[3]); //smaller distance first end; procedure QuickSort(SortList: TmyList; L, R: Integer); var I, J: Integer; P, T: Pointer; begin try repeat I := L; J := R; P := SortList[(L + R) shr 1]; repeat while SCompare(SortList[I], P) < 0 do Inc(I); while SCompare(SortList[J], P) > 0 do Dec(J); if I <= J then begin T := SortList[I]; SortList[I] := SortList[J]; SortList[J] := T; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(SortList, L, J); L := I; until I >= R; except end; end; begin if list.count>0 then QuickSort(List, 0, List.Count - 1); end; Procedure sortFarestContacts(list:Tmylist; FromTarget:pCU_INT128); function SCompare(item1,item2:pointer):integer; var c1,c2:TContact; begin c1:=TContact(item1); c2:=TContact(item2); result:=(c2.m_clientid[0] xor FromTarget[0]) - (c1.m_clientid[0] xor FromTarget[0]); //smaller distance first if result<>0 then exit; result:=(c2.m_clientid[1] xor FromTarget[1]) - (c1.m_clientid[1] xor FromTarget[1]); //smaller distance first if result<>0 then exit; result:=(c2.m_clientid[2] xor FromTarget[2]) - (c1.m_clientid[2] xor FromTarget[2]); //smaller distance first if result<>0 then exit; result:=(c2.m_clientid[3] xor FromTarget[3]) - (c1.m_clientid[3] xor FromTarget[3]); //smaller distance first end; procedure QuickSort(SortList: TmyList; L, R: Integer); var I, J: Integer; P, T: Pointer; begin repeat I := L; J := R; P := SortList[(L + R) shr 1]; repeat while SCompare(SortList[I], P) < 0 do Inc(I); while SCompare(SortList[J], P) > 0 do Dec(J); if I <= J then begin T := SortList[I]; SortList[I] := SortList[J]; SortList[J] := T; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(SortList, L, J); L := I; until I >= R; end; begin QuickSort(List, 0, List.Count - 1); end; constructor TContact.create; begin m_type:=3; m_expires:=0; m_lastTypeSet:=time_now; m_created:=m_lastTypeSet; m_inUse:=0; m_rtt:=0; m_outhellotime:=0; inc(vars_global.DHT_availableContacts); end; destructor TContact.destroy; begin dec(vars_global.DHT_availableContacts); inherited; end; procedure TContact.Init(const clientID:pCU_Int128; ip:cardinal; udpPort:word; tcpPort:word; const target:pCU_Int128); begin CU_INT128_Fill(@m_clientID,clientID); CU_INT128_FillNXor(@m_distance,@m_clientID,target); m_ip:=ip; m_udpPort:=udpPort; m_tcpPort:=tcpPort; end; procedure TContact.checkingType; begin if ((time_now-m_lastTypeSet<10) or (m_type=4)) then exit; m_lastTypeSet:=time_now; m_expires:=m_lastTypeSet + MIN2S(2); inc(m_type); if m_type=3 then dec(vars_global.DHT_AliveContacts); end; procedure TContact.updateType; var hours:cardinal; begin if m_type>=3 then inc(vars_global.DHT_AliveContacts); hours:=(time_now-m_created) div HR2S(1); case hours of 0:begin m_type:=2; m_expires:=time_now+HR2S(1); end; 1:begin m_type:=1; m_expires:=time_now+HR2S(1.5); end else begin m_type:=0; m_expires:=time_now+HR2S(2); end; end; end; end.
unit UDownloader; interface uses WinApi.Windows, WinApi.Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, XPMan, IdAntiFreezeBase, IdAntiFreeze, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, WinApi.URLmon; type IDownloadCallBack = interface(IBindStatusCallBack) procedure OnStatus(status:string); end; TFileDownloadThread = class(TThread) private FSourceURL: string; FSaveFileName: string; FProgress,FProgressMax:Cardinal; callback:IDownloadCallBack; protected procedure Execute; override; end; TDownloader = Class private t: TFileDownloadThread; public http: TIDHTTP; DownloadURL:string; Constructor Create(url:string); Procedure DownFileAsync(fileuRL:string; cb: IDownloadCallBack); Procedure DownFile(fileURL:String; cb: IDownloadCallBack); End; var IdHTTP1: TIdHTTP; IdAntiFreeze1: TIdAntiFreeze; startIndex:Integer; IsStop:Boolean; //ำรปงสวท๑ึีึน implementation procedure TFileDownloadThread.Execute; var ret: HRESULT; begin inherited; ret := URLDownloadToFile(nil, PWideChar(WideString(FSourceURL)), PWideChar(WideString(FSaveFileName)), 0, callback); if callback <> nil then if ret = S_OK then callback.OnStatus('Downloaded') else callback.OnStatus('Download Failed'); end; constructor TDownloader.Create(url: string); begin DownloadURL := url; t := TFileDownloadThread.Create(true); t.FSourceURL := url; end; function IntegerToString(i:Integer):string; var t:string; begin str(i,t); exit(t); end; Procedure TDownloader.DownFileAsync(fileuRL:string; cb: IDownloadCallback); begin try t.FSaveFileName := fileuRL; t.callback := cb; t.Start; except end; end; Procedure TDownloader.DownFile(fileURL: string; cb: IDownloadCallBack); var ret: HRESULT; begin if FileExists(fileURL) then DeleteFile(fileURL); ret := URLDownloadToFile(nil, PWideChar(WideString(DownloadURL)), PWideChar(WideString(fileURL)), 0, cb); if cb <> nil then if ret = S_OK then cb.OnStatus('Downloaded') else cb.OnStatus('Download Failed'); end; end.
unit Winapi_BCrypt; interface uses Windows; {$IF not DECLARED(PVOID)} type PVOID = Pointer; {$EXTERNALSYM PVOID} {$IFEND} {$IF not DECLARED(PWSTR)} type PWSTR = PWideChar; {$EXTERNALSYM PWSTR} {$IFEND} {$REGION 'bcrypt.h'} {$WARN SYMBOL_PLATFORM OFF} {$IF not DECLARED(NTSTATUS)} type NTSTATUS = Integer; {$EXTERNALSYM NTSTATUS} {$IFEND} {$IF not DECLARED(BCRYPT_SUCCESS)} function BCRYPT_SUCCESS(Status: NTSTATUS): Boolean; inline; {$EXTERNALSYM BCRYPT_SUCCESS} {$IFEND} // // Alignment macros // // // BCRYPT_OBJECT_ALIGNMENT must be a power of 2 // We align all our internal data structures to 16 to // allow fast XMM memory accesses. // BCrypt callers do not need to take any alignment precautions. // const BCRYPT_OBJECT_ALIGNMENT = 16; {$EXTERNALSYM BCRYPT_OBJECT_ALIGNMENT} // // BCRYPT_STRUCT_ALIGNMENT is an alignment macro that we no longer use. // It used to align declspec(align(4)) on x86 and declspec(align(8)) on x64/ia64 but // all structures that used it contained a pointer so they were already 4/8 aligned. // //#define BCRYPT_STRUCT_ALIGNMENT // // DeriveKey KDF Types // const BCRYPT_KDF_HASH = 'HASH'; {$EXTERNALSYM BCRYPT_KDF_HASH} BCRYPT_KDF_HMAC = 'HMAC'; {$EXTERNALSYM BCRYPT_KDF_HMAC} BCRYPT_KDF_TLS_PRF = 'TLS_PRF'; {$EXTERNALSYM BCRYPT_KDF_TLS_PRF} BCRYPT_KDF_SP80056A_CONCAT = 'SP800_56A_CONCAT'; {$EXTERNALSYM BCRYPT_KDF_SP80056A_CONCAT} // // DeriveKey KDF BufferTypes // // For BCRYPT_KDF_HASH and BCRYPT_KDF_HMAC operations, there may be an arbitrary // number of KDF_SECRET_PREPEND and KDF_SECRET_APPEND buffertypes in the // parameter list. The BufferTypes are processed in order of appearence // within the parameter list. // const KDF_HASH_ALGORITHM = $0; {$EXTERNALSYM KDF_HASH_ALGORITHM} KDF_SECRET_PREPEND = $1; {$EXTERNALSYM KDF_SECRET_PREPEND} KDF_SECRET_APPEND = $2; {$EXTERNALSYM KDF_SECRET_APPEND} KDF_HMAC_KEY = $3; {$EXTERNALSYM KDF_HMAC_KEY} KDF_TLS_PRF_LABEL = $4; {$EXTERNALSYM KDF_TLS_PRF_LABEL} KDF_TLS_PRF_SEED = $5; {$EXTERNALSYM KDF_TLS_PRF_SEED} KDF_SECRET_HANDLE = $6; {$EXTERNALSYM KDF_SECRET_HANDLE} KDF_TLS_PRF_PROTOCOL = $7; {$EXTERNALSYM KDF_TLS_PRF_PROTOCOL} KDF_ALGORITHMID = $8; {$EXTERNALSYM KDF_ALGORITHMID} KDF_PARTYUINFO = $9; {$EXTERNALSYM KDF_PARTYUINFO} KDF_PARTYVINFO = $A; {$EXTERNALSYM KDF_PARTYVINFO} KDF_SUPPPUBINFO = $B; {$EXTERNALSYM KDF_SUPPPUBINFO} KDF_SUPPPRIVINFO = $C; {$EXTERNALSYM KDF_SUPPPRIVINFO} KDF_LABEL = $D; {$EXTERNALSYM KDF_LABEL} KDF_CONTEXT = $E; {$EXTERNALSYM KDF_CONTEXT} KDF_SALT = $F; {$EXTERNALSYM KDF_SALT} KDF_ITERATION_COUNT = $10; {$EXTERNALSYM KDF_ITERATION_COUNT} // // // Parameters for BCrypt(/NCrypt)KeyDerivation: // Generic parameters: // KDF_GENERIC_PARAMETER and KDF_HASH_ALGORITHM are the generic parameters that can be passed for the following KDF algorithms: // BCRYPT/NCRYPT_SP800108_CTR_HMAC_ALGORITHM // KDF_GENERIC_PARAMETER = KDF_LABEL||0x00||KDF_CONTEXT // BCRYPT/NCRYPT_SP80056A_CONCAT_ALGORITHM // KDF_GENERIC_PARAMETER = KDF_ALGORITHMID || KDF_PARTYUINFO || KDF_PARTYVINFO {|| KDF_SUPPPUBINFO } {|| KDF_SUPPPRIVINFO } // BCRYPT/NCRYPT_PBKDF2_ALGORITHM // KDF_GENERIC_PARAMETER = KDF_SALT // BCRYPT/NCRYPT_CAPI_KDF_ALGORITHM // KDF_GENERIC_PARAMETER = Not used // // KDF specific parameters: // For BCRYPT/NCRYPT_SP800108_CTR_HMAC_ALGORITHM: // KDF_HASH_ALGORITHM, KDF_LABEL and KDF_CONTEXT are required // For BCRYPT/NCRYPT_SP80056A_CONCAT_ALGORITHM: // KDF_HASH_ALGORITHM, KDF_ALGORITHMID, KDF_PARTYUINFO, KDF_PARTYVINFO are required // KDF_SUPPPUBINFO, KDF_SUPPPRIVINFO are optional // For BCRYPT/NCRYPT_PBKDF2_ALGORITHM // KDF_HASH_ALGORITHM is required // KDF_ITERATION_COUNT, KDF_SALT are optional // Iteration count, (if not specified) will default to 10,000 // For BCRYPT/NCRYPT_CAPI_KDF_ALGORITHM // KDF_HASH_ALGORITHM is required // const KDF_GENERIC_PARAMETER = $11; {$EXTERNALSYM KDF_GENERIC_PARAMETER} KDF_KEYBITLENGTH = $12; {$EXTERNALSYM KDF_KEYBITLENGTH} // // DeriveKey Flags: // // KDF_USE_SECRET_AS_HMAC_KEY_FLAG causes the secret agreement to serve also // as the HMAC key. If this flag is used, the KDF_HMAC_KEY parameter should // NOT be specified. // const KDF_USE_SECRET_AS_HMAC_KEY_FLAG = $1; {$EXTERNALSYM KDF_USE_SECRET_AS_HMAC_KEY_FLAG} // // BCrypt structs // type PBCryptKeyLengthsStruct = ^TBCryptKeyLengthsStruct; __BCRYPT_KEY_LENGTHS_STRUCT = record dwMinLength: ULONG; dwMaxLength: ULONG; dwIncrement: ULONG; end; {$EXTERNALSYM __BCRYPT_KEY_LENGTHS_STRUCT} BCRYPT_KEY_LENGTHS_STRUCT = __BCRYPT_KEY_LENGTHS_STRUCT; {$EXTERNALSYM BCRYPT_KEY_LENGTHS_STRUCT} TBCryptKeyLengthsStruct = __BCRYPT_KEY_LENGTHS_STRUCT; type PBCryptAuthTagLengthsStruct = ^TBCryptAuthTagLengthsStruct; BCRYPT_AUTH_TAG_LENGTHS_STRUCT = __BCRYPT_KEY_LENGTHS_STRUCT; {$EXTERNALSYM BCRYPT_AUTH_TAG_LENGTHS_STRUCT} TBCryptAuthTagLengthsStruct = __BCRYPT_KEY_LENGTHS_STRUCT; type PBCryptOID = ^TBCryptOID; _BCRYPT_OID = record cbOID: ULONG; pbOID: PUCHAR; end; {$EXTERNALSYM _BCRYPT_OID} BCRYPT_OID = _BCRYPT_OID; {$EXTERNALSYM BCRYPT_OID} TBCryptOID = _BCRYPT_OID; type PBCryptOIDList = ^TBCryptOIDList; _BCRYPT_OID_LIST = record dwOIDCount: ULONG; pOIDs: PBCryptOID; end; {$EXTERNALSYM _BCRYPT_OID_LIST} BCRYPT_OID_LIST = _BCRYPT_OID_LIST; {$EXTERNALSYM BCRYPT_OID_LIST} TBCryptOIDList = _BCRYPT_OID_LIST; type PBCryptPKCS1PaddingInfo = ^TBCryptPKCS1PaddingInfo; _BCRYPT_PKCS1_PADDING_INFO = record pszAlgId: LPCWSTR; end; {$EXTERNALSYM _BCRYPT_PKCS1_PADDING_INFO} BCRYPT_PKCS1_PADDING_INFO = _BCRYPT_PKCS1_PADDING_INFO; {$EXTERNALSYM BCRYPT_PKCS1_PADDING_INFO} TBCryptPKCS1PaddingInfo = _BCRYPT_PKCS1_PADDING_INFO; type PBCryptPSSPaddingInfo = ^TBCryptPSSPaddingInfo; _BCRYPT_PSS_PADDING_INFO = record pszAlgId: LPCWSTR; cbSalt: ULONG; end; {$EXTERNALSYM _BCRYPT_PSS_PADDING_INFO} BCRYPT_PSS_PADDING_INFO = _BCRYPT_PSS_PADDING_INFO; {$EXTERNALSYM BCRYPT_PSS_PADDING_INFO} TBCryptPSSPaddingInfo = _BCRYPT_PSS_PADDING_INFO; type PBCryptOAEPPaddingInfo = ^TBCryptOAEPPaddingInfo; _BCRYPT_OAEP_PADDING_INFO = record pszAlgId: LPCWSTR; pbLabel: PUCHAR; cbLabel: ULONG; end; {$EXTERNALSYM _BCRYPT_OAEP_PADDING_INFO} BCRYPT_OAEP_PADDING_INFO = _BCRYPT_OAEP_PADDING_INFO; {$EXTERNALSYM BCRYPT_OAEP_PADDING_INFO} TBCryptOAEPPaddingInfo = _BCRYPT_OAEP_PADDING_INFO; const BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION = 1; {$EXTERNALSYM BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION} BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG = $00000001; {$EXTERNALSYM BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG} BCRYPT_AUTH_MODE_IN_PROGRESS_FLAG = $00000002; {$EXTERNALSYM BCRYPT_AUTH_MODE_IN_PROGRESS_FLAG} type PBCryptAuthenticatedCipherModeInfo = ^TBCryptAuthenticatedCipherModeInfo; _BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO = record cbSize: ULONG; dwInfoVersion: ULONG; pbNonce: PUCHAR; cbNonce: ULONG; pbAuthData: PUCHAR; cbAuthData: ULONG; pbTag: PUCHAR; cbTag: ULONG; pbMacContext: PUCHAR; cbMacContext: ULONG; cbAAD: ULONG; cbData: ULONGLONG; dwFlags: ULONG; end; {$EXTERNALSYM _BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO} BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO = _BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO; {$EXTERNALSYM BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO} TBCryptAuthenticatedCipherModeInfo = _BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO; PBCRYPT_AUTHENTICATED_CIPHER_MODE_INFO = PBCryptAuthenticatedCipherModeInfo; {$EXTERNALSYM PBCRYPT_AUTHENTICATED_CIPHER_MODE_INFO} procedure BCRYPT_INIT_AUTH_MODE_INFO(var _AUTH_INFO_STRUCT_: TBCryptAuthenticatedCipherModeInfo); inline; {$EXTERNALSYM BCRYPT_INIT_AUTH_MODE_INFO} // // BCrypt String Properties // // BCrypt(Import/Export)Key BLOB types const BCRYPT_OPAQUE_KEY_BLOB = 'OpaqueKeyBlob'; {$EXTERNALSYM BCRYPT_OPAQUE_KEY_BLOB} BCRYPT_KEY_DATA_BLOB = 'KeyDataBlob'; {$EXTERNALSYM BCRYPT_KEY_DATA_BLOB} BCRYPT_AES_WRAP_KEY_BLOB = 'Rfc3565KeyWrapBlob'; {$EXTERNALSYM BCRYPT_AES_WRAP_KEY_BLOB} // BCryptGetProperty strings const BCRYPT_OBJECT_LENGTH = 'ObjectLength'; {$EXTERNALSYM BCRYPT_OBJECT_LENGTH} BCRYPT_ALGORITHM_NAME = 'AlgorithmName'; {$EXTERNALSYM BCRYPT_ALGORITHM_NAME} BCRYPT_PROVIDER_HANDLE = 'ProviderHandle'; {$EXTERNALSYM BCRYPT_PROVIDER_HANDLE} BCRYPT_CHAINING_MODE = 'ChainingMode'; {$EXTERNALSYM BCRYPT_CHAINING_MODE} BCRYPT_BLOCK_LENGTH = 'BlockLength'; {$EXTERNALSYM BCRYPT_BLOCK_LENGTH} BCRYPT_KEY_LENGTH = 'KeyLength'; {$EXTERNALSYM BCRYPT_KEY_LENGTH} BCRYPT_KEY_OBJECT_LENGTH = 'KeyObjectLength'; {$EXTERNALSYM BCRYPT_KEY_OBJECT_LENGTH} BCRYPT_KEY_STRENGTH = 'KeyStrength'; {$EXTERNALSYM BCRYPT_KEY_STRENGTH} BCRYPT_KEY_LENGTHS = 'KeyLengths'; {$EXTERNALSYM BCRYPT_KEY_LENGTHS} BCRYPT_BLOCK_SIZE_LIST = 'BlockSizeList'; {$EXTERNALSYM BCRYPT_BLOCK_SIZE_LIST} BCRYPT_EFFECTIVE_KEY_LENGTH = 'EffectiveKeyLength'; {$EXTERNALSYM BCRYPT_EFFECTIVE_KEY_LENGTH} BCRYPT_HASH_LENGTH = 'HashDigestLength'; {$EXTERNALSYM BCRYPT_HASH_LENGTH} BCRYPT_HASH_OID_LIST = 'HashOIDList'; {$EXTERNALSYM BCRYPT_HASH_OID_LIST} BCRYPT_PADDING_SCHEMES = 'PaddingSchemes'; {$EXTERNALSYM BCRYPT_PADDING_SCHEMES} BCRYPT_SIGNATURE_LENGTH = 'SignatureLength'; {$EXTERNALSYM BCRYPT_SIGNATURE_LENGTH} BCRYPT_HASH_BLOCK_LENGTH = 'HashBlockLength'; {$EXTERNALSYM BCRYPT_HASH_BLOCK_LENGTH} BCRYPT_AUTH_TAG_LENGTH = 'AuthTagLength'; {$EXTERNALSYM BCRYPT_AUTH_TAG_LENGTH} BCRYPT_PRIMITIVE_TYPE = 'PrimitiveType'; {$EXTERNALSYM BCRYPT_PRIMITIVE_TYPE} BCRYPT_IS_KEYED_HASH = 'IsKeyedHash'; {$EXTERNALSYM BCRYPT_IS_KEYED_HASH} BCRYPT_IS_REUSABLE_HASH = 'IsReusableHash'; {$EXTERNALSYM BCRYPT_IS_REUSABLE_HASH} BCRYPT_MESSAGE_BLOCK_LENGTH = 'MessageBlockLength'; {$EXTERNALSYM BCRYPT_MESSAGE_BLOCK_LENGTH} // Additional BCryptGetProperty strings for the RNG Platform Crypto Provider const BCRYPT_PCP_PLATFORM_TYPE_PROPERTY = 'PCP_PLATFORM_TYPE'; {$EXTERNALSYM BCRYPT_PCP_PLATFORM_TYPE_PROPERTY} BCRYPT_PCP_PROVIDER_VERSION_PROPERTY = 'PCP_PROVIDER_VERSION'; {$EXTERNALSYM BCRYPT_PCP_PROVIDER_VERSION_PROPERTY} // BCryptSetProperty strings const BCRYPT_INITIALIZATION_VECTOR = 'IV'; {$EXTERNALSYM BCRYPT_INITIALIZATION_VECTOR} // Property Strings const BCRYPT_CHAIN_MODE_NA = 'ChainingModeN/A'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_NA} BCRYPT_CHAIN_MODE_CBC = 'ChainingModeCBC'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_CBC} BCRYPT_CHAIN_MODE_ECB = 'ChainingModeECB'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_ECB} BCRYPT_CHAIN_MODE_CFB = 'ChainingModeCFB'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_CFB} BCRYPT_CHAIN_MODE_CCM = 'ChainingModeCCM'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_CCM} BCRYPT_CHAIN_MODE_GCM = 'ChainingModeGCM'; {$EXTERNALSYM BCRYPT_CHAIN_MODE_GCM} // Supported RSA Padding Types const BCRYPT_SUPPORTED_PAD_ROUTER = $00000001; {$EXTERNALSYM BCRYPT_SUPPORTED_PAD_ROUTER} BCRYPT_SUPPORTED_PAD_PKCS1_ENC = $00000002; {$EXTERNALSYM BCRYPT_SUPPORTED_PAD_PKCS1_ENC} BCRYPT_SUPPORTED_PAD_PKCS1_SIG = $00000004; {$EXTERNALSYM BCRYPT_SUPPORTED_PAD_PKCS1_SIG} BCRYPT_SUPPORTED_PAD_OAEP = $00000008; {$EXTERNALSYM BCRYPT_SUPPORTED_PAD_OAEP} BCRYPT_SUPPORTED_PAD_PSS = $00000010; {$EXTERNALSYM BCRYPT_SUPPORTED_PAD_PSS} // // BCrypt Flags // const BCRYPT_PROV_DISPATCH = $00000001; // BCryptOpenAlgorithmProvider {$EXTERNALSYM BCRYPT_PROV_DISPATCH} BCRYPT_BLOCK_PADDING = $00000001; // BCryptEncrypt/Decrypt {$EXTERNALSYM BCRYPT_BLOCK_PADDING} // RSA padding schemes const BCRYPT_PAD_NONE = $00000001; {$EXTERNALSYM BCRYPT_PAD_NONE} BCRYPT_PAD_PKCS1 = $00000002; // BCryptEncrypt/Decrypt BCryptSignHash/VerifySignature {$EXTERNALSYM BCRYPT_PAD_PKCS1} BCRYPT_PAD_OAEP = $00000004; // BCryptEncrypt/Decrypt {$EXTERNALSYM BCRYPT_PAD_OAEP} BCRYPT_PAD_PSS = $00000008; // BCryptSignHash/VerifySignature {$EXTERNALSYM BCRYPT_PAD_PSS} BCRYPTBUFFER_VERSION = 0; {$EXTERNALSYM BCRYPTBUFFER_VERSION} type PBCryptBuffer = ^TBCryptBuffer; _BCryptBuffer = record cbBuffer: ULONG; // Length of buffer, in bytes BufferType: ULONG; // Buffer type pvBuffer: PVOID; // Pointer to buffer end; {$EXTERNALSYM _BCryptBuffer} BCryptBuffer = _BCryptBuffer; {$EXTERNALSYM BCryptBuffer} TBCryptBuffer = _BCryptBuffer; type PBCryptBufferDesc = ^TBCryptBufferDesc; _BCryptBufferDesc = record ulVersion: ULONG; // Version number cBuffers: ULONG; // Number of buffers pBuffers: PBCryptBuffer; // Pointer to array of buffers end; {$EXTERNALSYM _BCryptBufferDesc} BCryptBufferDesc = _BCryptBufferDesc; {$EXTERNALSYM BCryptBufferDesc} TBCryptBufferDesc = _BCryptBufferDesc; // // Primitive handles // type BCRYPT_HANDLE = PVOID; {$EXTERNALSYM BCRYPT_HANDLE} BCRYPT_ALG_HANDLE = PVOID; {$EXTERNALSYM BCRYPT_ALG_HANDLE} BCRYPT_KEY_HANDLE = PVOID; {$EXTERNALSYM BCRYPT_KEY_HANDLE} BCRYPT_HASH_HANDLE = PVOID; {$EXTERNALSYM BCRYPT_HASH_HANDLE} BCRYPT_SECRET_HANDLE = PVOID; {$EXTERNALSYM BCRYPT_SECRET_HANDLE} // // Structures used to represent key blobs. // const BCRYPT_PUBLIC_KEY_BLOB = 'PUBLICBLOB'; {$EXTERNALSYM BCRYPT_PUBLIC_KEY_BLOB} BCRYPT_PRIVATE_KEY_BLOB = 'PRIVATEBLOB'; {$EXTERNALSYM BCRYPT_PRIVATE_KEY_BLOB} type PBCryptKeyBlob = ^TBCryptKeyBlob; _BCRYPT_KEY_BLOB = record Magic: ULONG; end; {$EXTERNALSYM _BCRYPT_KEY_BLOB} BCRYPT_KEY_BLOB = _BCRYPT_KEY_BLOB; {$EXTERNALSYM BCRYPT_KEY_BLOB} TBCryptKeyBlob = _BCRYPT_KEY_BLOB; // The BCRYPT_RSAPUBLIC_BLOB and BCRYPT_RSAPRIVATE_BLOB blob types are used // to transport plaintext RSA keys. These blob types will be supported by // all RSA primitive providers. // The BCRYPT_RSAPRIVATE_BLOB includes the following values: // Public Exponent // Modulus // Prime1 // Prime2 const BCRYPT_RSAPUBLIC_BLOB = 'RSAPUBLICBLOB'; {$EXTERNALSYM BCRYPT_RSAPUBLIC_BLOB} BCRYPT_RSAPRIVATE_BLOB = 'RSAPRIVATEBLOB'; {$EXTERNALSYM BCRYPT_RSAPRIVATE_BLOB} LEGACY_RSAPUBLIC_BLOB = 'CAPIPUBLICBLOB'; {$EXTERNALSYM LEGACY_RSAPUBLIC_BLOB} LEGACY_RSAPRIVATE_BLOB = 'CAPIPRIVATEBLOB'; {$EXTERNALSYM LEGACY_RSAPRIVATE_BLOB} BCRYPT_RSAPUBLIC_MAGIC = $31415352; // RSA1 {$EXTERNALSYM BCRYPT_RSAPUBLIC_MAGIC} BCRYPT_RSAPRIVATE_MAGIC = $32415352; // RSA2 {$EXTERNALSYM BCRYPT_RSAPRIVATE_MAGIC} type PBCryptRSAKeyBlob = ^TBCryptRSAKeyBlob; _BCRYPT_RSAKEY_BLOB = record Magic: ULONG; BitLength: ULONG; cbPublicExp: ULONG; cbModulus: ULONG; cbPrime1: ULONG; cbPrime2: ULONG; end; {$EXTERNALSYM _BCRYPT_RSAKEY_BLOB} BCRYPT_RSAKEY_BLOB = _BCRYPT_RSAKEY_BLOB; {$EXTERNALSYM BCRYPT_RSAKEY_BLOB} TBCryptRSAKeyBlob = _BCRYPT_RSAKEY_BLOB; // The BCRYPT_RSAFULLPRIVATE_BLOB blob type is used to transport // plaintext private RSA keys. It includes the following values: // Public Exponent // Modulus // Prime1 // Prime2 // Private Exponent mod (Prime1 - 1) // Private Exponent mod (Prime2 - 1) // Inverse of Prime2 mod Prime1 // PrivateExponent const BCRYPT_RSAFULLPRIVATE_BLOB = 'RSAFULLPRIVATEBLOB'; {$EXTERNALSYM BCRYPT_RSAFULLPRIVATE_BLOB} BCRYPT_RSAFULLPRIVATE_MAGIC = $33415352; // RSA3 {$EXTERNALSYM BCRYPT_RSAFULLPRIVATE_MAGIC} //Properties of secret agreement algorithms const BCRYPT_GLOBAL_PARAMETERS = 'SecretAgreementParam'; {$EXTERNALSYM BCRYPT_GLOBAL_PARAMETERS} BCRYPT_PRIVATE_KEY = 'PrivKeyVal'; {$EXTERNALSYM BCRYPT_PRIVATE_KEY} // The BCRYPT_ECCPUBLIC_BLOB and BCRYPT_ECCPRIVATE_BLOB blob types are used // to transport plaintext ECC keys. These blob types will be supported by // all ECC primitive providers. const BCRYPT_ECCPUBLIC_BLOB = 'ECCPUBLICBLOB'; {$EXTERNALSYM BCRYPT_ECCPUBLIC_BLOB} BCRYPT_ECCPRIVATE_BLOB = 'ECCPRIVATEBLOB'; {$EXTERNALSYM BCRYPT_ECCPRIVATE_BLOB} BCRYPT_ECDH_PUBLIC_P256_MAGIC = $314B4345; // ECK1 {$EXTERNALSYM BCRYPT_ECDH_PUBLIC_P256_MAGIC} BCRYPT_ECDH_PRIVATE_P256_MAGIC = $324B4345; // ECK2 {$EXTERNALSYM BCRYPT_ECDH_PRIVATE_P256_MAGIC} BCRYPT_ECDH_PUBLIC_P384_MAGIC = $334B4345; // ECK3 {$EXTERNALSYM BCRYPT_ECDH_PUBLIC_P384_MAGIC} BCRYPT_ECDH_PRIVATE_P384_MAGIC = $344B4345; // ECK4 {$EXTERNALSYM BCRYPT_ECDH_PRIVATE_P384_MAGIC} BCRYPT_ECDH_PUBLIC_P521_MAGIC = $354B4345; // ECK5 {$EXTERNALSYM BCRYPT_ECDH_PUBLIC_P521_MAGIC} BCRYPT_ECDH_PRIVATE_P521_MAGIC = $364B4345; // ECK6 {$EXTERNALSYM BCRYPT_ECDH_PRIVATE_P521_MAGIC} BCRYPT_ECDSA_PUBLIC_P256_MAGIC = $31534345; // ECS1 {$EXTERNALSYM BCRYPT_ECDSA_PUBLIC_P256_MAGIC} BCRYPT_ECDSA_PRIVATE_P256_MAGIC = $32534345; // ECS2 {$EXTERNALSYM BCRYPT_ECDSA_PRIVATE_P256_MAGIC} BCRYPT_ECDSA_PUBLIC_P384_MAGIC = $33534345; // ECS3 {$EXTERNALSYM BCRYPT_ECDSA_PUBLIC_P384_MAGIC} BCRYPT_ECDSA_PRIVATE_P384_MAGIC = $34534345; // ECS4 {$EXTERNALSYM BCRYPT_ECDSA_PRIVATE_P384_MAGIC} BCRYPT_ECDSA_PUBLIC_P521_MAGIC = $35534345; // ECS5 {$EXTERNALSYM BCRYPT_ECDSA_PUBLIC_P521_MAGIC} BCRYPT_ECDSA_PRIVATE_P521_MAGIC = $36534345; // ECS6 {$EXTERNALSYM BCRYPT_ECDSA_PRIVATE_P521_MAGIC} type PBCryptECCKeyBlob = ^TBCryptECCKeyBlob; _BCRYPT_ECCKEY_BLOB = record dwMagic: ULONG; cbKey: ULONG; end; {$EXTERNALSYM _BCRYPT_ECCKEY_BLOB} BCRYPT_ECCKEY_BLOB = _BCRYPT_ECCKEY_BLOB; {$EXTERNALSYM BCRYPT_ECCKEY_BLOB} TBCryptECCKeyBlob = _BCRYPT_ECCKEY_BLOB; PBCRYPT_ECCKEY_BLOB = PBCryptECCKeyBlob; {$EXTERNALSYM PBCRYPT_ECCKEY_BLOB} // The BCRYPT_DH_PUBLIC_BLOB and BCRYPT_DH_PRIVATE_BLOB blob types are used // to transport plaintext DH keys. These blob types will be supported by // all DH primitive providers. const BCRYPT_DH_PUBLIC_BLOB = 'DHPUBLICBLOB'; {$EXTERNALSYM BCRYPT_DH_PUBLIC_BLOB} BCRYPT_DH_PRIVATE_BLOB = 'DHPRIVATEBLOB'; {$EXTERNALSYM BCRYPT_DH_PRIVATE_BLOB} LEGACY_DH_PUBLIC_BLOB = 'CAPIDHPUBLICBLOB'; {$EXTERNALSYM LEGACY_DH_PUBLIC_BLOB} LEGACY_DH_PRIVATE_BLOB = 'CAPIDHPRIVATEBLOB'; {$EXTERNALSYM LEGACY_DH_PRIVATE_BLOB} BCRYPT_DH_PUBLIC_MAGIC = $42504844; // DHPB {$EXTERNALSYM BCRYPT_DH_PUBLIC_MAGIC} BCRYPT_DH_PRIVATE_MAGIC = $56504844; // DHPV {$EXTERNALSYM BCRYPT_DH_PRIVATE_MAGIC} type PBCryptDHKeyBlob = ^TBCryptDHKeyBlob; _BCRYPT_DH_KEY_BLOB = record dwMagic: ULONG; cbKey: ULONG; end; {$EXTERNALSYM _BCRYPT_DH_KEY_BLOB} BCRYPT_DH_KEY_BLOB = _BCRYPT_DH_KEY_BLOB; {$EXTERNALSYM BCRYPT_DH_KEY_BLOB} TBCryptDHKeyBlob = _BCRYPT_DH_KEY_BLOB; PBCRYPT_DH_KEY_BLOB = PBCryptDHKeyBlob; {$EXTERNALSYM PBCRYPT_DH_KEY_BLOB} // Property Strings for DH const BCRYPT_DH_PARAMETERS = 'DHParameters'; {$EXTERNALSYM BCRYPT_DH_PARAMETERS} BCRYPT_DH_PARAMETERS_MAGIC = $4d504844; // DHPM {$EXTERNALSYM BCRYPT_DH_PARAMETERS_MAGIC} type PBCryptDHParameterHeader = ^TBCryptDHParameterHeader; _BCRYPT_DH_PARAMETER_HEADER = record cbLength: ULONG; dwMagic: ULONG; cbKeyLength: ULONG; end; {$EXTERNALSYM _BCRYPT_DH_PARAMETER_HEADER} BCRYPT_DH_PARAMETER_HEADER = _BCRYPT_DH_PARAMETER_HEADER; {$EXTERNALSYM BCRYPT_DH_PARAMETER_HEADER} TBCryptDHParameterHeader = _BCRYPT_DH_PARAMETER_HEADER; // The BCRYPT_DSA_PUBLIC_BLOB and BCRYPT_DSA_PRIVATE_BLOB blob types are used // to transport plaintext DSA keys. These blob types will be supported by // all DSA primitive providers. const BCRYPT_DSA_PUBLIC_BLOB = 'DSAPUBLICBLOB'; {$EXTERNALSYM BCRYPT_DSA_PUBLIC_BLOB} BCRYPT_DSA_PRIVATE_BLOB = 'DSAPRIVATEBLOB'; {$EXTERNALSYM BCRYPT_DSA_PRIVATE_BLOB} LEGACY_DSA_PUBLIC_BLOB = 'CAPIDSAPUBLICBLOB'; {$EXTERNALSYM LEGACY_DSA_PUBLIC_BLOB} LEGACY_DSA_PRIVATE_BLOB = 'CAPIDSAPRIVATEBLOB'; {$EXTERNALSYM LEGACY_DSA_PRIVATE_BLOB} LEGACY_DSA_V2_PUBLIC_BLOB = 'V2CAPIDSAPUBLICBLOB'; {$EXTERNALSYM LEGACY_DSA_V2_PUBLIC_BLOB} LEGACY_DSA_V2_PRIVATE_BLOB = 'V2CAPIDSAPRIVATEBLOB'; {$EXTERNALSYM LEGACY_DSA_V2_PRIVATE_BLOB} BCRYPT_DSA_PUBLIC_MAGIC = $42505344; // DSPB {$EXTERNALSYM BCRYPT_DSA_PUBLIC_MAGIC} BCRYPT_DSA_PRIVATE_MAGIC = $56505344; // DSPV {$EXTERNALSYM BCRYPT_DSA_PRIVATE_MAGIC} BCRYPT_DSA_PUBLIC_MAGIC_V2 = $32425044; // DPB2 {$EXTERNALSYM BCRYPT_DSA_PUBLIC_MAGIC_V2} BCRYPT_DSA_PRIVATE_MAGIC_V2 = $32565044; // DPV2 {$EXTERNALSYM BCRYPT_DSA_PRIVATE_MAGIC_V2} type PBCryptDSAKeyBlob = ^TBCryptDSAKeyBlob; _BCRYPT_DSA_KEY_BLOB = record dwMagic: ULONG; cbKey: ULONG; Count: array [0..3] of UCHAR; Seed: array [0..19] of UCHAR; q: array [0..19] of UCHAR; end; {$EXTERNALSYM _BCRYPT_DSA_KEY_BLOB} BCRYPT_DSA_KEY_BLOB = _BCRYPT_DSA_KEY_BLOB; {$EXTERNALSYM BCRYPT_DSA_KEY_BLOB} TBCryptDSAKeyBlob = _BCRYPT_DSA_KEY_BLOB; PBCRYPT_DSA_KEY_BLOB = PBCryptDSAKeyBlob; {$EXTERNALSYM PBCRYPT_DSA_KEY_BLOB} type PHashAlgorithmEnum = ^THashAlgorithmEnum; HASHALGORITHM_ENUM = ( DSA_HASH_ALGORITHM_SHA1, DSA_HASH_ALGORITHM_SHA256, DSA_HASH_ALGORITHM_SHA512 ); {$EXTERNALSYM HASHALGORITHM_ENUM} THashAlgorithmEnum = HASHALGORITHM_ENUM; type PDSAFipsVersionEnum = ^TDSAFipsVersionEnum; DSAFIPSVERSION_ENUM = ( DSA_FIPS186_2, DSA_FIPS186_3 ); {$EXTERNALSYM DSAFIPSVERSION_ENUM} TDSAFipsVersionEnum = DSAFIPSVERSION_ENUM; type PBCryptDSAKeyBlobV2 = ^TBCryptDSAKeyBlobV2; _BCRYPT_DSA_KEY_BLOB_V2 = record dwMagic: ULONG; cbKey: ULONG; hashAlgorithm: THashAlgorithmEnum; standardVersion: TDSAFipsVersionEnum; cbSeedLength: ULONG; cbGroupSize: ULONG; Count: array [0..3] of UCHAR; end; {$EXTERNALSYM _BCRYPT_DSA_KEY_BLOB_V2} BCRYPT_DSA_KEY_BLOB_V2 = _BCRYPT_DSA_KEY_BLOB_V2; {$EXTERNALSYM BCRYPT_DSA_KEY_BLOB_V2} TBCryptDSAKeyBlobV2 = _BCRYPT_DSA_KEY_BLOB_V2; PBCRYPT_DSA_KEY_BLOB_V2 = PBCryptDSAKeyBlobV2; {$EXTERNALSYM PBCRYPT_DSA_KEY_BLOB_V2} type PBCryptKeyDataBlobHeader = ^TBCryptKeyDataBlobHeader; _BCRYPT_KEY_DATA_BLOB_HEADER = record dwMagic: ULONG; dwVersion: ULONG; cbKeyData: ULONG; end; {$EXTERNALSYM _BCRYPT_KEY_DATA_BLOB_HEADER} BCRYPT_KEY_DATA_BLOB_HEADER = _BCRYPT_KEY_DATA_BLOB_HEADER; {$EXTERNALSYM BCRYPT_KEY_DATA_BLOB_HEADER} TBCryptKeyDataBlobHeader = _BCRYPT_KEY_DATA_BLOB_HEADER; PBCRYPT_KEY_DATA_BLOB_HEADER = PBCryptKeyDataBlobHeader; {$EXTERNALSYM PBCRYPT_KEY_DATA_BLOB_HEADER} const BCRYPT_KEY_DATA_BLOB_MAGIC = $4d42444b; //Key Data Blob Magic (KDBM) {$EXTERNALSYM BCRYPT_KEY_DATA_BLOB_MAGIC} BCRYPT_KEY_DATA_BLOB_VERSION1 = $1; {$EXTERNALSYM BCRYPT_KEY_DATA_BLOB_VERSION1} // Property Strings for DSA const BCRYPT_DSA_PARAMETERS = 'DSAParameters'; {$EXTERNALSYM BCRYPT_DSA_PARAMETERS} BCRYPT_DSA_PARAMETERS_MAGIC = $4d505344; // DSPM {$EXTERNALSYM BCRYPT_DSA_PARAMETERS_MAGIC} BCRYPT_DSA_PARAMETERS_MAGIC_V2 = $324d5044; // DPM2 {$EXTERNALSYM BCRYPT_DSA_PARAMETERS_MAGIC_V2} type PBCryptDSAParameterHeader = ^TBCryptDSAParameterHeader; _BCRYPT_DSA_PARAMETER_HEADER = record cbLength: ULONG; dwMagic: ULONG; cbKeyLength: ULONG; Count: array [0..3] of UCHAR; Seed: array [0..19] of UCHAR; q: array [0..19] of UCHAR; end; {$EXTERNALSYM _BCRYPT_DSA_PARAMETER_HEADER} BCRYPT_DSA_PARAMETER_HEADER = _BCRYPT_DSA_PARAMETER_HEADER; {$EXTERNALSYM BCRYPT_DSA_PARAMETER_HEADER} TBCryptDSAParameterHeader = _BCRYPT_DSA_PARAMETER_HEADER; type PBCryptDSAParameterHeaderV2 = ^TBCryptDSAParameterHeaderV2; _BCRYPT_DSA_PARAMETER_HEADER_V2 = record cbLength: ULONG; dwMagic: ULONG; cbKeyLength: ULONG; hashAlgorithm: THashAlgorithmEnum; standardVersion: TDSAFipsVersionEnum; cbSeedLength: ULONG; cbGroupSize: ULONG; Count: array [0..3] of UCHAR; end; {$EXTERNALSYM _BCRYPT_DSA_PARAMETER_HEADER_V2} BCRYPT_DSA_PARAMETER_HEADER_V2 = _BCRYPT_DSA_PARAMETER_HEADER_V2; {$EXTERNALSYM BCRYPT_DSA_PARAMETER_HEADER_V2} TBCryptDSAParameterHeaderV2 = _BCRYPT_DSA_PARAMETER_HEADER_V2; // // Microsoft built-in providers. // const MS_PRIMITIVE_PROVIDER = 'Microsoft Primitive Provider'; {$EXTERNALSYM MS_PRIMITIVE_PROVIDER} MS_PLATFORM_CRYPTO_PROVIDER = 'Microsoft Platform Crypto Provider'; {$EXTERNALSYM MS_PLATFORM_CRYPTO_PROVIDER} // // Common algorithm identifiers. // const BCRYPT_RSA_ALGORITHM = 'RSA'; {$EXTERNALSYM BCRYPT_RSA_ALGORITHM} BCRYPT_RSA_SIGN_ALGORITHM = 'RSA_SIGN'; {$EXTERNALSYM BCRYPT_RSA_SIGN_ALGORITHM} BCRYPT_DH_ALGORITHM = 'DH'; {$EXTERNALSYM BCRYPT_DH_ALGORITHM} BCRYPT_DSA_ALGORITHM = 'DSA'; {$EXTERNALSYM BCRYPT_DSA_ALGORITHM} BCRYPT_RC2_ALGORITHM = 'RC2'; {$EXTERNALSYM BCRYPT_RC2_ALGORITHM} BCRYPT_RC4_ALGORITHM = 'RC4'; {$EXTERNALSYM BCRYPT_RC4_ALGORITHM} BCRYPT_AES_ALGORITHM = 'AES'; {$EXTERNALSYM BCRYPT_AES_ALGORITHM} BCRYPT_DES_ALGORITHM = 'DES'; {$EXTERNALSYM BCRYPT_DES_ALGORITHM} BCRYPT_DESX_ALGORITHM = 'DESX'; {$EXTERNALSYM BCRYPT_DESX_ALGORITHM} BCRYPT_3DES_ALGORITHM = '3DES'; {$EXTERNALSYM BCRYPT_3DES_ALGORITHM} BCRYPT_3DES_112_ALGORITHM = '3DES_112'; {$EXTERNALSYM BCRYPT_3DES_112_ALGORITHM} BCRYPT_MD2_ALGORITHM = 'MD2'; {$EXTERNALSYM BCRYPT_MD2_ALGORITHM} BCRYPT_MD4_ALGORITHM = 'MD4'; {$EXTERNALSYM BCRYPT_MD4_ALGORITHM} BCRYPT_MD5_ALGORITHM = 'MD5'; {$EXTERNALSYM BCRYPT_MD5_ALGORITHM} BCRYPT_SHA1_ALGORITHM = 'SHA1'; {$EXTERNALSYM BCRYPT_SHA1_ALGORITHM} BCRYPT_SHA256_ALGORITHM = 'SHA256'; {$EXTERNALSYM BCRYPT_SHA256_ALGORITHM} BCRYPT_SHA384_ALGORITHM = 'SHA384'; {$EXTERNALSYM BCRYPT_SHA384_ALGORITHM} BCRYPT_SHA512_ALGORITHM = 'SHA512'; {$EXTERNALSYM BCRYPT_SHA512_ALGORITHM} BCRYPT_AES_GMAC_ALGORITHM = 'AES-GMAC'; {$EXTERNALSYM BCRYPT_AES_GMAC_ALGORITHM} BCRYPT_AES_CMAC_ALGORITHM = 'AES-CMAC'; {$EXTERNALSYM BCRYPT_AES_CMAC_ALGORITHM} BCRYPT_ECDSA_P256_ALGORITHM = 'ECDSA_P256'; {$EXTERNALSYM BCRYPT_ECDSA_P256_ALGORITHM} BCRYPT_ECDSA_P384_ALGORITHM = 'ECDSA_P384'; {$EXTERNALSYM BCRYPT_ECDSA_P384_ALGORITHM} BCRYPT_ECDSA_P521_ALGORITHM = 'ECDSA_P521'; {$EXTERNALSYM BCRYPT_ECDSA_P521_ALGORITHM} BCRYPT_ECDH_P256_ALGORITHM = 'ECDH_P256'; {$EXTERNALSYM BCRYPT_ECDH_P256_ALGORITHM} BCRYPT_ECDH_P384_ALGORITHM = 'ECDH_P384'; {$EXTERNALSYM BCRYPT_ECDH_P384_ALGORITHM} BCRYPT_ECDH_P521_ALGORITHM = 'ECDH_P521'; {$EXTERNALSYM BCRYPT_ECDH_P521_ALGORITHM} BCRYPT_RNG_ALGORITHM = 'RNG'; {$EXTERNALSYM BCRYPT_RNG_ALGORITHM} BCRYPT_RNG_FIPS186_DSA_ALGORITHM = 'FIPS186DSARNG'; {$EXTERNALSYM BCRYPT_RNG_FIPS186_DSA_ALGORITHM} BCRYPT_RNG_DUAL_EC_ALGORITHM = 'DUALECRNG'; {$EXTERNALSYM BCRYPT_RNG_DUAL_EC_ALGORITHM} BCRYPT_SP800108_CTR_HMAC_ALGORITHM = 'SP800_108_CTR_HMAC'; {$EXTERNALSYM BCRYPT_SP800108_CTR_HMAC_ALGORITHM} BCRYPT_SP80056A_CONCAT_ALGORITHM = 'SP800_56A_CONCAT'; {$EXTERNALSYM BCRYPT_SP80056A_CONCAT_ALGORITHM} BCRYPT_PBKDF2_ALGORITHM = 'PBKDF2'; {$EXTERNALSYM BCRYPT_PBKDF2_ALGORITHM} BCRYPT_CAPI_KDF_ALGORITHM = 'CAPI_KDF'; {$EXTERNALSYM BCRYPT_CAPI_KDF_ALGORITHM} // // Interfaces // const BCRYPT_CIPHER_INTERFACE = $00000001; {$EXTERNALSYM BCRYPT_CIPHER_INTERFACE} BCRYPT_HASH_INTERFACE = $00000002; {$EXTERNALSYM BCRYPT_HASH_INTERFACE} BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE = $00000003; {$EXTERNALSYM BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE} BCRYPT_SECRET_AGREEMENT_INTERFACE = $00000004; {$EXTERNALSYM BCRYPT_SECRET_AGREEMENT_INTERFACE} BCRYPT_SIGNATURE_INTERFACE = $00000005; {$EXTERNALSYM BCRYPT_SIGNATURE_INTERFACE} BCRYPT_RNG_INTERFACE = $00000006; {$EXTERNALSYM BCRYPT_RNG_INTERFACE} BCRYPT_KEY_DERIVATION_INTERFACE = $00000007; {$EXTERNALSYM BCRYPT_KEY_DERIVATION_INTERFACE} // // Primitive algorithm provider functions. // const BCRYPT_ALG_HANDLE_HMAC_FLAG = $00000008; {$EXTERNALSYM BCRYPT_ALG_HANDLE_HMAC_FLAG} BCRYPT_CAPI_AES_FLAG = $00000010; {$EXTERNALSYM BCRYPT_CAPI_AES_FLAG} BCRYPT_HASH_REUSABLE_FLAG = $00000020; {$EXTERNALSYM BCRYPT_HASH_REUSABLE_FLAG} // // The BUFFERS_LOCKED flag used in BCryptEncrypt/BCryptDecrypt signals that // the pbInput and pbOutput buffers have been locked (see MmProbeAndLockPages) // and CNG may not lock the buffers again. // This flag applies only to kernel mode, it is ignored in user mode. // const BCRYPT_BUFFERS_LOCKED_FLAG = $00000040; {$EXTERNALSYM BCRYPT_BUFFERS_LOCKED_FLAG} function BCryptOpenAlgorithmProvider( out phAlgorithm: BCRYPT_ALG_HANDLE; pszAlgId: LPCWSTR; pszImplementation: LPCWSTR; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptOpenAlgorithmProvider} // AlgOperations flags for use with BCryptEnumAlgorithms() const BCRYPT_CIPHER_OPERATION = $00000001; {$EXTERNALSYM BCRYPT_CIPHER_OPERATION} BCRYPT_HASH_OPERATION = $00000002; {$EXTERNALSYM BCRYPT_HASH_OPERATION} BCRYPT_ASYMMETRIC_ENCRYPTION_OPERATION = $00000004; {$EXTERNALSYM BCRYPT_ASYMMETRIC_ENCRYPTION_OPERATION} BCRYPT_SECRET_AGREEMENT_OPERATION = $00000008; {$EXTERNALSYM BCRYPT_SECRET_AGREEMENT_OPERATION} BCRYPT_SIGNATURE_OPERATION = $00000010; {$EXTERNALSYM BCRYPT_SIGNATURE_OPERATION} BCRYPT_RNG_OPERATION = $00000020; {$EXTERNALSYM BCRYPT_RNG_OPERATION} BCRYPT_KEY_DERIVATION_OPERATION = $00000040; {$EXTERNALSYM BCRYPT_KEY_DERIVATION_OPERATION} // USE EXTREME CAUTION: editing comments that contain "certenrolls_*" tokens // could break building CertEnroll idl files: // certenrolls_begin -- BCRYPT_ALGORITHM_IDENTIFIER type PBCryptAlgorithmIdentifier = ^TBCryptAlgorithmIdentifier; _BCRYPT_ALGORITHM_IDENTIFIER = record pszName: LPWSTR; dwClass: ULONG; dwFlags: ULONG; end; {$EXTERNALSYM _BCRYPT_ALGORITHM_IDENTIFIER} BCRYPT_ALGORITHM_IDENTIFIER = _BCRYPT_ALGORITHM_IDENTIFIER; {$EXTERNALSYM BCRYPT_ALGORITHM_IDENTIFIER} TBCryptAlgorithmIdentifier = _BCRYPT_ALGORITHM_IDENTIFIER; // certenrolls_end function BCryptEnumAlgorithms( dwAlgOperations: ULONG; out pAlgCount: ULONG; out ppAlgList: PBCryptAlgorithmIdentifier; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumAlgorithms} type PBCryptProviderName = ^TBCryptProviderName; _BCRYPT_PROVIDER_NAME = record pszProviderName: LPWSTR; end; {$EXTERNALSYM _BCRYPT_PROVIDER_NAME} BCRYPT_PROVIDER_NAME = _BCRYPT_PROVIDER_NAME; {$EXTERNALSYM BCRYPT_PROVIDER_NAME} TBCryptProviderName = _BCRYPT_PROVIDER_NAME; function BCryptEnumProviders( pszAlgId: LPCWSTR; out pImplCount: ULONG; out ppImplList: PBCryptProviderName; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumProviders} // Flags for use with BCryptGetProperty and BCryptSetProperty const BCRYPT_PUBLIC_KEY_FLAG = $00000001; {$EXTERNALSYM BCRYPT_PUBLIC_KEY_FLAG} BCRYPT_PRIVATE_KEY_FLAG = $00000002; {$EXTERNALSYM BCRYPT_PRIVATE_KEY_FLAG} function BCryptGetProperty( hObject: BCRYPT_HANDLE; pszProperty: LPCWSTR; pbOutput: PUCHAR; cbOutput: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptGetProperty} function BCryptSetProperty( hObject: BCRYPT_HANDLE; pszProperty: LPCWSTR; pbInput: PUCHAR; cbInput: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptSetProperty} function BCryptCloseAlgorithmProvider( hAlgorithm: BCRYPT_ALG_HANDLE; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptCloseAlgorithmProvider} procedure BCryptFreeBuffer( pvBuffer: PVOID); winapi; {$EXTERNALSYM BCryptFreeBuffer} // // Primitive encryption functions. // function BCryptGenerateSymmetricKey( hAlgorithm: BCRYPT_ALG_HANDLE; out phKey: BCRYPT_KEY_HANDLE; pbKeyObject: PUCHAR; cbKeyObject: ULONG; pbSecret: PUCHAR; cbSecret: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptGenerateSymmetricKey} function BCryptGenerateKeyPair( hAlgorithm: BCRYPT_ALG_HANDLE; out phKey: BCRYPT_KEY_HANDLE; dwLength: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptGenerateKeyPair} function BCryptEncrypt( hKey: BCRYPT_KEY_HANDLE; pbInput: PUCHAR; cbInput: ULONG; pPaddingInfo: Pointer; pbIV: PUCHAR; cbIV: ULONG; pbOutput: PUCHAR; cbOutput: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptEncrypt} function BCryptDecrypt( hKey: BCRYPT_KEY_HANDLE; pbInput: PUCHAR; cbInput: ULONG; pPaddingInfo: Pointer; pbIV: PUCHAR; cbIV: ULONG; pbOutput: PUCHAR; cbOutput: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDecrypt} function BCryptExportKey( hKey: BCRYPT_KEY_HANDLE; hExportKey: BCRYPT_KEY_HANDLE; pszBlobType: LPCWSTR; pbOutput: PUCHAR; cbOutput: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptExportKey} function BCryptImportKey( hAlgorithm: BCRYPT_ALG_HANDLE; hImportKey: BCRYPT_KEY_HANDLE; pszBlobType: LPCWSTR; out phKey: BCRYPT_KEY_HANDLE; pbKeyObject: PUCHAR; cbKeyObject: ULONG; pbInput: PUCHAR; cbInput: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptImportKey} const BCRYPT_NO_KEY_VALIDATION = $00000008; {$EXTERNALSYM BCRYPT_NO_KEY_VALIDATION} function BCryptImportKeyPair( hAlgorithm: BCRYPT_ALG_HANDLE; hImportKey: BCRYPT_KEY_HANDLE; pszBlobType: LPCWSTR; out phKey: BCRYPT_KEY_HANDLE; pbInput: PUCHAR; cbInput: ULONG; dwFlags: ULONG): NTSTATUS; winapi {$EXTERNALSYM BCryptImportKeyPair} function BCryptDuplicateKey( hKey: BCRYPT_KEY_HANDLE; out phNewKey: BCRYPT_KEY_HANDLE; pbKeyObject: PUCHAR; cbKeyObject: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDuplicateKey} function BCryptFinalizeKeyPair( hKey: BCRYPT_KEY_HANDLE; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptFinalizeKeyPair} function BCryptDestroyKey( hKey: BCRYPT_KEY_HANDLE): NTSTATUS; winapi; {$EXTERNALSYM BCryptDestroyKey} function BCryptDestroySecret( hSecret: BCRYPT_SECRET_HANDLE): NTSTATUS; winapi; {$EXTERNALSYM BCryptDestroySecret} function BCryptSignHash( hKey: BCRYPT_KEY_HANDLE; pPaddingInfo: Pointer; pbInput: PUCHAR; cbInput: ULONG; pbOutput: PUCHAR; cbOutput: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptSignHash} function BCryptVerifySignature( hKey: BCRYPT_KEY_HANDLE; pPaddingInfo: Pointer; pbHash: PUCHAR; cbHash: ULONG; pbSignature: PUCHAR; cbSignature: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptVerifySignature} function BCryptSecretAgreement( hPrivKey: BCRYPT_KEY_HANDLE; hPubKey: BCRYPT_KEY_HANDLE; out phAgreedSecret: BCRYPT_SECRET_HANDLE; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptSecretAgreement} function BCryptDeriveKey( hSharedSecret: BCRYPT_SECRET_HANDLE; pwszKDF: LPCWSTR; pParameterList: PBCryptBufferDesc; pbDerivedKey: PUCHAR; cbDerivedKey: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDeriveKey} function BCryptKeyDerivation( hKey: BCRYPT_KEY_HANDLE; pParameterList: PBCryptBufferDesc; pbDerivedKey: PUCHAR; cbDerivedKey: ULONG; out pcbResult: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptKeyDerivation} // // Primitive hashing functions. // function BCryptCreateHash( hAlgorithm: BCRYPT_ALG_HANDLE; out phHash: BCRYPT_HASH_HANDLE; pbHashObject: PUCHAR; cbHashObject: ULONG; pbSecret: PUCHAR; // optional cbSecret: ULONG; // optional dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptCreateHash} function BCryptHashData( hHash: BCRYPT_HASH_HANDLE; pbInput: PUCHAR; cbInput: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptHashData} function BCryptFinishHash( hHash: BCRYPT_HASH_HANDLE; pbOutput: PUCHAR; cbOutput: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptFinishHash} function BCryptDuplicateHash( hHash: BCRYPT_HASH_HANDLE; out phNewHash: BCRYPT_HASH_HANDLE; pbHashObject: PUCHAR; cbHashObject: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDuplicateHash} function BCryptDestroyHash( hHash: BCRYPT_HASH_HANDLE): NTSTATUS; winapi; {$EXTERNALSYM BCryptDestroyHash} // // Primitive random number generation. // // Flags to BCryptGenRandom const BCRYPT_RNG_USE_ENTROPY_IN_BUFFER = $00000001; {$EXTERNALSYM BCRYPT_RNG_USE_ENTROPY_IN_BUFFER} BCRYPT_USE_SYSTEM_PREFERRED_RNG = $00000002; {$EXTERNALSYM BCRYPT_USE_SYSTEM_PREFERRED_RNG} function BCryptGenRandom( hAlgorithm: BCRYPT_ALG_HANDLE; pbBuffer: PUCHAR; cbBuffer: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptGenRandom} // // Primitive key derivation functions. // function BCryptDeriveKeyCapi( hHash: BCRYPT_HASH_HANDLE; hTargetAlg: BCRYPT_ALG_HANDLE; pbDerivedKey: PUCHAR; cbDerivedKey: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDeriveKeyCapi} function BCryptDeriveKeyPBKDF2( hPrf: BCRYPT_ALG_HANDLE; pbPassword: PUCHAR; cbPassword: ULONG; pbSalt: PUCHAR; cbSalt: ULONG; cIterations: ULONGLONG; pbDerivedKey: PUCHAR; cbDerivedKey: ULONG; dwFlags: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptDeriveKeyPBKDF2} // // Interface version control... // type PBCryptInterfaceVersion = ^TBCryptInterfaceVersion; _BCRYPT_INTERFACE_VERSION = record MajorVersion: shortint; MinorVersion: shortint; end; {$EXTERNALSYM _BCRYPT_INTERFACE_VERSION} BCRYPT_INTERFACE_VERSION = _BCRYPT_INTERFACE_VERSION; {$EXTERNALSYM BCRYPT_INTERFACE_VERSION} TBCryptInterfaceVersion = _BCRYPT_INTERFACE_VERSION; PBCRYPT_INTERFACE_VERSION = PBCryptInterfaceVersion; {$EXTERNALSYM PBCRYPT_INTERFACE_VERSION} //#define BCRYPT_MAKE_INTERFACE_VERSION(major,minor) {(USHORT)major, (USHORT)minor} //#define BCRYPT_IS_INTERFACE_VERSION_COMPATIBLE(loader, provider) \ // ((loader).MajorVersion <= (provider).MajorVersion) // // Primitive provider interfaces. // const BCRYPT_CIPHER_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_CIPHER_INTERFACE_VERSION_1} BCRYPT_HASH_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_HASH_INTERFACE_VERSION_1} BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE_VERSION_1} BCRYPT_SECRET_AGREEMENT_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_SECRET_AGREEMENT_INTERFACE_VERSION_1} BCRYPT_SIGNATURE_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_SIGNATURE_INTERFACE_VERSION_1} BCRYPT_RNG_INTERFACE_VERSION_1: TBCryptInterfaceVersion = (MajorVersion:1; MinorVersion:0); {$EXTERNALSYM BCRYPT_RNG_INTERFACE_VERSION_1} ////////////////////////////////////////////////////////////////////////////// // CryptoConfig Definitions ////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Interface registration flags const CRYPT_MIN_DEPENDENCIES = ($00000001); {$EXTERNALSYM CRYPT_MIN_DEPENDENCIES} CRYPT_PROCESS_ISOLATE = ($00010000); // User-mode only {$EXTERNALSYM CRYPT_PROCESS_ISOLATE} // Processor modes supported by a provider // // (Valid for BCryptQueryProviderRegistration and BCryptResolveProviders): // const CRYPT_UM = ($00000001); // User mode only {$EXTERNALSYM CRYPT_UM} CRYPT_KM = ($00000002); // Kernel mode only {$EXTERNALSYM CRYPT_KM} CRYPT_MM = ($00000003); // Multi-mode: Must support BOTH UM and KM {$EXTERNALSYM CRYPT_MM} // // (Valid only for BCryptQueryProviderRegistration): // const CRYPT_ANY = ($00000004); // Wildcard: Either UM, or KM, or both {$EXTERNALSYM CRYPT_ANY} // Write behavior flags const CRYPT_OVERWRITE = ($00000001); {$EXTERNALSYM CRYPT_OVERWRITE} // Configuration tables const CRYPT_LOCAL = ($00000001); {$EXTERNALSYM CRYPT_LOCAL} CRYPT_DOMAIN = ($00000002); {$EXTERNALSYM CRYPT_DOMAIN} // Context configuration flags const CRYPT_EXCLUSIVE = ($00000001); {$EXTERNALSYM CRYPT_EXCLUSIVE} CRYPT_OVERRIDE = ($00010000); // Enterprise table only {$EXTERNALSYM CRYPT_OVERRIDE} // Resolution and enumeration flags const CRYPT_ALL_FUNCTIONS = ($00000001); {$EXTERNALSYM CRYPT_ALL_FUNCTIONS} CRYPT_ALL_PROVIDERS = ($00000002); {$EXTERNALSYM CRYPT_ALL_PROVIDERS} // Priority list positions const CRYPT_PRIORITY_TOP = ($00000000); {$EXTERNALSYM CRYPT_PRIORITY_TOP} CRYPT_PRIORITY_BOTTOM = ($FFFFFFFF); {$EXTERNALSYM CRYPT_PRIORITY_BOTTOM} // Default system-wide context const CRYPT_DEFAULT_CONTEXT = 'Default'; {$EXTERNALSYM CRYPT_DEFAULT_CONTEXT} ////////////////////////////////////////////////////////////////////////////// // CryptoConfig Structures /////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // Provider Registration Structures // type PPCryptInterfaceReg = ^PCryptInterfaceReg; PCryptInterfaceReg = ^TCryptInterfaceReg; _CRYPT_INTERFACE_REG = record dwInterface: ULONG; dwFlags: ULONG; cFunctions: ULONG; rgpszFunctions: ^PWSTR; end; {$EXTERNALSYM _CRYPT_INTERFACE_REG} CRYPT_INTERFACE_REG = _CRYPT_INTERFACE_REG; {$EXTERNALSYM CRYPT_INTERFACE_REG} TCryptInterfaceReg = _CRYPT_INTERFACE_REG; PCRYPT_INTERFACE_REG = PCryptInterfaceReg; {$EXTERNALSYM PCRYPT_INTERFACE_REG} type PPCryptImageReg = ^PCryptImageReg; PCryptImageReg = ^TCryptImageReg; _CRYPT_IMAGE_REG = record pszImage: PWSTR; cInterfaces: ULONG; rgpInterfaces: PPCryptInterfaceReg; end; {$EXTERNALSYM _CRYPT_IMAGE_REG} CRYPT_IMAGE_REG = _CRYPT_IMAGE_REG; {$EXTERNALSYM CRYPT_IMAGE_REG} TCryptImageReg = _CRYPT_IMAGE_REG; PCRYPT_IMAGE_REG = PCryptImageReg; {$EXTERNALSYM PCRYPT_IMAGE_REG} type PPCryptProviderReg = ^PCryptProviderReg; PCryptProviderReg = ^TCryptProviderReg; _CRYPT_PROVIDER_REG = record cAliases: ULONG; rgpszAliases: ^PWSTR; pUM: PCryptImageReg; pKM: PCryptImageReg; end; {$EXTERNALSYM _CRYPT_PROVIDER_REG} CRYPT_PROVIDER_REG = _CRYPT_PROVIDER_REG; {$EXTERNALSYM CRYPT_PROVIDER_REG} TCryptProviderReg = _CRYPT_PROVIDER_REG; PCRYPT_PROVIDER_REG = PCryptProviderReg; {$EXTERNALSYM PCRYPT_PROVIDER_REG} type PPCryptProviders = ^PCryptProviders; PCryptProviders = ^TCryptProviders; _CRYPT_PROVIDERS = record cProviders: ULONG; rgpszProviders: ^PWSTR; end; {$EXTERNALSYM _CRYPT_PROVIDERS} CRYPT_PROVIDERS = _CRYPT_PROVIDERS; {$EXTERNALSYM CRYPT_PROVIDERS} TCryptProviders = _CRYPT_PROVIDERS; PCRYPT_PROVIDERS = PCryptProviders; {$EXTERNALSYM PCRYPT_PROVIDERS} // // Context Configuration Structures // type PPCryptContextConfig = ^PCryptContextConfig; PCryptContextConfig = ^TCryptContextConfig; _CRYPT_CONTEXT_CONFIG = record dwFlags: ULONG; dwReserved: ULONG; end; {$EXTERNALSYM _CRYPT_CONTEXT_CONFIG} CRYPT_CONTEXT_CONFIG = _CRYPT_CONTEXT_CONFIG; {$EXTERNALSYM CRYPT_CONTEXT_CONFIG} TCryptContextConfig = _CRYPT_CONTEXT_CONFIG; PCRYPT_CONTEXT_CONFIG = PCryptContextConfig; {$EXTERNALSYM PCRYPT_CONTEXT_CONFIG} type PPCryptContextFunctionConfig = ^PCryptContextFunctionConfig; PCryptContextFunctionConfig = ^TCryptContextFunctionConfig; _CRYPT_CONTEXT_FUNCTION_CONFIG = record dwFlags: ULONG; dwReserved: ULONG; end; {$EXTERNALSYM _CRYPT_CONTEXT_FUNCTION_CONFIG} CRYPT_CONTEXT_FUNCTION_CONFIG = _CRYPT_CONTEXT_FUNCTION_CONFIG; {$EXTERNALSYM CRYPT_CONTEXT_FUNCTION_CONFIG} TCryptContextFunctionConfig = _CRYPT_CONTEXT_FUNCTION_CONFIG; PCRYPT_CONTEXT_FUNCTION_CONFIG = PCryptContextFunctionConfig; {$EXTERNALSYM PCRYPT_CONTEXT_FUNCTION_CONFIG} type PPCryptContexts = ^PCryptContexts; PCryptContexts = ^TCryptContexts; _CRYPT_CONTEXTS = record cContexts: ULONG; rgpszContexts: ^PWSTR; end; {$EXTERNALSYM _CRYPT_CONTEXTS} CRYPT_CONTEXTS = _CRYPT_CONTEXTS; {$EXTERNALSYM CRYPT_CONTEXTS} TCryptContexts = _CRYPT_CONTEXTS; PCRYPT_CONTEXTS = PCryptContexts; {$EXTERNALSYM PCRYPT_CONTEXTS} type PPCryptContextFunctions = ^PCryptContextFunctions; PCryptContextFunctions = ^TCryptContextFunctions; _CRYPT_CONTEXT_FUNCTIONS = record cFunctions: ULONG; rgpszFunctions: ^PWSTR; end; {$EXTERNALSYM _CRYPT_CONTEXT_FUNCTIONS} CRYPT_CONTEXT_FUNCTIONS = _CRYPT_CONTEXT_FUNCTIONS; {$EXTERNALSYM CRYPT_CONTEXT_FUNCTIONS} TCryptContextFunctions = _CRYPT_CONTEXT_FUNCTIONS; PCRYPT_CONTEXT_FUNCTIONS = PCryptContextFunctions; {$EXTERNALSYM PCRYPT_CONTEXT_FUNCTIONS} type PPCryptContextFunctionProviders = ^PCryptContextFunctionProviders; PCryptContextFunctionProviders = ^TCryptContextFunctionProviders; _CRYPT_CONTEXT_FUNCTION_PROVIDERS = record cProviders: ULONG; rgpszProviders: ^PWSTR; end; {$EXTERNALSYM _CRYPT_CONTEXT_FUNCTION_PROVIDERS} CRYPT_CONTEXT_FUNCTION_PROVIDERS = _CRYPT_CONTEXT_FUNCTION_PROVIDERS; {$EXTERNALSYM CRYPT_CONTEXT_FUNCTION_PROVIDERS} TCryptContextFunctionProviders = _CRYPT_CONTEXT_FUNCTION_PROVIDERS; PCRYPT_CONTEXT_FUNCTION_PROVIDERS = PCryptContextFunctionProviders; {$EXTERNALSYM PCRYPT_CONTEXT_FUNCTION_PROVIDERS} // // Provider Resolution Structures // type PPCryptPropertyRef = ^PCryptPropertyRef; PCryptPropertyRef = ^TCryptPropertyRef; _CRYPT_PROPERTY_REF = record pszProperty: PWSTR; cbValue: ULONG; pbValue: PUCHAR; end; {$EXTERNALSYM _CRYPT_PROPERTY_REF} CRYPT_PROPERTY_REF = _CRYPT_PROPERTY_REF; {$EXTERNALSYM CRYPT_PROPERTY_REF} TCryptPropertyRef = _CRYPT_PROPERTY_REF; PCRYPT_PROPERTY_REF = PCryptPropertyRef; {$EXTERNALSYM PCRYPT_PROPERTY_REF} type PPCryptImageRef = ^PCryptImageRef; PCryptImageRef = ^TCryptImageRef; _CRYPT_IMAGE_REF = record pszImage: PWSTR; dwFlags: ULONG; end; {$EXTERNALSYM _CRYPT_IMAGE_REF} CRYPT_IMAGE_REF = _CRYPT_IMAGE_REF; {$EXTERNALSYM CRYPT_IMAGE_REF} TCryptImageRef = _CRYPT_IMAGE_REF; PCRYPT_IMAGE_REF = PCryptImageRef; {$EXTERNALSYM PCRYPT_IMAGE_REF} type PPCryptProviderRef = ^PCryptProviderRef; PCryptProviderRef = ^TCryptProviderRef; _CRYPT_PROVIDER_REF = record dwInterface: ULONG; pszFunction: PWSTR; pszProvider: PWSTR; cProperties: ULONG; rgpProperties: PPCryptPropertyRef; pUM: PCryptImageRef; pKM: PCryptImageRef; end; {$EXTERNALSYM _CRYPT_PROVIDER_REF} CRYPT_PROVIDER_REF = _CRYPT_PROVIDER_REF; {$EXTERNALSYM CRYPT_PROVIDER_REF} TCryptProviderRef = _CRYPT_PROVIDER_REF; PCRYPT_PROVIDER_REF = PCryptProviderRef; {$EXTERNALSYM PCRYPT_PROVIDER_REF} type PPCryptProviderRefs = ^PCryptProviderRefs; PCryptProviderRefs = ^TCryptProviderRefs; _CRYPT_PROVIDER_REFS = record cProviders: ULONG; rgpProviders: PPCryptProviderRef; end; {$EXTERNALSYM _CRYPT_PROVIDER_REFS} CRYPT_PROVIDER_REFS = _CRYPT_PROVIDER_REFS; {$EXTERNALSYM CRYPT_PROVIDER_REFS} TCryptProviderRefs = _CRYPT_PROVIDER_REFS; PCRYPT_PROVIDER_REFS = PCryptProviderRefs; {$EXTERNALSYM PCRYPT_PROVIDER_REFS} ////////////////////////////////////////////////////////////////////////////// // CryptoConfig Functions //////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// function BCryptQueryProviderRegistration( pszProvider: LPCWSTR; dwMode: ULONG; dwInterface: ULONG; var pcbBuffer: ULONG; ppBuffer: PPCryptProviderReg): NTSTATUS; winapi; {$EXTERNALSYM BCryptQueryProviderRegistration} function BCryptEnumRegisteredProviders( var pcbBuffer: ULONG; ppBuffer: PPCryptProviders): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumRegisteredProviders} // // Context Configuration Functions // function BCryptCreateContext( dwTable: ULONG; pszContext: LPCWSTR; pConfig: PCryptContextConfig): NTSTATUS; winapi; {$EXTERNALSYM BCryptCreateContext} function BCryptDeleteContext( dwTable: ULONG; pszContext: LPCWSTR): NTSTATUS; winapi; {$EXTERNALSYM BCryptDeleteContext} function BCryptEnumContexts( dwTable: ULONG; var pcbBuffer: ULONG; ppBuffer: PPCryptContexts): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumContexts} function BCryptConfigureContext( dwTable: ULONG; pszContext: LPCWSTR; pConfig: PCryptContextConfig): NTSTATUS; winapi; {$EXTERNALSYM BCryptConfigureContext} function BCryptQueryContextConfiguration( dwTable: ULONG; pszContext: LPCWSTR; var pcbBuffer: ULONG; ppBuffer: PPCryptContextConfig): NTSTATUS; winapi; {$EXTERNALSYM BCryptQueryContextConfiguration} function BCryptAddContextFunction( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; dwPosition: ULONG): NTSTATUS; winapi; {$EXTERNALSYM BCryptAddContextFunction} function BCryptRemoveContextFunction( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR): NTSTATUS; winapi; {$EXTERNALSYM BCryptRemoveContextFunction} function BCryptEnumContextFunctions( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; var pcbBuffer: ULONG; ppBuffer: PPCryptContextFunctions): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumContextFunctions} function BCryptConfigureContextFunction( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; pConfig: PCryptContextFunctionConfig): NTSTATUS; winapi; {$EXTERNALSYM BCryptConfigureContextFunction} function BCryptQueryContextFunctionConfiguration( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; var pcbBuffer: ULONG; ppBuffer: PPCryptContextFunctionConfig): NTSTATUS; winapi; {$EXTERNALSYM BCryptQueryContextFunctionConfiguration} function BCryptEnumContextFunctionProviders( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; var pcbBuffer: ULONG; ppBuffer: PPCryptContextFunctionProviders): NTSTATUS; winapi; {$EXTERNALSYM BCryptEnumContextFunctionProviders} function BCryptSetContextFunctionProperty( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; pszProperty: LPCWSTR; cbValue: ULONG; pbValue: PUCHAR): NTSTATUS; winapi; {$EXTERNALSYM BCryptSetContextFunctionProperty} function BCryptQueryContextFunctionProperty( dwTable: ULONG; pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; pszProperty: LPCWSTR; var pcbValue: ULONG; out ppbValue: PUCHAR): NTSTATUS; winapi; {$EXTERNALSYM BCryptQueryContextFunctionProperty} // // Configuration Change Notification Functions // function BCryptRegisterConfigChangeNotify( out phEvent: THandle): NTSTATUS; winapi; {$EXTERNALSYM BCryptRegisterConfigChangeNotify} function BCryptUnregisterConfigChangeNotify( hEvent: THandle): NTSTATUS; winapi; {$EXTERNALSYM BCryptUnregisterConfigChangeNotify} // // Provider Resolution Functions // function BCryptResolveProviders( pszContext: LPCWSTR; dwInterface: ULONG; pszFunction: LPCWSTR; pszProvider: LPCWSTR; dwMode: ULONG; dwFlags: ULONG; var pcbBuffer: ULONG; ppBuffer: PPCryptProviderRefs): NTSTATUS; winapi; {$EXTERNALSYM BCryptResolveProviders} // // Miscellaneous queries about the crypto environment // function BCryptGetFipsAlgorithmMode( out pfEnabled: ByteBool): NTSTATUS; winapi; {$EXTERNALSYM BCryptGetFipsAlgorithmMode} {$ENDREGION} implementation const BCryptDll = 'bcrypt.dll'; {$REGION 'bcrypt.h'} function BCryptOpenAlgorithmProvider; external BCryptDll name 'BCryptOpenAlgorithmProvider'; function BCryptEnumAlgorithms; external BCryptDll name 'BCryptEnumAlgorithms'; function BCryptEnumProviders; external BCryptDll name 'BCryptEnumProviders'; function BCryptGetProperty; external BCryptDll name 'BCryptGetProperty'; function BCryptSetProperty; external BCryptDll name 'BCryptSetProperty'; function BCryptCloseAlgorithmProvider; external BCryptDll name 'BCryptCloseAlgorithmProvider'; procedure BCryptFreeBuffer; external BCryptDll name 'BCryptFreeBuffer'; function BCryptGenerateSymmetricKey; external BCryptDll name 'BCryptGenerateSymmetricKey'; function BCryptGenerateKeyPair; external BCryptDll name 'BCryptGenerateKeyPair'; function BCryptEncrypt; external BCryptDll name 'BCryptEncrypt'; function BCryptDecrypt; external BCryptDll name 'BCryptDecrypt'; function BCryptExportKey; external BCryptDll name 'BCryptExportKey'; function BCryptImportKey; external BCryptDll name 'BCryptImportKey'; function BCryptImportKeyPair; external BCryptDll name 'BCryptImportKeyPair'; function BCryptDuplicateKey; external BCryptDll name 'BCryptDuplicateKey'; function BCryptFinalizeKeyPair; external BCryptDll name 'BCryptFinalizeKeyPair'; function BCryptDestroyKey; external BCryptDll name 'BCryptDestroyKey'; function BCryptDestroySecret; external BCryptDll name 'BCryptDestroySecret'; function BCryptSignHash; external BCryptDll name 'BCryptSignHash'; function BCryptVerifySignature; external BCryptDll name 'BCryptVerifySignature'; function BCryptSecretAgreement; external BCryptDll name 'BCryptSecretAgreement'; function BCryptDeriveKey; external BCryptDll name 'BCryptDeriveKey'; function BCryptKeyDerivation; external BCryptDll name 'BCryptKeyDerivation'; function BCryptCreateHash; external BCryptDll name 'BCryptCreateHash'; function BCryptHashData; external BCryptDll name 'BCryptHashData'; function BCryptFinishHash; external BCryptDll name 'BCryptFinishHash'; function BCryptDuplicateHash; external BCryptDll name 'BCryptDuplicateHash'; function BCryptDestroyHash; external BCryptDll name 'BCryptDestroyHash'; function BCryptGenRandom; external BCryptDll name 'BCryptGenRandom'; function BCryptDeriveKeyCapi; external BCryptDll name 'BCryptDeriveKeyCapi'; function BCryptDeriveKeyPBKDF2; external BCryptDll name 'BCryptDeriveKeyPBKDF2'; function BCryptQueryProviderRegistration; external BCryptDll name 'BCryptQueryProviderRegistration'; function BCryptEnumRegisteredProviders; external BCryptDll name 'BCryptEnumRegisteredProviders'; function BCryptCreateContext; external BCryptDll name 'BCryptCreateContext'; function BCryptDeleteContext; external BCryptDll name 'BCryptDeleteContext'; function BCryptEnumContexts; external BCryptDll name 'BCryptEnumContexts'; function BCryptConfigureContext; external BCryptDll name 'BCryptConfigureContext'; function BCryptQueryContextConfiguration; external BCryptDll name 'BCryptQueryContextConfiguration'; function BCryptAddContextFunction; external BCryptDll name 'BCryptAddContextFunction'; function BCryptRemoveContextFunction; external BCryptDll name 'BCryptRemoveContextFunction'; function BCryptEnumContextFunctions; external BCryptDll name 'BCryptEnumContextFunctions'; function BCryptConfigureContextFunction; external BCryptDll name 'BCryptConfigureContextFunction'; function BCryptQueryContextFunctionConfiguration; external BCryptDll name 'BCryptQueryContextFunctionConfiguration'; function BCryptEnumContextFunctionProviders; external BCryptDll name 'BCryptEnumContextFunctionProviders'; function BCryptSetContextFunctionProperty; external BCryptDll name 'BCryptSetContextFunctionProperty'; function BCryptQueryContextFunctionProperty; external BCryptDll name 'BCryptQueryContextFunctionProperty'; function BCryptRegisterConfigChangeNotify; external BCryptDll name 'BCryptRegisterConfigChangeNotify'; function BCryptUnregisterConfigChangeNotify; external BCryptDll name 'BCryptUnregisterConfigChangeNotify'; function BCryptResolveProviders; external BCryptDll name 'BCryptResolveProviders'; function BCryptGetFipsAlgorithmMode; external BCryptDll name 'BCryptGetFipsAlgorithmMode'; function BCRYPT_SUCCESS(Status: NTSTATUS): Boolean; inline; begin Result := Status >= 0; end; procedure BCRYPT_INIT_AUTH_MODE_INFO(var _AUTH_INFO_STRUCT_: TBCryptAuthenticatedCipherModeInfo); inline; begin FillChar(_AUTH_INFO_STRUCT_, SizeOf(TBCryptAuthenticatedCipherModeInfo), $00); _AUTH_INFO_STRUCT_.cbSize := SizeOf(TBCryptAuthenticatedCipherModeInfo); _AUTH_INFO_STRUCT_.dwInfoVersion := BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION; end; {$ENDREGION} end.
unit server_thread; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fphttpserver; type THTTPServerThread = Class(TThread) Private FServer : TFPHTTPServer; Public constructor Create(APort : Word; const OnRequest : THTTPServerRequestHandler; const ParallelRequest : boolean); procedure Execute; override; procedure DoTerminate; override; property Server : TFPHTTPServer Read FServer; end; implementation constructor THTTPServerThread.Create(APort: Word; const OnRequest: THTTPServerRequestHandler; const ParallelRequest : boolean); begin FServer := TFPHTTPServer.Create(Nil); FServer.Port := APort; FServer.Threaded := ParallelRequest; FServer.OnRequest := OnRequest; Inherited Create(False); end; procedure THTTPServerThread.Execute; begin try FServer.Active := True; finally FreeAndNil(FServer); end; end; procedure THTTPServerThread.DoTerminate; begin inherited DoTerminate; FServer.Active:=False; end; end.
unit Test_FIToolkit.Reports.Parser.Types; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, FIToolkit.Reports.Parser.Types; type TestTFixInsightMessage = class (TGenericTestCase) published procedure TestCreate; procedure TestGetComparer; end; implementation uses System.SysUtils, System.Types; { TestTFixInsightMessage } procedure TestTFixInsightMessage.TestCreate; const MSGID_WARNING = 'W123'; MSGID_OPTIMIZATION = 'O123'; MSGID_CODING_CONVENTION = 'C123'; MSGID_FATAL = 'FATAL'; MSGID_TRIAL = 'Tria'; var FIM : TFixInsightMessage; begin FIM := TFixInsightMessage.Create(String.Empty, 0, 0, String.Empty, String.Empty); CheckEquals<TFixInsightMessageType>(fimtUnknown, FIM.MsgType, 'MsgType = fimtUnknown'); FIM := TFixInsightMessage.Create(String.Empty, 0, 0, MSGID_WARNING, String.Empty); CheckEquals<TFixInsightMessageType>(fimtWarning, FIM.MsgType, 'MsgType = fimtWarning'); FIM := TFixInsightMessage.Create(String.Empty, 0, 0, MSGID_OPTIMIZATION, String.Empty); CheckEquals<TFixInsightMessageType>(fimtOptimization, FIM.MsgType, 'MsgType = fimtOptimization'); FIM := TFixInsightMessage.Create(String.Empty, 0, 0, MSGID_CODING_CONVENTION, String.Empty); CheckEquals<TFixInsightMessageType>(fimtCodingConvention, FIM.MsgType, 'MsgType = fimtCodingConvention'); FIM := TFixInsightMessage.Create(String.Empty, 0, 0, MSGID_FATAL, String.Empty); CheckEquals<TFixInsightMessageType>(fimtFatal, FIM.MsgType, 'MsgType = fimtFatal'); FIM := TFixInsightMessage.Create(String.Empty, 0, 0, MSGID_TRIAL, String.Empty); CheckEquals<TFixInsightMessageType>(fimtTrial, FIM.MsgType, 'MsgType = fimtTrial'); end; procedure TestTFixInsightMessage.TestGetComparer; var // case #1 OrigMsg, EqualMsg, GreaterMsg1, GreaterMsg2, GreaterMsg3 : TFixInsightMessage; // case #2 OrigMsg2, EqualMsg2, EqualMsg3, GreaterMsg4 : TFixInsightMessage; begin { Case #1 - constructor with NO full file name } OrigMsg := TFixInsightMessage.Create('C:\abc.pas', 100, 32, String.Empty, String.Empty); EqualMsg := TFixInsightMessage.Create('C:\ABC.pas', 100, 32, 'W505', 'text'); GreaterMsg1 := TFixInsightMessage.Create('C:\bcd.pas', 100, 32, String.Empty, String.Empty); GreaterMsg2 := TFixInsightMessage.Create('C:\abc.pas', 101, 32, String.Empty, String.Empty); GreaterMsg3 := TFixInsightMessage.Create('C:\abc.pas', 100, 33, String.Empty, String.Empty); with TFixInsightMessage.GetComparer do begin CheckEquals(EqualsValue, Compare(OrigMsg, OrigMsg), 'OrigMsg = OrigMsg'); CheckEquals(EqualsValue, Compare(OrigMsg, EqualMsg), 'OrigMsg = EqualMsg'); CheckEquals(LessThanValue, Compare(OrigMsg, GreaterMsg1), 'OrigMsg < GreaterMsg1'); CheckEquals(LessThanValue, Compare(OrigMsg, GreaterMsg2), 'OrigMsg < GreaterMsg2'); CheckEquals(LessThanValue, Compare(OrigMsg, GreaterMsg3), 'OrigMsg < GreaterMsg3'); end; { Case #2 - constructor WITH full file name } OrigMsg2 := TFixInsightMessage.Create('..\TestUnit.pas', 'C:\TestUnit.pas', 100, 32, String.Empty, String.Empty); EqualMsg2 := TFixInsightMessage.Create('..\TestUnit.pas', 100, 32, String.Empty, String.Empty); EqualMsg3 := TFixInsightMessage.Create('..\TestUnit.pas', 'c:\testunit.pas', 100, 32, String.Empty, String.Empty); GreaterMsg4 := TFixInsightMessage.Create('..\TestUnit.pas', 'X:\TestUnit.pas', 100, 32, String.Empty, String.Empty); with TFixInsightMessage.GetComparer do begin CheckEquals(EqualsValue, Compare(OrigMsg2, EqualMsg2), 'OrigMsg2 = EqualMsg2'); CheckEquals(EqualsValue, Compare(OrigMsg2, EqualMsg3), 'OrigMsg2 = EqualMsg3'); CheckEquals(LessThanValue, Compare(OrigMsg2, GreaterMsg4), 'OrigMsg2 < GreaterMsg4'); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTFixInsightMessage.Suite); end.
unit UExWebType; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs; type TExWebResult = (ewrOk,ewrUnknownError,ewrNoResponse,ewrNoValidJSON,ewrErrorCreateHash,ewrRes0,ewrNeedConfirm,ewrHashSumNotCompare,ewrErrorPrepare); TExWebState = record public //1 идентификатор сообщения id: string[16]; //1 Результат операции webResult: TExWebResult; result: Boolean; end; const TExWebResultStr:array[0..8] of string = ('ewrOk','ewrUnknownError','ewrNoResponse','ewrNoValidJSON','ewrErrorCreateHash','ewrRes0','ewrNeedConfirm','ewrHashSumNotCompare','ewrErrorPrepare'); TExWebResultNotes:array[0..8] of string = ( 'Ok', 'Неизвестная ошибка', 'Нет ответа (возможно нет интернета)', 'Считанный JSON не валидный', 'Ошибка создания HASH', 'Сервер обработал запрос с ошибкой', 'Требуется подтверждение закрытия', 'Бинарные данные, сохраненные на сервере не совпадают с отправленными', 'Строка содержит недопустимые символы' ); implementation end.
unit ZLib; {we: ZLIB (functions), ZLIBH(types/consts), GZIO(gz functions) should be the only units USED by applications of zlib} (************************************************************************ zlib -- interface of the 'zlib' general purpose compression library version 1.1.3, July 9th, 1998 Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). Parts of Pascal translation Copyright (C) 1998 by Jacques Nomssi Nzali ------------------------------------------------------------------------ Modification/Pascal translation by W.Ehrhardt: Aug 2000 - ZLIB 113 changes Feb 2002 - Source code reformating/reordering Mar 2005 - Code cleanup for WWW upload Jul 2009 - D12 fixes ------------------------------------------------------------------------ *************************************************************************) {$x+} interface uses ZlibH; (***************************************************************************) (************************* Basic functions *******************************) (***************************************************************************) function deflateInit(var strm: z_stream; level: int): int; {Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate().} function deflate(var strm: z_stream; flush: int): int; {Performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. If the parameter flush is set to Z_PARTIAL_FLUSH, the current compression block is terminated and flushed to the output buffer so that the decompressor can get all input data available so far. For method 9, a future variant on method 8, the current block will be flushed but not terminated. Z_SYNC_FLUSH has the same effect as partial flush except that the compressed output is byte aligned (the compressor can clear its internal bit buffer) and the current block is always terminated; this can be useful if the compressor has to be restarted from scratch after an interruption (in which case the internal state of the compressor may be lost). If flush is set to Z_FULL_FLUSH, the compression block is terminated, a special marker is output and the compression dictionary is discarded; this is useful to allow the decompressor to synchronize if one compressed block has been damaged (see inflateSync below). Flushing degrades compression and so should be used only when necessary. Using Z_FULL_FLUSH too often can seriously degrade the compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). If the parameter flush is set to Z_FINISH, all pending input is processed, all pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space; if deflate returns with Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least 0.1% larger than avail_in plus 12 bytes. If deflate does not return Z_STREAM_END, then it must be called again as described above. deflate() may update data_type if it can make a good guess about the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible.} function deflateEnd(var strm: z_stream): int; {All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated).} function inflateInit(var z: z_stream): int; {Initializes the internal stream state for decompression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller. msg is set to null if there is no error message. inflateInit does not perform any decompression: this will be done by inflate().} function inflate(var z: z_stream; f: int): int; {inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call of inflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much output as possible to the output buffer. The flushing behavior of inflate is not specified for values of the flush parameter other than Z_SYNC_FLUSH and Z_FINISH, but the current implementation actually flushes as much output as possible anyway. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster routine may be used for the single inflate() call. If a preset dictionary is needed at this point (see inflateSetDictionary below), inflate sets strm-adler to the adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the adler32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR case, the application may then call inflateSync to look for a good compression block.} function inflateEnd(var z: z_stream): int; {All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated).} (***************************************************************************) (************************ Advanced functions *****************************) (***************************************************************************) function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel, strategy: int): int; {This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. (Method 9 will allow a 64K history buffer and partial block flushes.) The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library (the value 16 will be allowed for method 9). Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no string match). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. If next_in is not null, the library will use this buffer to hold also some history information; the buffer must either hold the entire input data, or have at least 1<<(windowBits+1) bytes and be writable. If next_in is null, the library will allocate its own history buffer (and leave next_in null). next_out need not be provided here but must be provided by the application for the next call of deflate(). If the history buffer is provided by the application, next_in must must never be changed by the application since the compressor maintains information inside this buffer from call to call; the application must provide more input only by increasing avail_in. next_in is always reset by the library in this case. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid method). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate().} function deflateSetDictionary(var strm: z_stream; dictionary: pBytef; dictLength: uint): int; {Initializes the compression dictionary (history buffer) from the given byte sequence without producing any compressed output. This function must be called immediately after deflateInit or deflateInit2, before any call of deflate. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. In this version of the library, only the last 32K bytes of the dictionary are used. Upon return of this function, strm->adler is set to the Adler32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent (for example if deflate has already been called for this stream). deflateSetDictionary does not perform any compression: this will be done by deflate().} function deflateCopy(dest: z_streamp; source: z_streamp): int; {Sets the destination stream as a complete copy of the source stream. If the source stream is using an application-supplied history buffer, a new buffer is allocated for the destination stream. The compressed output buffer is always application-supplied. It's the responsibility of the application to provide the correct values of next_out and avail_out for the next call of deflate. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being NULL). msg is left unchanged in both source and destination.} function deflateReset(var strm: z_stream): int; {This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate all the internal compression state. The stream will keep the same compression level and any other attributes that may have been set by deflateInit2. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being nil).} function deflateParams(var strm: z_stream; level: int; strategy: int): int; {Dynamically update the compression level and compression strategy. This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression level is changed, the input available so far is compressed with the old level (and may be flushed); the new level will take effect only at the next call of deflate(). Before the call of deflateParams, the stream state must be set as for a call of deflate(), since the currently available input may have to be compressed and flushed. In particular, strm->avail_out must be non-zero. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if strm->avail_out was zero.} function inflateInit2(var z: z_stream; windowBits: int): int; {This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative memLevel). msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from reading the zlib header if present: this will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.)} function inflateInit_(z: z_streamp; const version: str255; stream_size: int): int; function inflateInit2_(var z: z_stream; w: int; const version: str255; stream_size: int): int; {Another two version of inflateInit with an extra parameters} function inflateReset(var z: z_stream): int; {This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate all the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being NULL).} function inflateSetDictionary(var z: z_stream; dictionary: pBytef; dictLength: uInt): int; {Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate if this call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler32 value returned by this call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate().} function inflateSync(var z: z_stream): int; {Skips invalid compressed data until a full flush point (see above the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data.} function inflateSyncPoint(var z: z_stream): int; {-returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH.} (***************************************************************************) (****************** Utility functions except GZ.. ************************) (***************************************************************************) function compress2( dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong; level: int): int; {-Compresses the source into the destination buffer with variable level} {level has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid.} function compress( dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong): int; {-Compresses source into destination buffer with level=Z_DEFAULT_COMPRESSION} function uncompress ( dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong): int; {Decompresses the source buffer into the destination buffer.} {SourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. This function can be used to decompress a whole file at once if the input file is mmap'ed. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted.} (***************************************************************************) (************************** Misc functions *******************************) (***************************************************************************) function zlibVersion: str255; {-The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. } function zError(err: int): str255; {-conversion of error code to string} procedure zmemcpy(destp: pBytef; sourcep: pBytef; len: uInt); function zmemcmp(s1p, s2p: pBytef; len: uInt): int; procedure zmemzero(destp: pBytef; len: uInt); procedure zcfree(opaque: voidpf; ptr: voidpf); function zcalloc(opaque: voidpf; items: uInt; size: uInt): voidpf; implementation uses ZDeflate, ZInflate, ZUtil; {Transfer to corresponding functions in ZUtil} procedure zmemcpy(destp: pBytef; sourcep: pBytef; len: uInt); begin ZUtil.zmemcpy(destp, sourcep, len); end; {---------------------------------------------------------------------------} function zmemcmp(s1p, s2p: pBytef; len: uInt): int; begin zmemcmp := ZUtil.zmemcmp(s1p, s2p, len); end; {---------------------------------------------------------------------------} procedure zmemzero(destp: pBytef; len: uInt); begin ZUtil.zmemzero(destp, len); end; {---------------------------------------------------------------------------} procedure zcfree(opaque: voidpf; ptr: voidpf); begin ZUtil.zcfree(opaque, ptr); end; {---------------------------------------------------------------------------} function zcalloc(opaque: voidpf; items: uInt; size: uInt): voidpf; begin zcalloc := ZUtil.zcalloc(opaque, items, size); end; {Transfer to corresponding functions in ZDeflate/ZInflate} {---------------------------------------------------------------------------} function deflateInit(var strm: z_stream; level: int): int; begin deflateInit := ZDeflate.deflateInit(strm,level); end; {---------------------------------------------------------------------------} function deflate(var strm: z_stream; flush: int): int; begin deflate := ZDeflate.deflate(strm, flush); end; {---------------------------------------------------------------------------} function deflateEnd(var strm: z_stream): int; begin deflateEnd := ZDeflate.deflateEnd(strm); end; {---------------------------------------------------------------------------} function deflateInit2(var strm: z_stream; level, method, windowBits, memLevel, strategy: int): int; begin deflateInit2 := ZDeflate.deflateInit2(strm, level, method, windowBits, memLevel, strategy); end; {---------------------------------------------------------------------------} function deflateSetDictionary(var strm: z_stream; dictionary: pBytef; dictLength: uint): int; begin deflateSetDictionary := ZDeflate.deflateSetDictionary(strm, dictionary, dictLength); end; {---------------------------------------------------------------------------} function deflateCopy(dest: z_streamp; source: z_streamp): int; begin deflateCopy := ZDeflate.deflateCopy(dest, source); end; {---------------------------------------------------------------------------} function deflateReset(var strm: z_stream): int; begin deflateReset := ZDeflate.deflateReset(strm); end; {---------------------------------------------------------------------------} function deflateParams(var strm: z_stream; level: int; strategy: int): int; begin deflateParams := ZDeflate.deflateParams(strm, level, strategy); end; {---------------------------------------------------------------------------} function inflateInit(var z: z_stream): int; begin inflateInit := ZInflate.inflateInit(z); end; {---------------------------------------------------------------------------} function inflateInit_(z: z_streamp; const version: str255; stream_size: int): int; begin inflateInit_ := ZInflate.inflateInit_(z, version, stream_size); end; {---------------------------------------------------------------------------} function inflateInit2_(var z: z_stream; w: int; const version: str255; stream_size: int): int; begin inflateInit2_ := ZInflate.inflateInit2_(z, w, version, stream_size); end; {---------------------------------------------------------------------------} function inflateInit2(var z: z_stream; windowBits: int): int; begin inflateInit2 := ZInflate.inflateInit2(z, windowBits); end; {---------------------------------------------------------------------------} function inflateEnd(var z: z_stream): int; begin inflateEnd := ZInflate.inflateEnd(z); end; {---------------------------------------------------------------------------} function inflateReset(var z: z_stream): int; begin inflateReset := ZInflate.inflateReset(z); end; {---------------------------------------------------------------------------} function inflate(var z: z_stream; f: int): int; begin inflate := ZInflate.inflate(z, f); end; {---------------------------------------------------------------------------} function inflateSetDictionary(var z: z_stream; dictionary: pBytef; dictLength: uInt): int; begin inflateSetDictionary := ZInflate.inflateSetDictionary(z, dictionary, dictLength); end; {---------------------------------------------------------------------------} function inflateSync(var z: z_stream): int; begin inflateSync := ZInflate.inflateSync(z); end; {---------------------------------------------------------------------------} function inflateSyncPoint(var z: z_stream): int; begin inflateSyncPoint := ZInflate.inflateSyncPoint(z); end; (***************************************************************************) (***************************************************************************) {---------------------------------------------------------------------------} function zlibVersion: str255; begin zlibVersion := ZLIB_VERSION; end; {---------------------------------------------------------------------------} function zError(err: int): str255; begin zError := z_errmsg[Z_NEED_DICT-err]; end; {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function compress2( dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong; level: int): int; {-Compresses the source into the destination buffer with variable level} var stream: z_stream; err: int; begin stream.next_in := pBytef(@source); stream.avail_in := uInt(sourceLen); {$ifdef MAXSEG_64K} {Check for source > 64K on 16-bit machine:} if uLong(stream.avail_in) <> sourceLen then begin compress2 := Z_BUF_ERROR; exit; end; {$endif} stream.next_out := dest; stream.avail_out := uInt(destLen); if uLong(stream.avail_out) <> destLen then begin compress2 := Z_BUF_ERROR; exit; end; stream.zalloc := nil; {alloc_func(0);} stream.zfree := nil; {free_func(0);} stream.opaque := nil; {voidpf(0);} err := ZDeflate.deflateInit(stream, level); if err<>Z_OK then begin compress2 := err; exit; end; err := ZDeflate.deflate(stream, Z_FINISH); if err<>Z_STREAM_END then begin ZDeflate.deflateEnd(stream); if err=Z_OK then compress2 := Z_BUF_ERROR else compress2 := err; exit; end; destLen := stream.total_out; err := ZDeflate.deflateEnd(stream); compress2 := err; end; {---------------------------------------------------------------------------} function compress(dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong): int; {-Compresses source into destination buffer with level=Z_DEFAULT_COMPRESSION} begin compress := compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); end; {---------------------------------------------------------------------------} function uncompress ( dest: pBytef; var destLen: uLong; const source: array of byte; sourceLen: uLong): int; {-Decompresses the source buffer into the destination buffer.} var stream: z_stream; err: int; begin stream.next_in := pBytef(@source); stream.avail_in := uInt(sourceLen); { Check for source > 64K on 16-bit machine: } if uLong(stream.avail_in) <> sourceLen then begin uncompress := Z_BUF_ERROR; exit; end; stream.next_out := dest; stream.avail_out := uInt(destLen); if uLong(stream.avail_out) <> destLen then begin uncompress := Z_BUF_ERROR; exit; end; stream.zalloc := nil; { alloc_func(0); } stream.zfree := nil; { free_func(0); } err := ZInflate.inflateInit(stream); if err<>Z_OK then begin uncompress := err; exit; end; err := ZInflate.inflate(stream, Z_FINISH); if err<>Z_STREAM_END then begin ZInflate.inflateEnd(stream); if err=Z_OK then uncompress := Z_BUF_ERROR else uncompress := err; exit; end; destLen := stream.total_out; err := ZInflate.inflateEnd(stream); uncompress := err; end; end.
{ This maker note reader can handle CANON cameras. } unit fpeMakerNoteCanon; {$IFDEF FPC} // {$mode objfpc}{$H+} {$MODE DELPHI} {$ENDIF} interface uses Classes, SysUtils, fpeGlobal, fpeTags, fpeExifReadWrite; type TCanonMakerNoteReader = class(TMakerNoteReader) protected function AddTag(AStream: TStream; const AIFDRecord: TIFDRecord; const AData: TBytes; AParent: TTagID): Integer; override; procedure GetTagDefs({%H-}AStream: TStream); override; end; implementation uses fpeStrConsts, fpeUtils, fpeExifData; resourcestring rsCanonAELkup = '0:Normal AE,1:Exposure compensation,2:AE lock,'+ '3:AE lock + Exposure compensation,4:No AE'; { rsCanonAFLkup = '12288:None (MF),12289:Auto-selected,12290:Right,12291:Center,'+ '12292:Left'; } rsCanonAFLkup = '$2005:Manual AF point selection,$3000:None (MF),' + '$3001:Auto AF point selection,$3002:Right,$3003:Center,$3004:Left,' + '$4001:Auto AF point selection,$4006:Face Detect'; rsCanonAutoRotLkup = '0:None,1:Rotate 90 CW,2:Rotate 180,3:Rotate 270 CW'; rsCanonBiasLkup = '65472:-2 EV,65484:-1.67 EV,65488:-1.50 EV,65492:-1.33 EV,'+ '65504:-1 EV,65516:-0.67 EV,65520:-0.50 EV,65524:-0.33 EV,0:0 EV,'+ '12:0.33 EV,16:0.50 EV,20:0.67 EV,32:1 EV,44:1.33 EV,48:1.50 EV,'+ '52:1.67 EV,64:2 EV'; rsCanonCamTypeLkup = '248:EOS High-end,250:Compact,252:EOS Mid-range,255:DV Camera'; rsCanonEasyLkup = '0:Full Auto,1:Manual,2:Landscape,3:Fast Shutter,4:Slow Shutter,'+ '5:Night,6:Gray scale,7:Sepia,8:Portrait,9:Sports,10:Macro,11:Black & White,'+ '12:Pan Focus,13:Vivid,14:Neutral,15:Flash off,16:Long shutter,'+ '17:Super macro,18:Foliage,19:Indoor,20:Fireworks,21:Beach,22:Underwater,'+ '23:Snow,24:Kids & Pets,25:Night snapshot,26:Digital macro,27:My colors,'+ '28:Movie snap,29:Super macro 2,30:Color accent,31:Color swap,32:Aquarium,'+ '33:ISO3200,34:ISO6400,35:Creative light effect,36:Easy,37:Quick shot,'+ '38:Creative auto,39:Zoom blur,40:Low light,41:Nostalgic,42:Super vivid,'+ '43:Poster effect,44:Face self-timer,45:Smile,46:Wink self-timer,'+ '47:Fisheye effect,48:Miniature effect,49:High-speed burst,'+ '50:Best image selection,51:High dynamic range,52:Handheld night scene,'+ '53:Movie digest,54:Live view control,55:Discreet,56:Blur reduction,'+ '57:Monochrome,58:Toy camera effect,59:Scene intelligent auto,'+ '60:High-speed burst HQ,61:Smooth skin,62:Soft focus,257:Spotlight,'+ '258:Night 2,259:Night+,260:Super night,261:Sunset,263:Night scene,'+ '264:Surface,265:Low light 2'; rsCanonExposeLkup = '0:Easy shooting,1:Program AE,2:Shutter speed priority AE,'+ '3:Aperture priority AE,4:Manual,5:Depth-of-field AE,6:M-Dep,7:Bulb'; rsCanonFlashActLkup = '0:Did not fire,1:Fired'; rsCanonFlashLkup = '0:Not fired,1:Auto,2:On,3:Red-eye,4:Slow sync,'+ '5:Auto+red-eye,6:On+red eye,16:External flash'; rsCanonFocalTypeLkup = '1:Fixed,2:Zoom'; rsCanonFocTypeLkup = '0:Manual,1:Auto,3:Close-up (macro),8:Locked (pan mode)'; rsCanonFocusLkup = '0:One-Shot AF,1:AI Servo AF,2:AI Focus AF,3:Manual focus,'+ '4:Single,5:Continuous,6:Manual focus,16:Pan focus,256:AF+MF,'+ '512:Movie snap focus,519:Movie servo AF'; rsCanonGenLkup = '65535:Low,0:Normal,1:High'; { rsCanonImgStabLkup = '0:Off,1:On,2:Shoot only,3:Panning,4:Dynamic,256:Off,'+ '257:On,258:Shoot only,259:Panning,260:Dynamic'; } rsCanonISOLkup = '0:Not used,15:auto,16:50,17:100,18:200,19:400'; rsCanonMacroLkup = '1:Macro,2:Normal'; rsCanonMeterLkup = '0:Default,1:Spot,2:Average,3:Evaluative,4:Partial,'+ '5:Center-weighted average'; rsCanonPanDirLkup = '0:Left to right,1:Right to left,2:Bottom to top,'+ '3:Top to bottom,4:2x2 Matrix (clockwise)'; rsCanonQualityLkup = '65535:n/a,1:Economy,2:Normal,3:Fine,4:RAW,5:Superfine,'+ '130:Normal Movie,131:Movie (2)'; rsCanonRecLkup = '1:JPEG,2:CRW+THM,3:AVI+THM,4:TIF,5:TIF+JPEG,6:CR2,'+ '7:CR2+JPEG,9:MOV,10:MP4'; rsCanonSizeLkup = '65535:n/a,0:Large,1:Medium,2:Small,4:5 MPixel,5:2 MPixel,'+ '6:1.5 MPixel,8:Postcard,9:Widescreen,10:Medium widescreen,14:Small 1,'+ '15:Small 2,16:Small 3,128:640x480 movie,129:Medium movie,130:Small movie,'+ '137:128x720 movie,142:1920x1080 movie'; rsCanonSloShuttLkup = '65535:n/a,0:Off,1:Night scene,2:On,3:None'; rsCanonWhiteBalLkup = '0:Auto,1:Daylight,2:Cloudy,3:Tungsten,4:Flourescent,'+ '5:Flash,6:Custom,7:Black & white,8:Shade,9:Manual temperature (Kelvin),'+ '14:Daylight fluorescent,17:Under water'; rsCanonZoomLkup = '0:None,1:2x,2:4x,3:Other'; procedure BuildCanonTagDefs(AList: TTagDefList); const M = DWord(TAGPARENT_MAKERNOTE); begin Assert(AList <> nil); with AList do begin AddUShortTag(M+$0001, 'ExposureInfo1'); AddUShortTag(M+$0002, 'Panorama'); AddUShortTag(M+$0004, 'ExposureInfo2'); AddStringTag(M+$0006, 'ImageType'); AddStringTag(M+$0007, 'FirmwareVersion'); AddULongTag (M+$0008, 'ImageNumber'); AddStringTag(M+$0009, 'OwnerName'); AddULongTag (M+$000C, 'CameraSerialNumber'); AddUShortTag(M+$000F, 'CustomFunctions'); end; end; //============================================================================== // TCanonMakerNoteReader //============================================================================== function TCanonMakerNoteReader.AddTag(AStream: TStream; const AIFDRecord: TIFDRecord; const AData: TBytes; AParent: TTagID): Integer; var tagDef: TTagDef; w: array of Word; n,i: Integer; t: TTagID; begin Result := -1; tagDef := FindTagDef(AIFDRecord.TagID or AParent); if (tagDef = nil) then exit; Result := inherited AddTag(AStream, AIFDRecord, AData, AParent); // We only handle 16-bit integer types here for further processing if not (tagDef.TagType in [ttUInt16, ttSInt16]) then exit; // Put binary data into a word array and fix endianness n := Length(AData) div TagElementSize[ord(tagDef.TagType)]; if n = 0 then exit; if FBigEndian then for i:=0 to n-1 do AData[i] := BEtoN(AData[i]) else for i:=0 to n-1 do AData[i] := LEtoN(AData[i]); SetLength(w, n); Move(AData[0], w[0], Length(AData)); // This is a special treatment of array tags which will be added as // separate "MakerNote" tags. t := AIFDRecord.TagID; case AIFDRecord.TagID of 1: // Exposure Info 1 with FImgInfo.ExifData do begin AddMakerNoteTag( 1, t, 'Macro mode', w[1], rsCanonMacroLkup); if n = 2 then exit; AddMakerNoteTag( 2, t, 'Self-timer', w[2]/10, '%2:.1f s'); if n = 3 then exit; AddMakerNoteTag( 3, t, 'Quality', w[3], rsCanonQualityLkup); if n = 4 then exit; AddMakerNoteTag( 4, t, 'Flash mode', w[4], rsCanonFlashLkup); if n = 5 then exit; AddMakerNoteTag( 5, t, 'Drive mode', w[5], rsSingleContinuous); if n = 7 then exit; AddMakerNoteTag( 7, t, 'Focus mode', w[7], rsCanonFocusLkup); if n = 9 then exit; AddMakerNoteTag( 9, t, 'Record mode', w[9], rsCanonRecLkup); if n = 10 then exit; AddMakerNoteTag(10, t, 'Image size', w[10], rsCanonSizeLkup); if n = 11 then exit; AddMakerNoteTag(11, t, 'Easy shoot', w[11], rsCanonEasyLkup); if n = 12 then exit; AddMakerNoteTag(12, t, 'Digital zoom', w[12], rsCanonZoomLkup); if n = 13 then exit; AddMakerNoteTag(13, t, 'Contrast', w[13], rsCanonGenLkup); if n = 14 then exit; AddMakerNoteTag(14, t, 'Saturation', w[14], rsCanonGenLkup); if n = 15 then exit; AddMakerNoteTag(15, t, 'Sharpness', w[15], rsCanonGenLkup); if n = 16 then exit; AddMakerNoteTag(16, t, 'CCD ISO', w[16], rsCanonISOLkup); if n = 17 then exit; AddMakerNoteTag(17, t, 'Metering mode', w[17], rsCanonMeterLkup); if n = 18 then exit; AddMakerNoteTag(18, t, 'Focus type', w[18], rsCanonFocTypeLkup); if n = 19 then exit; AddMakerNoteTag(19, t, 'AFPoint', w[19], rsCanonAFLkup); if n = 20 then exit; AddMakerNoteTag(20, t, 'Exposure mode', w[20], rsCanonExposeLkup); if n = 24 then exit; AddMakerNoteTag(24, t, 'Long focal', w[24]); if n = 25 then exit; AddMakerNoteTag(25, t, 'Short focal', w[25]); if n = 26 then exit; AddMakerNoteTag(26, t, 'Focal units', w[26]); if n = 28 then exit; AddMakerNoteTag(28, t, 'Flash activity', w[28], rsCanonFlashActLkup); if n = 29 then exit; AddMakerNoteTag(29, t, 'Flash details', w[29]); if n = 32 then exit; AddMakerNoteTag(32, t, 'Focus mode', w[32], rsSingleContinuous); if n = 33 then exit; AddMakerNoteTag(33, t, 'AESetting', w[33], rsCanonAELkup); if n = 34 then exit; AddMakerNoteTag(34, t, 'Image stabilization', w[34], rsSingleContinuous); end; 2: // Focal length with FImgInfo.ExifData do begin AddMakerNoteTag(0, t, 'FocalType', w[0], rsCanonFocalTypeLkup); if n = 1 then exit; AddMakerNoteTag(1, t, 'FocalLength', w[1]); end; 4: // ExposureInfo2 with FImgInfo.ExifData do begin if n = 7 then exit; AddMakerNoteTag( 7, t, 'WhiteBalance', w[7], rsCanonWhiteBalLkup); if n = 8 then exit; AddMakerNoteTag( 8, t, 'Slow shutter', w[8], rsCanonSloShuttLkup); if n = 9 then exit; AddMakerNoteTag( 9, t, 'SequenceNumber', w[9]); if n = 11 then exit; AddMakerNoteTag(11, t, 'OpticalZoomStep', w[11]); if n = 12 then exit; AddMakerNoteTag(12, t, 'Camera temperature', w[12]); if n = 14 then exit; AddMakerNoteTag(14, t, 'AFPoint', w[14]); if n = 15 then exit; AddMakerNoteTag(15, t, 'FlashBias', w[15], rsCanonBiasLkup); if n = 19 then exit; AddMakerNoteTag(19, t, 'Distance', w[19]); if n = 21 then exit; AddMakerNoteTag(21, t, 'FNumber', w[21]); if n = 22 then exit; AddMakerNoteTag(22, t, 'Exposure time', w[22]); if n = 23 then exit; AddMakerNoteTag(23, t, 'Measured EV2', w[23]); if n = 24 then exit; AddMakerNoteTag(24, t, 'Bulb duration', w[24]); if n = 26 then exit; AddMakerNoteTag(26, t, 'Camera type', w[26], rsCanonCamTypeLkup); if n = 27 then exit; AddMakerNoteTag(27, t, 'Auto rotation', w[27], rsCanonAutoRotLkup); if n = 28 then exit; AddMakerNoteTag(28, t, 'NDFilter', w[28], rsCanonGenLkup); end; 5: // Panorma with FImgInfo.ExifData do begin if n = 2 then exit; AddMakerNoteTag(2, t, 'Panorama frame number', w[2]); if n = 5 then exit; AddMakerNoteTag(5, t, 'Panorama direction', w[5], rsCanonPanDirLkup); end; end; end; procedure TCanonMakerNoteReader.GetTagDefs(AStream: TStream); begin BuildCanonTagDefs(FTagDefs); end; initialization RegisterMakerNoteReader(TCanonMakerNoteReader, 'Canon', ''); 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 untFrmDsnEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ed_DsnBase, ed_Designer, ed_dsncont, untEasyPageControl, ExtCtrls, untEasyGroupBox, ecSyntAnal, ecSyntMemo, StdCtrls, TypInfo, edcDsnEvents; type TFrmDsnEdit = class(TFrame) FormDesigner: TzFormDesigner; pgcDesignFormCode: TEasyPageControl; EasyTabSheet1: TEasyTabSheet; EasyTabSheet2: TEasyTabSheet; DesignSurface1: TDesignSurface; EasyPanel1: TEasyPanel; EasyPanel2: TEasyPanel; Splitter1: TSplitter; CodeEditor: TSyntaxMemo; SyntAnalyzer1: TSyntAnalyzer; EventsList: TListBox; DesignerEvents1: TDesignerEvents; procedure FormDesignerCanRename(Sender: TObject; Component: TComponent; const NewName: String; var Accept: Boolean); procedure FormDesignerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDesignerGetMethodNames(Sender: TObject; TypeData: PTypeData; Proc: TGetStrProc); procedure FormDesignerGetScriptProc(Sender, Instance: TObject; pInfo: PPropInfo; var ProcName: String); procedure FormDesignerSetScriptProc(Sender, Instance: TObject; pInfo: PPropInfo; const EventProc: String); procedure FormDesignerShowMethod(Sender: TObject; const MethodName: String); procedure DesignerEvents1ItemDeleted(Sender, AItem: TObject); private { Private declarations } function CreateMethod(const MethName: string; Instance: TObject; pInfo: PPropInfo): Boolean; function FindMethod(const MethName: string): TTextRange; function ShowMethod(const MethodName: string): Boolean; public { Public declarations } AForm: TForm; destructor Destroy; override; end; implementation uses untEasyFormDesigner; {$R *.dfm} {ParamList: array[1..ParamCount] of record Flags: TParamFlags; ParamName: ShortString; TypeName: ShortString; end; ResultType: ShortString} procedure GetParamList(ptData: PTypeData; SL: TStrings); var i, k: integer; pName, pType: PShortString; begin k := 0; for i := 1 to ptData^.ParamCount do begin Inc(k); pName := @ptData^.ParamList[k]; Inc(k, Length(pName^) + 1); pType := @ptData^.ParamList[k]; Inc(k, Length(pType^) + 1); SL.Add(pName^ + '=' + pType^); end; end; function TFrmDsnEdit.CreateMethod(const MethName: string; Instance: TObject; pInfo: PPropInfo): Boolean; var Code, Comment: string; SL : TStringList; i, offs, ins_p : integer; begin Result := (MethName <> '') and (FindMethod(MethName) = nil) and (pInfo^.PropType^^.Kind = tkMethod); if Result then begin SL := TStringList.Create; try GetParamList(GetTypeData(pInfo^.PropType^), SL); if (Instance is TComponent) then Comment := (Instance as TComponent).Name + '.' + pInfo^.Name else Comment := pInfo^.Name + ' handler'; Code := sLineBreak + '// ' + Comment + sLineBreak + 'procedure ' + MethName + '('; for i := 0 to SL.Count - 1 do begin if i > 0 then Code := Code + '; '; Code := Code + SL.Names[i] + ': ' + SL.ValueFromIndex[i]; end; Code := Code + ');' + sLineBreak + 'begin' + sLineBreak + ' '; offs := Length(Code); Code := Code + sLineBreak + 'end;' + sLineBreak; ins_p := 0; with CodeEditor do begin if (SyntObj <> nil) and (SyntObj.TagCount > 0) and (SyntObj.Tags[0].TokenType = 1) then begin ins_p := CaretPosToStrPos(Point(0, StrPosToCaretPos(SyntObj.Tags[0].EndPos).Y + 1)); end; CaretStrPos := ins_p; InsertText(Code); CaretStrPos := ins_p + offs; SetFocus; end; finally SL.Free; end; end; end; destructor TFrmDsnEdit.Destroy; begin if FormDesigner.Target <> nil then FormDesigner.Target.Free; inherited; end; function TFrmDsnEdit.FindMethod(const MethName: string): TTextRange; var i: integer; R: TTagBlockCondition; begin if MethName <> '' then with CodeEditor.SyntObj do begin R := TTagBlockCondition(Owner.BlockRules.ItemByName('function')); if R <> nil then for i := 0 to RangeCount - 1 do if (Ranges[i].Rule = R) and SameText(TagStr[Ranges[i].StartIdx + 1], MethName) then begin Result := Ranges[i]; Exit; end; end; Result := nil; end; procedure TFrmDsnEdit.FormDesignerCanRename(Sender: TObject; Component: TComponent; const NewName: String; var Accept: Boolean); begin if (Component = FormDesigner.Root) or (Component = nil) then (Parent as TEasyTabSheet).Caption := NewName; end; function TFrmDsnEdit.ShowMethod(const MethodName: string): Boolean; var R: TTextRange; st, en: integer; begin R := FindMethod(MethodName); Result := R <> nil; if Result then with CodeEditor.SyntObj do begin st := Tags[R.StartIdx].StartPos; if R.EndIdx <> -1 then en := Tags[R.EndIdx].EndPos else en := st; Windows.SetFocus(CodeEditor.Handle); CodeEditor.CaretStrPos := st; CodeEditor.CaretStrPos := en; CodeEditor.SetSelection(st , en - st); end; end; procedure TFrmDsnEdit.FormDesignerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ssCtrl in Shift then if Key = Ord('C') then FormDesigner.CopySelection else if Key = Ord('V') then FormDesigner.PasteSelection else if Key = Ord('X') then FormDesigner.CutSelection; end; procedure TFrmDsnEdit.FormDesignerGetMethodNames(Sender: TObject; TypeData: PTypeData; Proc: TGetStrProc); var i: integer; R: TTagBlockCondition; begin with CodeEditor.SyntObj do begin // Looking for all text ranges with rule "function" R := TTagBlockCondition(Owner.BlockRules.ItemByName('function')); if R <> nil then for i := 0 to RangeCount - 1 do if (Ranges[i].Rule = R) then Proc(TagStr[Ranges[i].StartIdx + 1]); end; end; procedure TFrmDsnEdit.FormDesignerGetScriptProc(Sender, Instance: TObject; pInfo: PPropInfo; var ProcName: String); begin ProcName := ''; if Instance is TComponent then if FormDesigner.Root = Instance then ProcName := EventsList.Items.Values[PInfo^.Name] else ProcName := EventsList.Items.Values[(Instance as TComponent).Name + '.' + PInfo^.Name]; end; procedure TFrmDsnEdit.FormDesignerSetScriptProc(Sender, Instance: TObject; pInfo: PPropInfo; const EventProc: String); var idx: integer; pn: string; begin if pgcDesignFormCode.ActivePageIndex <> 1 then pgcDesignFormCode.ActivePageIndex := 1; if Instance is TComponent then begin if FormDesigner.Root = Instance then pn := PInfo^.Name else pn := (Instance as TComponent).Name + '.' + PInfo^.Name; idx := EventsList.Items.IndexOfName(pn); if idx <> -1 then EventsList.Items.Delete(idx); if EventProc <> '' then begin // Saving associating EventsList.Items.Add(pn + '=' + EventProc); // Creating event handler text body CreateMethod(EventProc, Instance, pInfo); end; end; end; procedure TFrmDsnEdit.FormDesignerShowMethod(Sender: TObject; const MethodName: String); begin ShowMethod(MethodName); end; procedure TFrmDsnEdit.DesignerEvents1ItemDeleted(Sender, AItem: TObject); var i: integer; S: string; begin if not (AItem is TComponent) then Exit; S := TComponent(AItem).Name; for i := EventsList.Items.Count - 1 downto 0 do if SameText(S, Copy(EventsList.Items[i], 1, Length(S))) then EventsList.Items.Delete(i); end; end.
unit nxLookupEdit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, LCLType, Forms, Controls, Graphics, Dialogs, StdCtrls, DB, rxdbgrid; type { TnxLookupEdit } TnxLookupEdit = class(TCustomEdit) private FDataset: TDataset; FDisplayField: string; FEmptyReturnCount: integer; FFilter: string; FGrid: TRxDBGrid; FGridFromRight: boolean; FGridPosition: TAlign; FOnChangeEx: TNotifyEvent; FOnKeyDownEx: TKeyEvent; protected procedure FOnChange(Sender:TObject); procedure FOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); function BuildFilter:string; public procedure Loaded;override; property EmptyReturnCount:integer read FEmptyReturnCount write FEmptyReturnCount; property AutoSelected; published property DisplayField:string read FDisplayField write FDisplayField; property Fillter:string read FFilter write FFilter; property Dataset:TDataset read FDataset write FDataset; property Grid:TRxDBGrid read FGrid write FGrid; property GridPosition:TAlign read FGridPosition write FGridPosition; property GridFromRight:boolean read FGridFromRight write FGridFromRight; property OnKeyDownEx:TKeyEvent read FOnKeyDownEx write FOnKeyDownEx; property OnChangeEx:TNotifyEvent read FOnChangeEx write FOnChangeEx; property Align; property Alignment; property Anchors; property AutoSize; property AutoSelect; property BidiMode; property BorderSpacing; property BorderStyle; property CharCase; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property EchoMode; property Enabled; property Font; property HideSelection; property MaxLength; property NumbersOnly; property ParentBidiMode; property OnChangeBounds; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEditingDone; property OnEndDrag; property OnEnter; property OnExit; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDrag; property OnUTF8KeyPress; property ParentColor; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly; property ShowHint; property TabStop; property TabOrder; property Text; property TextHint; property Visible; end; procedure Register; implementation procedure Register; begin RegisterComponents('Additional',[TnxLookupEdit]); end; { TnxLookupEdit } procedure TnxLookupEdit.FOnChange(Sender: TObject); var mFilter:string; begin if Self.Enabled=False then Exit; if Assigned(FDataset) then begin if Trim(FFilter)<>'' then begin if Trim(Self.Text)<>'' then begin mFilter:=Self.BuildFilter; FDataset.Filtered:=False; FDataset.Filter:=mFilter; FDataset.Filtered:=True; if Assigned(FGrid) then begin FGrid.BringToFront; FGrid.Visible:=True; end; end else begin if Pos(' ',Self.Text)=1 then begin if Assigned(FDataset) then FDataset.Filtered:=False; if Assigned(FGrid) then FGrid.Visible:=True; end else begin if Assigned(FGrid) then FGrid.Visible:=False; end; end; end; end; if Assigned(FOnChangeEx) then FOnChangeEx(Sender); end; procedure TnxLookupEdit.FOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=VK_Down) or (key=VK_Up) then if Assigned(FGrid) then if FGrid.Visible then FGrid.SetFocus; if key=VK_ESCAPE then if Assigned(FGrid) then FGrid.Visible:=False; if key=VK_RETURN then begin if Assigned(FDataset) then begin if Trim(FDisplayField)<>'' then begin if not FDataset.FieldByName(FDisplayField).IsNull then begin Self.Text:=FDataset.FieldByName(FDisplayField).Text; if Assigned(FGrid) then begin FGrid.Visible:=False; end; end else begin Self.Text:=''; if Assigned(FGrid) then begin FGrid.Visible:=False; end; end; end; end; if Trim(Self.Text)='' then begin FEmptyReturnCount:=FEmptyReturnCount+1; end else FEmptyReturnCount:=0; end; if Assigned(FOnKeyDownEx) then FOnKeyDownEx(Sender, Key, Shift); end; function TnxLookupEdit.BuildFilter: string; var m:string; begin m:=FFilter; m:=StringReplace(m,'#text#',Trim(Self.Text),[rfReplaceAll]); Result:=m; end; procedure TnxLookupEdit.Loaded; begin inherited Loaded; Self.OnChange:=@FOnChange; Self.OnKeyDown:=@FOnKeyDown; FGridPosition:=alBottom; end; end.
unit Security4D.Aspect; interface uses System.SysUtils, System.Rtti, Aspect4D, Security4D; type RequiredPermissionAttribute = class(AspectAttribute) private fResource: string; fOperation: string; protected { protected declarations } public constructor Create(const resource, operation: string); property Resource: string read fResource; property Operation: string read fOperation; end; RequiredRoleAttribute = class(AspectAttribute) private fRole: string; protected { protected declarations } public constructor Create(const role: string); property Role: string read fRole; end; TSecurityAspect = class(TAspect, IAspect) private const NO_PERMISSION = 'You do not have permission to access this feature.'; NO_ROLE = 'You do not have role to access this feature.'; private fSecurityContext: ISecurityContext; protected function GetName: string; procedure DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean; out result: TValue); procedure DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue); procedure DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean; theException: Exception; out result: TValue); public constructor Create(securityContext: ISecurityContext); end; implementation { RequiredPermissionAttribute } constructor RequiredPermissionAttribute.Create(const resource, operation: string); begin inherited Create; fResource := resource; fOperation := operation; end; { RequiredRoleAttribute } constructor RequiredRoleAttribute.Create(const role: string); begin inherited Create; fRole := role; end; { TSecurityAspect } constructor TSecurityAspect.Create(securityContext: ISecurityContext); begin inherited Create; fSecurityContext := securityContext; end; procedure TSecurityAspect.DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue); begin // Method unused end; procedure TSecurityAspect.DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean; out result: TValue); var att: TCustomAttribute; hasPermission: Boolean; hasRole: Boolean; begin hasPermission := True; for att in method.GetAttributes do if att is RequiredPermissionAttribute then begin hasPermission := fSecurityContext.HasPermission( RequiredPermissionAttribute(att).Resource, RequiredPermissionAttribute(att).Operation ); if hasPermission then Break; end; hasRole := True; for att in method.GetAttributes do if att is RequiredRoleAttribute then begin hasRole := fSecurityContext.HasRole(RequiredRoleAttribute(att).Role); if hasRole then Break; end; if not hasPermission then raise EAuthorizationException.Create(NO_PERMISSION); if not hasRole then raise EAuthorizationException.Create(NO_ROLE); end; procedure TSecurityAspect.DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean; theException: Exception; out result: TValue); begin // Method unused end; function TSecurityAspect.GetName: string; begin Result := Self.QualifiedClassName; end; end.
Program 4Act7; Type // Lista de enteros lista = ^nodoL; nodoL = record dato: integer; sig: lista; end; // Arbol de enteros arbol= ^nodoA; nodoA = Record dato: integer; HI: arbol; HD: arbol; End; // Lista de Arboles listaNivel = ^nodoN; nodoN = record info: arbol; sig: listaNivel; end; {----------------------------------------------------------------------------- AgregarAdelante - Agrega nro adelante de l} procedure agregarAdelante(var l: Lista; nro: integer); var aux: lista; begin new(aux); aux^.dato := nro; aux^.sig := l; l:= aux; end; {----------------------------------------------------------------------------- CREARLISTA - Genera una lista con números aleatorios } procedure crearLista(var l: Lista); var n: integer; begin l:= nil; n := random (20); While (n <> 0) do Begin agregarAdelante(L, n); n := random (20); End; end; {----------------------------------------------------------------------------- IMPRIMIRLISTA - Muestra en pantalla la lista l } procedure imprimirLista(l: Lista); begin While (l <> nil) do begin write(l^.dato, ' - '); l:= l^.sig; End; end; {----------------------------------------------------------------------------- CONTARELEMENTOS - Devuelve la cantidad de elementos de una lista l } function ContarElementos (l: listaNivel): integer; var c: integer; begin c:= 0; While (l <> nil) do begin c:= c+1; l:= l^.sig; End; contarElementos := c; end; {----------------------------------------------------------------------------- AGREGARATRAS - Agrega un elemento atrás en l} Procedure AgregarAtras (var l, ult: listaNivel; a:arbol); var nue:listaNivel; begin new (nue); nue^.info := a; nue^.sig := nil; if l= nil then l:= nue else ult^.sig:= nue; ult:= nue; end; {Actividad} procedure Insertar(num:integer; var a:arbol); begin if (a=nil) then begin new(a); a^.dato:=num; a^.HI:=nil; a^.HD:=nil; end else if (a^.dato>num) then Insertar(num,a^.HI) else if (a^.dato<num) then Insertar(num,a^.HD) end; procedure InsertarElementos (L:lista; var a:arbol); begin if (L<>nil) then begin Insertar(L^.dato,a); InsertarElementos(L^.sig,a); end; end; Procedure enOrden( a: arbol ); begin if ( a <> nil ) then begin enOrden (a^.HI); write (a^.dato, ' '); enOrden (a^.HD) end; end; procedure VerValoresEnRango ( a:arbol; inf:integer; sup:integer); begin if (a<>nil) then if(a^.dato>=inf)then if(a^.dato<=sup)then begin write(a^.dato;' - '); VerValoresEnRango(a^.HI,inf,sup); VerValoresEnRango(a^.HD,inf,sup); end else VerValoresEnRango(a^.HI,inf,sup) else VerValoresEnRango(a^.HD,inf,sup) end; {----------------------------------------------------------------------------- IMPRIMIRPORNIVEL - Muestra los datos del árbol a por niveles } Procedure imprimirpornivel(a: arbol); var l, aux, ult: listaNivel; nivel, cant, i: integer; begin l:= nil; if(a <> nil)then begin nivel:= 0; agregarAtras (l,ult,a); while (l<> nil) do begin nivel := nivel + 1; cant:= contarElementos(l); write ('Nivel ', nivel, ': '); for i:= 1 to cant do begin write (l^.info^.dato, ' - '); if (l^.info^.HI <> nil) then agregarAtras (l,ult,l^.info^.HI); if (l^.info^.HD <> nil) then agregarAtras (l,ult,l^.info^.HD); aux:= l; l:= l^.sig; dispose (aux); end; writeln; end; end; end; Var l: lista; a:arbol; inf,sup:integer; begin Randomize; crearLista(l); writeln ('Lista generada: '); imprimirLista(l); InsertarElementos(L,a); enOrden(a); writeln('Informar Rango: '); readln(inf); readln(sup); VerValoresEnRango(a,inf,sup); readln; end.
{ LaKraven Studios Standard Library [LKSL] Copyright (c) 2014, LaKraven Studios Ltd, All Rights Reserved Original Source Location: https://github.com/LaKraven/LKSL License: - You may use this library as you see fit, including use within commercial applications. - You may modify this library to suit your needs, without the requirement of distributing modified versions. - You may redistribute this library (in part or whole) individually, or as part of any other works. - You must NOT charge a fee for the distribution of this library (compiled or in its source form). It MUST be distributed freely. - This license and the surrounding comment block MUST remain in place on all copies and modified versions of this source code. - Modified versions of this source MUST be clearly marked, including the name of the person(s) and/or organization(s) responsible for the changes, and a SEPARATE "changelog" detailing all additions/deletions/modifications made. Disclaimer: - Your use of this source constitutes your understanding and acceptance of this disclaimer. - LaKraven Studios Ltd and its employees (including but not limited to directors, programmers and clerical staff) cannot be held liable for your use of this source code. This includes any losses and/or damages resulting from your use of this source code, be they physical, financial, or psychological. - There is no warranty or guarantee (implicit or otherwise) provided with this source code. It is provided on an "AS-IS" basis. Donations: - While not mandatory, contributions are always appreciated. They help keep the coffee flowing during the long hours invested in this and all other Open Source projects we produce. - Donations can be made via PayPal to PayPal [at] LaKraven (dot) Com ^ Garbled to prevent spam! ^ } unit LKSL_Settings_Fields; { About this unit: (FPC/Lazarus) - This unit provides the objects that contain key/value pairs. Changelog (newest on top): 3rd October 2014: - Initial Scaffolding } {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TLKSettingsFieldTypes - Enum of field types } TLKSettingsFieldTypes = ( sftUnknown, sftInteger, sftString ); { TLKSettingsField - This is the base class for key/value pair. } PLKSettingsField = ^TLKSettingsField; TLKSettingsField = class(TComponent) private protected FFieldType: TLKSettingsFieldTypes; FFieldName: String; FDisplayName: String; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property FieldType: TLKSettingsFieldTypes read FFieldType; property FieldName: String read FFieldName write FFieldName; property DisplayName: String read FDisplayName write FDisplayName; end; TLKSettingsFieldClass = class of TLKSettingsField; { TLKSettingsFieldInteger - Class implementing and Integer field. } TLKSettingsFieldInteger = class(TLKSettingsField) private FFieldValue: Integer; procedure SetValue(AValue: Integer); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Value: Integer read FFieldValue write SetValue; end; TLKSettingsFieldIntegerClass = class of TLKSettingsFieldInteger; { TLKSettingsFieldString - Class implementing and Integer field. } TLKSettingsFieldString = class(TLKSettingsField) private FFieldValue: String; procedure SetValue(AValue: String); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Value: String read FFieldValue write SetValue; end; TLKSettingsFieldStringClass = class of TLKSettingsFieldString; { TLKSettingsFields - This class implements a list of fields } TLKSettingsFields = class(TComponent) private FSettingsFieldItems: TFPList; function GetCount: Integer; function GetSettingsField(Index: Integer): TLKSettingsField; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Add(AField: TLKSettingsField): Integer; procedure Delete(AField: TLKSettingsField); procedure Delete(AIndex: Integer); overload; procedure Clear; property Items[Index: Integer]: TLKSettingsField read GetSettingsField; default; property Count: Integer read GetCount; published end; {$IFDEF FPC} { TLKSettingsFieldsEnumerator - Enumeration class for field list } TLKSettingsFieldsEnumerator = class private FList: TLKSettingsFields; FPosition: Integer; public constructor Create(ASettingsFields: TLKSettingsFields); function GetCurrent: TLKSettingsField; function MoveNext: Boolean; property Current: TLKSettingsField read GetCurrent; end; {$IFEND} implementation {$IFDEF FPC} { TLKSettingsFieldsEnumerator } constructor TLKSettingsFieldsEnumerator.Create(ASettingsFields: TLKSettingsFields); begin FList:= ASettingsFields; FPosition:= -1; end; function TLKSettingsFieldsEnumerator.GetCurrent: TLKSettingsField; begin Result:= FList[FPosition]; end; function TLKSettingsFieldsEnumerator.MoveNext: Boolean; begin Inc(FPosition); Result:= FPosition < FList.Count; end; {$IFEND} { TLKSettingsFieldString } procedure TLKSettingsFieldString.SetValue(AValue: String); begin if FFieldValue <> AValue then begin FFieldValue:=AValue; end; end; constructor TLKSettingsFieldString.Create(AOwner: TComponent); begin inherited Create(AOwner); FFieldType:= sftString; FFieldValue:= ''; // TODO: Should I initilize it? end; destructor TLKSettingsFieldString.Destroy; begin inherited Destroy; end; { TLKSettingsFields } function TLKSettingsFields.GetSettingsField(Index: Integer): TLKSettingsField; begin Result:= TLKSettingsField(FSettingsFieldItems[Index]); end; function TLKSettingsFields.GetCount: Integer; begin Result:= FSettingsFieldItems.Count; end; constructor TLKSettingsFields.Create(AOwner: TComponent); begin inherited Create(AOwner); FSettingsFieldItems:= TFPList.Create; end; destructor TLKSettingsFields.Destroy; var Index: Integer; begin if Assigned(FSettingsFieldItems) then begin for Index:= FSettingsFieldItems.Count - 1 downto 0 do begin if Assigned(FSettingsFieldItems[Index]) then begin TLKSettingsField(FSettingsFieldItems[Index]).Free; FSettingsFieldItems.Delete(Index); end; end; FSettingsFieldItems.Free; end; inherited Destroy; end; function TLKSettingsFields.Add(AField: TLKSettingsField): Integer; begin Result:= FSettingsFieldItems.Add(AField); end; procedure TLKSettingsFields.Delete(AField: TLKSettingsField); var Index: Integer; begin for Index:= 0 to FSettingsFieldItems.Count - 1 do begin if AField = TLKSettingsField(FSettingsFieldItems[Index]) then begin TLKSettingsField(FSettingsFieldItems[Index]).Free; FSettingsFieldItems.Delete(Index); break; end; end; end; procedure TLKSettingsFields.Delete(AIndex: Integer); begin FSettingsFieldItems.Delete(AIndex); end; procedure TLKSettingsFields.Clear; var Index: Integer; begin for Index:= FSettingsFieldItems.Count - 1 downto 0 do begin if Assigned(FSettingsFieldItems[Index]) then begin TLKSettingsField(FSettingsFieldItems[Index]).Free; end; FSettingsFieldItems.Delete(Index); end; end; { TLKSettingsField } constructor TLKSettingsField.Create(AOwner: TComponent); begin inherited Create(AOwner); FFieldType:= sftUnknown; end; destructor TLKSettingsField.Destroy; begin inherited Destroy; end; { TLKSettingsFieldInteger } procedure TLKSettingsFieldInteger.SetValue(AValue: Integer); begin if FFieldValue <> AValue then begin FFieldValue:=AValue; end; end; constructor TLKSettingsFieldInteger.Create(AOwner: TComponent); begin inherited Create(AOwner); FFieldType:= sftInteger; FFieldValue:= 0; // TODO: Should I initilize it? end; destructor TLKSettingsFieldInteger.Destroy; begin inherited Destroy; end; end.
unit Test.SecurityDialogsView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Security.User, Security.Matrix, Security.Permission, Security.ChangePassword, Security.Login, Security.Manage, Security.ChangePassword.View, Security.Matrix.View, Security.Login.View ; type TSecurityDialogsView = class(TForm) FlowPanel: TFlowPanel; ButtonLogin: TButton; ButtonChangePassword: TButton; ButtonPermission: TButton; ButtonMatrix: TButton; ButtonUser: TButton; ButtonManage: TButton; MemoEvent: TMemo; SecurityLogin1: TSecurityLogin; SecurityMatrix1: TSecurityMatrix; SecurityChangePassword1: TSecurityChangePassword; Manage1: TSecurityManage; SecurityUser1: TSecurityUser; procedure ButtonLoginClick(Sender: TObject); procedure OnAuthenticate(const aEmail, aPassword: string; var aAuthenticated: Boolean; var aEmailError, aPasswordError: string); procedure OnResult(const aResult: Boolean); procedure ButtonChangePasswordClick(Sender: TObject); procedure OnChangePassword(const aID: Int64; const aNewPassword: string; var aError: string; var aChanged: Boolean); procedure ButtonPermissionClick(Sender: TObject); procedure OnPermission(aID: Int64; aCan, aName: string; var aError: string; var aChanged: Boolean); procedure ButtonDevClick(Sender: TObject); private procedure SetLog(Legend: Variant; const Value: Variant); { Private declarations } public { Public declarations } property Log[Legend: Variant]: Variant write SetLog; end; var Form2: TSecurityDialogsView; implementation {$R *.dfm} procedure TSecurityDialogsView.SetLog(Legend: Variant; const Value: Variant); begin MemoEvent.Lines.Append( Format('%20-s = %s', [VarToStr(Legend), VarToStr(Value)]) ); end; procedure TSecurityDialogsView.ButtonLoginClick(Sender: TObject); begin with Manage1 do begin // Legendas Login.ServerIP := '192.168.0.1'; Login.ComputerIP := '192.168.0.12'; Login.Sigla := 'Test'; Login.Version := '1.0.0.1'; Login.UpdatedAt := DateToStr(Date); // Login.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg'); // Execute Log['SAIDA'] := 'Result: '; Login.Execute; end; end; procedure TSecurityDialogsView.OnAuthenticate(const aEmail, aPassword: string; var aAuthenticated: Boolean; var aEmailError, aPasswordError: string); begin Log['LOCAL'] := 'LoginAuthenticate'; Log['aEmail'] := aEmail; Log['aPassword'] := aPassword; Log['aAuthenticated'] := aAuthenticated; Log['aEmailError'] := aPassword; Log['aPasswordError'] := aPasswordError; if not aEmail.Equals('luisnt') then aEmailError := 'Login Inválido!'; if not aPassword.Equals('7ujkl05') then aPasswordError := 'Senha Inválida!'; aAuthenticated := SameStr(aEmailError + aPasswordError, EmptyStr); end; procedure TSecurityDialogsView.ButtonChangePasswordClick(Sender: TObject); begin with Manage1 do begin // Legendas ChangePassword.ServerIP := '192.168.0.1'; ChangePassword.ComputerIP := '192.168.0.12'; ChangePassword.Sigla := 'Test'; ChangePassword.Version := '1.0.0.1'; ChangePassword.UpdatedAt := DateToStr(Date); // ChangePassword.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg'); // Config ChangePassword.ID := 1; ChangePassword.Password := '123'; ChangePassword.Usuario := 'LuisNt : Luis Alfredo G Caldas Neto'; // Execute Log['SAIDA'] := 'Result: '; ChangePassword.Execute; end; end; procedure TSecurityDialogsView.OnChangePassword(const aID: Int64; const aNewPassword: string; var aError: string; var aChanged: Boolean); begin aError := EmptyStr; Log['LOCAL'] := 'ChangePassword'; Log['aID'] := aID; Log['aNewPassword'] := aNewPassword; Log['aError'] := aError; Log['aChanged'] := aChanged; aChanged := SameStr(aError, EmptyStr); end; procedure TSecurityDialogsView.ButtonPermissionClick(Sender: TObject); begin with Manage1 do begin // Legendas Permission.ServerIP := '192.168.0.1'; Permission.ComputerIP := '192.168.0.12'; Permission.Sigla := 'Test'; Permission.Version := '1.0.0.1'; Permission.UpdatedIn := DateToStr(Date); // Permission.Logo.Picture.LoadFromFile('D:\res\Logo\Logo SETSL 150px.jpg'); // Config Permission.ID := 0; Permission.UpdatedAt := Now; Permission.Can := '01.01.01.00'; Permission.NamePermission := 'Teste de Permissão'; // Execute Log['SAIDA'] := 'Result: '; Permission.Execute; end; end; procedure TSecurityDialogsView.OnPermission(aID: Int64; aCan, aName: string; var aError: string; var aChanged: Boolean); begin Log['LOCAL'] := 'Permission'; Log['aID'] := aID; Log['aCan'] := aCan; Log['aName'] := aName; Log['aError'] := aError; Log['aChanged'] := aChanged; aChanged := true; end; procedure TSecurityDialogsView.OnResult(const aResult: Boolean); begin Log['SAIDA'] := BoolToStr(aResult, true); end; procedure TSecurityDialogsView.ButtonDevClick(Sender: TObject); begin Log['LOCAL'] := TButton(Sender).Name + ' Em Desenvolvimento'; end; initialization ReportMemoryLeaksOnShutdown := true; end.
{$mode objfpc}{$H+}{$J-} uses SysUtils; type TGun = class end; TPlayer = class Gun1, Gun2: TGun; constructor Create; destructor Destroy; override; end; constructor TPlayer.Create; begin inherited; Gun1 := TGun.Create; raise Exception.Create('Предизвикано изключение от конструктор!'); Gun2 := TGun.Create; end; destructor TPlayer.Destroy; begin { в случай, че конструктора крашне, бихме могли да имаме ситуация с Gun1 <> nil и Gun2 = nil. Справете се с това. ... Всъщност в случая FreeAndNil ще се справи без допълнителни усилия от наша страна, защото FreeAndNil проверява дали инстанцията е nil преди да извика деструктора. } FreeAndNil(Gun1); FreeAndNil(Gun2); inherited; end; begin try TPlayer.Create; except on E: Exception do WriteLn('Уловено ' + E.ClassName + ': ' + E.Message); end; end.
unit caMessages; interface uses // Standard Delphi units  SysUtils, Classes, Messages; type //--------------------------------------------------------------------------- // IcaMessages   //--------------------------------------------------------------------------- IcaMessages = interface ['{DBAB0823-0BA3-466C-A5FF-532EDE3603C2}'] // Interface methods  function MsgToString(AMsg: Word): string; end; //--------------------------------------------------------------------------- // TcaMessages   //--------------------------------------------------------------------------- TcaMessages = class(TInterfacedObject, IcaMessages) private // Private fields  FList: TStrings; // Private methods  procedure BuildEmptyList; procedure BuildMessageList; protected // Interface methods  function MsgToString(AMsg: Word): string; public // Create/Destroy  constructor Create; destructor Destroy; override; end; implementation //--------------------------------------------------------------------------- // TcaMessages   //--------------------------------------------------------------------------- // Create/Destroy  constructor TcaMessages.Create; begin inherited; FList := TStringList.Create; BuildEmptyList; BuildMessageList; end; destructor TcaMessages.Destroy; begin FList.Free; inherited; end; // Interface methods  function TcaMessages.MsgToString(AMsg: Word): string; begin Result := ''; if AMsg < WM_USER then Result := FList[AMsg]; end; // Private methods  procedure TcaMessages.BuildEmptyList; var Index: Integer; begin for Index := 0 to Pred(WM_USER) do FList.Add(''); end; procedure TcaMessages.BuildMessageList; begin FList[$0000] := 'WM_NULL'; FList[$0001] := 'WM_CREATE '; FList[$0002] := 'WM_DESTROY '; FList[$0003] := 'WM_MOVE '; FList[$0005] := 'WM_SIZE '; FList[$0006] := 'WM_ACTIVATE '; FList[$0007] := 'WM_SETFOCUS '; FList[$0008] := 'WM_KILLFOCUS '; FList[$000A] := 'WM_ENABLE '; FList[$000B] := 'WM_SETREDRAW '; FList[$000C] := 'WM_SETTEXT '; FList[$000D] := 'WM_GETTEXT '; FList[$000E] := 'WM_GETTEXTLENGTH '; FList[$000F] := 'WM_PAINT '; FList[$0010] := 'WM_CLOSE '; FList[$0011] := 'WM_QUERYENDSESSION '; FList[$0012] := 'WM_QUIT '; FList[$0013] := 'WM_QUERYOPEN '; FList[$0014] := 'WM_ERASEBKGND '; FList[$0015] := 'WM_SYSCOLORCHANGE '; FList[$0016] := 'WM_ENDSESSION '; FList[$0017] := 'WM_SYSTEMERROR '; FList[$0018] := 'WM_SHOWWINDOW '; FList[$0019] := 'WM_CTLCOLOR '; FList[$001A] := 'WM_SETTINGCHANGE '; FList[$001B] := 'WM_DEVMODECHANGE '; FList[$001C] := 'WM_ACTIVATEAPP '; FList[$001D] := 'WM_FONTCHANGE '; FList[$001E] := 'WM_TIMECHANGE '; FList[$001F] := 'WM_CANCELMODE '; FList[$0020] := 'WM_SETCURSOR '; FList[$0021] := 'WM_MOUSEACTIVATE '; FList[$0022] := 'WM_CHILDACTIVATE '; FList[$0023] := 'WM_QUEUESYNC '; FList[$0024] := 'WM_GETMINMAXINFO '; FList[$0026] := 'WM_PAINTICON '; FList[$0027] := 'WM_ICONERASEBKGND '; FList[$0028] := 'WM_NEXTDLGCTL '; FList[$002A] := 'WM_SPOOLERSTATUS '; FList[$002B] := 'WM_DRAWITEM '; FList[$002C] := 'WM_MEASUREITEM '; FList[$002D] := 'WM_DELETEITEM '; FList[$002E] := 'WM_VKEYTOITEM '; FList[$002F] := 'WM_CHARTOITEM '; FList[$0030] := 'WM_SETFONT '; FList[$0031] := 'WM_GETFONT '; FList[$0032] := 'WM_SETHOTKEY '; FList[$0033] := 'WM_GETHOTKEY '; FList[$0037] := 'WM_QUERYDRAGICON '; FList[$0039] := 'WM_COMPAREITEM '; FList[$003D] := 'WM_GETOBJECT '; FList[$0041] := 'WM_COMPACTING '; FList[$0044] := 'WM_COMMNOTIFY '; FList[$0046] := 'WM_WINDOWPOSCHANGING '; FList[$0047] := 'WM_WINDOWPOSCHANGED '; FList[$0048] := 'WM_POWER '; FList[$004A] := 'WM_COPYDATA '; FList[$004B] := 'WM_CANCELJOURNAL '; FList[$004E] := 'WM_NOTIFY '; FList[$0050] := 'WM_INPUTLANGCHANGEREQUEST '; FList[$0051] := 'WM_INPUTLANGCHANGE '; FList[$0052] := 'WM_TCARD '; FList[$0053] := 'WM_HELP '; FList[$0054] := 'WM_USERCHANGED '; FList[$0055] := 'WM_NOTIFYFORMAT '; FList[$007B] := 'WM_CONTEXTMENU '; FList[$007C] := 'WM_STYLECHANGING '; FList[$007D] := 'WM_STYLECHANGED '; FList[$007E] := 'WM_DISPLAYCHANGE '; FList[$007F] := 'WM_GETICON '; FList[$0080] := 'WM_SETICON '; FList[$0081] := 'WM_NCCREATE '; FList[$0082] := 'WM_NCDESTROY '; FList[$0083] := 'WM_NCCALCSIZE '; FList[$0084] := 'WM_NCHITTEST '; FList[$0085] := 'WM_NCPAINT '; FList[$0086] := 'WM_NCACTIVATE '; FList[$0087] := 'WM_GETDLGCODE '; FList[$00A0] := 'WM_NCMOUSEMOVE '; FList[$00A1] := 'WM_NCLBUTTONDOWN '; FList[$00A2] := 'WM_NCLBUTTONUP '; FList[$00A3] := 'WM_NCLBUTTONDBLCLK '; FList[$00A4] := 'WM_NCRBUTTONDOWN '; FList[$00A5] := 'WM_NCRBUTTONUP '; FList[$00A6] := 'WM_NCRBUTTONDBLCLK '; FList[$00A7] := 'WM_NCMBUTTONDOWN '; FList[$00A8] := 'WM_NCMBUTTONUP '; FList[$00A9] := 'WM_NCMBUTTONDBLCLK '; FList[$00AB] := 'WM_NCXBUTTONDOWN '; FList[$00AC] := 'WM_NCXBUTTONUP '; FList[$00AD] := 'WM_NCXBUTTONDBLCLK '; FList[$00FF] := 'WM_INPUT '; FList[$0100] := 'WM_KEYDOWN '; FList[$0100] := 'WM_KEYFIRST '; FList[$0101] := 'WM_KEYUP '; FList[$0102] := 'WM_CHAR '; FList[$0103] := 'WM_DEADCHAR '; FList[$0104] := 'WM_SYSKEYDOWN '; FList[$0105] := 'WM_SYSKEYUP '; FList[$0106] := 'WM_SYSCHAR '; FList[$0107] := 'WM_SYSDEADCHAR '; FList[$0108] := 'WM_KEYLAST '; FList[$010D] := 'WM_IME_STARTCOMPOSITION '; FList[$010E] := 'WM_IME_ENDCOMPOSITION '; FList[$010F] := 'WM_IME_COMPOSITION '; FList[$010F] := 'WM_IME_KEYLAST '; FList[$0110] := 'WM_INITDIALOG '; FList[$0111] := 'WM_COMMAND '; FList[$0112] := 'WM_SYSCOMMAND '; FList[$0113] := 'WM_TIMER '; FList[$0114] := 'WM_HSCROLL '; FList[$0115] := 'WM_VSCROLL '; FList[$0116] := 'WM_INITMENU '; FList[$0117] := 'WM_INITMENUPOPUP '; FList[$011F] := 'WM_MENUSELECT '; FList[$0120] := 'WM_MENUCHAR '; FList[$0121] := 'WM_ENTERIDLE '; FList[$0122] := 'WM_MENURBUTTONUP '; FList[$0123] := 'WM_MENUDRAG '; FList[$0124] := 'WM_MENUGETOBJECT '; FList[$0125] := 'WM_UNINITMENUPOPUP '; FList[$0126] := 'WM_MENUCOMMAND '; FList[$0127] := 'WM_CHANGEUISTATE '; FList[$0128] := 'WM_UPDATEUISTATE '; FList[$0129] := 'WM_QUERYUISTATE '; FList[$0132] := 'WM_CTLCOLORMSGBOX '; FList[$0133] := 'WM_CTLCOLOREDIT '; FList[$0134] := 'WM_CTLCOLORLISTBOX '; FList[$0135] := 'WM_CTLCOLORBTN '; FList[$0136] := 'WM_CTLCOLORDLG '; FList[$0137] := 'WM_CTLCOLORSCROLLBAR '; FList[$0138] := 'WM_CTLCOLORSTATIC '; FList[$0200] := 'WM_MOUSEFIRST '; FList[$0200] := 'WM_MOUSEMOVE '; FList[$0201] := 'WM_LBUTTONDOWN '; FList[$0202] := 'WM_LBUTTONUP '; FList[$0203] := 'WM_LBUTTONDBLCLK '; FList[$0204] := 'WM_RBUTTONDOWN '; FList[$0205] := 'WM_RBUTTONUP '; FList[$0206] := 'WM_RBUTTONDBLCLK '; FList[$0207] := 'WM_MBUTTONDOWN '; FList[$0208] := 'WM_MBUTTONUP '; FList[$0209] := 'WM_MBUTTONDBLCLK '; FList[$020A] := 'WM_MOUSELAST '; FList[$020A] := 'WM_MOUSEWHEEL '; FList[$0210] := 'WM_PARENTNOTIFY '; FList[$0211] := 'WM_ENTERMENULOOP '; FList[$0212] := 'WM_EXITMENULOOP '; FList[$0213] := 'WM_NEXTMENU '; FList[$0214] := 'WM_SIZING '; FList[$0215] := 'WM_CAPTURECHANGED '; FList[$0216] := 'WM_MOVING '; FList[$0218] := 'WM_POWERBROADCAST '; FList[$0219] := 'WM_DEVICECHANGE '; FList[$0220] := 'WM_MDICREATE '; FList[$0221] := 'WM_MDIDESTROY '; FList[$0222] := 'WM_MDIACTIVATE '; FList[$0223] := 'WM_MDIRESTORE '; FList[$0224] := 'WM_MDINEXT '; FList[$0225] := 'WM_MDIMAXIMIZE '; FList[$0226] := 'WM_MDITILE '; FList[$0227] := 'WM_MDICASCADE '; FList[$0228] := 'WM_MDIICONARRANGE '; FList[$0229] := 'WM_MDIGETACTIVE '; FList[$0230] := 'WM_MDISETMENU '; FList[$0231] := 'WM_ENTERSIZEMOVE '; FList[$0232] := 'WM_EXITSIZEMOVE '; FList[$0233] := 'WM_DROPFILES '; FList[$0234] := 'WM_MDIREFRESHMENU '; FList[$0281] := 'WM_IME_SETCONTEXT '; FList[$0282] := 'WM_IME_NOTIFY '; FList[$0283] := 'WM_IME_CONTROL '; FList[$0284] := 'WM_IME_COMPOSITIONFULL '; FList[$0285] := 'WM_IME_SELECT '; FList[$0286] := 'WM_IME_CHAR '; FList[$0288] := 'WM_IME_REQUEST '; FList[$0290] := 'WM_IME_KEYDOWN '; FList[$0291] := 'WM_IME_KEYUP '; FList[$02A0] := 'WM_NCMOUSEHOVER '; FList[$02A1] := 'WM_MOUSEHOVER '; FList[$02A2] := 'WM_NCMOUSELEAVE '; FList[$02A3] := 'WM_MOUSELEAVE '; FList[$02B1] := 'WM_WTSSESSION_CHANGE '; FList[$02C0] := 'WM_TABLET_FIRST '; FList[$02DF] := 'WM_TABLET_LAST '; FList[$0300] := 'WM_CUT '; FList[$0301] := 'WM_COPY '; FList[$0302] := 'WM_PASTE '; FList[$0303] := 'WM_CLEAR '; FList[$0304] := 'WM_UNDO '; FList[$0305] := 'WM_RENDERFORMAT '; FList[$0306] := 'WM_RENDERALLFORMATS '; FList[$0307] := 'WM_DESTROYCLIPBOARD '; FList[$0308] := 'WM_DRAWCLIPBOARD '; FList[$0309] := 'WM_PAINTCLIPBOARD '; FList[$030A] := 'WM_VSCROLLCLIPBOARD '; FList[$030B] := 'WM_SIZECLIPBOARD '; FList[$030C] := 'WM_ASKCBFORMATNAME '; FList[$030D] := 'WM_CHANGECBCHAIN '; FList[$030E] := 'WM_HSCROLLCLIPBOARD '; FList[$030F] := 'WM_QUERYNEWPALETTE '; FList[$0310] := 'WM_PALETTEISCHANGING '; FList[$0311] := 'WM_PALETTECHANGED '; FList[$0312] := 'WM_HOTKEY '; FList[$0317] := 'WM_PRINT '; FList[$0318] := 'WM_PRINTCLIENT '; FList[$0319] := 'WM_APPCOMMAND '; FList[$031A] := 'WM_THEMECHANGED '; FList[$0358] := 'WM_HANDHELDFIRST '; FList[$035F] := 'WM_HANDHELDLAST '; FList[$0380] := 'WM_PENWINFIRST '; FList[$038F] := 'WM_PENWINLAST '; FList[$0390] := 'WM_COALESCE_FIRST '; FList[$039F] := 'WM_COALESCE_LAST '; FList[$03E0] := 'WM_DDE_INITIATE '; FList[$03E1] := 'WM_DDE_TERMINATE '; FList[$03E2] := 'WM_DDE_ADVISE '; FList[$03E3] := 'WM_DDE_UNADVISE '; FList[$03E4] := 'WM_DDE_ACK '; FList[$03E5] := 'WM_DDE_DATA '; FList[$03E6] := 'WM_DDE_REQUEST '; FList[$03E7] := 'WM_DDE_POKE '; FList[$03E8] := 'WM_DDE_EXECUTE '; FList[$03E9] := 'WM_DDE_LAST '; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 71 O(N2) Dynamic Memoize Method Nim Value Calc. } program AnnihilationGame; const MaxN = 100; var N, E, M : Integer; G : array [1 .. MaxN, 1 .. MaxN] of Boolean; Nim : array [1 .. MaxN] of Integer; S, T, Mark : array [0 .. MaxN] of Boolean; I, J, K : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, E, M); for I := 1 to M do begin Read(J); S[J] := True; end; Readln; for I := 1 to E do begin Readln(J, K); G[J, K] := True; end; Close(Input); Assign(Input, ''); Reset(Input); end; function Min (A, B : Integer) : Integer; begin if A <= B then Min := A else Min := B; end; function NimValue (V : Integer) : Integer; var I : Integer; begin Mark[V] := True; for I := 1 to N do if G[V, I] and not Mark[I] then J := NimValue(I); FillChar(T, SizeOf(T), 0); for I := 1 to N do if G[V, I] then T[Nim[I]] := True; for I := 0 to N do if not T[I] then Break; Nim[V] := I; end; procedure CalcNimValues; begin for I := 1 to N do NimValue(I); end; function Finished : Boolean; begin for I := 1 to N do if S[I] then for J := 1 to N do if G[I, J] then begin Finished := False; Exit; end; Finished := True; end; procedure Play; begin while not Finished do begin if K = 0 then begin Write('You move a pebble from? '); Readln(I); Write('to? '); Readln(J); if (I < 1) or (I > N) or (J < 1) or (J > N) or not S[I] or not G[I, J] then begin Writeln('Error'); Halt; end; S[I] := not S[I]; S[J] := not S[J]; K := K xor Nim[I] xor Nim[J]; end else begin for I := 1 to N do if S[I] then begin for J := 1 to N do if G[I, J] and (K = Nim[I] xor Nim[J]) then begin Writeln('I move a pebble from vertex #', I, ' to vertex #', J); S[I] := not S[I]; S[J] := not S[J]; K := K xor Nim[I] xor Nim[J]; end; if K = 0 then Break; end; end; end; end; procedure Solve; begin CalcNimValues; K := 0; for I := 1 to N do if S[I] then K := K xor Nim[I]; if K <> 0 then Writeln('The first player has a winning strategy.') else Writeln('The second player has a winning strategy.'); Play; Writeln('I won!'); end; begin ReadInput; Solve; end.
unit AutoCtl; { This program demonstrates Delphi's automation control abilities by inserting a query into a document, using Microsoft Word as an automation server } interface uses Windows, Classes, SysUtils, Graphics, Forms, Controls, DB, DBGrids, DBTables, Grids, StdCtrls, ExtCtrls, ComCtrls, Dialogs; type TForm1 = class(TForm) Query1: TQuery; Panel1: TPanel; InsertBtn: TButton; Query1Company: TStringField; Query1OrderNo: TFloatField; Query1SaleDate: TDateTimeField; Edit1: TEdit; Label1: TLabel; procedure InsertBtnClick(Sender: TObject); end; var Form1: TForm1; implementation uses ComObj; {$R *.dfm} procedure TForm1.InsertBtnClick(Sender: TObject); var S, Lang: string; MSWord: Variant; L: Integer; begin try MsWord := CreateOleObject('Word.Basic'); except ShowMessage('Could not start Microsoft Word.'); Exit; end; try { Return Application Info. This call is the same for English and French Microsoft Word. } Lang := MsWord.AppInfo(Integer(16)); except try { for German Microsoft Word the procedure name is translated } Lang := MsWord.AnwInfo(Integer(16)); except { if this procedure does not exist there is a different translation of Microsoft Word } ShowMessage('Microsoft Word version is not German, French or English.'); Exit; end; end; with Query1 do begin Form1.Caption := Lang; Close; Params[0].Text := Edit1.Text; Open; try First; L := 0; while not EOF do begin S := S + Query1Company.AsString + ListSeparator + Query1OrderNo.AsString + ListSeparator + Query1SaleDate.AsString + #13; Inc(L); Next; end; if (Lang = 'English (US)') or (Lang = 'English (United States)') or (Lang = 'English (UK)') or (Lang = 'German (Standard)') or (Lang = 'French (Standard') then begin MsWord.AppShow; MSWord.FileNew; MSWord.Insert(S); MSWord.LineUp(L, 1); MSWord.TextToTable(ConvertFrom := 2, NumColumns := 3); end; if Lang = 'Français' then begin MsWord.FenAppAfficher; MsWord.FichierNouveau; MSWord.Insertion(S); MSWord.LigneVersHaut(L, 1); MSWord.TexteEnTableau(ConvertirDe := 2, NbColonnesTableau := 3); end; if (Lang = 'German (De)') or (Lang = 'Deutsch') then begin MsWord.AnwAnzeigen; MSWord.DateiNeu; MSWord.Einfügen(S); MSWord.ZeileOben(L, 1); MSWord.TextInTabelle(UmWandelnVon := 2, AnzSpalten := 3); end; finally Close; end; end; end; end.
unit Form; interface uses {$IFDEF VER150} // Delphi 7 declaration Windows, SysUtils, Controls, Forms, Dialogs, StdCtrls, Classes; {$ELSE} Winapi.Windows, System.SysUtils, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Classes, StdCtrls, Controls, Classes; {$ENDIF} type TFormOTP = class(TForm) EdtKey: TEdit; Label1: TLabel; CBTOPT: TCheckBox; Label2: TLabel; EdtHOTP: TEdit; BtnCalculate: TButton; Label3: TLabel; EdtResult: TEdit; procedure BtnCalculateClick(Sender: TObject); procedure CBTOPTClick(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var FormOTP: TFormOTP; implementation {$R *.dfm} uses GoogleOTP; procedure TFormOTP.BtnCalculateClick(Sender: TObject); var Secret: String; n: Integer; begin Secret := EdtKey.Text; if (CBTOPT.Checked) then begin // This is the default in case the parameter is missing! n := -1; end else begin if (not TryStrToInt(EdtHOTP.Text, n)) then begin MessageBox(Handle, 'Please enter a valid number into the counter', 'One Time Password Example', MB_ICONEXCLAMATION); Exit; end; end; EdtResult.Text := Format('%.6d', [CalculateOTP(Secret, n)]); end; procedure TFormOTP.CBTOPTClick(Sender: TObject); begin Label2.Enabled := not CBTOPT.Checked; EdtHOTP.Enabled := not CBTOPT.Checked; end; end.
unit BaseComponentsGroupUnit2; interface uses QueryGroupUnit2, NotifyEvents, System.Classes, System.Generics.Collections, ProducersQuery, BaseComponentsQuery, BaseFamilyQuery, DocFieldInfo, ComponentsCountQuery, EmptyFamilyCountQuery; type TBaseComponentsGroup2 = class(TQueryGroup2) private FAfterApplyUpdates: TNotifyEventsEx; FFullDeleted: TList<Integer>; FNeedUpdateCount: Boolean; FProducers: TQueryProducers; FQueryComponentsCount: TQueryComponentsCount; FQueryEmptyFamilyCount: TQueryEmptyFamilyCount; procedure AfterComponentPostOrDelete(Sender: TObject); function GetProducers: TQueryProducers; function GetqBaseComponents: TQueryBaseComponents; function GetqBaseFamily: TQueryBaseFamily; function GetQueryComponentsCount: TQueryComponentsCount; function GetQueryEmptyFamilyCount: TQueryEmptyFamilyCount; function GetTotalCount: Integer; protected property QueryComponentsCount: TQueryComponentsCount read GetQueryComponentsCount; property QueryEmptyFamilyCount: TQueryEmptyFamilyCount read GetQueryEmptyFamilyCount; public destructor Destroy; override; procedure Commit; override; procedure LoadDocFile(const AFileName: String; ADocFieldInfo: TDocFieldInfo); procedure Rollback; override; constructor Create(AOwner: TComponent); override; procedure AfterConstruction; override; property AfterApplyUpdates: TNotifyEventsEx read FAfterApplyUpdates; property FullDeleted: TList<Integer> read FFullDeleted; property Producers: TQueryProducers read GetProducers; property qBaseComponents: TQueryBaseComponents read GetqBaseComponents; property qBaseFamily: TQueryBaseFamily read GetqBaseFamily; property TotalCount: Integer read GetTotalCount; end; implementation uses System.SysUtils, BaseEventsQuery, StrHelper; constructor TBaseComponentsGroup2.Create(AOwner: TComponent); begin inherited; FFullDeleted := TList<Integer>.Create; // Создаём событие FAfterApplyUpdates := TNotifyEventsEx.Create(Self); end; destructor TBaseComponentsGroup2.Destroy; begin FreeAndNil(FAfterApplyUpdates); FreeAndNil(FFullDeleted); inherited; end; procedure TBaseComponentsGroup2.AfterComponentPostOrDelete(Sender: TObject); var S: string; begin S := Sender.ClassName; FNeedUpdateCount := True; end; procedure TBaseComponentsGroup2.AfterConstruction; begin TNotifyEventWrap.Create(qBaseFamily.W.AfterPostM, AfterComponentPostOrDelete, EventList); TNotifyEventWrap.Create(qBaseFamily.W.AfterDelete, AfterComponentPostOrDelete, EventList); TNotifyEventWrap.Create(qBaseComponents.W.AfterPostM, AfterComponentPostOrDelete, EventList); TNotifyEventWrap.Create(qBaseComponents.W.AfterDelete, AfterComponentPostOrDelete, EventList); end; procedure TBaseComponentsGroup2.Commit; begin inherited; FFullDeleted.Clear; FNeedUpdateCount := True; end; function TBaseComponentsGroup2.GetProducers: TQueryProducers; begin if FProducers = nil then begin FProducers := TQueryProducers.Create(Self); FProducers.FDQuery.Open; end; Result := FProducers; end; function TBaseComponentsGroup2.GetqBaseComponents: TQueryBaseComponents; var Q: TQueryBaseEvents; begin Assert(QList.Count > 0); Result := nil; for Q in QList do begin if Q is TQueryBaseComponents then begin Result := Q as TQueryBaseComponents; Exit; end; end; Assert(Result <> nil); end; function TBaseComponentsGroup2.GetqBaseFamily: TQueryBaseFamily; var Q: TQueryBaseEvents; begin Assert(QList.Count > 0); Result := nil; for Q in QList do begin if Q is TQueryBaseFamily then begin Result := Q as TQueryBaseFamily; Exit; end; end; Assert(Result <> nil); end; function TBaseComponentsGroup2.GetQueryComponentsCount: TQueryComponentsCount; begin if FQueryComponentsCount = nil then begin FQueryComponentsCount := TQueryComponentsCount.Create(Self); // FQueryComponentsCount.FDQuery.Connection := qBaseFamily.FDQuery.Connection; end; Result := FQueryComponentsCount; end; function TBaseComponentsGroup2.GetQueryEmptyFamilyCount: TQueryEmptyFamilyCount; begin if FQueryEmptyFamilyCount = nil then begin FQueryEmptyFamilyCount := TQueryEmptyFamilyCount.Create(Self); // FQueryEmptyFamilyCount.FDQuery.Connection := qBaseFamily.FDQuery.Connection; end; Result := FQueryEmptyFamilyCount; end; function TBaseComponentsGroup2.GetTotalCount: Integer; var x: Integer; begin if FNeedUpdateCount or not QueryEmptyFamilyCount.FDQuery.Active then begin // Обновляем кол-во компонентов без семей QueryEmptyFamilyCount.FDQuery.Close; QueryEmptyFamilyCount.FDQuery.Open; // Обновляем кол-во дочерних компонентов QueryComponentsCount.FDQuery.Close; QueryComponentsCount.FDQuery.Open; FNeedUpdateCount := false; end; x := QueryEmptyFamilyCount.Count + QueryComponentsCount.Count; Result := x; end; procedure TBaseComponentsGroup2.LoadDocFile(const AFileName: String; ADocFieldInfo: TDocFieldInfo); var IsEdited: Boolean; S: string; begin if not AFileName.IsEmpty then begin // В БД храним путь до файла относительно папки с документацией S := GetRelativeFileName(AFileName, ADocFieldInfo.Folder); IsEdited := not qBaseFamily.W.TryEdit; qBaseFamily.FDQuery.FieldByName(ADocFieldInfo.FieldName).AsString := S; // Сохраняем только если запись уже была сохранена до редактирования if not IsEdited then qBaseFamily.W.TryPost; end; end; procedure TBaseComponentsGroup2.Rollback; begin inherited; FFullDeleted.Clear; end; end.
unit uIntXLibTypes; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF FPC} fgl, {$ENDIF FPC} SysUtils; type TFormatSettings = SysUtils.TFormatSettings; EOverflowException = EOverflow; EArgumentNilException = class(Exception); EFhtMultiplicationException = class(Exception); EFormatException = class(Exception); EArithmeticException = SysUtils.EMathError; EArgumentException = SysUtils.EArgumentException; EArgumentOutOfRangeException = SysUtils.EArgumentOutOfRangeException; EDivByZero = SysUtils.EDivByZero; {$IFDEF FPC} TDictionary<TKey, TValue> = class(TFPGMap<TKey, TValue>); {$ENDIF FPC} {$IFDEF DELPHIXE_UP} /// <summary> /// Represents a dynamic array of UInt32. /// </summary> TIntXLibUInt32Array = TArray<UInt32>; /// <summary> /// Represents a dynamic array of Double. /// </summary> TIntXLibDoubleArray = TArray<Double>; /// <summary> /// Represents a dynamic array of char. /// </summary> TIntXLibCharArray = TArray<Char>; {$ELSE} /// <summary> /// Represents a dynamic array of UInt32. /// </summary> TIntXLibUInt32Array = array of UInt32; /// <summary> /// Represents a dynamic array of Double. /// </summary> TIntXLibDoubleArray = array of Double; /// <summary> /// Represents a dynamic array of char. /// </summary> TIntXLibCharArray = array of Char; {$ENDIF DELPHIXE_UP} implementation end.
unit FC.StockChart.UnitTask.Calendar.BarListDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FC.Dialogs.DockedDialogCloseAndAppWindow_B, JvDockControlForm, ImgList, JvComponentBase, JvCaptionButton, StdCtrls, ExtendControls, ExtCtrls,StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, DB,FC.StockData.InputDataCollectionToDataSetMediator, FC.StockChart.CustomDialog_B, MemoryDS; type TfmCalendarBarListDialog = class(TfmStockChartCustomDialog_B) dsData: TDataSource; grData: TEditDBGrid; taData: TMemoryDataSet; taDataDate: TDateTimeField; taDataCountry: TStringField; taDataClass: TIntegerField; taDataIndicator: TStringField; taDataPeriod: TStringField; taDataPriority: TStringField; taDataPrevious: TStringField; taDataForecast: TStringField; taDataFact: TStringField; taDataPFTrend: TStringField; taDataFFTrend: TStringField; private FIndicator : ISCIndicatorCalendar; protected public constructor Create(const aExpert: ISCIndicatorCalendar; const aStockChart: IStockChart; aTime: TDateTime); reintroduce; class procedure Run(const aExpert: ISCIndicatorCalendar; const aStockChart: IStockChart; aTime: TDateTime); end; implementation uses ufmDialog_B,DateUtils, Application.Definitions; {$R *.dfm} { TfmCalendarBarListDialog } constructor TfmCalendarBarListDialog.Create(const aExpert: ISCIndicatorCalendar; const aStockChart: IStockChart; aTime: TDateTime); var aFrom,aTo: TDateTime; i: integer; aItem: ISCCalendarItem; begin inherited Create(aStockChart); FIndicator:=aExpert; aFrom:=aTime; aTo:=aFrom+aStockChart.StockSymbol.GetTimeIntervalValue/1440; Caption:=IndicatorFactory.GetIndicatorInfo(FIndicator.GetIID).Name+': '+'Events from '+DateTimeToStr(aFrom)+' to '+DateTimeToStr(aTo); i:=FIndicator.GetData.FindFirstItemGE(aFrom); taData.Open; taData.EmptyTable; while i<>-1 do begin aItem:=FIndicator.GetData.GetItem(i); taData.Append; taDataDate.Value:=aItem.GetDateTime; taDataCountry.Value:=aItem.GetCountry; taDataClass.Value:=aItem.GetClass; taDataIndicator.Value:=aItem.GetIndicator; taDataPeriod.Value:=aItem.GetPeriod; taDataPriority.Value:=aItem.GetPeriod; taDataPrevious.Value:=aItem.GetPreviousValue; taDataForecast.Value:=aItem.GetForecastValue; taDataFact.Value:=aItem.GetFactValue; taDataPFTrend.Value:=CalendarChangeTypeNames[aItem.GetPFChangeType]; taDataFFTrend.Value:=CalendarChangeTypeNames[aItem.GetFFChangeType]; taData.Post; if i=FIndicator.GetData.Count-1 then break; inc(i); if (aItem.GetDateTime>=aTo) then break; end; end; class procedure TfmCalendarBarListDialog.Run(const aExpert: ISCIndicatorCalendar; const aStockChart: IStockChart; aTime: TDateTime); begin with TfmCalendarBarListDialog.Create(aExpert,aStockChart,aTime) do Show; end; end.
namespace RemObjects.Elements.Linq; interface uses Foundation; [assembly: NamespaceAlias('Linq', ['RemObjects.Elements.Linq'])] type PredicateBlock = public block(aItem: not nullable id): Boolean; IDBlock = public block(aItem: not nullable id): id; ForSelector<T> = public delegate(aIndex: Integer): T; IGrouping<K,T> = public interface(RemObjects.Elements.System.INSFastEnumeration<T>) property Key: K read; end; // Standard Linq Operators extension method Foundation.INSFastEnumeration.Where(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Any(): Boolean; public; extension method Foundation.INSFastEnumeration.Any(aBlock: not nullable PredicateBlock): Boolean; public; extension method Foundation.INSFastEnumeration.Take(aCount: NSInteger): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Skip(aCount: NSInteger): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.TakeWhile(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.SkipWhile(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.OrderBy(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.OrderByDescending(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.GroupBy(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Select(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.OfType<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; iterator; public; extension method Foundation.INSFastEnumeration.Cast<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; iterator; public; extension method Foundation.INSFastEnumeration.Concat(aSecond: not nullable Foundation.INSFastEnumeration): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Reverse: not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Distinct(aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Intersect(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Except(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; iterator; public; extension method Foundation.INSFastEnumeration.Contains(aItem: id): Boolean; public; extension method Foundation.INSFastEnumeration.First: nullable id; public; extension method Foundation.INSFastEnumeration.First(aBlock: not nullable PredicateBlock): nullable id; public; extension method Foundation.INSFastEnumeration.FirstOrDefault: nullable id; public; extension method Foundation.INSFastEnumeration.FirstOrDefault(aBlock: not nullable PredicateBlock): nullable id; public; extension method Foundation.INSFastEnumeration.Last: nullable id; public; extension method Foundation.INSFastEnumeration.Last(aBlock: not nullable PredicateBlock): nullable id; public; extension method Foundation.INSFastEnumeration.LastOrDefault: nullable id; public; extension method Foundation.INSFastEnumeration.LastOrDefault(aBlock: not nullable PredicateBlock): nullable id; public; extension method Foundation.INSFastEnumeration.Count: NSInteger; public; extension method Foundation.INSFastEnumeration.Max: id; public; extension method Foundation.INSFastEnumeration.Max(aBlock: not nullable IDBlock): id; public; extension method Foundation.INSFastEnumeration.Min: id; public; extension method Foundation.INSFastEnumeration.Min(aBlock: not nullable IDBlock): id; public; // Generic: extension method RemObjects.Elements.System.INSFastEnumeration<T>.Where(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Any(): Boolean; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Any(aBlock: not nullable block(aItem: not nullable T): Boolean): Boolean; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Take(aCount: NSInteger): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Skip(aCount: NSInteger): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.TakeWhile(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.SkipWhile(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OrderBy(aBlock: not nullable block(aItem: not nullable T): id): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OrderByDescending(aBlock: not nullable block(aItem: not nullable T): id): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.GroupBy<T,K>(aBlock: not nullable block(aItem: not nullable T): K): not nullable RemObjects.Elements.System.INSFastEnumeration<IGrouping<K,T>>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Select<T, R>(aBlock: not nullable block(aItem: not nullable T): R): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OfType<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Cast<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Concat(aSecond: not nullable RemObjects.Elements.System.INSFastEnumeration<T>): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Reverse: not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Distinct(aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Intersect(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Except(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Contains(aItem: T): Boolean; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.First: {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.First(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.FirstOrDefault: {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.FirstOrDefault(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Last: {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Last(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.LastOrDefault: {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.LastOrDefault(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Count: NSInteger; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Max: T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Max<T,R>(aBlock: not nullable block(aItem: not nullable T): R): R; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Min: T; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Min<T,R>(aBlock: not nullable block(aItem: not nullable T): R): R; inline; public; // Join // GroupJoin // ThenBy // GroupBy // Union // Useful helper methods extension method Foundation.INSFastEnumeration.array: not nullable NSArray; public; extension method Foundation.INSFastEnumeration.ToNSArray: not nullable NSArray; public; extension method Foundation.INSFastEnumeration.dictionary(aKeyBlock: IDBlock; aValueBlock: IDBlock): not nullable NSDictionary; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.array: not nullable NSArray<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.ToNSArray: not nullable NSArray<T>; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.dictionary(aKeyBlock: block(aItem: id): id; aValueBlock: block(aItem: id): id): not nullable NSDictionary; inline; public; extension method RemObjects.Elements.System.INSFastEnumeration<T>.dictionary<T,K,V>(aKeyBlock: block(aItem: T): K; aValueBlock: block(aItem: T): V): not nullable NSDictionary<K, V>; inline; public; // Internal Helpers extension method Foundation.INSFastEnumeration.orderBy(aBlock: not nullable block(aItem: id): id) comparator(aComparator: NSComparator): not nullable Foundation.INSFastEnumeration; public; //extension method NSArray.orderBy(aBlock: not nullable block(aItem: id): Int32; aComparator: NSComparator): not nullable Foundation.INSFastEnumeration; //iterator; public; type // // // CAUTION: Magic type name. // The compiler will use __Toffee_Linq_Helpers() to assist with LINQ support // // __Toffee_Linq_Helpers = public static class private class method IntForHelper(aStart, aEnd, aStep: Integer; aBackward: Boolean; aMethod: ForSelector<id>): not nullable INSFastEnumeration; iterator; public class method ForHelper<T>(aStart, aEnd, aStep: Integer; aBackward: Boolean; aMethod: ForSelector<T>): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; end; implementation {$GLOBALS ON} const LOOP_SIZE = 16; {$GLOBALS OFF} // // Where // extension method Foundation.INSFastEnumeration.Where(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; begin for each i in self do if aBlock(i) then yield i; end; extension method Foundation.INSFastEnumeration.Any(aBlock: not nullable PredicateBlock): Boolean; begin for each i in self do if aBlock(i) then exit true; end; extension method Foundation.INSFastEnumeration.Take(aCount: NSInteger): not nullable Foundation.INSFastEnumeration; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObjects: array[0..LOOP_SIZE-1] of id; var lCount := 0; while lCount < aCount do begin var lNext := if aCount-lCount < 16 then aCount-lCount else LOOP_SIZE; //MIN(aCount-lCount, 16); var lGot := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(lObjects) count(lNext); //cast is workaround, remove; if lGot = 0 then break; if lGot > lNext then lGot := lNext; for i: NSInteger := 0 to lGot-1 do yield lState.itemsPtr[i]; lCount := lCount+lGot; end; end; extension method Foundation.INSFastEnumeration.Skip(aCount: NSInteger): not nullable Foundation.INSFastEnumeration; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObjects: array[0..LOOP_SIZE-1] of id; var lCount := 0; loop begin var lNext := LOOP_SIZE; var lGot := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(lObjects) count(lNext); //cast is workaround, remove; if lGot = 0 then break; for i: NSInteger := 0 to lGot-1 do begin if lCount < aCount then inc(lCount) else yield lState.itemsPtr[i]; end; end; end; extension method Foundation.INSFastEnumeration.TakeWhile(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObjects: array[0..LOOP_SIZE] of id; loop begin var lGot := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(lObjects) count(LOOP_SIZE); //cast is workaround, remove; if lGot = 0 then break; for i: NSInteger := 0 to lGot-1 do begin if not aBlock(lState.itemsPtr[i]) then exit; yield lState.itemsPtr[i]; end; end; end; // Segmentation fault: 11: 65577: Toffee: Passing "array of id" to ^id parameter extension method Foundation.INSFastEnumeration.SkipWhile(aBlock: not nullable PredicateBlock): not nullable Foundation.INSFastEnumeration; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObjects: array[0..LOOP_SIZE-1] of id; var lFound := false; loop begin var lGot := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(lObjects) count(LOOP_SIZE); //cast is workaround, remove; if lGot = 0 then break; for i: NSInteger := 0 to lGot-1 do begin if not lFound then if not aBlock(lState.itemsPtr[i]) then lFound := true; if lFound then yield lState.itemsPtr[i]; end; end; end; // // Order by // extension method Foundation.INSFastEnumeration.orderBy(aBlock: not nullable block(aItem: id): id) comparator(aComparator: NSComparator): not nullable Foundation.INSFastEnumeration; begin result := self.ToNSArray().sortedArrayUsingComparator(aComparator) as not nullable; end; extension method Foundation.INSFastEnumeration.OrderBy(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; begin var lOrdered := orderBy(aBlock) comparator( (a,b) -> begin var va := aBlock(a); var vb := aBlock(b); if va = nil then if vb = nil then exit NSComparisonResult.OrderedSame else exit NSComparisonResult.OrderedAscending; if vb = nil then exit NSComparisonResult.OrderedDescending; exit va.compare(vb) end); for each i in lOrdered do yield i; end; extension method Foundation.INSFastEnumeration.OrderByDescending(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; begin var lOrdered := orderBy(aBlock) comparator( (a,b) -> begin var va := aBlock(a); var vb := aBlock(b); if va = nil then if vb = nil then exit NSComparisonResult.OrderedSame else exit NSComparisonResult.OrderedDescending; if vb = nil then exit NSComparisonResult.OrderedAscending; exit vb.compare(va) end); for each i in lOrdered do yield i; end; type Grouping<K,T> = class(IGrouping<K,T>) private var fArray := new NSMutableArray; implements public RemObjects.Elements.System.INSFastEnumeration<T>; unit method addObject(aValue: T); begin fArray.addObject(aValue); end; public property Key: K read unit write; end; extension method Foundation.INSFastEnumeration.GroupBy(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; begin var lDictionary := new NSMutableDictionary; for each i in self do begin var lKey := aBlock(i); var lGrouping: Grouping<id,id> := lDictionary[lKey]; if not assigned(lGrouping) then begin lGrouping := new Grouping<id,id>(); lGrouping.Key := lKey; lDictionary[lKey] := lGrouping; end; lGrouping.addObject(i); end; for each g in lDictionary.allValues do yield g; end; // // Select // extension method Foundation.INSFastEnumeration.Select(aBlock: not nullable IDBlock): not nullable Foundation.INSFastEnumeration; begin for each i in self do yield aBlock(i); end; extension method Foundation.INSFastEnumeration.OfType<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; begin for each i in self do begin var i2 := R(i); if assigned(i2) then yield i2; end; end; extension method Foundation.INSFastEnumeration.Cast<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; begin for each i in self do yield i as R; end; // // // extension method Foundation.INSFastEnumeration.Concat(aSecond: not nullable Foundation.INSFastEnumeration): not nullable Foundation.INSFastEnumeration; begin for each i in self do yield i; if assigned(aSecond) then for each i in aSecond do yield i; end; extension method Foundation.INSFastEnumeration.Reverse: not nullable Foundation.INSFastEnumeration; begin var lArray := self.ToNSArray(); for i: NSInteger := lArray.count-1 downto 0 do yield lArray[i]; end; // // Set Operators // extension method Foundation.INSFastEnumeration.Distinct(aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; begin var lReturned := new NSMutableArray; for each i in self do if not lReturned.containsObject(i) then begin lReturned.addObject(i); yield i; end; end; extension method Foundation.INSFastEnumeration.Intersect(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; begin var lSecond := aSecond.ToNSArray(); for each i in self do if lSecond.containsObject(i) then yield i; end; extension method Foundation.INSFastEnumeration.Except(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable Foundation.INSFastEnumeration; begin var lFirst := self.Distinct().ToNSArray(); var lSecond := aSecond.Distinct().ToNSArray(); for each i in lFirst do if not lSecond.containsObject(i) then yield i; for each i in lSecond do if not lFirst.containsObject(i) then yield i; end; // // Helpers // [Obsolete("Use ToNSArray() instead")] extension method Foundation.INSFastEnumeration.array(): not nullable NSArray; begin result := self.ToNSArray(); end; extension method Foundation.INSFastEnumeration.ToNSArray(): not nullable NSArray; begin if (self is NSArray) then exit self as NSArray; result := new NSMutableArray; for each i in self do NSMutableArray(result).addObject(i); end; extension method Foundation.INSFastEnumeration.dictionary(aKeyBlock: IDBlock; aValueBlock: IDBlock): not nullable NSDictionary; begin var lArray := self.ToNSArray(); result := new NSMutableDictionary withCapacity(lArray.count); for each i in lArray do NSMutableDictionary(result)[aKeyBlock(i)] := aValueBlock(i); end; extension method Foundation.INSFastEnumeration.Contains(aItem: id): Boolean; begin if self is NSArray then exit (self as NSArray).containsObject(aItem); for each i in self do begin if (i = nil) then begin if (aItem = nil) then exit true; end else begin if i.isEqual(aItem) then exit true; end; end; end; extension method Foundation.INSFastEnumeration.First(): nullable id; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObject: id; if Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(var lObject) count(1) ≥ 1 then //cast is workaround, remove; result := lState.itemsPtr[0] else raise new Exception("Sequence is empty."); end; extension method Foundation.INSFastEnumeration.First(aBlock: not nullable PredicateBlock): nullable id; begin for each i in self do if aBlock(i) then exit i; raise new Exception("Sequence is empty."); end; extension method Foundation.INSFastEnumeration.FirstOrDefault(): nullable id; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObject: id; if Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(var lObject) count(1) ≥ 1 then //cast is workaround, remove; result := lState.itemsPtr[0]; end; extension method Foundation.INSFastEnumeration.FirstOrDefault(aBlock: not nullable PredicateBlock): nullable id; begin for each i in self do if aBlock(i) then exit i; end; extension method Foundation.INSFastEnumeration.Last(): nullable id; begin if self is NSArray then begin result := (self as NSArray).lastObject; end else begin for each i in self do result := i; end; if not assigned(result) then raise new Exception("Sequence is empty."); end; extension method Foundation.INSFastEnumeration.Last(aBlock: not nullable PredicateBlock): nullable id; begin for each i in self do if aBlock(i) then result := i; if not assigned(result) then raise new Exception("Sequence is empty."); end; extension method Foundation.INSFastEnumeration.LastOrDefault(): nullable id; begin if self is NSArray then begin result := (self as NSArray).lastObject; end else begin for each i in self do result := i; end; end; extension method Foundation.INSFastEnumeration.LastOrDefault(aBlock: not nullable PredicateBlock): nullable id; begin for each i in self do if aBlock(i) then result := i; end; extension method Foundation.INSFastEnumeration.Any(): Boolean; begin var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObject: id; result := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(var lState) objects(var lObject) count(1) ≥ 1; //cast is workaround, remove; end; extension method Foundation.INSFastEnumeration.Count: NSInteger; begin if self is NSArray then exit (self as NSArray).count; if self.respondsToSelector(selector(count)) then exit (self as id).count; var lState: NSFastEnumerationState := default(NSFastEnumerationState); var lObjects: array[0..LOOP_SIZE-1] of id; result := 0; loop begin var lGot := Foundation.INSFastEnumeration(self).countByEnumeratingWithState(@lState) objects(lObjects) count(LOOP_SIZE); //cast is workaround, remove; if lGot = 0 then break; result := result+lGot; end; end; extension method Foundation.INSFastEnumeration.Max: id; begin for each i in self do if not assigned(result) or (result.compare(i) = NSComparisonResult.OrderedAscending) then result := i; end; extension method Foundation.INSFastEnumeration.Max(aBlock: not nullable IDBlock): id; begin for each i in self do begin var i2 := aBlock(i); if not assigned(result) or (result.compare(i2) = NSComparisonResult.OrderedAscending) then result := i2; end; end; extension method Foundation.INSFastEnumeration.Min: id; begin for each i in self do if not assigned(result) or (result.compare(i) = NSComparisonResult.OrderedDescending) then result := i; end; extension method Foundation.INSFastEnumeration.Min(aBlock: not nullable IDBlock): id; begin for each i in self do begin var i2 := aBlock(i); if not assigned(result) or (result.compare(i2) = NSComparisonResult.OrderedDescending) then result := i2; end; end; // // Generic versions // extension method RemObjects.Elements.System.INSFastEnumeration<T>.Where(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Where(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Any(aBlock: not nullable block(aItem: not nullable T): Boolean): Boolean; begin exit Foundation.INSFastEnumeration(self).Any(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Take(aCount: NSInteger): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Take(aCount); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Skip(aCount: NSInteger): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Skip(aCount); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.TakeWhile(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).TakeWhile(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.SkipWhile(aBlock: not nullable block(aItem: not nullable T): Boolean): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).SkipWhile(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OrderBy(aBlock: not nullable block(aItem: not nullable T): id): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).OrderBy(IDBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OrderByDescending(aBlock: not nullable block(aItem: not nullable T): id): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).OrderByDescending(IDBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.GroupBy<T,K>(aBlock: not nullable block(aItem: not nullable T): K): not nullable RemObjects.Elements.System.INSFastEnumeration<IGrouping<K,T>>; begin exit Foundation.INSFastEnumeration(self).GroupBy(IDBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Select<T, R>(aBlock: not nullable block(aItem: not nullable T): R): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; begin exit Foundation.INSFastEnumeration(self).Select(IDBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.OfType<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; begin exit Foundation.INSFastEnumeration(self).OfType<R>(); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Cast<R>(): not nullable RemObjects.Elements.System.INSFastEnumeration<R>; begin exit Foundation.INSFastEnumeration(self).Cast<R>(); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Concat(aSecond: not nullable RemObjects.Elements.System.INSFastEnumeration<T>): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Concat(Foundation.INSFastEnumeration(aSecond)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Reverse: not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Reverse; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Distinct(aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Distinct(aComparator); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Intersect(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Intersect(aSecond, aComparator); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Except(aSecond: not nullable Foundation.INSFastEnumeration; aComparator: NSComparator := nil): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit Foundation.INSFastEnumeration(self).Except(aSecond, aComparator); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Contains(aItem: T): Boolean; begin exit Foundation.INSFastEnumeration(self).Contains(aItem); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.First: {nullable} T; begin exit Foundation.INSFastEnumeration(self).First; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.First(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; begin exit Foundation.INSFastEnumeration(self).First(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.FirstOrDefault: {nullable} T; begin exit Foundation.INSFastEnumeration(self).FirstOrDefault; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.FirstOrDefault(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; begin exit Foundation.INSFastEnumeration(self).FirstOrDefault(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Last: {nullable} T; begin exit Foundation.INSFastEnumeration(self).Last; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Last(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; begin exit Foundation.INSFastEnumeration(self).Last(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.LastOrDefault: {nullable} T; begin exit Foundation.INSFastEnumeration(self).LastOrDefault; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.LastOrDefault(aBlock: not nullable block(aItem: not nullable T): Boolean): {nullable} T; begin exit Foundation.INSFastEnumeration(self).LastOrDefault(PredicateBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Any(): Boolean; begin exit Foundation.INSFastEnumeration(self).Any; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Count: NSInteger; begin exit Foundation.INSFastEnumeration(self).Count; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Max: T; begin result := Foundation.INSFastEnumeration(self).Max; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Max<T,R>(aBlock: not nullable block(aItem: not nullable T): R): R; begin result := Foundation.INSFastEnumeration(self).Max(IDBlock(aBlock)); end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Min: T; begin result := Foundation.INSFastEnumeration(self).Min; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.Min<T,R>(aBlock: not nullable block(aItem: not nullable T): R): R; begin result := Foundation.INSFastEnumeration(self).Min(IDBlock(aBlock)); end; [Obsolete("Use ToNSArray() instead")] extension method RemObjects.Elements.System.INSFastEnumeration<T>.array: not nullable NSArray<T>; begin exit Foundation.INSFastEnumeration(self).ToNSArray() as NSArray<T>; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.ToNSArray: not nullable NSArray<T>; begin exit Foundation.INSFastEnumeration(self).ToNSArray() as NSArray<T>; end; extension method RemObjects.Elements.System.INSFastEnumeration<T>.dictionary(aKeyBlock: block(aItem: id): id; aValueBlock: block(aItem: id): id): not nullable NSDictionary; begin exit Foundation.INSFastEnumeration(self).dictionary(IDBlock(aKeyBlock), IDBlock(aValueBlock)); end; //76496: Toffee: internal error and cant match complex generic extension method extension method RemObjects.Elements.System.INSFastEnumeration<T>.dictionary<T,K,V>(aKeyBlock: block(aItem: T): K; aValueBlock: block(aItem: T): V): not nullable NSDictionary<K, V>; begin exit Foundation.INSFastEnumeration(self).dictionary(IDBlock(aKeyBlock), IDBlock(aValueBlock)); end; class method __Toffee_Linq_Helpers.ForHelper<T>(aStart: Integer; aEnd: Integer; aStep: Integer; aBackward: Boolean; aMethod: ForSelector<T>): not nullable RemObjects.Elements.System.INSFastEnumeration<T>; begin exit IntForHelper(aStart, aEnd, aStep, aBackward, aMethod); end; class method __Toffee_Linq_Helpers.IntForHelper(aStart: Integer; aEnd: Integer; aStep: Integer; aBackward: Boolean; aMethod: ForSelector<id>): not nullable INSFastEnumeration; begin if aBackward then for i: Integer := aStart downto aEnd step aStep do yield aMethod(i) else for i: Integer := aStart to aEnd step aStep do yield aMethod(i) end; end.
unit Word; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections; type TTypeCase = (TNormal, TLeftCommun, TRightCommun, TTopCommun, TBottomCommun, TBottomTopCommun, TRightLeftCommun, TCommun, TEnd); TSens = (TVertical, THorizontal); TCase = record P: TPoint; TC: TTypeCase; end; TLetterPosition = array of TCase; TWord = class private Fstr: String; Fpos: TLetterPosition; Fsens: TSens; Fdef: string; Fnum: Integer; public function PosToString: string; published property str: String read Fstr write Fstr; property pos: TLetterPosition read Fpos write Fpos; property sens: TSens read Fsens write Fsens; property def: string read Fdef write Fdef; property num: Integer read Fnum write Fnum; end; function inList(s: TPoint; P: Tlist<TPoint>): boolean; procedure RandSort(var tlp: TLetterPosition); implementation function TWord.PosToString: string; var i: Integer; begin Result := ''; for i := 0 to Length(pos) - 2 do begin Result := Result + '(' + IntToStr(pos[i].P.X) + ', ' + IntToStr(pos[i].P.Y) + '), '; end; i := Length(pos) - 1; if i <> -1 then Result := Result + '(' + IntToStr(pos[i].P.X) + ', ' + IntToStr(pos[i].P.Y) + ')'; end; procedure RandSort(var tlp: TLetterPosition); var i, j: Integer; temp: TCase; begin for i := Length(tlp) - 1 downto 1 do begin temp := tlp[i]; j := Random(i + 1); tlp[i] := tlp[j]; tlp[j] := temp; end; end; function inList(s: TPoint; P: Tlist<TPoint>): boolean; var i: Integer; begin Result := false; for i := 0 to P.Count - 1 do begin if s = P[i] then begin Result := true; exit; end; end; end; end.
unit DecisionBox; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, RzButton, Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel; type TfrmDecisionBox = class(TfrmBasePopup) Image1: TImage; pnlNo: TRzPanel; btnNo: TRzShapeButton; pnlYes: TRzPanel; btnYes: TRzShapeButton; lblMessage: TLabel; procedure btnNoClick(Sender: TObject); procedure btnYesClick(Sender: TObject); private { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; const confMessage: string); reintroduce; overload; end; implementation {$R *.dfm} constructor TfrmDecisionBox.Create(AOwner: TComponent); begin inherited; end; procedure TfrmDecisionBox.btnNoClick(Sender: TObject); begin inherited; ModalResult := mrNo; end; procedure TfrmDecisionBox.btnYesClick(Sender: TObject); begin inherited; ModalResult := mrYes; end; constructor TfrmDecisionBox.Create(AOwner: TComponent; const confMessage: string); begin inherited Create(AOwner); lblMessage.Caption := confMessage; end; end.
unit char_symbols; interface implementation var c: char; b: UInt8; procedure Test; begin c := #65; b := UInt8(c); end; initialization Test(); finalization Assert(b = 65); end.
Program Lists_26; Uses myIntegerList; //подключение собственноручно созданного модуля Type lPoint = ^lLists; nonNegativeNumber = 0..Integer.MaxValue;//неотрицательное множесвто целых чисел lLists = record info: ^oList; next: lPoint; end; Var lHead,lTail:lPoint; //глобальные указатели Procedure getList(i:integer);//получение данных об одном списке var y:lPoint; count:nonNegativeNumber; begin new(y); WriteLn('Введите количество чисел в ',i,' - ом списке'); ReadLn(count); y^.info:=myIntegerList.getOList(count);//получение данных для односвязного списка if lHead = nil then begin lHead:=y; lTail:=y; end else begin lTail^.next:=y; lTail:=y; end; end; Procedure getListOfLists();//получение данных о списке списков var i,n:nonNegativeNumber; x:integer; begin WriteLn('Введите количество списков в списке'); ReadLn(n); for i:=1 to n do begin WriteLn('Ввод данных ',i,' - го списка'); getList(i);//получение данных об одном списке end; end; Function isEmpty():boolean;//проверка на пустоту списка begin isEmpty:=lHead = nil; end; Function getLength():integer;//возвращает количество списков var count:integer; metk:lPoint; begin if isEmpty() then count:=0 else begin metk:=lHead; while metk<>nil do begin count+=1; metk:=metk^.next; end; end; getLength:=count; end; Procedure printList();//вывод элементов списка списков var lQ:lPoint; pQ:oPoint; begin lQ:=lHead; while lQ<>nil do begin pQ:=lQ^.info; while pQ<>nil do begin Write(pQ^.info,' '); pQ:=pQ^.next; end; lQ:=lQ^.next; end; WriteLn(); end; Procedure initSort(var metk:lPoint;var last:lPoint);//инициализаөия некоторых переменных для сортировки списка списков begin metk:=lHead; last:=nil; end; Procedure sort();//сортировка списка списков по возрастанию количества элементов в этих списках var last,metk,dop:lPoint; isSorted:boolean; begin isSorted:=false; initSort(metk,last);//инициализаөия некоторых переменных для сортировки списка списков while not isSorted do begin if myIntegerList.getLength(metk^.info)>myIntegerList.getLength(metk^.next^.info) then begin //получение элементов одного односвязного dop:=metk^.next; //списка metk^.next:=metk^.next^.next; dop^.next:=metk; if last<>nil then last^.next:=dop; if lHead = metk then lHead:=dop; if lTail = dop then lTail:=dop^.next; initSort(metk,last);//инициализаөия некоторых переменных для сортировки списка списков end else begin last:=metk; metk:=metk^.next; isSorted:=metk^.next = nil; end; end; end; Procedure getUnion(metkOne,metkTwo:lPoint);//объединение двух упорядоченных односвязных списков begin myIntegerList.getUnion(metkOne^.info,metkTwo^.info);//объединение двух упорядоченных односвязных списков в модуле metkOne^.info:=myIntegerList.getPHead();//получение указателя-начала нового односвязного списка end; Procedure deletePoint(point:lPoint);//удаление указателя var metk,last:lPoint; begin metk:=lHead; last:=nil; while metk<>point do begin last:=metk; metk:=metk^.next; end; last^.next:=metk^.next; dispose(point); if lHead = nil then lHead:=last; if lTail = nil then lTail:=last^.next; end; Procedure getUnionLists();//объединение списков begin while getLength()<>1 do begin //возвращает количество списков sort();//сортировка списка списков по возрастанию количества элементов в этих списках getUnion(lHead,lHead^.next);//объединение двух упорядоченных односвязных списков deletePoint(lHead^.next);//удаление указателя end; end; Procedure printOneList();//вывод нового упорядоченного списка var metk:oPoint; begin metk:=lHead^.info; while metk<>nil do begin Write(metk^.info,' '); metk:=metk^.next; end; end; Begin getListOfLists();//получение данных о списке списков printList(); getUnionLists();//объединение списков printOneList();//вывод нового упорядоченного списка End.
unit AConsolidarCR; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, DBKeyViolation, StdCtrls, Buttons, Localizacao, ComCtrls, Mask, numericos, UnDados, UnContasAReceber; type TFConsolidarCR = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BGravar: TBitBtn; BCancelar: TBitBtn; ValidaGravacao1: TValidaGravacao; Localiza: TConsultaPadrao; ECliente: TEditLocaliza; SpeedButton4: TSpeedButton; Label20: TLabel; Label18: TLabel; EDatVencimento: TCalendario; Label1: TLabel; EPerDesconto: Tnumerico; EValDesconto: Tnumerico; Label2: TLabel; Label3: TLabel; EValTotal: Tnumerico; Label4: TLabel; BitBtn1: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure EPerDescontoChange(Sender: TObject); procedure EValDescontoChange(Sender: TObject); procedure EClienteChange(Sender: TObject); private { Private declarations } VprDContas : TRBDContasConsolidadasCR; VprAcao : Boolean; VprOperacao : Integer; procedure InicializaTela; procedure CarDClasse; procedure CarDTela; public { Public declarations } function ConsolidarContas: Boolean; end; var FConsolidarCR: TFConsolidarCR; implementation uses APrincipal, AContasAConsolidarCR,Constantes, ConstMsg; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFConsolidarCR.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao := false; VprDContas := TRBDContasConsolidadasCR.cria; VprOperacao := 1; end; { ******************* Quando o formulario e fechado ************************** } procedure TFConsolidarCR.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDContas.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} function TFConsolidarCR.ConsolidarContas: Boolean; begin InicializaTela; VprOperacao := 1; Showmodal; end; {******************************************************************************} procedure TFConsolidarCR.BCancelarClick(Sender: TObject); begin VprAcao := False; close; end; {******************************************************************************} procedure TFConsolidarCR.BGravarClick(Sender: TObject); var VpfResultado : String; begin VprAcao := true; CarDClasse; VpfResultado := FunContasAReceber.GravaDContaConsolidada(VprDContas); if Vpfresultado = '' then close else aviso(VpfResultado); end; {******************************************************************************} procedure TFConsolidarCR.InicializaTela; begin EDatVencimento.DateTime := date; end; {******************************************************************************} procedure TFConsolidarCR.CarDClasse; begin VprDContas.CodFilial := varia.CodigoEmpFil; VprDContas.CodCliente := ECliente.AInteiro; VprDContas.DatVencimento := EDatVencimento.DateTime; VprDContas.PerDesconto := EPerDesconto.AValor; VprDContas.ValDesconto := EValDesconto.AValor; VprDContas.ValConsolidacao := EValTotal.AValor; FunContasAReceber.CarNroNotas(VprDContas); end; {******************************************************************************} procedure TFConsolidarCR.CarDTela; begin EDatVencimento.DateTime := VprDContas.DatVencimento; EValTotal.AValor := VprDContas.ValConsolidacao; ECliente.AInteiro := VprDContas.CodCliente; ECliente.Atualiza; EValDesconto.AValor := VprDContas.ValDesconto; EPerDesconto.AValor := VprDContas.PerDesconto; end; {******************************************************************************} procedure TFConsolidarCR.BitBtn1Click(Sender: TObject); begin CarDClasse; FContasAConsolidarCR := TFContasAConsolidarCR.criarSDI(Application,'',FPrincipal.VerificaPermisao('FContasAConsolidarCR')); FContasAConsolidarCR.AdicionarContas(VprDContas); FContasAConsolidarCR.free; CarDTela; end; {******************************************************************************} procedure TFConsolidarCR.EPerDescontoChange(Sender: TObject); begin VprDContas.PerDesconto := EPerDesconto.AValor; VprDContas.ValConsolidacao := FunContasAReceber.RValTotalContas(VprDContas); EValTotal.AValor := VprDContas.ValConsolidacao; end; {******************************************************************************} procedure TFConsolidarCR.EValDescontoChange(Sender: TObject); begin VprDContas.ValDesconto := EValDesconto.AValor; VprDContas.ValConsolidacao := FunContasAReceber.RValTotalContas(VprDContas); EValTotal.AValor := VprDContas.ValConsolidacao; end; {******************************************************************************} procedure TFConsolidarCR.EClienteChange(Sender: TObject); begin if VprOperacao in [1,2] then ValidaGravacao1.execute; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFConsolidarCR]); end.
unit nkMqtt; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, MQTT; type //运行状态 TnkMQTTStates = (nkmCONNECT,nkmWAIT_CONNECT,nkmRUNNING,nkmFAILING); //Log事件 TnkMQTTOnLogEvent = procedure (AInfo:string) of object; //发布前事件 TnkMQTTOnBeforePublishEvent = procedure (var AMessageID:integer;var ATopic, AMessage:string) of object; //发布后事件 TnkMQTTOnAfterPublishEvent = procedure (AMessageID:integer;ATopic, AMessage:string;ASuccess:boolean) of object; //读取消息事件 TnkMQTTOnReceiveMessageEvent = procedure (ATopic, AMessage:string) of object; //主对象 { TnkMqtt } TnkMqtt = class(TComponent) private FClient: TMQTTClient; FOnAfterPublish: TnkMQTTOnAfterPublishEvent; FOnBeforePublish: TnkMQTTOnBeforePublishEvent; FOnLog: TnkMQTTOnLogEvent; //FOnPublish: TnkMQTTOnPublishEvent; FOnReceiveMessage: TnkMQTTOnReceiveMessageEvent; FPingTimerInterval: integer; FPort: integer; FPubTimerInterval: integer; FServer: string; FState: TnkMQTTStates; FPingCounter: integer; FPingTimer: integer; FPubTimer: integer; FConnectTimer: integer; FTopics: TStrings; function GetTopics: TStrings; procedure SetTopics(AValue: TStrings); protected public Terminate:boolean; constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Run;//执行消息循环 published property PubTimerInterval:integer read FPubTimerInterval write FPubTimerInterval;//发布定时间隔 property PingTimerInterval:integer read FPingTimerInterval write FPingTimerInterval;//Ping定时间隔 property Server:string read FServer write FServer;//服务器地址 property Port:integer read FPort write FPort;//服务器端口 property Topics:TStrings read GetTopics write SetTopics;//订阅主题列表 property OnLog:TnkMQTTOnLogEvent read FOnLog write FOnLog; //Log事件 property OnBeforePublish:TnkMQTTOnBeforePublishEvent read FOnBeforePublish write FOnBeforePublish;//发布消息事件 property OnAfterPublish:TnkMQTTOnAfterPublishEvent read FOnAfterPublish write FOnAfterPublish;//发布成功事件 property OnReceiveMessage:TnkMQTTOnReceiveMessageEvent read FOnReceiveMessage write FOnReceiveMessage;//收到消息 end; procedure Register; implementation procedure Register; begin RegisterComponents('Additional',[TnkMqtt]); end; { TnkMqtt } function TnkMqtt.GetTopics: TStrings; begin Result:=FTopics; end; procedure TnkMqtt.SetTopics(AValue: TStrings); begin FTopics.Assign(AValue); end; constructor TnkMqtt.Create(AOwner: TComponent); begin inherited Create(AOwner); FPort:=1883; FPubTimerInterval := 100;//10秒 FPingTimerInterval := 100; Ftopics:=TStringList.Create; end; destructor TnkMqtt.Destroy; begin FTopics.Free; inherited Destroy; end; procedure TnkMqtt.Run; var mMessageID:integer; mTopic,mMessage:string; msg : TMQTTMessage; ack : TMQTTMessageAck; i:integer; begin if Assigned(FOnLog) then FOnLog('initing'); FClient := TMQTTClient.Create(FServer, FPort); while not Self.Terminate do begin FState:=nkmCONNECT; case FState of nkmCONNECT : begin // Connect to MQTT server FPingCounter := 0; FPingTimer := 0; FPubTimer := 0; FConnectTimer := 0; FClient.Connect; FState := nkmWAIT_CONNECT; end; nkmWAIT_CONNECT : begin // Can only move to RUNNING state on recieving ConnAck FConnectTimer := FConnectTimer + 1; if FConnectTimer > 300 then begin if Assigned(FOnLog) then FOnlog('Error: ConnAck time out.'); FState := nkmFAILING; end; end; nkmRUNNING : begin // Publish stuff if FPubTimer mod FPubTimerInterval > 0 then begin //发布消息 //if Assigned(FOnBeforePublish) then begin //FOnBeforePublish(mMessageID,mTopic,mMessage); mTopic:='testtopic'; mMessage:='Hello there, this is a message send from DLL'; if not FClient.Publish(mTopic, mMessage) then begin if Assigned(FOnLog) then FOnLog('Error: Publish Failed.'); FState := nkmFAILING; //if Assigned(FOnAfterPublish) then //FOnAfterPublish(mMessageID,mTopic,mMessage,False); end else begin //FOnAfterPublish(mMessageID,mTopic,mMessage,True); end; end; end; FPubTimer := FPubTimer + 1; // Ping the MQTT server occasionally if (FPingTimer mod 100) = 0 then begin // Time to PING ! if not FClient.PingReq then begin if Assigned(FOnLog) then FOnLog('Error: PingReq Failed.'); FState := nkmFAILING; end; FPingCounter := FPingCounter + 1; // Check that pings are being answered if FPingCounter > 3 then begin if Assigned(FOnLog) then FOnLog('Error: Ping timeout.'); FState := nkmFAILING; end; end; FPingTimer := FPingTimer + 1; end; end; // Read incomming MQTT messages. repeat msg := FClient.getMessage; if Assigned(msg) then begin if Assigned(FOnReceiveMessage) then FOnReceiveMessage(msg.Topic, msg.PayLoad); if Assigned(FOnLog) then FOnLog('Got message from ' + msg.topic); // Important to free messages here. msg.free; end; until not Assigned(msg); // Read incomming MQTT message acknowledgments repeat ack := FClient.getMessageAck; if Assigned(ack) then begin case ack.messageType of CONNACK : begin if ack.returnCode = 0 then begin // Make subscriptions if Trim(FTopics.Text)<>'' then begin for i:=0 to FTopics.Count-1 do begin if Trim(FTopics.Strings[i])<>'' then FClient.Subscribe(FTopics.Strings[i]); end; end; // Enter the running state FState := nkmRUNNING; end else FState := nkmFAILING; end; PINGRESP : begin if Assigned(FOnLog) then FOnLog('PING! PONG!'); // Reset ping counter to indicate all is OK. FPingCounter := 0; end; SUBACK : begin if Assigned(FOnLog) then FOnLog('SUBACK: '+inttostr(ack.messageId)+', '+inttostr(ack.qos)); end; UNSUBACK : begin if Assigned(FOnLog) then FOnLog('UNSUBACK: '+inttostr(ack.messageId)); end; end; end; // Important to free messages here. ack.free; until not Assigned(ack); // Main application loop must call this else we leak threads! CheckSynchronize; // Yawn. sleep(100); Application.ProcessMessages; end; FClient.ForceDisconnect; FreeAndNil(FClient); end; end.
unit uContent; {$mode objfpc}{$H+} interface uses SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils; type // 1 TSQLContent = class(TSQLRecord) private fEncode: RawUTF8; fContentTypeEncode: RawUTF8; fContentType: TSQLContentTypeID; fOwnerContent: TSQLContentID; fDecoratorContent: TSQLContentID; fInstanceOfContent: TSQLContentID; fDataResource: TSQLDataResourceID; fTemplateDataResource: TSQLDataResourceID; fDataSource: TSQLDataSourceID; fStatus: TSQLStatusItemID; fPrivilegeEnum: TSQLEnumerationID; fServiceName: RawUTF8; fCustomMethod: TSQLCustomMethodID; fContentName: RawUTF8; fDescription: RawUTF8; fLocaleString: RawUTF8; fMimeType: TSQLMimeTypeID; fCharacterSet: TSQLCharacterSetID; fChildLeafCount: Integer; fChildBranchCount: Integer; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ContentTypeEncode: RawUTF8 read fContentTypeEncode write fContentTypeEncode; property ContentType: TSQLContentTypeID read fContentType write fContentType; property OwnerContent: TSQLContentID read fOwnerContent write fOwnerContent; property DecoratorContent: TSQLContentID read fDecoratorContent write fDecoratorContent; property InstanceOfContent: TSQLContentID read fInstanceOfContent write fInstanceOfContent; property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property TemplateDataResource: TSQLDataResourceID read fTemplateDataResource write fTemplateDataResource; property DataSource: TSQLDataSourceID read fDataSource write fDataSource; property Status: TSQLStatusItemID read fStatus write fStatus; property PrivilegeEnum: TSQLEnumerationID read fPrivilegeEnum write fPrivilegeEnum; property ServiceName: RawUTF8 read fServiceName write fServiceName; property CustomMethod: TSQLCustomMethodID read fCustomMethod write fCustomMethod; property ContentName: RawUTF8 read fContentName write fContentName; property Description: RawUTF8 read fDescription write fDescription; property LocaleString: RawUTF8 read fLocaleString write fLocaleString; property MimeType: TSQLMimeTypeID read fMimeType write fMimeType; property CharacterSet: TSQLCharacterSetID read fCharacterSet write fCharacterSet; property ChildLeafCount: Integer read fChildLeafCount write fChildLeafCount; property ChildBranchCount: Integer read fChildBranchCount write fChildBranchCount; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 2 TSQLContentApproval = class(TSQLRecord) private fContent: TSQLContentRevisionID; //contentId, contentRevisionSeqId fParty: TSQLPartyID; fRoleType: TSQLRoleTypeID; fApprovalStatus: TSQLStatusItemID; fApprovalDate: TDateTime; fSequenceNum: Integer; fComments: RawUTF8; published property Content: TSQLContentRevisionID read fContent write fContent; property Party: TSQLPartyID read fParty write fParty; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property ApprovalStatus: TSQLStatusItemID read fApprovalStatus write fApprovalStatus; property ApprovalDate: TDateTime read fApprovalDate write fApprovalDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property Comments: RawUTF8 read fComments write fComments; end; // 3 TSQLContentAssoc = class(TSQLRecord) private fContent: TSQLContentID; fContentIdTo: TSQLContentID; fContentAssocType: TSQLContentAssocTypeID; fFromDate: TDateTime; fThruDate: TDateTime; fContentAssocPredicate: TSQLContentAssocPredicateID; fDataSource: TSQLDataSourceID; fSequenceNum: Integer; fMapKey: RawUTF8; fUpperCoordinate: Integer; fLeftCoordinate: Integer; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property Content: TSQLContentID read fContent write fContent; property ContentIdTo: TSQLContentID read fContentIdTo write fContentIdTo; property ContentAssocType: TSQLContentAssocTypeID read fContentAssocType write fContentAssocType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property ContentAssocPredicate: TSQLContentAssocPredicateID read fContentAssocPredicate write fContentAssocPredicate; property DataSource: TSQLDataSourceID read fDataSource write fDataSource; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property MapKey: RawUTF8 read fMapKey write fMapKey; property UpperCoordinate: Integer read fUpperCoordinate write fUpperCoordinate; property LeftCoordinate: Integer read fLeftCoordinate write fLeftCoordinate; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 4 TSQLContentAssocPredicate = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 5 TSQLContentAssocType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 6 TSQLContentAttribute = class(TSQLRecord) private fContent: TSQLContentID; fAttrName: RawUTF8; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property Content: TSQLContentID read fContent write fContent; property AttrName: RawUTF8 read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 7 TSQLContentMetaData = class(TSQLRecord) private fContent: TSQLContentID; fMetaDataPredicate: TSQLMetaDataPredicateID; fMetaDataValue: RawUTF8; fDataSource: TSQLDataSourceID; published property Content: TSQLContentID read fContent write fContent; property MetaDataPredicate: TSQLMetaDataPredicateID read fMetaDataPredicate write fMetaDataPredicate; property MetaDataValue: RawUTF8 read fMetaDataValue write fMetaDataValue; property DataSource: TSQLDataSourceID read fDataSource write fDataSource; end; // 8 TSQLContentOperation = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 9 TSQLContentPurpose = class(TSQLRecord) private fContent: TSQLContentID; fContentPurposeType: TSQLContentPurposeTypeID; fSequenceNum: Integer; published property Content: TSQLContentID read fContent write fContent; property ContentPurposeType: TSQLContentPurposeTypeID read fContentPurposeType write fContentPurposeType; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 10 TSQLContentPurposeOperation = class(TSQLRecord) private fContentPurposeType: TSQLContentPurposeTypeID; fRoleType: TSQLRoleTypeID; fStatus: TSQLStatusItemID; fPrivilegeEnum: TSQLEnumerationID; published property ContentPurposeType: TSQLContentPurposeTypeID read fContentPurposeType write fContentPurposeType; property RoleType: TSQLRoleTypeID read fRoleType write fRoleType; property Status: TSQLStatusItemID read fStatus write fStatus; property PrivilegeEnum: TSQLEnumerationID read fPrivilegeEnum write fPrivilegeEnum; end; // 11 TSQLContentPurposeType = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 12 TSQLContentRevision = class(TSQLRecord) private fContent: TSQLContentID; fContentRevisionSeq: Integer; fCommittedByParty: TSQLPartyID; fComments: RawUTF8; published property Content: TSQLContentID read fContent write fContent; property ContentRevisionSeq: Integer read fContentRevisionSeq write fContentRevisionSeq; property CommittedByParty: TSQLPartyID read fCommittedByParty write fCommittedByParty; property Comments: RawUTF8 read fComments write fComments; end; // 13 TSQLContentRevisionItem = class(TSQLRecord) private fContentRevision: TSQLContentRevisionID; //contentId, contentRevisionSeqId fItemContent: Integer; fOldDataResource: TSQLDataResourceID; fNewDataResource: TSQLDataResourceID; published property ContentRevision: TSQLContentRevisionID read fContentRevision write fContentRevision; property ItemContent: Integer read fItemContent write fItemContent; property OldDataResource: TSQLDataResourceID read fOldDataResource write fOldDataResource; property NewDataResource: TSQLDataResourceID read fNewDataResource write fNewDataResource; end; // 14 TSQLContentRole = class(TSQLRecord) private fContent: TSQLContentID; fParty: TSQLPartyRoleID; //partyId, roleTypeId fFromDate: TDateTime; fThruDate: TDateTime; published property Content: TSQLContentID read fContent write fContent; property Party: TSQLPartyRoleID read fParty write fParty; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 15 TSQLContentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLContentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLContentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 16 TSQLContentTypeAttr = class(TSQLRecord) private fContentType: TSQLContentTypeID; fAttrName: TSQLContentAttributeID; fDescription: RawUTF8; published property ContentType: TSQLContentTypeID read fContentType write fContentType; property AttrName: TSQLContentAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 17 TSQLAudioDataResource = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fAudioData: TSQLRawBlob; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property AudioData: TSQLRawBlob read fAudioData write fAudioData; end; // 18 TSQLCharacterSet = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 19 TSQLDataCategory = class(TSQLRecord) private fParentCategory: TSQLDataCategoryID; fCategoryName: RawUTF8; published property ParentCategory: TSQLDataCategoryID read fParentCategory write fParentCategory; property CategoryName: RawUTF8 read fCategoryName write fCategoryName; end; // 20 TSQLDataResource = class(TSQLRecord) private fDataResourceType: TSQLDataResourceTypeID; fDataTemplateType: TSQLDataTemplateTypeID; fDataCategory: TSQLDataCategoryID; fDataSource: TSQLDataSourceID; fStatus: TSQLStatusItemID; fDataResourceName: RawUTF8; fLocaleString: RawUTF8; fMimeType: TSQLMimeTypeID; fCharacterSet: TSQLCharacterSetID; fObjectInfo: RawUTF8; fSurvey: TSQLSurveyID; fSurveyResponse: TSQLSurveyResponseID; fRelatedDetailId: TRecordReference; //根据dataResourceType,关联Survey, SurveyResponse等 fIsPublic: Boolean; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property DataResourceType: TSQLDataResourceTypeID read fDataResourceType write fDataResourceType; property DataTemplateType: TSQLDataTemplateTypeID read fDataTemplateType write fDataTemplateType; property DataCategory: TSQLDataCategoryID read fDataCategory write fDataCategory; property DataSource: TSQLDataSourceID read fDataSource write fDataSource; property Status: TSQLStatusItemID read fStatus write fStatus; property DataResourceName: RawUTF8 read fDataResourceName write fDataResourceName; property LocaleString: RawUTF8 read fLocaleString write fLocaleString; property MimeType: TSQLMimeTypeID read fMimeType write fMimeType; property CharacterSet: TSQLCharacterSetID read fCharacterSet write fCharacterSet; property ObjectInfo: RawUTF8 read fObjectInfo write fObjectInfo; property Survey: TSQLSurveyID read fSurvey write fSurvey; property SurveyResponse: TSQLSurveyResponseID read fSurveyResponse write fSurveyResponse; property RelatedDetailId: TRecordReference read fRelatedDetailId write fRelatedDetailId; property IsPublic: Boolean read fIsPublic write fIsPublic; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 21 TSQLDataResourceAttribute = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fAttrName: TRecordReference; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property AttrName: TRecordReference read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 22 TSQLDataResourceMetaData = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fMetaDataPredicate: TSQLMetaDataPredicateID; fMetaDataValue: RawUTF8; fDataSource: TSQLDataSourceID; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property MetaDataPredicate: TSQLMetaDataPredicateID read fMetaDataPredicate write fMetaDataPredicate; property MetaDataValue: RawUTF8 read fMetaDataValue write fMetaDataValue; property DataSource: TSQLDataSourceID read fDataSource write fDataSource; end; // 23 TSQLDataResourcePurpose = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fContentPurposeType: TSQLContentPurposeTypeID; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property ContentPurposeType: TSQLContentPurposeTypeID read fContentPurposeType write fContentPurposeType; end; // 24 TSQLDataResourceRole = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId fFromDate: TDateTime; fThruDate: TDateTime; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 25 TSQLDataResourceType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLDataResourceTypeID; fHasTable: Boolean; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLDataResourceTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 26 TSQLDataResourceTypeAttr = class(TSQLRecord) private fDataResourceType: TSQLDataResourceTypeID; fAttrName: TSQLDataResourceAttributeID; fDescription: RawUTF8; published property DataResourceType: TSQLDataResourceTypeID read fDataResourceType write fDataResourceType; property AttrName: TSQLDataResourceAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 27 TSQLDataTemplateType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; fExtension: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; property Extension: RawUTF8 read fExtension write fExtension; end; // 28 TSQLElectronicText = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fTextData: RawUTF8; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property TextData: RawUTF8 read fTextData write fTextData; end; // 29 TSQLFileExtension = class(TSQLRecord) private fFileExtensionName: RawUTF8; fMimeType: TSQLMimeTypeID; published property FileExtensionName: RawUTF8 read fFileExtensionName write fFileExtensionName; property MimeType: TSQLMimeTypeID read fMimeType write fMimeType; end; // 30 TSQLImageDataResource = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fImageData: TSQLRawBlob; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property ImageData: TSQLRawBlob read fImageData write fImageData; end; // 31 TSQLMetaDataPredicate = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 32 TSQLMimeType = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 33 TSQLMimeTypeHtmlTemplate = class(TSQLRecord) private fMimeType: TSQLMimeTypeID; fTemplateLocation: RawUTF8; published property MimeType: TSQLMimeTypeID read fMimeType write fMimeType; property TemplateLocation: RawUTF8 read fTemplateLocation write fTemplateLocation; end; // 34 TSQLOtherDataResource = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fDataResourceContent: TSQLRawBlob; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property DataResourceContent: TSQLRawBlob read fDataResourceContent write fDataResourceContent; end; // 35 TSQLVideoDataResource = class(TSQLRecord) private fDataResource: TSQLDataResourceID; fVideoData: TSQLRawBlob; published property DataResource: TSQLDataResourceID read fDataResource write fDataResource; property VideoData: TSQLRawBlob read fVideoData write fVideoData; end; // 36 TSQLDocument = class(TSQLRecord) private fDocumentType: TSQLDocumentTypeID; fDateCreated: TDateTime; fComments: RawUTF8; fDocumentLocation: RawUTF8; fDocumentText: RawUTF8; fImageData: TSQLRawBlob; published property DocumentType: TSQLDocumentTypeID read fDocumentType write fDocumentType; property DateCreated: TDateTime read fDateCreated write fDateCreated; property Comments: RawUTF8 read fComments write fComments; property DocumentLocation: RawUTF8 read fDocumentLocation write fDocumentLocation; property DocumentText: RawUTF8 read fDocumentText write fDocumentText; property ImageData: TSQLRawBlob read fImageData write fImageData; end; // 37 TSQLDocumentAttribute = class(TSQLRecord) private fDocument: TSQLDocumentID; fAttrName: TSQLDocumentTypeAttrID; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property Document: TSQLDocumentID read fDocument write fDocument; property AttrName: TSQLDocumentTypeAttrID read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 38 TSQLDocumentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLDocumentTypeID; fHasTable: Boolean; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLDocumentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 39 TSQLDocumentTypeAttr = class(TSQLRecord) private fDocumentType: TSQLDocumentTypeID; fAttrName: TSQLDocumentAttributeID; fDescription: RawUTF8; published property DocumentType: TSQLDocumentTypeID read fDocumentType write fDocumentType; property AttrName: TSQLDocumentAttributeID read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 40 TSQLWebPreferenceType = class(TSQLRecord) private fName: RawUTF8; fDescription: RawUTF8; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 41 TSQLWebUserPreference = class(TSQLRecord) private fUserLogin: TSQLUserLoginID; fParty: TSQLPartyID; fVisitId: Integer; //session fWebPreferenceType: TSQLWebPreferenceTypeID; fWebPreferenceValue: RawUTF8; published property UserLogin: TSQLUserLoginID read fUserLogin write fUserLogin; property Party: TSQLPartyID read fParty write fParty; property VisitId: Integer read fVisitId write fVisitId; property WebPreferenceType: TSQLWebPreferenceTypeID read fWebPreferenceType write fWebPreferenceType; property WebPreferenceValue: RawUTF8 read fWebPreferenceValue write fWebPreferenceValue; end; // 42 TSQLSurvey = class(TSQLRecord) private fSurveyName: RawUTF8; fDescription: RawUTF8; fComments: RawUTF8; fSubmitCaption: RawUTF8; fResponseService: RawUTF8; fIsAnonymous: Boolean; fAllowMultiple: Boolean; fAllowUpdate: Boolean; fAcroFormContentId: Integer; //PDF with AcroForm published property SurveyName: RawUTF8 read fSurveyName write fSurveyName; property Description: RawUTF8 read fDescription write fDescription; property Comments: RawUTF8 read fComments write fComments; property SubmitCaption: RawUTF8 read fSubmitCaption write fSubmitCaption; property ResponseService: RawUTF8 read fResponseService write fResponseService; property IsAnonymous: Boolean read fIsAnonymous write fIsAnonymous; property AllowMultiple: Boolean read fAllowMultiple write fAllowMultiple; property AllowUpdate: Boolean read fAllowUpdate write fAllowUpdate; property AcroFormContentId: Integer read fAcroFormContentId write fAcroFormContentId; end; // 43 TSQLSurveyApplType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 44 TSQLSurveyMultiResp = class(TSQLRecord) private fSurvey: TSQLSurveyID; fMultiRespTitle: RawUTF8; published property Survey: TSQLSurveyID read fSurvey write fSurvey; property MultiRespTitle: RawUTF8 read fMultiRespTitle write fMultiRespTitle; end; // 45 TSQLSurveyMultiRespColumn = class(TSQLRecord) private fSurvey: TSQLSurveyID; fSurveyMultiResp: TSQLSurveyMultiRespID; fSurveyMultiRespColId: Integer; fColumnTitle: RawUTF8; fSequenceNum: Integer; published property Survey: TSQLSurveyID read fSurvey write fSurvey; property SurveyMultiResp: TSQLSurveyMultiRespID read fSurveyMultiResp write fSurveyMultiResp; property SurveyMultiRespColId: Integer read fSurveyMultiRespColId write fSurveyMultiRespColId; property ColumnTitle: RawUTF8 read fColumnTitle write fColumnTitle; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 46 TSQLSurveyPage = class(TSQLRecord) private fSurvey: TSQLSurveyID; fSurveyPageSeqId: Integer; fPageName: RawUTF8; fSequenceNum: Integer; published property Survey: TSQLSurveyID read fSurvey write fSurvey; property SurveyPageSeqId: Integer read fSurveyPageSeqId write fSurveyPageSeqId; property PageName: RawUTF8 read fPageName write fPageName; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 47 TSQLSurveyQuestion = class(TSQLRecord) private fSurveyQuestionCategory: TSQLSurveyQuestionCategoryID; fSurveyQuestionType: TSQLSurveyQuestionTypeID; fDescription: RawUTF8; fQuestion: RawUTF8; fHint: RawUTF8; fEnumType: TSQLEnumerationID; fGeo: TSQLGeoID; fFormatString: RawUTF8; published property SurveyQuestionCategory: TSQLSurveyQuestionCategoryID read fSurveyQuestionCategory write fSurveyQuestionCategory; property SurveyQuestionType: TSQLSurveyQuestionTypeID read fSurveyQuestionType write fSurveyQuestionType; property Description: RawUTF8 read fDescription write fDescription; property Question: RawUTF8 read fQuestion write fQuestion; property Hint: RawUTF8 read fHint write fHint; property EnumType: TSQLEnumerationID read fEnumType write fEnumType; property Geo: TSQLGeoID read fGeo write fGeo; property FormatString: RawUTF8 read fFormatString write fFormatString; end; // 48 TSQLSurveyQuestionAppl = class(TSQLRecord) private fSurvey: TSQLSurveyID; fSurveyQuestion: TSQLSurveyQuestionID; fFromDate: TDateTime; fThruDate: TDateTime; fSurveyPage: TSQLSurveyPageID; //surveyId, surveyPageSeqId fSurveyMultiResp: TSQLSurveyMultiRespID; //surveyId, surveyMultiRespId fSurveyMultiRespColumn: TSQLSurveyMultiRespColumnID; //surveyId, surveyMultiRespId, surveyMultiRespColId fRequiredField: Boolean; fSequenceNum: Integer; fExternalFieldRef: RawUTF8; fSurveyQuestionOption: TSQLSurveyQuestionOptionID; //withSurveyQuestionId, withSurveyOptionSeqId published property Survey: TSQLSurveyID read fSurvey write fSurvey; property SurveyQuestion: TSQLSurveyQuestionID read fSurveyQuestion write fSurveyQuestion; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SurveyPage: TSQLSurveyPageID read fSurveyPage write fSurveyPage; property SurveyMultiResp: TSQLSurveyMultiRespID read fSurveyMultiResp write fSurveyMultiResp; property SurveyMultiRespColumn: TSQLSurveyMultiRespColumnID read fSurveyMultiRespColumn write fSurveyMultiRespColumn; property RequiredField: Boolean read fRequiredField write fRequiredField; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property ExternalFieldRef: RawUTF8 read fExternalFieldRef write fExternalFieldRef; property SurveyQuestionOption: TSQLSurveyQuestionOptionID read fSurveyQuestionOption write fSurveyQuestionOption; end; // 49 TSQLSurveyQuestionCategory = class(TSQLRecord) private fParent: TSQLSurveyQuestionCategoryID; fName: RawUTF8; fDescription: RawUTF8; published property Parent: TSQLSurveyQuestionCategoryID read fParent write fParent; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 50 TSQLSurveyQuestionOption = class(TSQLRecord) private fSurveyQuestion: TSQLSurveyQuestionID; fSurveyOptionSeqId: Integer; fDescription: RawUTF8; fSequenceNum: Integer; fAmountBase: Currency; fAmountBaseUom: TSQLUomID; fWeightFactor: Double; fDuration: Integer; fDurationUom: TSQLUomID; published property SurveyQuestion: TSQLSurveyQuestionID read fSurveyQuestion write fSurveyQuestion; property SurveyOptionSeqId: Integer read fSurveyOptionSeqId write fSurveyOptionSeqId; property Description: RawUTF8 read fDescription write fDescription; property SequenceNum: Integer read fSequenceNum write fSequenceNum; property AmountBase: Currency read fAmountBase write fAmountBase; property AmountBaseUom: TSQLUomID read fAmountBaseUom write fAmountBaseUom; property WeightFactor: Double read fWeightFactor write fWeightFactor; property Duration: Integer read fDuration write fDuration; property DurationUom: TSQLUomID read fDurationUom write fDurationUom; end; // 51 TSQLSurveyQuestionType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 52 TSQLSurveyResponse = class(TSQLRecord) private fSurvey: TSQLSurveyID; fParty: TSQLPartyID; fResponseDate: TDateTime; fLastModifiedDate: TDateTime; fReference: TRecordReference; fGeneralFeedback: RawUTF8; fOrderId: TSQLOrderItemID; //orderId, orderItemSeqId fStatus: TSQLStatusItemID; published property Survey: TSQLSurveyID read fSurvey write fSurvey; property Party: TSQLPartyID read fParty write fParty; property ResponseDate: TDateTime read fResponseDate write fResponseDate; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property Reference: TRecordReference read fReference write fReference; property GeneralFeedback: RawUTF8 read fGeneralFeedback write fGeneralFeedback; property OrderId: TSQLOrderItemID read fOrderId write fOrderId; property Status: TSQLStatusItemID read fStatus write fStatus; end; // 53 TSQLSurveyResponseAnswer = class(TSQLRecord) private fSurveyResponse: TSQLSurveyResponseID; fSurveyQuestion: TSQLSurveyQuestionID; fSurveyMultiRespCol: TRecordReference; fSurveyMultiResp: TRecordReference; fBooleanResponse: Boolean; fCurrencyResponse: Currency; fFloatResponse: Double; fNumericResponse: Integer; fTextResponse: RawUTF8; fSurveyOptionSeq: TSQLSurveyQuestionOptionID; fContent: TSQLContentID; fAnsweredDate: TDateTime; fAmountBase: Currency; fAmountBaseUom: TSQLUomID; fWeightFactor: Double; fDuration: Integer; fDurationUom: TSQLUomID; fSequenceNum: Integer; published property SurveyResponse: TSQLSurveyResponseID read fSurveyResponse write fSurveyResponse; property SurveyQuestion: TSQLSurveyQuestionID read fSurveyQuestion write fSurveyQuestion; property SurveyMultiRespCol: TRecordReference read fSurveyMultiRespCol write fSurveyMultiRespCol; property SurveyMultiResp: TRecordReference read fSurveyMultiResp write fSurveyMultiResp; property BooleanResponse: Boolean read fBooleanResponse write fBooleanResponse; property CurrencyResponse: Currency read fCurrencyResponse write fCurrencyResponse; property FloatResponse: Double read fFloatResponse write fFloatResponse; property NumericResponse: Integer read fNumericResponse write fNumericResponse; property TextResponse: RawUTF8 read fTextResponse write fTextResponse; property SurveyOptionSeq: TSQLSurveyQuestionOptionID read fSurveyOptionSeq write fSurveyOptionSeq; property Content: TSQLContentID read fContent write fContent; property AnsweredDate: TDateTime read fAnsweredDate write fAnsweredDate; property AmountBase: Currency read fAmountBase write fAmountBase; property AmountBaseUom: TSQLUomID read fAmountBaseUom write fAmountBaseUom; property WeightFactor: Double read fWeightFactor write fWeightFactor; property Duration: Integer read fDuration write fDuration; property DurationUom: TSQLUomID read fDurationUom write fDurationUom; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 54 TSQLSurveyTrigger = class(TSQLRecord) private fSurvey: TSQLSurveyID; fSurveyApplType: TSQLSurveyApplTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property Survey: TSQLSurveyID read fSurvey write fSurvey; property SurveyApplType: TSQLSurveyApplTypeID read fSurveyApplType write fSurveyApplType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 55 TSQLWebSiteContent = class(TSQLRecord) private fWebSite: TSQLWebSiteID; fContent: TSQLContentID; fWebSiteContentType: TSQLWebSiteContentTypeID; fFromDate: TDateTime; fThruDate: TDateTime; published property WebSite: TSQLWebSiteID read fWebSite write fWebSite; property Content: TSQLContentID read fContent write fContent; property WebSiteContentType: TSQLWebSiteContentTypeID read fWebSiteContentType write fWebSiteContentType; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; end; // 56 TSQLWebSiteContentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLWebSiteContentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLWebSiteContentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 57 TSQLWebSitePathAlias = class(TSQLRecord) private fWebSite: TSQLWebSiteID; fPathAlias: RawUTF8; fFromDate: TDateTime; fThruDate: TDateTime; fAliasTo: RawUTF8; fContent: TSQLContentID; fMapKey: RawUTF8; published property WebSite: TSQLWebSiteID read fWebSite write fWebSite; property PathAlias: RawUTF8 read fPathAlias write fPathAlias; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property AliasTo: RawUTF8 read fAliasTo write fAliasTo; property Content: TSQLContentID read fContent write fContent; property MapKey: RawUTF8 read fMapKey write fMapKey; end; // 58 TSQLWebSitePublishPoint = class(TSQLRecord) private fContent: TSQLContentID; fTemplateTitle: RawUTF8; fStyleSheetFile: RawUTF8; fLogo: RawUTF8; fMedallionLogo: RawUTF8; fLineLogo: RawUTF8; fLeftBarId: TRecordReference; fRightBarId: TRecordReference; fContentDept: TRecordReference; fAboutContentId: TRecordReference; published property Content: TSQLContentID read fContent write fContent; property TemplateTitle: RawUTF8 read fTemplateTitle write fTemplateTitle; property StyleSheetFile: RawUTF8 read fStyleSheetFile write fStyleSheetFile; property Logo: RawUTF8 read fLogo write fLogo; property MedallionLogo: RawUTF8 read fMedallionLogo write fMedallionLogo; property LineLogo: RawUTF8 read fLineLogo write fLineLogo; property LeftBarId: TRecordReference read fLeftBarId write fLeftBarId; property RightBarId: TRecordReference read fRightBarId write fRightBarId; property ContentDept: TRecordReference read fContentDept write fContentDept; property AboutContentId: TRecordReference read fAboutContentId write fAboutContentId; end; // 59 TSQLWebSiteRole = class(TSQLRecord) private fParty: TSQLPartyRoleID; //partyId, roleTypeId fWebSite: TSQLWebSiteID; fFromDate: TDateTime; fThruDate: TDateTime; fSequenceNum: Integer; published property Party: TSQLPartyRoleID read fParty write fParty; property WebSite: TSQLWebSiteID read fWebSite write fWebSite; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 60 TSQLContentKeyword = class(TSQLRecord) private fContent: TSQLContentID; fKeyword: RawUTF8; fRelevancyWeight: Integer; published property Content: TSQLContentID read fContent write fContent; property Keyword: RawUTF8 read fKeyword write fKeyword; property RelevancyWeight: Integer read fRelevancyWeight write fRelevancyWeight; end; // 61 TSQLContentSearchConstraint = class(TSQLRecord) private fContentSearchResult: TSQLContentSearchResultID; fConstraintSeq: Integer; fConstraintName: RawUTF8; fInfoString: RawUTF8; fIncludeSubCategories: Boolean; fIsAnd: Boolean; fAnyPrefix: Boolean; fAnySuffix: Boolean; fRemoveStems: Boolean; fLowValue: RawUTF8; fHighValue: RawUTF8; published property ContentSearchResult: TSQLContentSearchResultID read fContentSearchResult write fContentSearchResult; property ConstraintSeq: Integer read fConstraintSeq write fConstraintSeq; property ConstraintName: RawUTF8 read fConstraintName write fConstraintName; property InfoString: RawUTF8 read fInfoString write fInfoString; property IncludeSubCategories: Boolean read fIncludeSubCategories write fIncludeSubCategories; property IsAnd: Boolean read fIsAnd write fIsAnd; property AnyPrefix: Boolean read fAnyPrefix write fAnyPrefix; property AnySuffix: Boolean read fAnySuffix write fAnySuffix; property RemoveStems: Boolean read fRemoveStems write fRemoveStems; property LowValue: RawUTF8 read fLowValue write fLowValue; property HighValue: RawUTF8 read fHighValue write fHighValue; end; // 62 TSQLContentSearchResult = class(TSQLRecord) private fVisitId: Integer; fOrderByName: RawUTF8; fIsAscending: Boolean; fNumResults: Integer; fSecondsTotal: Double; fSearchDate: TDateTime; published property VisitId: Integer read fVisitId write fVisitId; property OrderByName: RawUTF8 read fOrderByName write fOrderByName; property IsAscending: Boolean read fIsAscending write fIsAscending; property NumResults: Integer read fNumResults write fNumResults; property SecondsTotal: Double read fSecondsTotal write fSecondsTotal; property SearchDate: TDateTime read fSearchDate write fSearchDate; end; // 63 TSQLWebAnalyticsConfig = class(TSQLRecord) private fWebSite: TSQLWebSiteID; fWebAnalyticsType: TSQLWebAnalyticsTypeID; fWebAnalyticsCode: RawUTF8; published property WebSite: TSQLWebSiteID read fWebSite write fWebSite; property WebAnalyticsType: TSQLWebAnalyticsTypeID read fWebAnalyticsType write fWebAnalyticsType; property WebAnalyticsCode: RawUTF8 read fWebAnalyticsCode write fWebAnalyticsCode; end; // 64 TSQLWebAnalyticsType = class(TSQLRecord) private fParent: TSQLWebAnalyticsTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; published property Parent: TSQLWebAnalyticsTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; implementation uses Classes, SysUtils; // 1 class procedure TSQLContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLContentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ContentType set parent=(select c.id from ContentType c where c.Encode=ContentType.ParentEncode);'); Server.Execute('update Content set ContentType=(select c.id from ContentType c where c.Encode=Content.ContentTypeEncode);'); finally Rec.Free; end; end; // 2 class procedure TSQLContentAssocType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLContentAssocType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLContentAssocType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContentAssocType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 3 class procedure TSQLContentAssocPredicate.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLContentAssocPredicate; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLContentAssocPredicate.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContentAssocPredicate.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 4 class procedure TSQLMetaDataPredicate.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLMetaDataPredicate; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLMetaDataPredicate.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','MetaDataPredicate.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 5 class procedure TSQLDataResourceType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLDataResourceType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLDataResourceType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','DataResourceType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update DataResourceType set parent=(select c.id from DataResourceType c where c.Encode=DataResourceType.ParentEncode);'); finally Rec.Free; end; end; // 6 class procedure TSQLDataTemplateType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLDataTemplateType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLDataTemplateType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','DataTemplateType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 7 class procedure TSQLDocumentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLDocumentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLDocumentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','DocumentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update DocumentType set parent=(select c.id from DocumentType c where c.Encode=DocumentType.ParentEncode);'); finally Rec.Free; end; end; // 8 class procedure TSQLWebSiteContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLWebSiteContentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLWebSiteContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','WebSiteContentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update WebSiteContentType set parent=(select c.id from WebSiteContentType c where c.Encode=WebSiteContentType.ParentEncode);'); finally Rec.Free; end; end; // 9 class procedure TSQLContent.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLContent; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLContent.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','Content.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update Content set ContentType=(select c.id from ContentType c where c.Encode=Content.ContentTypeEncode);'); finally Rec.Free; end; end; // 10 class procedure TSQLSurveyApplType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLSurveyApplType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLSurveyApplType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','SurveyApplType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 11 class procedure TSQLSurveyQuestionType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLSurveyQuestionType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLSurveyQuestionType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','SurveyQuestionType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; end.
unit MediaStream.Statistics; interface uses SysUtils,Classes,SyncObjs,MediaStream.DataSource.Base,Generics.Collections,Player.VideoOutput.Base,MediaProcessing.Definitions; type TBytesInfo = record Value:cardinal; DateTime: TDateTime; end; TFrameInfo = record DateTime: TDateTime; end; TMediaStreamStatistics = class private FBPSLock : TCriticalSection; FBPS: TQueue<TBytesInfo>; FFPSLock : TCriticalSection; FFPS: TQueue<TFrameInfo>; FBytesPerSecondTestIntervalSecs: cardinal; FFramesPerSecondTestIntervalSecs: cardinal; FAttrLock: TCriticalSection; FTotalBytes: int64; FTotalFrames: int64; FMaxFrameSize : int64; FMinFrameSize : int64; FFirstDateTime: TDateTime; FLastDateTime: TDateTime; public constructor Create; destructor Destroy; override; property BytesPerSecondTestIntervalSecs:cardinal read FBytesPerSecondTestIntervalSecs write FBytesPerSecondTestIntervalSecs default 3; property FramesPerSecondTestIntervalSecs:cardinal read FFramesPerSecondTestIntervalSecs write FFramesPerSecondTestIntervalSecs default 3; procedure AddData(aDataSize: cardinal; aInfoSize: cardinal); function GetBytesPerSecond: cardinal; function GetFramesPerSecondFloat: double; function GetFramesPerSecond: cardinal; function GetTotalBytes: int64; inline; function GetTotalFrames: int64; inline; function GetAverageFrameSize: int64; inline; function GetMaxFrameSize: int64; inline; function GetMinFrameSize: int64; inline; function GetLastDateTime: TDateTime; inline; function GetFirstDateTime: TDateTime; inline; procedure Clear; end; implementation uses Math; { TMediaStreamStatistics } procedure TMediaStreamStatistics.AddData(aDataSize: cardinal; aInfoSize: cardinal); var aNow: TDateTime; aBytesInfo: TBytesInfo; aFrameInfo: TFrameInfo; aFrameSize: integer; begin aNow:=Now; FBPSLock.Enter; try aBytesInfo.Value:=aDataSize+aInfoSize; aBytesInfo.DateTime:=aNow; FBPS.Enqueue(aBytesInfo); while (FBPS.Count>1) and ((aNow-FBPS.Peek.DateTime)*SecsPerDay>FBytesPerSecondTestIntervalSecs) do FBPS.Dequeue; finally FBPSLock.Leave; end; FFPSLock.Enter; try aFrameInfo.DateTime:=aNow; FFPS.Enqueue(aFrameInfo); while (FFPS.Count>1) and ((aNow-FFPS.Peek.DateTime)*SecsPerDay>FFramesPerSecondTestIntervalSecs) do FFPS.Dequeue; finally FFPSLock.Leave; end; FAttrLock.Enter; try FLastDateTime:=Now; if FFirstDateTime=0 then FFirstDateTime:=FLastDateTime; aFrameSize:=aDataSize+aInfoSize; if FTotalFrames=0 then begin FMaxFrameSize:=aFrameSize; FMinFrameSize:=aFrameSize; end else begin FMaxFrameSize:=Max(FMaxFrameSize,aFrameSize); FMinFrameSize:=Min(FMinFrameSize,aFrameSize); end; inc(FTotalBytes,aFrameSize); inc(FTotalFrames); finally FAttrLock.Leave; end; end; procedure TMediaStreamStatistics.Clear; begin FBPSLock.Enter; try FBPS.Clear; finally FBPSLock.Leave; end; FFPSLock.Enter; try FFPS.Clear; finally FFPSLock.Leave; end; FAttrLock.Enter; try FLastDateTime:=0; FMaxFrameSize:=0; FMinFrameSize:=0; FTotalBytes:=0; FTotalFrames:=0; finally FAttrLock.Leave; end; end; constructor TMediaStreamStatistics.Create; begin FBPSLock:=TCriticalSection.Create; FBPS:=TQueue<TBytesInfo>.Create; FFPSLock:=TCriticalSection.Create; FFPS:=TQueue<TFrameInfo>.Create; FAttrLock:=TCriticalSection.Create; FBytesPerSecondTestIntervalSecs:=3; FFramesPerSecondTestIntervalSecs:=3; end; destructor TMediaStreamStatistics.Destroy; begin inherited; FreeAndNil(FBPSLock); FreeAndNil(FBPS); FreeAndNil(FFPSLock); FreeAndNil(FFPS); FreeAndNil(FAttrLock); end; function TMediaStreamStatistics.GetAverageFrameSize: int64; begin FAttrLock.Enter; try if FTotalFrames>0 then result:=FTotalBytes div FTotalFrames else result:=0; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetBytesPerSecond: cardinal; var aEnd,aStart: TDateTime; aBPSEnumerator: TQueue<TBytesInfo>.TEnumerator; begin result:=0; aStart:=0; aEnd:=0; FBPSLock.Enter; try if FBPS.Count>1 then begin aStart:=FBPS.Peek.DateTime; aEnd:=aStart; aBPSEnumerator:=FBPS.GetEnumerator; try while aBPSEnumerator.MoveNext do begin aEnd:=aBPSEnumerator.Current.DateTime; result:=result+aBPSEnumerator.Current.Value; end; finally aBPSEnumerator.Free; end; end; finally FBPSLock.Leave; end; if (aStart<>0) and (aEnd>aStart) then result:=Round(result/ ((aEnd-aStart)*SecsPerDay)) else result:=0; end; function TMediaStreamStatistics.GetFirstDateTime: TDateTime; begin FAttrLock.Enter; try result:=FFirstDateTime; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetFramesPerSecond: cardinal; begin result:=Round(GetFramesPerSecondFloat); end; function TMediaStreamStatistics.GetFramesPerSecondFloat: double; var aEnd,aStart: TDateTime; aFPSEnumerator: TQueue<TFrameInfo>.TEnumerator; begin result:=0; aStart:=0; aEnd:=0; FFPSLock.Enter; try if FFPS.Count>1 then begin aStart:=FFPS.Peek.DateTime; aEnd:=aStart; aFPSEnumerator:=FFPS.GetEnumerator; try while aFPSEnumerator.MoveNext do begin aEnd:=aFPSEnumerator.Current.DateTime; result:=result+1; end; finally aFPSEnumerator.Free; end; end; finally FFPSLock.Leave; end; if (aStart<>0) and (aEnd>aStart) then result:=result/ ((aEnd-aStart)*SecsPerDay) else result:=0; end; function TMediaStreamStatistics.GetLastDateTime: TDateTime; begin FAttrLock.Enter; try result:=FLastDateTime; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetMaxFrameSize: int64; begin FAttrLock.Enter; try result:=FMaxFrameSize; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetMinFrameSize: int64; begin FAttrLock.Enter; try result:=FMinFrameSize; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetTotalBytes: int64; begin FAttrLock.Enter; try result:=FTotalBytes; finally FAttrLock.Leave; end; end; function TMediaStreamStatistics.GetTotalFrames: int64; begin FAttrLock.Enter; try result:=FTotalFrames; finally FAttrLock.Leave; end; end; end.
unit Main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Types, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, Buttons, IntfGraphics, ColorBox, mvGeoNames, mvMapViewer, mvTypes, mvGpsObj, mvDrawingEngine, mvDE_RGBGraphics, mvDE_BGRA; type { TMainForm } TMainForm = class(TForm) Bevel1: TBevel; BtnSearch: TButton; BtnGoTo: TButton; BtnGPSPoints: TButton; BtnSaveToFile: TButton; BtnLoadGPXFile: TButton; BtnPOITextFont: TButton; CbDoubleBuffer: TCheckBox; CbFoundLocations: TComboBox; CbLocations: TComboBox; CbProviders: TComboBox; CbUseThreads: TCheckBox; CbMouseCoords: TGroupBox; CbDistanceUnits: TComboBox; CbDebugTiles: TCheckBox; CbDrawingEngine: TComboBox; CbShowPOIImage: TCheckBox; cbPOITextBgColor: TColorBox; FontDialog: TFontDialog; GbCenterCoords: TGroupBox; GbScreenSize: TGroupBox; GbSearch: TGroupBox; GbGPS: TGroupBox; InfoCenterLatitude: TLabel; InfoViewportHeight: TLabel; InfoCenterLongitude: TLabel; InfoBtnGPSPoints: TLabel; GPSPointInfo: TLabel; InfoViewportWidth: TLabel; Label1: TLabel; LblPOITextBgColor: TLabel; LblSelectLocation: TLabel; LblCenterLatitude: TLabel; LblViewportHeight: TLabel; LblViewportWidth: TLabel; LblPositionLongitude: TLabel; LblPositionLatitude: TLabel; InfoPositionLongitude: TLabel; InfoPositionLatitude: TLabel; LblCenterLongitude: TLabel; LblProviders: TLabel; LblZoom: TLabel; MapView: TMapView; GeoNames: TMVGeoNames; BtnLoadMapProviders: TSpeedButton; BtnSaveMapProviders: TSpeedButton; OpenDialog: TOpenDialog; PageControl: TPageControl; PgData: TTabSheet; PgConfig: TTabSheet; ZoomTrackBar: TTrackBar; procedure BtnGoToClick(Sender: TObject); procedure BtnLoadGPXFileClick(Sender: TObject); procedure BtnSearchClick(Sender: TObject); procedure BtnGPSPointsClick(Sender: TObject); procedure BtnSaveToFileClick(Sender: TObject); procedure BtnPOITextFontClick(Sender: TObject); procedure CbDebugTilesChange(Sender: TObject); procedure CbDrawingEngineChange(Sender: TObject); procedure CbDoubleBufferChange(Sender: TObject); procedure CbFoundLocationsDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); procedure cbPOITextBgColorChange(Sender: TObject); procedure CbProvidersChange(Sender: TObject); procedure CbShowPOIImageChange(Sender: TObject); procedure CbUseThreadsChange(Sender: TObject); procedure CbDistanceUnitsChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure GeoNamesNameFound(const AName: string; const ADescr: String; const ALoc: TRealPoint); procedure MapViewChange(Sender: TObject); procedure MapViewDrawGpsPoint(Sender: TObject; ADrawer: TMvCustomDrawingEngine; APoint: TGpsPoint); procedure MapViewMouseLeave(Sender: TObject); procedure MapViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure MapViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MapViewZoomChange(Sender: TObject); procedure BtnLoadMapProvidersClick(Sender: TObject); procedure BtnSaveMapProvidersClick(Sender: TObject); procedure ZoomTrackBarChange(Sender: TObject); private FRGBGraphicsDrawingEngine: TMvRGBGraphicsDrawingEngine; FBGRADrawingEngine: TMvBGRADrawingEngine; POIImage: TCustomBitmap; procedure ClearFoundLocations; procedure UpdateCoords(X, Y: Integer); procedure UpdateDropdownWidth(ACombobox: TCombobox); procedure UpdateLocationHistory(ALocation: String); procedure UpdateViewportSize; public procedure ReadFromIni; procedure WriteToIni; end; var MainForm: TMainForm; implementation {$R *.lfm} uses LCLType, IniFiles, Math, FPCanvas, FPImage, GraphType, mvEngine, mvGPX, globals, gpslistform; type TLocationParam = class Descr: String; Loc: TRealPoint; end; const MAX_LOCATIONS_HISTORY = 50; HOMEDIR = '../../../'; // share the cache in both example projects MAP_PROVIDER_FILENAME = 'map-providers.xml'; USE_DMS = true; var PointFormatSettings: TFormatsettings; function CalcIniName: String; begin Result := ChangeFileExt(Application.ExeName, '.ini'); end; { TMainForm } procedure TMainForm.BtnLoadMapProvidersClick(Sender: TObject); var fn: String; msg: String; begin fn := Application.Location + MAP_PROVIDER_FILENAME; if FileExists(fn) then begin if MapView.Engine.ReadProvidersFromXML(fn, msg) then begin MapView.GetMapProviders(CbProviders.Items); CbProviders.ItemIndex := 0; MapView.MapProvider := CbProviders.Text; end else ShowMessage(msg); end; end; procedure TMainForm.BtnSaveMapProvidersClick(Sender: TObject); begin MapView.Engine.WriteProvidersToXML(Application.Location + MAP_PROVIDER_FILENAME); end; procedure TMainForm.BtnSearchClick(Sender: TObject); begin ClearFoundLocations; GeoNames.Search(CbLocations.Text, MapView.DownloadEngine); UpdateDropdownWidth(CbFoundLocations); UpdateLocationHistory(CbLocations.Text); if CbFoundLocations.Items.Count > 0 then CbFoundLocations.ItemIndex := 0; end; procedure TMainForm.BtnGPSPointsClick(Sender: TObject); var F: TGpsListViewer; begin F := TGpsListViewer.Create(nil); try F.MapViewer := MapView; F.ShowModal; finally F.Free; end; end; procedure TMainForm.BtnGoToClick(Sender: TObject); var s: String; P: TLocationParam; begin if CbFoundLocations.ItemIndex = -1 then exit; // Extract parameters of found locations. We need that to get the coordinates. s := CbFoundLocations.Items.Strings[CbFoundLocations.ItemIndex]; P := TLocationParam(CbFoundLocations.Items.Objects[CbFoundLocations.ItemIndex]); if P = nil then exit; CbFoundLocations.Text := s; // Show location in center of mapview MapView.Zoom := 12; MapView.Center := P.Loc; MapView.Invalidate; end; procedure TMainForm.BtnLoadGPXFileClick(Sender: TObject); var reader: TGpxReader; b: TRealArea; begin if OpenDialog.FileName <> '' then OpenDialog.InitialDir := ExtractFileDir(OpenDialog.Filename); if OpenDialog.Execute then begin reader := TGpxReader.Create; try reader.LoadFromFile(OpenDialog.FileName, MapView.GPSItems, b); MapView.Engine.ZoomOnArea(b); MapViewZoomChange(nil); finally reader.Free; end; end; end; procedure TMainForm.BtnSaveToFileClick(Sender: TObject); begin MapView.SaveToFile(TPortableNetworkGraphic, 'mapview.png'); ShowMessage('Map saved to "mapview.png".'); end; procedure TMainForm.BtnPOITextFontClick(Sender: TObject); begin FontDialog.Font.Assign(MapView.Font); if FontDialog.Execute then MapView.Font.Assign(FontDialog.Font); end; procedure TMainForm.CbDebugTilesChange(Sender: TObject); begin MapView.DebugTiles := CbDebugTiles.Checked; end; procedure TMainForm.CbDrawingEngineChange(Sender: TObject); begin case CbDrawingEngine.ItemIndex of 0: MapView.DrawingEngine := nil; 1: begin if FRGBGraphicsDrawingEngine = nil then FRGBGraphicsDrawingEngine := TMvRGBGraphicsDrawingEngine.Create(self); MapView.DrawingEngine := FRGBGraphicsDrawingEngine; end; 2: begin if FBGRADrawingEngine = nil then FBGRADrawingEngine := TMvBGRADrawingEngine.Create(self); MapView.DrawingEngine := FBGRADrawingEngine; end; end; end; procedure TMainForm.CbDoubleBufferChange(Sender: TObject); begin MapView.DoubleBuffered := CbDoubleBuffer.Checked; end; procedure TMainForm.CbFoundLocationsDrawItem(Control: TWinControl; Index: Integer; ARect: TRect; State: TOwnerDrawState); var s: String; P: TLocationParam; combo: TCombobox; x, y: Integer; begin combo := TCombobox(Control); if (State * [odSelected, odFocused] <> []) then begin combo.Canvas.Brush.Color := clHighlight; combo.Canvas.Font.Color := clHighlightText; end else begin combo.Canvas.Brush.Color := clWindow; combo.Canvas.Font.Color := clWindowText; end; combo.Canvas.FillRect(ARect); combo.Canvas.Brush.Style := bsClear; s := combo.Items.Strings[Index]; P := TLocationParam(combo.Items.Objects[Index]); x := ARect.Left + 2; y := ARect.Top + 2; combo.Canvas.Font.Style := [fsBold]; combo.Canvas.TextOut(x, y, s); inc(y, combo.Canvas.TextHeight('Tg')); combo.Canvas.Font.Style := []; combo.Canvas.TextOut(x, y, P.Descr); end; procedure TMainForm.cbPOITextBgColorChange(Sender: TObject); begin MapView.POITextBgColor := cbPOITextBgColor.Selected; end; procedure TMainForm.CbProvidersChange(Sender: TObject); begin MapView.MapProvider := CbProviders.Text; end; procedure TMainForm.CbShowPOIImageChange(Sender: TObject); begin if CbShowPOIImage.Checked then MapView.POIImage.Assign(POIImage) else MapView.POIImage.Clear; end; procedure TMainForm.CbUseThreadsChange(Sender: TObject); begin MapView.UseThreads := CbUseThreads.Checked; end; procedure TMainForm.CbDistanceUnitsChange(Sender: TObject); begin DistanceUnit := TDistanceUnits(CbDistanceUnits.ItemIndex); UpdateViewPortSize; end; procedure TMainForm.ClearFoundLocations; var i: Integer; P: TLocationParam; begin for i:=0 to CbFoundLocations.Items.Count-1 do begin P := TLocationParam(CbFoundLocations.Items.Objects[i]); P.Free; end; CbFoundLocations.Items.Clear; end; procedure TMainForm.FormCreate(Sender: TObject); begin // FMapMarker := CreateMapMarker(32, clRed, clBlack); POIImage := TPortableNetworkGraphic.Create; POIImage.PixelFormat := pf32bit; POIImage.LoadFromFile('../../mapmarker.png'); ForceDirectories(HOMEDIR + 'example_cache/'); MapView.CachePath := HOMEDIR + 'example_cache/'; MapView.GetMapProviders(CbProviders.Items); CbProviders.ItemIndex := CbProviders.Items.Indexof(MapView.MapProvider); MapView.DoubleBuffered := true; MapView.Zoom := 1; CbUseThreads.Checked := MapView.UseThreads; CbDoubleBuffer.Checked := MapView.DoubleBuffered; CbPOITextBgColor.Selected := MapView.POITextBgColor; InfoPositionLongitude.Caption := ''; InfoPositionLatitude.Caption := ''; InfoCenterLongitude.Caption := ''; InfoCenterLatitude.Caption := ''; InfoViewportWidth.Caption := ''; InfoViewportHeight.Caption := ''; GPSPointInfo.caption := ''; ReadFromIni; end; procedure TMainForm.FormDestroy(Sender: TObject); begin WriteToIni; ClearFoundLocations; FreeAndNil(POIImage) end; procedure TMainForm.FormShow(Sender: TObject); begin MapView.Active := true; end; procedure TMainForm.GeoNamesNameFound(const AName: string; const ADescr: String; const ALoc: TRealPoint); var P: TLocationParam; begin P := TLocationParam.Create; P.Descr := ADescr; P.Loc := ALoc; CbFoundLocations.Items.AddObject(AName, P); end; procedure TMainForm.MapViewChange(Sender: TObject); begin UpdateViewportSize; end; procedure TMainForm.MapViewDrawGpsPoint(Sender: TObject; ADrawer: TMvCustomDrawingEngine; APoint: TGpsPoint); const R = 5; var P: TPoint; ext: TSize; begin // Screen coordinates of the GPS point P := TMapView(Sender).LonLatToScreen(APoint.RealPoint); // Draw the GPS point with MapMarker bitmap { if CbShowPOIImage.Checked and not MapView.POIImage.Empty then begin ADrawer.DrawBitmap(P.X - MapView.POIImage.Width div 2, P.Y - MapView.POIImage.Height, MapView.POIImage, true); end else begin } // Draw the GPS point as a circle ADrawer.BrushColor := clRed; ADrawer.BrushStyle := bsSolid; ADrawer.Ellipse(P.X - R, P.Y - R, P.X + R, P.Y + R); P.Y := P.Y + R; //end; { // Draw the caption of the GPS point ext := ADrawer.TextExtent(APoint.Name); ADrawer.BrushColor := clWhite; ADrawer.BrushStyle := bsClear; ADrawer.TextOut(P.X - ext.CX div 2, P.Y + 5, APoint.Name); } end; procedure TMainForm.MapViewMouseLeave(Sender: TObject); begin UpdateCoords(MaxInt, MaxInt); end; procedure TMainForm.MapViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); const DELTA = 3; var rArea: TRealArea; gpsList: TGpsObjList; L: TStrings; i: Integer; begin UpdateCoords(X, Y); rArea.TopLeft := MapView.ScreenToLonLat(Point(X-DELTA, Y-DELTA)); rArea.BottomRight := MapView.ScreenToLonLat(Point(X+DELTA, Y+DELTA)); gpsList := MapView.GpsItems.GetObjectsInArea(rArea); try if gpsList.Count > 0 then begin L := TStringList.Create; try for i:=0 to gpsList.Count-1 do if gpsList[i] is TGpsPoint then with TGpsPoint(gpsList[i]) do L.Add(Format('%s (%s / %s)', [ Name, LatToStr(Lat, USE_DMS), LonToStr(Lon, USE_DMS) ])); GPSPointInfo.Caption := L.Text; finally L.Free; end; end else GPSPointInfo.Caption := ''; finally gpsList.Free; end; end; procedure TMainForm.MapViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var rPt: TRealPoint; gpsPt: TGpsPoint; gpsName: String; begin if (Button = mbRight) then begin if not InputQuery('Name of GPS location', 'Please enter name', gpsName) then exit; rPt := MapView.ScreenToLonLat(Point(X, Y)); gpsPt := TGpsPoint.CreateFrom(rPt); gpsPt.Name := gpsName; MapView.GpsItems.Add(gpsPt, _CLICKED_POINTS_); end; end; procedure TMainForm.MapViewZoomChange(Sender: TObject); begin ZoomTrackbar.Position := MapView.Zoom; end; procedure TMainForm.ReadFromIni; var ini: TCustomIniFile; List: TStringList; L, T, W, H: Integer; R: TRect; i: Integer; s: String; pt: TRealPoint; du: TDistanceUnits; begin ini := TMemIniFile.Create(CalcIniName); try HERE_AppID := ini.ReadString('HERE', 'APP_ID', ''); HERE_AppCode := ini.ReadString('HERE', 'APP_CODE', ''); OpenWeatherMap_ApiKey := ini.ReadString('OpenWeatherMap', 'API_Key', ''); if ((HERE_AppID <> '') and (HERE_AppCode <> '')) or (OpenWeatherMap_ApiKey <> '') then begin MapView.Engine.ClearMapProviders; MapView.Engine.RegisterProviders; MapView.GetMapProviders(CbProviders.Items); end; R := Screen.DesktopRect; L := ini.ReadInteger('MainForm', 'Left', Left); T := ini.ReadInteger('MainForm', 'Top', Top); W := ini.ReadInteger('MainForm', 'Width', Width); H := ini.ReadInteger('MainForm', 'Height', Height); if L + W > R.Right then L := R.Right - W; if L < R.Left then L := R.Left; if T + H > R.Bottom then T := R.Bottom - H; if T < R.Top then T := R.Top; SetBounds(L, T, W, H); s := ini.ReadString('MapView', 'Provider', MapView.MapProvider); if CbProviders.Items.IndexOf(s) = -1 then begin MessageDlg('Map provider "' + s + '" not found.', mtError, [mbOK], 0); s := CbProviders.Items[0]; end; MapView.MapProvider := s; CbProviders.Text := MapView.MapProvider; MapView.Zoom := ini.ReadInteger('MapView', 'Zoom', MapView.Zoom); pt.Lon := StrToFloatDef(ini.ReadString('MapView', 'Center.Longitude', ''), 0.0, PointFormatSettings); pt.Lat := StrToFloatDef(ini.ReadString('MapView', 'Center.Latitude', ''), 0.0, PointFormatSettings); MapView.Center := pt; s := ini.ReadString('MapView', 'DistanceUnits', ''); if s <> '' then begin for du in TDistanceUnits do if DistanceUnit_Names[du] = s then begin DistanceUnit := du; CbDistanceUnits.ItemIndex := ord(du); break; end; end; List := TStringList.Create; try ini.ReadSection('Locations', List); for i:=0 to List.Count-1 do begin s := ini.ReadString('Locations', List[i], ''); if s <> '' then CbLocations.Items.Add(s); end; finally List.Free; end; finally ini.Free; end; end; procedure TMainForm.UpdateCoords(X, Y: Integer); var rPt: TRealPoint; begin rPt := MapView.Center; InfoCenterLongitude.Caption := LonToStr(rPt.Lon, USE_DMS); InfoCenterLatitude.Caption := LatToStr(rPt.Lat, USE_DMS); if (X <> MaxInt) and (Y <> MaxInt) then begin rPt := MapView.ScreenToLonLat(Point(X, Y)); InfoPositionLongitude.Caption := LonToStr(rPt.Lon, USE_DMS); InfoPositionLatitude.Caption := LatToStr(rPt.Lat, USE_DMS); end else begin InfoPositionLongitude.Caption := '-'; InfoPositionLatitude.Caption := '-'; end; end; procedure TMainForm.UpdateDropdownWidth(ACombobox: TCombobox); var cnv: TControlCanvas; i, w: Integer; s: String; P: TLocationParam; begin w := 0; cnv := TControlCanvas.Create; try cnv.Control := ACombobox; cnv.Font.Assign(ACombobox.Font); for i:=0 to ACombobox.Items.Count-1 do begin cnv.Font.Style := [fsBold]; s := ACombobox.Items.Strings[i]; w := Max(w, cnv.TextWidth(s)); P := TLocationParam(ACombobox.Items.Objects[i]); cnv.Font.Style := []; w := Max(w, cnv.TextWidth(P.Descr)); end; ACombobox.ItemWidth := w + 16; ACombobox.ItemHeight := 2 * cnv.TextHeight('Tg') + 6; finally cnv.Free; end; end; procedure TMainForm.UpdateLocationHistory(ALocation: String); var idx: Integer; begin idx := CbLocations.Items.IndexOf(ALocation); if idx <> -1 then CbLocations.Items.Delete(idx); CbLocations.Items.Insert(0, ALocation); while CbLocations.Items.Count > MAX_LOCATIONS_HISTORY do CbLocations.Items.Delete(Cblocations.items.Count-1); CbLocations.Text := ALocation; end; procedure TMainForm.UpdateViewportSize; begin InfoViewportWidth.Caption := Format('%.2n %s', [ CalcGeoDistance( MapView.GetVisibleArea.TopLeft.Lat, MapView.GetVisibleArea.TopLeft.Lon, MapView.GetVisibleArea.TopLeft.Lat, MapView.GetVisibleArea.BottomRight.Lon, DistanceUnit ), DistanceUnit_Names[DistanceUnit] ]); InfoViewportHeight.Caption := Format('%.2n %s', [ CalcGeoDistance( MapView.GetVisibleArea.TopLeft.Lat, MapView.GetVisibleArea.TopLeft.Lon, MapView.GetVisibleArea.BottomRight.Lat, MapView.GetVisibleArea.TopLeft.Lon, DistanceUnit ), DistanceUnit_Names[DistanceUnit] ]); end; procedure TMainForm.WriteToIni; var ini: TCustomIniFile; L: TStringList; i: Integer; begin ini := TMemIniFile.Create(CalcIniName); try ini.WriteInteger('MainForm', 'Left', Left); ini.WriteInteger('MainForm', 'Top', Top); ini.WriteInteger('MainForm', 'Width', Width); ini.WriteInteger('MainForm', 'Height', Height); ini.WriteString('MapView', 'Provider', MapView.MapProvider); ini.WriteInteger('MapView', 'Zoom', MapView.Zoom); ini.WriteString('MapView', 'Center.Longitude', FloatToStr(MapView.Center.Lon, PointFormatSettings)); ini.WriteString('MapView', 'Center.Latitude', FloatToStr(MapView.Center.Lat, PointFormatSettings)); ini.WriteString('MapView', 'DistanceUnits', DistanceUnit_Names[DistanceUnit]); if HERE_AppID <> '' then ini.WriteString('HERE', 'APP_ID', HERE_AppID); if HERE_AppCode <> '' then ini.WriteString('HERE', 'APP_CODE', HERE_AppCode); if OpenWeatherMap_ApiKey <> '' then ini.WriteString('OpenWeatherMap', 'API_Key', OpenWeatherMap_ApiKey); ini.EraseSection('Locations'); for i := 0 to CbLocations.Items.Count-1 do ini.WriteString('Locations', 'Item'+IntToStr(i), CbLocations.Items[i]); finally ini.Free; end; end; procedure TMainForm.ZoomTrackBarChange(Sender: TObject); begin MapView.Zoom := ZoomTrackBar.Position; LblZoom.Caption := Format('Zoom (%d):', [ZoomTrackbar.Position]); end; initialization PointFormatSettings.DecimalSeparator := '.'; end.
unit p2jsres; {$mode objfpc} {$h+} {$modeswitch externalclass} {$define SkipAsync} interface uses types; Type TResourceSource = (rsJS,rsHTML); TResourceInfo = record name : string; encoding : string; resourceunit : string; format : string; data : string; end; TResourceEnumCallBack = Reference to function(const resName : string) : boolean; TResourcesLoadedEnumCallBack = Reference to Procedure(const LoadedResources : Array of String); TResourcesLoadErrorCallBack = Reference to Procedure(const aError : string); Function SetResourceSource(aSource : TResourceSource) : TResourceSource; Function GetResourceNames : TStringDynArray; Function GetResourceNames(aSource : TResourceSource) : TStringDynArray; Function EnumResources(aCallback : TResourceEnumCallBack) : Integer; Function EnumResources(aSource : TResourceSource; aCallback : TResourceEnumCallBack) : Integer; Function GetResourceInfo(Const aName : String; var aInfo : TResourceInfo) : Boolean; Function GetResourceInfo(aSource : TResourceSource; Const aName : String; var aInfo : TResourceInfo) : Boolean; Procedure LoadHTMLLinkResources(const aURL : String; OnLoad : TResourcesLoadedEnumCallBack = Nil; OnError : TResourcesLoadErrorCallBack = Nil); implementation uses sysutils, js, web; type TJSHTMLTemplateElement = class external name 'HTMLTemplateElement' (TJSHTMLElement) content : TJSHTMLElement; end; TJSReadableStream = class external name 'ReadableStream' (TJSObject) private flocked: Boolean; external name 'locked'; public property locked: Boolean read flocked; constructor new(underlyingSource: TJSObject); constructor new(underlyingSource, queueingStrategy: TJSObject); function cancel(reason: TJSDOMString): TJSPromise; function getReader(): TJSObject; overload; function getReader(mode: TJSObject): TJSObject; overload; function pipeThrough(transformStream: TJSObject): TJSReadableStream; overload; function pipeThrough(transformStream, options: TJSObject): TJSReadableStream; overload; function pipeTo(destination: TJSObject): TJSPromise; overload; function pipeTo(destination, options: TJSObject): TJSPromise; overload; function tee(): TJSArray; // array containing two TJSReadableStream instances end; TJSBody = class external name 'Body' (TJSObject) private fbody: TJSReadableStream; external name 'body'; fbodyUsed: Boolean; external name 'bodyUsed'; public property body: TJSReadableStream read fbody; property bodyUsed: Boolean read fbodyUsed; function arrayBuffer(): TJSPromise; // resolves to TJSArrayBuffer //function blob(): TJSPromise; // resolves to TJSBlob function blob: TJSBlob; {$IFNDEF SkipAsync}async;{$ENDIF} function json(): TJSPromise; // resolves to JSON / TJSValue //function text(): TJSPromise; // resolves to USVString, always decoded using UTF-8 function text(): string; {$IFNDEF SkipAsync}async;{$ENDIF} end; TJSResponse = class external name 'Response' (TJSBody) private fheaders: TJSObject;external name 'headers'; fok: Boolean; external name 'ok'; fredirected: Boolean; external name 'redirected'; fstatus: NativeInt; external name 'status'; fstatusText: String; external name 'statusText'; ftype: String; external name 'type'; furl: String; external name 'url'; fuseFinalUrl: Boolean; external name 'useFinalUrl'; public property headers: TJSObject read fheaders; // property ok: Boolean read fok; property redirected: Boolean read fredirected; property status: NativeInt read fstatus; property statusText: String read fstatusText; // property type_: String read ftype; // property url: String read furl; // property useFinalUrl: Boolean read fuseFinalUrl write fuseFinalUrl; constructor new(body: TJSObject; init: TJSObject); varargs; external name 'new'; function clone(): TJSResponse; function error(): TJSResponse; function redirect(url: String; Status: NativeInt): TJSResponse; end; TJSDOMSettableTokenList = class external name 'DOMSettableTokenList' (TJSDOMTokenList) private fvalue: TJSDOMString; external name 'value'; public property value: TJSDOMString read fvalue; // readonly end; TJSHTMLOutputElement = class external name 'HTMLOutputElement' (TJSHTMLElement) private flabels: TJSNodeList; external name 'labels'; fform: TJSHTMLFormElement; external name 'form'; ftype: TJSDOMString; external name 'type'; fdefaultValue: TJSDOMString; external name 'defaultValue'; fvalue: TJSDOMString; external name 'value'; fwillValidate: Boolean; external name 'willValidate'; fvalidity: TJSValidityState; external name 'validity'; fvalidationMessage: TJSDOMString; external name 'validationMessage'; public htmlFor: TJSDOMSettableTokenList; function checkValidity: Boolean; function reportValidity: Boolean; procedure setCustomValidity(error: TJSDOMString); public property labels: TJSNodeList read flabels; property form: TJSHTMLFormElement read fform; property type_: TJSDOMString read ftype; property defaultValue: TJSDOMString read fdefaultValue; property value: TJSDOMString read fvalue write fvalue; property willValidate: Boolean read fwillValidate; property validity: TJSValidityState read fvalidity; property validationMessage: TJSDOMString read fvalidationMessage; end; TJSHTMLLinkElement = class external name 'HTMLLinkElement'(TJSHTMLElement) Private frelList: TJSDOMTokenList; external name 'relList'; fsizes: TJSDOMSettableTokenList {TJSDOMTokenList}; external name 'sizes'; Public href: string; crossOrigin: string; rel: string; as_: string; external name 'as'; media: string; integrity: string; hreflang: string; type_: string external name 'type'; imageSrcset: string; imageSizes: string; referrerPolicy: string; disabled: string; charset: string deprecated; // obsolete rev: string deprecated; // obsolete property target: string deprecated; // obsolete property Property relList: TJSDOMTokenList read frelList; Property sizes: TJSDOMSettableTokenList{TJSDOMTokenList} read fsizes; end; var gMode: TResourceSource; { --------------------------------------------------------------------- Global entry points ---------------------------------------------------------------------} Function SeTResourceSource(aSource : TResourceSource) : TResourceSource; begin Result:=gMode; gMode:=aSource; end; Function GetResourceNames : TStringDynArray; begin Result:=GetResourceNames(gMode); end; Function EnumResources(aCallback : TResourceEnumCallBack) : Integer; begin Result:=EnumResources(gMode,aCallback); end; Function GetResourceInfo(Const aName : String; var aInfo : TResourceInfo) : Boolean; begin Result:=GetResourceInfo(gMode,aName,aInfo); end; { --------------------------------------------------------------------- JS resources ---------------------------------------------------------------------} Type TRTLResourceInfo = class external name 'Object' (TJSObject) name : string; encoding : string; resourceunit : string; external name 'unit'; format : string; data : string; end; function rtlGetResourceList : TStringDynArray; external name 'rtl.getResourceList'; function rtlGetResource(const aName : string) : TRTLResourceInfo; external name 'rtl.getResource'; Function GetRTLResourceInfo(Const aName : String; var aInfo : TResourceInfo) : Boolean; Var RTLInfo : TRTLResourceInfo; begin RTLInfo:=rtlGetResource(lowercase(aName)); Result:=Assigned(RTLInfo); if Result then begin aInfo.name:=RTLinfo.name; aInfo.encoding:=RTLinfo.encoding; aInfo.format:=RTLinfo.format; aInfo.resourceunit:=RTLinfo.resourceunit; aInfo.data:=RTLinfo.data; end; end; { --------------------------------------------------------------------- HTML resources ---------------------------------------------------------------------} Const IDPrefix = 'resource-'; Function IsResourceLink(L : TJSHTMLLinkElement) : Boolean; begin Result:=(Copy(L.id,1,Length(IDPrefix))=IDPrefix) and (isDefined(L.Dataset['unit'])) and (Copy(L.href,1,4)='data') end; Function GetHTMLResources : TStringDynArray; Var LC : TJSHTMLCollection; L : TJSHTMLLinkElement; I : Integer; ID : String; begin SetLength(Result,0); if not isDefined(document) then // If called in Node... exit; // No cache, we do this dynamically: it's possible to add link nodes at runtime. LC:=document.getElementsByTagName('link'); For I:=0 to LC.length-1 do begin L:=TJSHTMLLinkElement(LC[i]); ID:=L.ID; if IsResourceLink(L) then begin Delete(ID,1,Length(IDPrefix)); if (ID<>'') then TJSArray(Result).Push(ID); end; end; end; Function GetHTMLResourceInfo(Const aName : String; var aInfo : TResourceInfo) : Boolean; Var el : TJSElement; L : TJSHTMLLinkElement absolute el; S : String; I : Integer; begin Result:=False; if not isDefined(document) then // If called in Node... exit; El:=document.getElementByID(IDPrefix+lowercase(aName)); Result:=assigned(el) and SameText(el.tagName,'link'); if not Result then exit; ainfo.name:=lowercase(aName); ainfo.Resourceunit:=String(L.Dataset['unit']); S:=L.href; S:=Copy(S,6,Length(S)-5); // strip data; I:=Pos(',',S); aInfo.data:=Copy(S,I+1,Length(S)-1); S:=copy(S,1,I-1); I:=Pos(';',S); if I=0 then aInfo.encoding:='' else begin aInfo.encoding:=Copy(S,I+1,Length(S)-1); S:=Copy(S,1,I-1); end; aInfo.Format:=S; end; Function HasTemplate : Boolean; begin asm return ('content' in document.createElement('template')) end; end; Procedure LoadHTMLLinkResources(const aURL : String; OnLoad : TResourcesLoadedEnumCallBack = Nil; OnError : TResourcesLoadErrorCallBack = Nil); function FetchOK(Res : JSValue) : JSValue; var Response : TJSResponse absolute res; begin Result:=Nil; if not Response.ok then begin if Assigned(OnError) then Raise TJSError.New('HTTP Error for URL aURL, status = '+IntToStr(Response.status)+' : '+Response.statusText) end else Result:=Response.Text(); end; function BlobOK(Res : JSValue) : JSValue; Var aText : String absolute res; ID : String; Tmpl : TJSHTMLTemplateElement; El : TJSHTMLElement; L : TJSHTMLLinkElement absolute El; Arr : TStringDynArray; aParent : TJSHTMLElement; begin Result:=Nil; aParent:=TJSHTMLElement(document.head); if aParent=Nil then aParent:=TJSHTMLElement(document.body); SetLength(Arr,0); Tmpl:=TJSHTMLTemplateElement(Document.createElement('template')); Tmpl.innerhtml:=TJSString(aText).trim; el:=TJSHTMLElement(Tmpl.Content.firstElementChild); While El<>Nil do begin if SameText(El.tagName,'link') and IsResourceLink(L) then begin aParent.Append(TJSHTMLElement(document.importNode(l,true))); ID:=L.ID; Delete(ID,1,Length(IDPrefix)); if (ID<>'') then TJSArray(Arr).Push(ID); end; el:=TJSHTMLElement(el.nextElementSibling); end; if Assigned(OnLoad) then OnLoad(Arr); end; function DoError (aValue : JSValue) : JSValue; Var aErr : TJSError absolute aValue; begin Result:=Nil; if Assigned(OnError) then if aErr=Nil then OnError('Error: ' + aErr.message) end; begin if not HasTemplate then begin if Assigned(OnError) then OnError('No template support in this browser') end // else window.fetch(aURL)._then(@FetchOK)._then(@BlobOK).catch(@doError); end; { --------------------------------------------------------------------- Global entries, specifying resource mode ---------------------------------------------------------------------} Function GetResourceNames(aSource : TResourceSource) : TStringDynArray; begin case aSource of rsJS : Result:=rtlGetResourceList; rsHTML : Result:=GetHTMLResources; end; end; Function EnumResources(aSource : TResourceSource; aCallback : TResourceEnumCallBack) : Integer; Var RL : TStringDynArray; I : Integer; ContinueEnum : Boolean; begin Result:=0; RL:=GetResourceNames(aSource); I:=0; Result:=Length(RL); ContinueEnum:=True; While (I<Result) and ContinueEnum do begin ContinueEnum:=aCallBack(RL[i]); Inc(I); end; end; Function GetResourceInfo(aSource : TResourceSource; Const aName : String; var aInfo : TResourceInfo) : Boolean; begin case aSource of rsJS : Result:=GetRTLResourceInfo(aName,aInfo); rsHTML : Result:=GetHTMLResourceInfo(aName,aInfo); end; end; end.
unit uVTVDisableAutoScroll; interface procedure Register; implementation uses System.TypInfo, VCL.Controls, VCL.Forms; const AllowResetFonts = True; function Append(const Left, Delim, Right: string): string; begin if Left = '' then Result := Right else if Right = '' then Result := Left else Result := Left + Delim + Right; end; function IncludeS(var SetValue: string; const EnumValue: string): Boolean; begin Result := Pos(EnumValue, SetValue) = 0; if Result then SetValue := Append(SetValue, ',', EnumValue); end; procedure PatchVST(Control: TControl); const STreeOptions = 'TreeOptions'; SAutoOptions = 'AutoOptions'; SDisableAutoscrollOnFocus = 'toDisableAutoscrollOnFocus'; var o: TObject; s: string; begin // simulate Control.TreeOptions.AutoOptions := Control.TreeOptions.AutoOptions + [toDisableAutoscrollOnFocus]; o := GetObjectProp(Control, STreeOptions); s := GetSetProp(o, SAutoOptions); if IncludeS(s, SDisableAutoscrollOnFocus) then SetSetProp(o, SAutoOptions, s); end; procedure Register; var F: TForm; C: TControl; I: Integer; J: Integer; begin for I := 0 to Screen.CustomFormCount - 1 do begin F := TForm(Screen.CustomForms[I]); if AllowResetFonts then F.ParentFont := True; for J := 0 to F.ControlCount - 1 do begin C := F.Controls[J]; if AllowResetFonts then TForm(C).ParentFont := True; if C.ClassNameIs('TVirtualStringTree') or C.ClassNameIs('TRefactoringTree') then PatchVST(Screen.CustomForms[I].Controls[J]); end; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLCelShader<p> A shader that applies cel shading through a vertex program and shade definition texture.<p> <b>History : </b><font size=-1><ul> <li>23/08/10 - Yar - Upgraded program handles <li>22/04/10 - Yar - Fixes after GLState revision <li>05/03/10 - DanB - More state added to TGLStateCache <li>22/01/10 - Yar - Added bmp32.Blank:=false for memory allocation <li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) <li>31/03/07 - DaStr - Added $I GLScene.inc <li>21/03/07 - DaStr - Added explicit pointer dereferencing (thanks Burkhard Carstens) (Bugtracker ID = 1678644) <li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas <li>28/09/04 - SG - Vertex program now uses ARB_position_invariant option. <li>09/06/04 - SG - Added OutlineColor, vertex programs now use GL state. <li>28/05/04 - SG - Creation. </ul></font> } unit GLCelShader; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, //GLS GLTexture, GLContext, GLGraphics, GLUtils, GLVectorGeometry, OpenGLTokens, GLColor, GLRenderContextInfo, GLMaterial, GLState, GLTextureFormat; type // TGLCelShaderOption // {: Cel shading options.<p> csoOutlines: Render a second outline pass. csoTextured: Allows for a primary texture that the cel shading is modulated with and forces the shade definition to render as a second texture. } TGLCelShaderOption = (csoOutlines, csoTextured, csoNoBuildShadeTexture); TGLCelShaderOptions = set of TGLCelShaderOption; // TGLCelShaderGetIntensity // //: An event for user defined cel intensity. TGLCelShaderGetIntensity = procedure(Sender: TObject; var intensity: Byte) of object; // TGLCelShader // {: A generic cel shader.<p> } TGLCelShader = class(TGLShader) private FOutlineWidth: Single; FCelShaderOptions: TGLCelShaderOptions; FVPHandle: TGLARBVertexProgramHandle; FShadeTexture: TGLTexture; FOnGetIntensity: TGLCelShaderGetIntensity; FOutlinePass, FUnApplyShadeTexture: Boolean; FOutlineColor: TGLColor; protected procedure SetCelShaderOptions(const val: TGLCelShaderOptions); procedure SetOutlineWidth(const val: Single); procedure SetOutlineColor(const val: TGLColor); procedure BuildShadeTexture; procedure Loaded; override; function GenerateVertexProgram: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TRenderContextInfo): Boolean; override; property ShadeTexture: TGLTexture read FShadeTexture; published property CelShaderOptions: TGLCelShaderOptions read FCelShaderOptions write SetCelShaderOptions; property OutlineColor: TGLColor read FOutlineColor write SetOutlineColor; property OutlineWidth: Single read FOutlineWidth write SetOutlineWidth; property OnGetIntensity: TGLCelShaderGetIntensity read FOnGetIntensity write FOnGetIntensity; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------ // ------------------ TGLCelShader ------------------ // ------------------ // Create // constructor TGLCelShader.Create(AOwner: TComponent); begin inherited; FOutlineWidth := 3; FCelShaderOptions := [csoOutlines]; FShadeTexture := TGLTexture.Create(Self); with FShadeTexture do begin Enabled := True; MinFilter := miNearest; MagFilter := maNearest; TextureWrap := twNone; TextureMode := tmModulate; end; FOutlineColor := TGLColor.Create(Self); FOutlineColor.OnNotifyChange := NotifyChange; FOutlineColor.Initialize(clrBlack); ShaderStyle := ssLowLevel; FVPHandle := TGLARBVertexProgramHandle.Create; end; // Destroy // destructor TGLCelShader.Destroy; begin FVPHandle.Free; FShadeTexture.Free; FOutlineColor.Free; inherited; end; // Loaded // procedure TGLCelShader.Loaded; begin inherited; BuildShadeTexture; end; // BuildShadeTexture // procedure TGLCelShader.BuildShadeTexture; var bmp32: TGLBitmap32; i: Integer; intensity: Byte; begin if csoNoBuildShadeTexture in FCelShaderOptions then exit; with FShadeTexture do begin ImageClassName := 'TGLBlankImage'; TGLBlankImage(Image).Width := 128; TGLBlankImage(Image).Height := 2; end; bmp32 := FShadeTexture.Image.GetBitmap32; bmp32.Blank := false; for i := 0 to bmp32.Width - 1 do begin intensity := i * (256 div bmp32.Width); if Assigned(FOnGetIntensity) then FOnGetIntensity(Self, intensity) else begin if intensity > 230 then intensity := 255 else if intensity > 150 then intensity := 230 else if intensity > 100 then intensity := intensity + 50 else intensity := 150; end; bmp32.Data^[i].r := intensity; bmp32.Data^[i].g := intensity; bmp32.Data^[i].b := intensity; bmp32.Data^[i].a := 1; bmp32.Data^[i + bmp32.Width] := bmp32.Data^[i]; end; end; // GenerateVertexProgram // function TGLCelShader.GenerateVertexProgram: string; var VP: TStringList; begin VP := TStringList.Create; VP.Add('!!ARBvp1.0'); VP.Add('OPTION ARB_position_invariant;'); VP.Add('PARAM mvinv[4] = { state.matrix.modelview.inverse };'); VP.Add('PARAM lightPos = program.local[0];'); VP.Add('TEMP temp, light, normal;'); VP.Add(' DP4 light.x, mvinv[0], lightPos;'); VP.Add(' DP4 light.y, mvinv[1], lightPos;'); VP.Add(' DP4 light.z, mvinv[2], lightPos;'); VP.Add(' ADD light, light, -vertex.position;'); VP.Add(' DP3 temp.x, light, light;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL light, temp.x, light;'); VP.Add(' DP3 temp, vertex.normal, vertex.normal;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL normal, temp.x, vertex.normal;'); VP.Add(' MOV result.color, state.material.diffuse;'); if csoTextured in FCelShaderOptions then begin VP.Add(' MOV result.texcoord[0], vertex.texcoord[0];'); VP.Add(' DP3 result.texcoord[1].x, normal, light;'); end else begin VP.Add(' DP3 result.texcoord[0].x, normal, light;'); end; VP.Add('END'); Result := VP.Text; VP.Free; end; // DoApply // procedure TGLCelShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); var light: TVector; begin if (csDesigning in ComponentState) then exit; FVPHandle.AllocateHandle; if FVPHandle.IsDataNeedUpdate then begin FVPHandle.LoadARBProgram(GenerateVertexProgram); Enabled := FVPHandle.Ready; FVPHandle.NotifyDataUpdated; if not Enabled then Abort; end; rci.GLStates.Disable(stLighting); GL.GetLightfv(GL_LIGHT0, GL_POSITION, @light.V[0]); FVPHandle.Enable; FVPHandle.Bind; GL.ProgramLocalParameter4fv(GL_VERTEX_PROGRAM_ARB, 0, @light.V[0]); if (csoTextured in FCelShaderOptions) then FShadeTexture.ApplyAsTexture2(rci, nil) else FShadeTexture.Apply(rci); FOutlinePass := csoOutlines in FCelShaderOptions; FUnApplyShadeTexture := True; end; // DoUnApply // function TGLCelShader.DoUnApply(var rci: TRenderContextInfo): Boolean; begin Result := False; if (csDesigning in ComponentState) then exit; FVPHandle.Disable; if FUnApplyShadeTexture then begin if (csoTextured in FCelShaderOptions) then FShadeTexture.UnApplyAsTexture2(rci, false) else FShadeTexture.UnApply(rci); FUnApplyShadeTexture := False; end; if FOutlinePass then with rci.GLStates do begin ActiveTexture := 0; ActiveTextureEnabled[ttTexture2D] := False; Enable(stBlend); Enable(stLineSmooth); Disable(stLineStipple); Enable(stCullFace); PolygonMode := pmLines; LineWidth := FOutlineWidth; CullFaceMode := cmFront; LineSmoothHint := hintNicest; SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha); DepthFunc := cfLEqual; GL.Color4fv(FOutlineColor.AsAddress); Result := True; FOutlinePass := False; Exit; end else with rci.GLStates do begin rci.GLStates.PolygonMode := pmFill; rci.GLStates.CullFaceMode := cmBack; rci.GLStates.DepthFunc := cfLEqual; end; end; // SetCelShaderOptions // procedure TGLCelShader.SetCelShaderOptions(const val: TGLCelShaderOptions); begin if val <> FCelShaderOptions then begin FCelShaderOptions := val; BuildShadeTexture; FVPHandle.NotifyChangesOfData; NotifyChange(Self); end; end; // SetOutlineWidth // procedure TGLCelShader.SetOutlineWidth(const val: Single); begin if val <> FOutlineWidth then begin FOutlineWidth := val; NotifyChange(Self); end; end; // SetOutlineColor // procedure TGLCelShader.SetOutlineColor(const val: TGLColor); begin if val <> FOutlineColor then begin FOutlineColor.Assign(val); NotifyChange(Self); end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.8 9/30/2004 5:04:20 PM BGooijen Self was not initialized Rev 1.7 01/06/2004 00:28:46 CCostelloe Minor bug fix Rev 1.6 5/30/04 11:29:36 PM RLebeau Added OwnerMessage property to TIdMessageParts for use with TIdMessagePart.ResolveContentType() under Delphi versions prior to v6, where the TCollection.Owner method does not exist. Rev 1.5 16/05/2004 18:55:46 CCostelloe New TIdText/TIdAttachment processing Rev 1.4 2004.02.03 5:44:06 PM czhower Name changes Rev 1.3 10/17/03 12:06:04 PM RLebeau Updated TIdMessagePart.Assign() to copy all available header values rather than select ones. Rev 1.2 10/17/2003 12:43:12 AM DSiders Added localization comments. Rev 1.1 26/09/2003 01:07:18 CCostelloe Added FParentPart, so that nested MIME types (like multipart/alternative nested in multipart/related and vica-versa) can be encoded and decoded (when encoding, need to know this so the correct boundary is emitted) and so the user can properly define which parts belong to which sections. Rev 1.0 11/13/2002 07:57:32 AM JPMugaas 24-Sep-2003 Ciaran Costelloe - Added FParentPart, so that nested MIME types (like multipart/alternative nested in multipart/related and vica-versa) can be encoded and decoded (when encoding, need to know this so the correct boundary is emitted) and so the user can properly define which parts belong to which sections. 2002-08-30 Andrew P.Rybin - ExtractHeaderSubItem - virtual methods. Now descendant can add functionality. Ex: TIdText.GetContentType = GetContentType w/o charset } unit IdMessageParts; interface {$i IdCompilerDefines.inc} uses Classes, IdHeaderList, IdExceptionCore, IdGlobal; type TOnGetMessagePartStream = procedure(AStream: TStream) of object; TIdMessagePartType = (mptText, mptAttachment); // if you add to this, please also adjust the case statement in // TIdMessageParts.CountParts; TIdMessageParts = class; TIdMessagePart = class(TCollectionItem) protected FContentMD5: string; FCharSet: string; FEndBoundary: string; FExtraHeaders: TIdHeaderList; FFileName: String; FName: String; FHeaders: TIdHeaderList; FIsEncoded: Boolean; FOnGetMessagePartStream: TOnGetMessagePartStream; FParentPart: Integer; // function GetContentDisposition: string; virtual; function GetContentType: string; virtual; function GetContentTransfer: string; virtual; function GetContentID: string; virtual; function GetContentLocation: string; virtual; function GetContentDescription: string; virtual; function GetMessageParts: TIdMessageParts; function GetOwnerMessage: TPersistent; procedure SetContentDisposition(const Value: string); virtual; procedure SetContentType(const Value: string); virtual; procedure SetContentTransfer(const Value: string); virtual; procedure SetExtraHeaders(const Value: TIdHeaderList); procedure SetContentID(const Value: string); virtual; procedure SetContentDescription(const Value: string); virtual; procedure SetContentLocation(const Value: string); virtual; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function GetCharSet(AHeader: string): String; function ResolveContentType(AContentType: string): string; //Fixes up ContentType class function PartType: TIdMessagePartType; virtual; // property IsEncoded: Boolean read FIsEncoded; property MessageParts: TIdMessageParts read GetMessageParts; property OwnerMessage: TPersistent read GetOwnerMessage; property OnGetMessagePartStream: TOnGetMessagePartStream read FOnGetMessagePartStream write FOnGetMessagePartStream; property Headers: TIdHeaderList read FHeaders; published property CharSet: string read FCharSet write FCharSet; property ContentDescription: string read GetContentDescription write SetContentDescription; property ContentDisposition: string read GetContentDisposition write SetContentDisposition; property ContentID: string read GetContentID write SetContentID; property ContentLocation: string read GetContentLocation write SetContentLocation; property ContentTransfer: string read GetContentTransfer write SetContentTransfer; property ContentType: string read GetContentType write SetContentType; property ExtraHeaders: TIdHeaderList read FExtraHeaders write SetExtraHeaders; property FileName: String read FFileName write FFileName; property Name: String read FName write FName; property ParentPart: integer read FParentPart write FParentPart; end; TIdMessagePartClass = class of TIdMessagePart; TIdMessageParts = class(TOwnedCollection) protected FAttachmentEncoding: string; FAttachmentCount: integer; FMessageEncoderInfo: TObject; FRelatedPartCount: integer; FTextPartCount: integer; // function GetItem(Index: Integer): TIdMessagePart; function GetOwnerMessage: TPersistent; procedure SetAttachmentEncoding(const AValue: string); procedure SetItem(Index: Integer; const Value: TIdMessagePart); public function Add: TIdMessagePart; procedure CountParts; constructor Create(AOwner: TPersistent); reintroduce; // property AttachmentCount: integer read FAttachmentCount; property AttachmentEncoding: string read FAttachmentEncoding write SetAttachmentEncoding; property Items[Index: Integer]: TIdMessagePart read GetItem write SetItem; default; property MessageEncoderInfo: TObject read FMessageEncoderInfo; property OwnerMessage: TPersistent read GetOwnerMessage; property RelatedPartCount: integer read FRelatedPartCount; property TextPartCount: integer read FTextPartCount; end; EIdCanNotCreateMessagePart = class(EIdMessageException); implementation uses IdMessage, IdGlobalProtocols, IdResourceStringsProtocols, IdMessageCoder, IdCoderHeader, SysUtils; { TIdMessagePart } procedure TIdMessagePart.Assign(Source: TPersistent); var mp: TIdMessagePart; begin if Source is TIdMessagePart then begin mp := TIdMessagePart(Source); // RLebeau 10/17/2003 Headers.Assign(mp.Headers); ExtraHeaders.Assign(mp.ExtraHeaders); CharSet := mp.CharSet; FileName := mp.FileName; Name := mp.Name; end else begin inherited Assign(Source); end; end; constructor TIdMessagePart.Create(Collection: TCollection); begin inherited; if ClassType = TIdMessagePart then begin raise EIdCanNotCreateMessagePart.Create(RSTIdMessagePartCreate); end; FIsEncoded := False; FHeaders := TIdHeaderList.Create(QuoteRFC822); FExtraHeaders := TIdHeaderList.Create(QuoteRFC822); FParentPart := -1; end; destructor TIdMessagePart.Destroy; begin FHeaders.Free; FExtraHeaders.Free; inherited Destroy; end; function TIdMessagePart.GetContentDisposition: string; begin Result := Headers.Values['Content-Disposition']; {do not localize} end; function TIdMessagePart.GetContentID: string; begin Result := Headers.Values['Content-ID']; {do not localize} end; function TIdMessagePart.GetContentDescription: string; begin Result := Headers.Values['Content-Description']; {do not localize} end; function TIdMessagePart.GetContentLocation: string; begin Result := Headers.Values['Content-Location']; {do not localize} end; function TIdMessagePart.GetContentTransfer: string; begin Result := Headers.Values['Content-Transfer-Encoding']; {do not localize} end; function TIdMessagePart.GetCharSet(AHeader: string): String; begin Result := ExtractHeaderSubItem(AHeader, 'charset', QuoteMIME); {do not localize} end; function TIdMessagePart.ResolveContentType(AContentType: string): string; var LMsg: TIdMessage; LParts: TIdMessageParts; begin //This extracts 'text/plain' from 'text/plain; charset="xyz"; boundary="123"' //or, if '', it finds the correct default value for MIME messages. if AContentType <> '' then begin Result := AContentType; end else begin //If it is MIME, then we need to find the correct default... LParts := MessageParts; if Assigned(LParts) then begin LMsg := TIdMessage(LParts.OwnerMessage); if Assigned(LMsg) and (LMsg.Encoding = meMIME) then begin //There is an exception if we are a child of multipart/digest... if ParentPart <> -1 then begin AContentType := LParts.Items[ParentPart].Headers.Values['Content-Type']; {do not localize} if IsHeaderMediaType(AContentType, 'multipart/digest') then begin {do not localize} Result := 'message/rfc822'; {do not localize} Exit; end; end; //The default type... Result := 'text/plain'; {do not localize} Exit; end; end; Result := ''; //Default for non-MIME messages end; end; function TIdMessagePart.GetContentType: string; begin Result := Headers.Values['Content-Type']; {do not localize} end; function TIdMessagePart.GetMessageParts: TIdMessageParts; begin if Collection is TIdMessageParts then begin Result := TIdMessageParts(Collection); end else begin Result := nil; end; end; function TIdMessagePart.GetOwnerMessage: TPersistent; var LParts: TIdMessageParts; begin LParts := MessageParts; if Assigned(LParts) then begin Result := LParts.OwnerMessage; end else begin Result := nil; end; end; class function TIdMessagePart.PartType: TIdMessagePartType; begin Result := mptAttachment; end; procedure TIdMessagePart.SetContentID(const Value: string); begin Headers.Values['Content-ID'] := Value; {do not localize} end; procedure TIdMessagePart.SetContentDescription(const Value: string); begin Headers.Values['Content-Description'] := Value; {do not localize} end; procedure TIdMessagePart.SetContentDisposition(const Value: string); var LFileName: string; begin Headers.Values['Content-Disposition'] := RemoveHeaderEntry(Value, 'filename', LFileName, QuoteMIME); {do not localize} {RLebeau: override the current value only if the header specifies a new one} if LFileName <> '' then begin LFileName := DecodeHeader(LFileName); end; if LFileName <> '' then begin FFileName := LFileName; end; end; procedure TIdMessagePart.SetContentLocation(const Value: string); begin Headers.Values['Content-Location'] := Value; {do not localize} end; procedure TIdMessagePart.SetContentTransfer(const Value: string); begin Headers.Values['Content-Transfer-Encoding'] := Value; {do not localize} end; procedure TIdMessagePart.SetContentType(const Value: string); var LTmp, LCharSet, LName: string; begin LTmp := RemoveHeaderEntry(Value, 'charset', LCharSet, QuoteMIME);{do not localize} LTmp := RemoveHeaderEntry(LTmp, 'name', LName, QuoteMIME);{do not localize} Headers.Values['Content-Type'] := LTmp; {RLebeau: override the current values only if the header specifies new ones} if LCharSet <> '' then begin FCharSet := LCharSet; end; if LName <> '' then begin FName := LName; end; end; procedure TIdMessagePart.SetExtraHeaders(const Value: TIdHeaderList); begin FExtraHeaders.Assign(Value); end; { TMessageParts } function TIdMessageParts.Add: TIdMessagePart; begin // This helps prevent TIdMessagePart from being added Result := nil; end; procedure TIdMessageParts.CountParts; var i: integer; begin FAttachmentCount := 0; FRelatedPartCount := 0; FTextPartCount := 0; for i := 0 to Count - 1 do begin if Length(TIdMessagePart(Items[i]).ContentID) > 0 then begin Inc(FRelatedPartCount); end; case TIdMessagePart(Items[i]).PartType of mptText : begin Inc(FTextPartCount) end; mptAttachment: begin Inc(FAttachmentCount); end; end; end; end; constructor TIdMessageParts.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdMessagePart); // Must set prop and not variable so it will initialize it AttachmentEncoding := 'MIME'; {do not localize} end; function TIdMessageParts.GetItem(Index: Integer): TIdMessagePart; begin Result := TIdMessagePart(inherited GetItem(Index)); end; function TIdMessageParts.GetOwnerMessage: TPersistent; var LOwner: TPersistent; begin LOwner := inherited GetOwner; if LOwner is TIdMessage then begin Result := LOwner; end else begin Result := nil; end; end; procedure TIdMessageParts.SetAttachmentEncoding(const AValue: string); begin FMessageEncoderInfo := TIdMessageEncoderList.ByName(AValue); FAttachmentEncoding := AValue; end; procedure TIdMessageParts.SetItem(Index: Integer; const Value: TIdMessagePart); begin inherited SetItem(Index, Value); end; end.