text
stringlengths
14
6.51M
unit support; interface uses Classes; function Int2Str(wT: word; bSize: byte = 2): string; function PackLine(wSize: word): string; function PackStrR(stT: string; wSize: word): string; function PackStrL(stT: string; wSize: word): string; function DateTime2Str: string; function FromBCD(bT: byte): byte; function ToBCD(bT: byte): byte; procedure ErrBox(stT: string); procedure WrnBox(stT: string); procedure InfBox(stT: string); procedure Delay(MSec: longword); procedure AddInfo(stT: string); procedure AddInfoAll(stT: TStrings); procedure AddTerm(stT: string); procedure DeleteInfo(c: word); function GetColWidth: integer; function IsChecked(i: word): boolean; function GetAddress: byte; function GetPassword: string; function GetDigitalsMin: word; function GetDigitalsCount: word; implementation uses Windows, Forms, SysUtils, Graphics, main, output, get_config; function Int2Str(wT: word; bSize: byte = 2): string; begin Result := IntToStr(wT); while Length(Result) < bSize do Result := '0' + Result; end; function PackLine(wSize: word): string; begin Result := ''; while Length(Result) < wSize do Result := Result + '-'; end; function PackStrR(stT: string; wSize: word): string; begin Result := stT; while Length(Result) < wSize do Result := Result + ' '; end; function PackStrL(stT: string; wSize: word): string; begin Result := stT; while Length(Result) < wSize do Result := ' ' + Result; end; function DateTime2Str: string; begin Result := FormatDateTime('hh.mm.ss dd.mm.yyyy',Now); end; function FromBCD(bT: byte): byte; begin Result := (bT div 16)*10 + (bT mod 16); end; function ToBCD(bT: byte): byte; begin Result := (bT div 10)*16 + bT mod 10; end; procedure ErrBox(stT: string); begin try AddInfo('Ошибка: '+stT); except end; Application.MessageBox(PChar(stT + ' '), 'Ошибка', mb_Ok + mb_IconHand); end; procedure WrnBox(stT: string); begin try AddInfo('Внимание: '+stT); except end; Application.MessageBox(PChar(stT + ' '), 'Внимание', mb_Ok + mb_IconWarning); end; procedure InfBox(stT: string); begin try AddInfo('Информация: '+stT); except end; Application.MessageBox(PChar(stT + ' '), 'Информация', mb_Ok + mb_IconAsterisk); end; procedure Delay(MSec: longword); var FirstTickCount,Now: longword; begin FirstTickCount := GetTickCount; repeat Application.ProcessMessages; Now := GetTickCount; until (Now - FirstTickCount >= MSec) or (Now < FirstTickCount); end; procedure AddInfo(stT: string); begin frmMain.AddInfo(stT); end; procedure AddInfoAll(stT: TStrings); begin frmMain.AddInfoAll(stT); end; procedure AddTerm(stT: string); begin frmMain.AddTerminal(stT, clGray); end; procedure DeleteInfo(c: word); var i: byte; begin with frmMain.memInfo do begin Lines.BeginUpdate; for i := 0 to c - 1 do Lines.Delete(Lines.Count - 1); Lines.EndUpdate; end; end; function GetColWidth: integer; begin Result := frmMain.updColWidth.Position; end; function IsChecked(i: word): boolean; begin Result := frmMain.clbMain.Checked[i]; end; function GetAddress: byte; begin Result := frmMain.updAddress.Position; end; function GetPassword: string; begin Result := frmMain.medDevicePass.Text; end; function GetDigitalsMin: word; begin with frmMain do begin if chbDigitals.Checked then Result := updDigitalsMin.Position else Result := 1; end; end; function GetDigitalsCount: word; begin with frmMain do begin if chbDigitals.Checked then Result := updDigitalsCount.Position else Result := wDigitals; end; end; end.
unit AuxProcs; interface uses mstask, windows, SysUtils; function GetLocalComputerName: string; function StrToWide(p_sSource: string): LPCWSTR; function MessageFromValue(Value: Integer): string; implementation var wsBuffer: PWideChar; function GetLocalComputerName: string; var Count: Cardinal; begin Count := MAX_COMPUTERNAME_LENGTH + 1; SetLength(Result, Count); { set the length } if GetComputerName(PCHar(Result), Count) then SetLength(Result, Count) { set the exact length if it succeeded } else begin RaiseLastWin32Error; { raise exception if it failed } end; end; function StrToWide(p_sSource: string): LPCWSTR; begin result := StringToWideChar(p_sSource, wsBuffer, Length(p_sSource) + 1); end; function MessageFromValue(Value: Integer): string; begin case Value of SCHED_S_TASK_READY: Result := 'The task is ready to run at its next scheduled time.'; SCHED_S_TASK_RUNNING: Result := 'The task is currently running.'; SCHED_S_TASK_DISABLED: Result := 'The task will not run at the scheduled times because it has been disabled.'; SCHED_S_TASK_HAS_NOT_RUN: Result := 'The task has not yet run.'; SCHED_S_TASK_NO_MORE_RUNS: Result := 'There are no more runs scheduled for this task.'; SCHED_S_TASK_NOT_SCHEDULED: Result := 'One or more of the properties that are needed to run this task on a schedule have not been set.'; SCHED_S_TASK_TERMINATED: Result := 'The last run of the task was terminated by the user.'; SCHED_S_TASK_NO_VALID_TRIGGERS: Result := 'Either the task has no triggers or the existing triggers are disabled or not set.'; SCHED_S_EVENT_TRIGGER: Result := 'Event triggers dont have set run times.'; SCHED_E_TRIGGER_NOT_FOUND: Result := 'Trigger not found.'; SCHED_E_TASK_NOT_READY: Result := 'One or more of the properties that are needed to run this task have not been set.'; SCHED_E_TASK_NOT_RUNNING: Result := 'There is no running instance of the task to terminate.'; SCHED_E_SERVICE_NOT_INSTALLED: Result := 'The Task Scheduler Service is not installed on this computer.'; SCHED_E_CANNOT_OPEN_TASK: Result := 'The task object could not be opened.'; SCHED_E_INVALID_TASK: Result := 'The object is either an invalid task object or is not a task object.'; SCHED_E_ACCOUNT_INFORMATION_NOT_SET: Result := 'No account information could be found in the Task Scheduler security database for the task indicated.'; SCHED_E_ACCOUNT_NAME_NOT_FOUND: Result := 'Unable to establish existence of the account specified.'; SCHED_E_ACCOUNT_DBASE_CORRUPT: Result := 'Corruption was detected in the Task Scheduler security database; the database has been reset.'; SCHED_E_NO_SECURITY_SERVICES: Result := 'Task Scheduler security services are available only on Windows NT.'; SCHED_E_UNKNOWN_OBJECT_VERSION: Result := 'The task object version is either unsupported or invalid.'; SCHED_E_UNSUPPORTED_ACCOUNT_OPTION: Result := 'The task has been configured with an unsupported combination of account settings and run time options.'; SCHED_E_SERVICE_NOT_RUNNING: Result := 'The Task Scheduler Service is not running.'; E_INVALIDARG: Result := 'The arguments are not valid.'; E_OUTOFMEMORY: Result := 'Not enough memory is available.'; end; end; initialization GetMem(wsBuffer, 1024); finalization freeMem(wsBuffer); end.
unit uMainDM; interface uses System.SysUtils, System.Classes, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent, System.Threading, FMX.Objects; type TMainDM = class(TDataModule) NetHTTPClient1: TNetHTTPClient; NetHTTPRequest1: TNetHTTPRequest; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } aTask: ITask; bActive: boolean; public { Public declarations } function IsActive: boolean; procedure StartVideoStream(sURL: string; aImage: TImage); procedure StopVideoStream; end; implementation { %CLASSGROUP 'FMX.Controls.TControl' } {$R *.dfm} { TMainDM } procedure TMainDM.DataModuleCreate(Sender: TObject); begin bActive := False; end; procedure TMainDM.DataModuleDestroy(Sender: TObject); begin if IsActive then StopVideoStream; end; function TMainDM.IsActive: boolean; begin Result := bActive; end; procedure TMainDM.StartVideoStream(sURL: string; aImage: TImage); begin bActive := True; aTask := TTask.Create( procedure() var ResponseContent: TMemoryStream; begin ResponseContent := TMemoryStream.Create; try while aTask.Status <> TTaskStatus.Canceled do begin ResponseContent.Clear; NetHTTPClient1.Get(sURL, ResponseContent); if (ResponseContent.Size = 0) then exit else begin ResponseContent.Position := 0; TThread.Synchronize(TThread.CurrentThread, procedure begin aImage.Bitmap.LoadFromStream(ResponseContent); end); end; end; finally ResponseContent.Free; end; end); aTask.Start; end; procedure TMainDM.StopVideoStream; begin bActive := False; aTask.Cancel; end; end.
{------------------------------------------------------------------------- Copyright by Haeger + Busch, Germany / >>>>>>>>> /----- Ingenieurbuero fuer Kommunikationslösungen / <<<<<<<<< / ----------------------------------------------------/ >>>>>>>>> / Homepage : http://www.hbTapi.com EMail : info@hbTapi.com Package : hbTapi Components -------------------------------------------------------------------------} unit uMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, hbTapi, StdCtrls, hbTapiApi, ExtCtrls, hbTAPIUtils; type TForm1 = class(TForm) hbTapiLine1: ThbTapiLine; ListBox1: TListBox; GroupBox_CallInfo: TGroupBox; Label_CallerID: TLabel; Edit_CallerID: TEdit; Label_CallerIDName: TLabel; Edit_CallerIDName: TEdit; Label_CalledID: TLabel; Edit_CalledID: TEdit; Label_CalledIDName: TLabel; Edit_CalledIDName: TEdit; Label_ConnectedID: TLabel; Edit_ConnectedID: TEdit; Label_ConnectedIDName: TLabel; Edit_ConnectedIDName: TEdit; Label_RedirectionID: TLabel; Edit_RedirectionID: TEdit; Label_RedirectionIDName: TLabel; Edit_RedirectionIDName: TEdit; Label_RedirectingID: TLabel; Edit_RedirectingID: TEdit; Label_RedirectingIDName: TLabel; Edit_RedirectingIDName: TEdit; GroupBox1: TGroupBox; ComboBox_Device: TComboBox; ComboBox_Privileges: TComboBox; ComboBox_Address: TComboBox; ComboBox_MediaMode: TComboBox; LabelDevice: TLabel; Label4: TLabel; Label3: TLabel; Label1: TLabel; GroupBox2: TGroupBox; Label_PhoneNo: TLabel; Edit_PhoneNo: TEdit; Button1: TButton; Button2: TButton; Button3: TButton; procedure FormCreate(Sender: TObject); procedure ComboBox_DeviceChange(Sender: TObject); procedure hbTapiLine1CallState(Sender: ThbTapiLine; Call: ThbTapiCall; CallState: Cardinal); procedure DoMakeCall(Sender: TObject); procedure DoDropCall(Sender: TObject); procedure hbTapiLine1CallDeallocate(Sender: ThbTapiLine; Call: ThbTapiCall); procedure hbTapiLine1TapiReply(Sender: TObject; RequestID, ReplyCode: Cardinal); procedure hbTapiLine1TapiTimeout(Sender: TObject; RequestID: Cardinal); procedure DoClear(Sender: TObject); procedure ComboBox_PrivilegesChange(Sender: TObject); procedure DoAnswerCall(Sender: TObject); procedure hbTapiLine1CallInfo(Sender: ThbTapiLine; Call: ThbTapiCall; InfoState: Cardinal); procedure Edit_PhoneNoKeyPress(Sender: TObject; var Key: Char); private procedure UpdateCallInfo(Sender: ThbTapiLine; Call: ThbTapiCall; InfoState: Cardinal); public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin // Fill in the ComboBox with all available telephony line devices ComboBox_Device.Items.Assign(hbTapiLine1.DeviceList); if ComboBox_Device.Items.Count > 0 then ComboBox_Device.Items.Insert(0, '- none -') else ComboBox_Device.Items.Add('- none -'); ComboBox_Device.ItemIndex := 0; ComboBox_Privileges.ItemIndex := 0; end; procedure TForm1.ComboBox_DeviceChange(Sender: TObject); begin // If TapiLine is currently open then close it hbTapiLine1.Active := False; // Set the TapiLine.DeviceID to use the device selected in the list box hbTapiLine1.DeviceID := ComboBox_Device.ItemIndex - 1; // If there was a problem opening TapiLine last time then make sure that the // following properties are reset to their default. hbTapiLine1.Privileges.None := TRUE; if Pos('Owner', ComboBox_Privileges.Text) > 0 then hbTapiLine1.Privileges.Owner := TRUE; if Pos('Monitor', ComboBox_Privileges.Text) > 0 then hbTapiLine1.Privileges.Monitor := TRUE; if not hbTapiLine1.Available then begin ComboBox_MediaMode.Items.Clear; Combobox_Address.Items.Clear; Exit; end; // Fill in the ComboBox with all supporting media modes. LineMediaModesToStrList(hbTapiLine1.Caps.MediaModes, ComboBox_MediaMode.Items); if ComboBox_MediaMode.Items.Count > 0 then ComboBox_MediaMode.ItemIndex := 0; Combobox_Address.Items.Assign(hbTapiLine1.AddressList); if ComboBox_Address.Items.Count > 0 then ComboBox_Address.ItemIndex := 0; try hbTapiLine1.Active := True; except on E:EhbTapiError do case E.ErrorCode of LINEERR_INVALMEDIAMODE : begin try hbTapiLine1.Privileges.Owner := FALSE; hbTapiLine1.Active := True; except on E:Exception do MessageDlg('Error opening line device: ' + E.Message, mtError, [mbOk],0); end; MessageDlg('This device is not 100% TAPI compliant',mtWarning, [mbOk],0); end; else // Time for a little error checking MessageDlg('Error opening line device: ' + E.Message, mtError, [mbOk],0); end; end; end; procedure TForm1.hbTapiLine1CallState(Sender: ThbTapiLine; Call: ThbTapiCall; CallState: Cardinal); begin ListBox1.Items.Add('::OnCallState call state changed ' + Call.StateText + ' (Call=' + IntToHex(integer(Call),8) + ')'); UpdateCallInfo(Sender, Call, 0); end; procedure TForm1.DoMakeCall(Sender: TObject); begin try hbTapiLine1.CallParams.MediaMode := StrToLineMediaMode(ComboBox_MediaMode.Text); hbTapiLine1.CallParams.AddressID := ComboBox_Address.ItemIndex; hbTapiLine1.MakeCall(Edit_PhoneNo.Text); except on E:EhbTapiError do MessageDlg('MakeCall failed! ' + E.Message, mtError, [mbok], 0); end; end; procedure TForm1.DoDropCall(Sender: TObject); begin if hbTapiLine1.Calls.count > 0 then begin ListBox1.Items.Add('Calling Call.Drop...'); hbTapiLine1.Calls[0].Drop; if hbTapiLine1.options.SyncMode then ListBox1.Items.Add('Call.Drop returned') else ListBox1.Items.Add('Drop returned. LastRequestID = 0x' + IntToHex(hbTapiLine1.LastRequestID, 2)); end; end; procedure TForm1.hbTapiLine1CallDeallocate(Sender: ThbTapiLine; Call: ThbTapiCall); begin ListBox1.Items.Add('::OnCallDeallocate (0x=' + IntToHex(integer(Call),8) + ')'); end; procedure TForm1.hbTapiLine1TapiReply(Sender: TObject; RequestID, ReplyCode: Cardinal); var tr: DWORD; begin if hbTapiLine1.Options.SyncMode = FALSE then ListBox1.Items.Add(Format('::OnTapiReply RequestID=0x%X, ReplyCode=0x%X',[RequestID, ReplyCode])) else exit; if (ReplyCode <> 0) then begin tr := hbTapiLine1.GetRequestNote(RequestID, '&TapiRequest'); case tr of TAPIREQUEST_LINEMAKECALL : begin MessageDlg(Format('TapiReply: MakeCall #%d failed! %s', [Integer(hbTapiLine1.GetRequestNote(RequestID, 'NumMakeCall')), GetTapiErrorMessage(ReplyCode)]), mtError, [mbOK], 0); end; TAPIREQUEST_LINEDROP : MessageDlg('TapiReply: DropCall failed!' +#13 + #10 + GetTapiErrorMessage(ReplyCode), mtError, [mbOK], 0); TAPIREQUEST_LINEANSWER : MessageDlg('TapiReply: AnswerCall failed!' +#13 + #10 + GetTapiErrorMessage(ReplyCode), mtError, [mbOK], 0); else MessageDlg('TapiReply: Error' +#13 + #10 + GetTapiErrorMessage(ReplyCode), mtError, [mbOK], 0); end end; end; procedure TForm1.hbTapiLine1TapiTimeout(Sender: TObject; RequestID: Cardinal); begin if hbTapiLine1.Options.SyncMode = FALSE then ListBox1.Items.Add(Format('::OnTapiTimeout RequestID=0x%X',[RequestID])); end; procedure TForm1.DoClear(Sender: TObject); begin ListBox1.Items.Clear; end; procedure TForm1.ComboBox_PrivilegesChange(Sender: TObject); begin if ComboBox_Device.ItemIndex > 0 then ComboBox_DeviceChange(nil); end; procedure TForm1.DoAnswerCall(Sender: TObject); begin if hbTapiLine1.Calls.count > 0 then begin ListBox1.Items.Add('Calling Call.Answer...'); hbTapiLine1.Calls[0].Answer; if hbTapiLine1.Options.SyncMode then ListBox1.Items.Add('Call.Answer returned') else ListBox1.Items.Add('Answer returned. LastRequestID = 0x' + IntToHex(hbTapiLine1.LastRequestID, 2)); end; end; procedure TForm1.hbTapiLine1CallInfo(Sender: ThbTapiLine; Call: ThbTapiCall; InfoState: Cardinal); begin ListBox1.Items.Add('::OnCallInfo callinfo changed or available (0x' + IntToHex(integer(Call),8) + ')'); UpdateCallInfo(Sender, Call, InfoState); end; procedure TForm1.UpdateCallInfo(Sender: ThbTapiLine; Call: ThbTapiCall; InfoState: Cardinal); begin ListBox1.Items.Add('::OnCallInfo callinfo changed or available ' + LineCallInfoStateToStr(InfoState) + ' (0x' + IntToHex(integer(Call),8) + ')'); if Call.State = LINECALLSTATE_IDLE then begin Edit_CallerID.Text := ''; Edit_CallerIDName.Text := ''; Edit_CalledID.Text := ''; Edit_CalledIDName.Text := ''; Edit_ConnectedID.Text := ''; Edit_ConnectedIDName.Text := ''; Edit_RedirectionID.Text := ''; Edit_RedirectionIDName.Text := ''; Edit_RedirectingID.Text := ''; Edit_RedirectingID.Text := ''; Label_CallerID.Font.Style := Label_CallerID.Font.Style - [fsBold]; Label_CallerIDName.Font.Style := Label_CallerIDName.Font.Style - [fsBold]; Label_CalledID.Font.Style := Label_CalledID.Font.Style - [fsBold]; Label_CalledIDName.Font.Style := Label_CalledIDName.Font.Style - [fsBold]; Label_ConnectedID.Font.Style := Label_ConnectedID.Font.Style - [fsBold]; Label_ConnectedIDName.Font.Style := Label_ConnectedIDName.Font.Style - [fsBold]; Label_RedirectionID.Font.Style := Label_RedirectionID.Font.Style - [fsBold]; Label_RedirectionIDName.Font.Style := Label_RedirectionIDName.Font.Style - [fsBold]; Label_RedirectingID.Font.Style := Label_RedirectingID.Font.Style - [fsBold]; Label_RedirectingIDName.Font.Style := Label_RedirectingIDName.Font.Style - [fsBold]; Exit; end; // CallerID if Call.CallerID.AddressAvail then Label_CallerID.Font.Style := Label_CallerID.Font.Style + [fsBold] else Label_CallerID.Font.Style := Label_CallerID.Font.Style - [fsBold]; if Call.CallerID.NameAvail then Label_CallerIDName.Font.Style := Label_CallerIDName.Font.Style + [fsBold] else Label_CallerIDName.Font.Style := Label_CallerIDName.Font.Style - [fsBold]; Edit_CallerID.Text := Call.CallerID.Address; Edit_CallerIDName.Text := Call.CallerID.Name; // CalledID if Call.CalledID.AddressAvail then Label_CalledID.Font.Style := Label_CalledID.Font.Style + [fsBold] else Label_CalledID.Font.Style := Label_CalledID.Font.Style - [fsBold]; if Call.CalledID.NameAvail then Label_CalledIDName.Font.Style := Label_CalledIDName.Font.Style + [fsBold] else Label_CalledIDName.Font.Style := Label_CalledIDName.Font.Style - [fsBold]; Edit_CalledID.Text := Call.CalledID.Address; Edit_CalledIDName.Text := Call.CalledID.Name; // ConnectedID if Call.ConnectedID.AddressAvail then Label_ConnectedID.Font.Style := Label_ConnectedID.Font.Style + [fsBold] else Label_ConnectedID.Font.Style := Label_ConnectedID.Font.Style - [fsBold]; if Call.ConnectedID.NameAvail then Label_ConnectedIDName.Font.Style := Label_ConnectedIDName.Font.Style + [fsBold] else Label_ConnectedIDName.Font.Style := Label_ConnectedIDName.Font.Style - [fsBold]; Edit_ConnectedID.Text := Call.ConnectedID.Address; Edit_ConnectedIDName.Text := Call.ConnectedID.Name; // RedirectionID if Call.RedirectionID.AddressAvail then Label_RedirectionID.Font.Style := Label_RedirectionID.Font.Style + [fsBold] else Label_RedirectionID.Font.Style := Label_RedirectionID.Font.Style - [fsBold]; if Call.RedirectionID.NameAvail then Label_RedirectionIDName.Font.Style := Label_RedirectionIDName.Font.Style + [fsBold] else Label_RedirectionIDName.Font.Style := Label_RedirectionIDName.Font.Style - [fsBold]; Edit_RedirectionID.Text := Call.RedirectionID.Address; Edit_RedirectionIDName.Text := Call.RedirectionID.Name; // RedirectingID if Call.RedirectingID.AddressAvail then Label_RedirectingID.Font.Style := Label_RedirectingID.Font.Style + [fsBold] else Label_RedirectingID.Font.Style := Label_RedirectingID.Font.Style - [fsBold]; if Call.RedirectingID.NameAvail then Label_RedirectingIDName.Font.Style := Label_RedirectingIDName.Font.Style + [fsBold] else Label_RedirectingIDName.Font.Style := Label_RedirectingIDName.Font.Style - [fsBold]; Edit_RedirectingID.Text := Call.RedirectingID.Address; Edit_RedirectingID.Text := Call.RedirectingID.Name; end; procedure TForm1.Edit_PhoneNoKeyPress(Sender: TObject; var Key: Char); begin if Key = chr(VK_RETURN) then DoMakeCall(nil); end; end.
unit uSendDataFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentForm, Provider, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, XiButton, ExtCtrls, StdCtrls; const MR_PET_DATA = 'MRPetData.exe'; type TSendDataFrm = class(TParentForm) pnlBottom: TPanel; btnOk: TXiButton; btnCancel: TXiButton; dDate: TcxDateEdit; Label1: TLabel; procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private function SendSaleData : Boolean; public function Init(SilentMode : Boolean) : Boolean; end; implementation uses uDMPetCenter, uDMPet, uFileFunctions, mrMsgBox; {$R *.dfm} { TSendDataFrm } function TSendDataFrm.Init(SilentMode : Boolean): Boolean; begin dDate.Date := Trunc(Now-1); Result := True; if not SilentMode then ShowModal else begin SendSaleData; Close; end; end; function TSendDataFrm.SendSaleData: Boolean; var sSaleDate : String; begin Result := False; try Screen.Cursor := crHourGlass; sSaleDate := FormatDateTime('mm/dd/yyyy', Trunc(dDate.Date)); if FileExists(DMPet.LocalPath + MR_PET_DATA) then ExecuteFile(DMPet.LocalPath + MR_PET_DATA, sSaleDate, '', SW_SHOW) else MsgBox('Send Pet Center data not installed!', vbInformation + vbOKOnly); finally Screen.Cursor := crDefault; end; end; procedure TSendDataFrm.btnOkClick(Sender: TObject); begin inherited; SendSaleData; end; procedure TSendDataFrm.btnCancelClick(Sender: TObject); begin inherited; Close; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFRequestHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefRequestHandlerOwn = class(TCefBaseRefCountedOwn, ICefRequestHandler) protected function OnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean; virtual; function OnOpenUrlFromTab(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean): Boolean; virtual; function OnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue; virtual; function GetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): ICefResourceHandler; virtual; procedure OnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring); virtual; function OnResourceResponse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean; virtual; function GetResourceResponseFilter(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter; virtual; procedure OnResourceLoadComplete(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64); virtual; function GetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; virtual; function OnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback): Boolean; virtual; function GetCookieManager(const browser: ICefBrowser; const mainUrl: ustring): ICefCookieManager; virtual; procedure OnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean); virtual; function OnCertificateError(const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback): Boolean; virtual; function OnSelectClientCertificate(const browser: ICefBrowser; isProxy: boolean; const host: ustring; port: integer; certificatesCount: NativeUInt; const certificates: TCefX509CertificateArray; const callback: ICefSelectClientCertificateCallback): boolean; virtual; procedure OnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); virtual; procedure OnRenderViewReady(const browser: ICefBrowser); virtual; procedure OnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus); virtual; public constructor Create; virtual; end; TCustomRequestHandler = class(TCefRequestHandlerOwn) protected FEvent: IChromiumEvents; function OnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean; override; function OnOpenUrlFromTab(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean): Boolean; override; function OnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue; override; function GetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): ICefResourceHandler; override; procedure OnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring); override; function OnResourceResponse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean; override; function GetResourceResponseFilter(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter; override; procedure OnResourceLoadComplete(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64); override; function GetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; override; function OnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback): Boolean; override; procedure OnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean); override; function OnCertificateError(const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback): Boolean; override; function OnSelectClientCertificate(const browser: ICefBrowser; isProxy: boolean; const host: ustring; port: integer; certificatesCount: NativeUInt; const certificates: TCefX509CertificateArray; const callback: ICefSelectClientCertificateCallback): boolean; override; procedure OnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); override; procedure OnRenderViewReady(const browser: ICefBrowser); override; procedure OnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus); override; public constructor Create(const events: IChromiumEvents); reintroduce; virtual; destructor Destroy; override; end; implementation uses {$IFDEF DELPHI16_UP} WinApi.Windows, System.SysUtils, {$ELSE} Windows, SysUtils, {$ENDIF} uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFFrame, uCEFRequest, uCEFRequestCallback, uCEFResponse, uCEFAuthCallback, uCEFSslInfo, uCEFSelectClientCertificateCallback, uCEFX509Certificate, uCEFApplication; function cef_request_handler_on_before_browse(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest; isRedirect: Integer): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnBeforeBrowse(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), isRedirect <> 0)); end; function cef_request_handler_on_open_urlfrom_tab(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; const target_url: PCefString; target_disposition: TCefWindowOpenDisposition; user_gesture: Integer): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnOpenUrlFromTab(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), CefString(target_url), target_disposition, user_gesture <> 0)); end; function cef_request_handler_on_before_resource_load(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest; callback: PCefRequestCallback): TCefReturnValue; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := OnBeforeResourceLoad( TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), TcefRequestCallbackRef.UnWrap(callback)); end; function cef_request_handler_get_resource_handler(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest): PCefResourceHandler; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := CefGetData(GetResourceHandler(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request))); end; procedure cef_request_handler_on_resource_redirect(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; const request: PCefRequest; response: PCefResponse; new_url: PCefString); stdcall; var url: ustring; begin url := CefString(new_url); with TCefRequestHandlerOwn(CefGetObject(self)) do OnResourceRedirect(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), TCefResponseRef.UnWrap(response), url); if url <> '' then CefStringSet(new_url, url); end; function cef_request_handler_on_resource_response(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest; response: PCefResponse): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnResourceResponse(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), TCefResponseRef.UnWrap(response))); end; function cef_request_handler_get_resource_response_filter(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest; response: PCefResponse): PCefResponseFilter; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := CefGetData(GetResourceResponseFilter(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), TCefResponseRef.UnWrap(response))); end; procedure cef_request_handler_on_resource_load_complete(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; request: PCefRequest; response: PCefResponse; status: TCefUrlRequestStatus; received_content_length: Int64); stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do OnResourceLoadComplete(TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), TCefRequestRef.UnWrap(request), TCefResponseRef.UnWrap(response), status, received_content_length); end; function cef_request_handler_get_auth_credentials(self: PCefRequestHandler; browser: PCefBrowser; frame: PCefFrame; isProxy: Integer; const host: PCefString; port: Integer; const realm, scheme: PCefString; callback: PCefAuthCallback): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(GetAuthCredentials( TCefBrowserRef.UnWrap(browser), TCefFrameRef.UnWrap(frame), isProxy <> 0, CefString(host), port, CefString(realm), CefString(scheme), TCefAuthCallbackRef.UnWrap(callback))); end; function cef_request_handler_on_quota_request(self: PCefRequestHandler; browser: PCefBrowser; const origin_url: PCefString; new_size: Int64; callback: PCefRequestCallback): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnQuotaRequest(TCefBrowserRef.UnWrap(browser), CefString(origin_url), new_size, TCefRequestCallbackRef.UnWrap(callback))); end; procedure cef_request_handler_on_protocol_execution(self: PCefRequestHandler; browser: PCefBrowser; const url: PCefString; allow_os_execution: PInteger); stdcall; var allow: Boolean; begin allow := allow_os_execution^ <> 0; with TCefRequestHandlerOwn(CefGetObject(self)) do OnProtocolExecution( TCefBrowserRef.UnWrap(browser), CefString(url), allow); allow_os_execution^ := Ord(allow); end; function cef_request_handler_on_certificate_error(self: PCefRequestHandler; browser: PCefBrowser; cert_error: TCefErrorcode; const request_url: PCefString; ssl_info: PCefSslInfo; callback: PCefRequestCallback): Integer; stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnCertificateError(TCefBrowserRef.UnWrap(browser), cert_error, CefString(request_url), TCefSslInfoRef.UnWrap(ssl_info), TCefRequestCallbackRef.UnWrap(callback))); end; procedure cef_request_handler_on_plugin_crashed(self: PCefRequestHandler; browser: PCefBrowser; const plugin_path: PCefString); stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do OnPluginCrashed(TCefBrowserRef.UnWrap(browser), CefString(plugin_path)); end; procedure cef_request_handler_on_render_view_ready(self: PCefRequestHandler; browser: PCefBrowser); stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do OnRenderViewReady(TCefBrowserRef.UnWrap(browser)); end; procedure cef_request_handler_on_render_process_terminated(self: PCefRequestHandler; browser: PCefBrowser; status: TCefTerminationStatus); stdcall; begin with TCefRequestHandlerOwn(CefGetObject(self)) do OnRenderProcessTerminated(TCefBrowserRef.UnWrap(browser), status); end; function cef_request_handler_on_select_client_certificate(self: PCefRequestHandler; browser: PCefBrowser; isProxy: integer; const host: PCefString; port: integer; certificatesCount: NativeUInt; const certificates: PPCefX509Certificate; callback: PCefSelectClientCertificateCallback): integer; stdcall; var TempCertArray : TCefX509CertificateArray; i : NativeUInt; begin TempCertArray := nil; Result := 0; try try if (certificatesCount > 0) and (certificates <> nil) then begin SetLength(TempCertArray, certificatesCount); i := 0; while (i < certificatesCount) do begin TempCertArray[i] := TCEFX509CertificateRef.UnWrap(PPointerArray(certificates)[i]); inc(i); end; with TCefRequestHandlerOwn(CefGetObject(self)) do Result := Ord(OnSelectClientCertificate(TCefBrowserRef.UnWrap(browser), (isProxy <> 0), CefString(host), port, certificatesCount, TempCertArray, TCefSelectClientCertificateCallbackRef.UnWrap(callback))); i := 0; while (i < certificatesCount) do begin TempCertArray[i] := nil; inc(i); end; end; except on e : exception do if CustomExceptionHandler('uCEFRequestHandler.cef_request_handler_on_select_client_certificate', e) then raise; end; finally if (TempCertArray <> nil) then begin Finalize(TempCertArray); TempCertArray := nil; end; end; end; constructor TCefRequestHandlerOwn.Create; begin inherited CreateData(SizeOf(TCefRequestHandler)); with PCefRequestHandler(FData)^ do begin on_before_browse := cef_request_handler_on_before_browse; on_open_urlfrom_tab := cef_request_handler_on_open_urlfrom_tab; on_before_resource_load := cef_request_handler_on_before_resource_load; get_resource_handler := cef_request_handler_get_resource_handler; on_resource_redirect := cef_request_handler_on_resource_redirect; on_resource_response := cef_request_handler_on_resource_response; get_resource_response_filter := cef_request_handler_get_resource_response_filter; on_resource_load_complete := cef_request_handler_on_resource_load_complete; get_auth_credentials := cef_request_handler_get_auth_credentials; on_quota_request := cef_request_handler_on_quota_request; on_protocol_execution := cef_request_handler_on_protocol_execution; on_certificate_error := cef_request_handler_on_certificate_error; on_select_client_certificate := cef_request_handler_on_select_client_certificate; on_plugin_crashed := cef_request_handler_on_plugin_crashed; on_render_view_ready := cef_request_handler_on_render_view_ready; on_render_process_terminated := cef_request_handler_on_render_process_terminated; end; end; function TCefRequestHandlerOwn.GetAuthCredentials(const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback): Boolean; begin Result := False; end; function TCefRequestHandlerOwn.GetCookieManager(const browser: ICefBrowser; const mainUrl: ustring): ICefCookieManager; begin Result := nil; end; function TCefRequestHandlerOwn.OnBeforeBrowse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean): Boolean; begin Result := False; end; function TCefRequestHandlerOwn.OnBeforeResourceLoad(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const callback: ICefRequestCallback): TCefReturnValue; begin Result := RV_CONTINUE; end; function TCefRequestHandlerOwn.OnCertificateError(const browser: ICefBrowser; certError: TCefErrorcode; const requestUrl: ustring; const sslInfo: ICefSslInfo; const callback: ICefRequestCallback): Boolean; begin Result := False; end; function TCefRequestHandlerOwn.OnSelectClientCertificate(const browser : ICefBrowser; isProxy : boolean; const host : ustring; port : integer; certificatesCount : NativeUInt; const certificates : TCefX509CertificateArray; const callback : ICefSelectClientCertificateCallback): boolean; begin Result := False; end; function TCefRequestHandlerOwn.OnOpenUrlFromTab(const browser: ICefBrowser; const frame: ICefFrame; const targetUrl: ustring; targetDisposition: TCefWindowOpenDisposition; userGesture: Boolean): Boolean; begin Result := False; end; function TCefRequestHandlerOwn.GetResourceHandler(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest): ICefResourceHandler; begin Result := nil; end; procedure TCefRequestHandlerOwn.OnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); begin end; procedure TCefRequestHandlerOwn.OnProtocolExecution(const browser: ICefBrowser; const url: ustring; out allowOsExecution: Boolean); begin end; function TCefRequestHandlerOwn.OnQuotaRequest(const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefRequestCallback): Boolean; begin Result := False; end; procedure TCefRequestHandlerOwn.OnRenderProcessTerminated( const browser: ICefBrowser; status: TCefTerminationStatus); begin end; procedure TCefRequestHandlerOwn.OnRenderViewReady(const browser: ICefBrowser); begin end; procedure TCefRequestHandlerOwn.OnResourceRedirect(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; var newUrl: ustring); begin end; function TCefRequestHandlerOwn.OnResourceResponse(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): Boolean; begin Result := False; end; function TCefRequestHandlerOwn.GetResourceResponseFilter( const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter; begin Result := nil; end; procedure TCefRequestHandlerOwn.OnResourceLoadComplete( const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse; status: TCefUrlRequestStatus; receivedContentLength: Int64); begin end; // TCustomRequestHandler constructor TCustomRequestHandler.Create(const events: IChromiumEvents); begin inherited Create; FEvent := events; end; destructor TCustomRequestHandler.Destroy; begin FEvent := nil; inherited Destroy; end; function TCustomRequestHandler.GetAuthCredentials(const browser : ICefBrowser; const frame : ICefFrame; isProxy : Boolean; const host : ustring; port : Integer; const realm : ustring; const scheme : ustring; const callback : ICefAuthCallback): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnGetAuthCredentials(browser, frame, isProxy, host, port, realm, scheme, callback) else Result := inherited GetAuthCredentials(browser, frame, isProxy, host, port, realm, scheme, callback); end; function TCustomRequestHandler.GetResourceHandler(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest): ICefResourceHandler; begin if (FEvent <> nil) then Result := FEvent.doOnGetResourceHandler(browser, frame, request) else Result := inherited GetResourceHandler(browser, frame, request); end; function TCustomRequestHandler.OnBeforeBrowse(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest; isRedirect : Boolean): Boolean; begin Result := FEvent.doOnBeforeBrowse(browser, frame, request, isRedirect); end; function TCustomRequestHandler.OnBeforeResourceLoad(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest; const callback : ICefRequestCallback): TCefReturnValue; begin if (FEvent <> nil) then Result := FEvent.doOnBeforeResourceLoad(browser, frame, request, callback) else Result := inherited OnBeforeResourceLoad(browser, frame, request, callback); end; function TCustomRequestHandler.OnCertificateError(const browser : ICefBrowser; certError : TCefErrorcode; const requestUrl : ustring; const sslInfo : ICefSslInfo; const callback : ICefRequestCallback): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnCertificateError(browser, certError, requestUrl, sslInfo, callback) else Result := inherited OnCertificateError(browser, certError, requestUrl, sslInfo, callback); end; function TCustomRequestHandler.OnOpenUrlFromTab(const browser : ICefBrowser; const frame : ICefFrame; const targetUrl : ustring; targetDisposition : TCefWindowOpenDisposition; userGesture : Boolean): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnOpenUrlFromTab(browser, frame, targetUrl, targetDisposition, userGesture) else Result := inherited OnOpenUrlFromTab(browser, frame, targetUrl, targetDisposition, userGesture); end; function TCustomRequestHandler.OnSelectClientCertificate(const browser : ICefBrowser; isProxy : boolean; const host : ustring; port : integer; certificatesCount : NativeUInt; const certificates : TCefX509CertificateArray; const callback : ICefSelectClientCertificateCallback): boolean; begin if (FEvent <> nil) then Result := FEvent.doOnSelectClientCertificate(browser, isProxy, host, port, certificatesCount, certificates, callback) else Result := inherited OnSelectClientCertificate(browser, isProxy, host, port, certificatesCount, certificates, callback); end; procedure TCustomRequestHandler.OnPluginCrashed(const browser: ICefBrowser; const pluginPath: ustring); begin if (FEvent <> nil) then FEvent.doOnPluginCrashed(browser, pluginPath); end; procedure TCustomRequestHandler.OnProtocolExecution(const browser : ICefBrowser; const url : ustring; out allowOsExecution : Boolean); begin if (FEvent <> nil) then FEvent.doOnProtocolExecution(browser, url, allowOsExecution); end; function TCustomRequestHandler.OnQuotaRequest(const browser : ICefBrowser; const originUrl : ustring; newSize : Int64; const callback : ICefRequestCallback): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnQuotaRequest(browser, originUrl, newSize, callback) else Result := inherited OnQuotaRequest(browser, originUrl, newSize, callback); end; procedure TCustomRequestHandler.OnRenderProcessTerminated(const browser: ICefBrowser; status: TCefTerminationStatus); begin if (FEvent <> nil) then FEvent.doOnRenderProcessTerminated(browser, status); end; procedure TCustomRequestHandler.OnRenderViewReady(const browser: ICefBrowser); begin if (FEvent <> nil) then FEvent.doOnRenderViewReady(browser); end; procedure TCustomRequestHandler.OnResourceRedirect(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest; const response : ICefResponse; var newUrl : ustring); begin if (FEvent <> nil) then FEvent.doOnResourceRedirect(browser, frame, request, response, newUrl); end; function TCustomRequestHandler.OnResourceResponse(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest; const response : ICefResponse): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnResourceResponse(browser, frame, request, response) else Result := inherited OnResourceResponse(browser, frame, request, response); end; function TCustomRequestHandler.GetResourceResponseFilter(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; const response: ICefResponse): ICefResponseFilter; begin if (FEvent <> nil) then Result := FEvent.doOnGetResourceResponseFilter(browser, frame, request, response) else Result := inherited GetResourceResponseFilter(browser, frame, request, response); end; procedure TCustomRequestHandler.OnResourceLoadComplete(const browser : ICefBrowser; const frame : ICefFrame; const request : ICefRequest; const response : ICefResponse; status : TCefUrlRequestStatus; receivedContentLength : Int64); begin if (FEvent <> nil) then FEvent.doOnResourceLoadComplete(browser, frame, request, response, status, receivedContentLength); end; end.
{: Benchmark and stress test for PFX.<p> Fires are made of additively blended particles, smoke of transparently blended ones. Smokes of distinct fires should hide each other, and smoke in a particular fire should hide its top flames a bit.<p> 02/03/2005 - GF3 / AXP 2 GHz - 53 FPS } unit Unit1; {$MODE Delphi} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLCadencer, GLParticleFX, GLPerlinPFX, GLScene, GLObjects, GLLCLViewer, ExtCtrls, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLSceneViewer: TGLSceneViewer; GLScene: TGLScene; GLCamera: TGLCamera; DCFire1: TGLDummyCube; ParticleFXRenderer: TGLParticleFXRenderer; SmokePFX: TGLPerlinPFXManager; FlamePFX: TGLCustomSpritePFXManager; GLCadencer: TGLCadencer; DCTarget: TGLDummyCube; Timer: TTimer; procedure GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); procedure TimerTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.lfm} procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); begin SmokePFX.Rotation:=newTime; GLSceneViewer.Invalidate; end; procedure TForm1.TimerTimer(Sender: TObject); begin Caption:= GLSceneViewer.FramesPerSecondText +Format(' - %d Particles - %.3f ms Sort', [SmokePFX.ParticleCount+FlamePFX.ParticleCount, ParticleFXRenderer.LastSortTime]); GLSceneViewer.ResetPerformanceMonitor; end; end.
unit frmStdArtInfo; {*|<PRE>***************************************************************************** 软件名称 FNM CLIENT MODEL 版权所有 (C) 2004-2005 ESQUEL GROUP GET/IT 单元名称 frmStdArtInfo.pas 创建日期 2004-8-30 下午 04:26:18 创建人员 lvzd 对应用例 2.1. 制定标准工艺 相关数据库表: 1: fnStdArtHdr 2: fnStdArtDtl 调用重要函数/SQL对象说明 1: 调用中间层函数:FNMServerArtObj.GetNoArtOrCheckGFNO 功能描述: 建立, 修改, 确认标准工艺 ******************************************************************************} interface uses uFNMArtInfo, Forms, SysUtils, Windows, Graphics, Messages, Menus, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, StdCtrls, Grids, ValEdit, ExtCtrls, cxSplitter, Tabs, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGrid, Controls, ComCtrls, Buttons, Classes, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridDBTableView, DBClient, DBGrids; type TStdArtInfoForm = class(TForm) btn_CheckArtData: TSpeedButton; btn_CopyExistArt: TSpeedButton; btn_Exit: TSpeedButton; btn_Help: TSpeedButton; btn_RefrshGFNOList: TSpeedButton; btn_SaveArt: TSpeedButton; cxbe_GFKeyValue: TcxButtonEdit; cxspl_Only: TcxSplitter; edt_Anti_Fluorescence: TEdit; edt_Check: TEdit; edt_Check_Time: TEdit; edt_CopyExistArt: TEdit; edt_Customer: TEdit; edt_GreyDensity: TEdit; edt_Designer: TEdit; edt_Designer_Time: TEdit; edt_BR: TEdit; edt_Grey_Width: TEdit; edt_Version: TEdit; edt_Density: TEdit; pm_CopyExistArt: TPopupMenu; pnl_Only: TPanel; txt_Only: TStaticText; edt_ReedWidth: TEdit; edt_Width: TEdit; btn_ViewArtDtl: TSpeedButton; pgc_GFNOList: TPageControl; lv_CurNOCheckArt: TListView; ts_Other: TTabSheet; lv_OtherNOCheckArt: TListView; ts_NoCheck: TTabSheet; edtGFID: TEdit; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; pnl_Only1: TPanel; spl1: TSplitter; grp_Only: TGroupBox; mmo_Remark: TMemo; lst_Operationlist: TListBox; btn_MoveUP_Operation: TSpeedButton; btn_MoveDown_Operation: TSpeedButton; btn_Del_Operation: TSpeedButton; btn_Add_Operation: TSpeedButton; pgc_Operation: TPageControl; cbb_Operation_Name: TComboBox; Vle_Operation_Parlist: TValueListEditor; cbb_ColorCode: TComboBox; cbb_FN_Art_NO1: TComboBox; cbb_FN_Art_NO2: TComboBox; cbb_FN_Art_NO4: TComboBox; cbb_Shrinkage: TComboBox; edt_HandFeel: TEdit; chk_Is_Active: TCheckBox; edt_ProductWidth: TEdit; cxGridDBTVFeedback: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; Panel1: TPanel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; mmoPDA: TMemo; mmoPDM: TMemo; chbPDA: TCheckBox; chbPDM: TCheckBox; ts_Feedback: TTabSheet; dsFeedback: TDataSource; cdsFeedback: TClientDataSet; lv_Feedback: TListView; TabSheet3: TTabSheet; mmoArtView: TMemo; rgFilter: TRadioGroup; sbFeedback: TSpeedButton; Panel2: TPanel; edt_Feedback: TEdit; edt_Feedback_Time: TEdit; edtSpecialYarnRate: TEdit; cdsRecipe: TClientDataSet; cdsCheckRecipe: TClientDataSet; lblRadio: TLabel; cdsRadio: TClientDataSet; btnDeleteArtByHand: TBitBtn; chkArtByHand: TCheckBox; cdsArtbyHand: TClientDataSet; ts_UnConfirm: TTabSheet; lv_UNConfirm: TListView; procedure cxbe_PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure btn_Operation(Sender: TObject); procedure KeyDownAControl(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure lst_OperationlistClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure Vle_Operation_ParlistValidate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); procedure btn_SaveArtClick(Sender: TObject); procedure btn_CopyExistArtClick(Sender: TObject); procedure pm_CopyExistArtPopup(Sender: TObject); procedure btn_Add_OperationClick(Sender: TObject); procedure ChangeAEdit(Sender: TObject); procedure btn_RefrshGFNOListClick(Sender: TObject); procedure Vle_Operation_ParlistEditButtonClick(Sender: TObject); procedure KeyDownAComboBox(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pgc_OperationChange(Sender: TObject); procedure Vle_Operation_ParlistKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btn_CheckArtDataClick(Sender: TObject); procedure btn_ExitClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure btn_ViewArtDtlClick(Sender: TObject); procedure cbb_FN_Art_NO2CloseUp(Sender: TObject); procedure lv_CurNOCheckArtColumnClick(Sender: TObject; Column: TListColumn); procedure lv_OtherNOCheckArtColumnClick(Sender: TObject; Column: TListColumn); procedure chbPDAClick(Sender: TObject); procedure chbPDMClick(Sender: TObject); procedure lv_FeedbackColumnClick(Sender: TObject; Column: TListColumn); procedure lv_CurNOCheckArtCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure lv_OtherNOCheckArtCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure lv_FeedbackCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure cxGridDBTVFeedbackCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure pgc_GFNOListChange(Sender: TObject); procedure rgFilterClick(Sender: TObject); procedure sbFeedbackClick(Sender: TObject); procedure getRedio(); procedure btnDeleteArtByHandClick(Sender: TObject); private { private declarations } OldFNArtNO2: string; function FindItem(FindStr: string; ListView: TListView): Boolean; procedure SaveData(Index: Integer); procedure SaveFnmArtbyHand; {* 工艺明细插入品名库信息表.} function CheckArtByHand(gf_no: string):Boolean; {* 判断品名是否已存在品名库信息表中.} public { public declarations } StdArtData: TSTDArtDtlInfo; {* 标准工艺类对象} procedure ChangeEditControlEnable(EnableEdit: Boolean); {* 改变工序等编辑控件的编辑状态.} procedure ChangeParameterEditMode(EditMode: Boolean); {* 改变工序参数等编辑控件的编辑状态} procedure OpenStdArt(DataID: Integer; OpenType: String); {* 取出工艺供用户编辑} procedure SelectAOperation; {* 用户选择了一个工序} procedure CopyStdArtClick(Sender: TObject); {* 拷贝工艺菜单的单击事件} procedure ArtAfterEdit(Sender: TObject); {* 当工艺被编辑后,见FormCreate事件中:StdArtData.OnAfterEdit:=ArtAfterEdit;} procedure ArtBeforeSave(Sender: TObject); {* 工艺保存之前工艺类调用函数,见FormCreate事件中:StdArtData.OnBeforeSave:=ArtBeforeSave;} procedure ArtAfterSave(Sender: TObject); {* 当工艺保存成功后,见FormCreate事件中:StdArtData.OnAfterSave:=ArtAfterSave;} procedure ArtAfterOpen(Sender: TObject); {* 当工艺打开后,见FormCreate事件中:StdArtData.OnAfterOpen:=ArtAfterOpen;} procedure ArtAfterClose(Sender: TObject); {* 当工艺关闭后,见FormCreate事件中:StdArtData.OnArtAfterClose:=ArtAfterClose;} end; var StdArtInfoForm: TStdArtInfoForm; implementation uses Variants, Math, StrUtils, frmCreateSample, uDictionary, Dialogs, uFNMResource, ULogin, UGlobal, uShowMessage, UGridDecorator, ServerDllPub, UAppOption, uCADInfo, frmCreateStdPrescription; {$R *.dfm} function TStdArtInfoForm.FindItem(FindStr: string; ListView: TListView):Boolean; var i: integer; begin Result := False; for i:=0 to ListView.Items.Count -1 do if ListView.Items[i].Caption = FindStr then begin Result := True; ListView.Items[i].Selected := true; TPageControl(ListView.Parent.Parent).ActivePage := TTabSheet(ListView.Parent); ListView.SetFocus; break; end; end; procedure TStdArtInfoForm.SelectAOperation; var Step_NO: Integer; begin if lst_Operationlist.Focused then pgc_Operation.ActivePageIndex := 1; if lst_Operationlist.ItemIndex <> -1 then begin Step_NO:=Integer(lst_Operationlist.Items.Objects[lst_Operationlist.ItemIndex]); if (Vle_Operation_Parlist.Tag <> Step_NO) or (Vle_Operation_Parlist.Strings.Count = 0) then begin StdArtData.FillAStepToAListControls(Step_NO, Vle_Operation_Parlist); Vle_Operation_Parlist.Tag:=Step_NO; end; end; Vle_Operation_Parlist.Enabled:=Vle_Operation_Parlist.Strings.Count > 0; if Trim(StdArtData.Checker) <>'' then //CHECK后不能编辑 Vle_Operation_Parlist.Options:=Vle_Operation_Parlist.Options - [goEditing] else Vle_Operation_Parlist.Options:=Vle_Operation_Parlist.Options + [goEditing]; end; procedure TStdArtInfoForm.ChangeEditControlEnable(EnableEdit: Boolean); begin if not EnableEdit then begin cbb_ColorCode.ItemIndex:=-1; cbb_FN_Art_NO1.ItemIndex:=-1; cbb_FN_Art_NO2.ItemIndex:=-1; cbb_FN_Art_NO4.ItemIndex:=-1; cbb_Shrinkage.Text:=''; edt_BR.Text:=''; edt_Anti_Fluorescence.Text:=''; edt_Check.Text:=''; edt_Check_Time.Text:=''; edt_Feedback.Text :=''; edt_Feedback_Time.Text :=''; edt_Customer.Text:=''; edt_Density.Text:=''; edt_Designer.Text:=''; edt_Designer_Time.Text:=''; edt_Grey_Width.Text:=''; edt_GreyDensity.Text:=''; edt_ReedWidth.Text:=''; edt_Version.Text:=''; edt_Width.Text:=''; edt_CopyExistArt.Text:=''; lst_Operationlist.Clear; mmo_Remark.Lines.Clear; mmoPDA.Lines.Clear; mmoPDM.Lines.Clear; Vle_Operation_Parlist.Enabled:=EnableEdit; Vle_Operation_Parlist.Strings.Clear; end; //请求ID : 258664 取消所有用户”复制工艺”权限 tracy tan 2016-9-12 // edt_CopyExistArt.Enabled:=EnableEdit; // btn_CopyExistArt.Enabled:=EnableEdit; btn_Add_Operation.Enabled:=EnableEdit and (pgc_Operation.ActivePageIndex = 0); btn_Del_Operation.Enabled:=EnableEdit; btn_MoveDown_Operation.Enabled:=EnableEdit; btn_MoveUP_Operation.Enabled:=EnableEdit; cbb_ColorCode.Enabled:=EnableEdit; cbb_FN_Art_NO1.Enabled:=EnableEdit; cbb_FN_Art_NO2.Enabled:=EnableEdit; cbb_FN_Art_NO4.Enabled:=EnableEdit; cbb_Shrinkage.Enabled:=EnableEdit; chk_Is_Active.Enabled:=EnableEdit; lst_Operationlist.Enabled:=EnableEdit; mmo_Remark.Enabled:=EnableEdit; // tv_Operation_Name.Enabled:=EnableEdit; end; procedure TStdArtInfoForm.ChangeParameterEditMode(EditMode: Boolean); begin Vle_Operation_Parlist.Enabled:=EditMode; end; procedure TStdArtInfoForm.OpenStdArt(DataID: Integer; OpenType: String); begin if OpenType = 'Open' then begin //if StdArtData.OrgArt_ID = DataID then exit; StdArtData.OrgArt_ID:=DataID; StdArtData.OpenFNSTDArt; end; if OpenType = 'Create' then begin if VarToStr(StdArtData.GF_ID) = IntToStr(DataID) then exit; if TMsgDialog.ShowMsgDialog(GetResourceString(@MSG_WillCreateStdArt), mtConfirmation, [mebYes, mebNo]) = mrYes then begin StdArtData.CreateStdArt(DataID, Login.CurrentDepartment, Login.LoginName); cxbe_PropertiesButtonClick(cxbe_GFKeyValue,0); end; end; end; procedure TStdArtInfoForm.CopyStdArtClick(Sender: TObject); var Department: String; iSTD_Art_ID, iGF_ID: Integer; begin if edt_CopyExistArt.Text = '' then exit; //取品名ID或Std_Art_ID with Dictionary.cds_DepartmentList do if Locate('Iden', (Sender as TMenuItem).Tag, []) then Department:=FieldByName('Department').AsString; GetStdArtIDbyGFNO(edt_CopyExistArt.Text, Department, iSTD_Art_ID, iGF_ID); if iSTD_Art_ID = -1 then raise Exception.CreateRes(@EMP_StdArtInfoDtlCantCopy); StdArtData.CopyAExistSTDArt(iSTD_Art_ID); end; procedure TStdArtInfoForm.ArtAfterEdit(Sender: TObject); begin btn_SaveArt.Enabled:=(Sender as TSTDArtDtlInfo).Modify; end; procedure TStdArtInfoForm.ArtBeforeSave(Sender: TObject); begin cxbe_GFKeyValue.SetFocus; //把界面上的数据保存到工艺实例中 with Sender as TSTDArtDtlInfo do begin FN_Art_NO:=format('%s;%s;%s;', [LeftStr(cbb_FN_Art_NO1.Text, Pos(' ', cbb_FN_Art_NO1.Text) - 1), LeftStr(cbb_FN_Art_NO2.Text, Pos(' ', cbb_FN_Art_NO2.Text) - 1), LeftStr(cbb_FN_Art_NO4.Text, Pos(' ', cbb_FN_Art_NO4.Text) - 1)]); Shrinkage:=cbb_Shrinkage.Text; Handfeel:=edt_HandFeel.Text; Product_Width:=edt_ProductWidth.Text; FN_Color_Code:=cbb_ColorCode.Text; Remark:=mmo_Remark.Text; Is_Active:=ifthen(chk_Is_Active.Checked, '1', '0'); Operator:=Login.LoginName; end; end; procedure TStdArtInfoForm.ArtAfterSave(Sender: TObject); begin btn_SaveArt.Enabled:=false; end; procedure TStdArtInfoForm.ArtAfterOpen(Sender: TObject); var SubStrLen: Integer; TheFN_Art_NO: String; a:BOOL; begin with Sender as TSTDArtDtlInfo do begin TheFN_Art_NO:=FN_Art_NO; //工艺代号 SubStrLen:=pos(';', TheFN_Art_NO); TGlobal.SetComboBoxValue(cbb_FN_Art_NO1, LeftStr(TheFN_Art_NO, SubStrLen - 1)); System.Delete(TheFN_Art_NO, 1, SubStrLen); //荧光 SubStrLen:=pos(';', TheFN_Art_NO); TGlobal.SetComboBoxValue(cbb_FN_Art_NO2, LeftStr(TheFN_Art_NO, SubStrLen - 1)); System.Delete(TheFN_Art_NO, 1, SubStrLen); //组织结构 SubStrLen:=pos(';', TheFN_Art_NO); TGlobal.SetComboBoxValue(cbb_FN_Art_NO4, LeftStr(TheFN_Art_NO, SubStrLen - 1)); System.Delete(TheFN_Art_NO, 1, SubStrLen); //缩水要求 cbb_Shrinkage.Text:=Shrinkage; //手感要求 edt_HandFeel.Text:=HandFeel; //门幅 edt_ProductWidth.Text:=Product_Width; //颜色 TGlobal.SetComboBoxValue(cbb_ColorCode, FN_Color_Code); chk_Is_Active.Checked:=Is_Active = '1'; edt_Check.Text:=Checker; edt_Check_Time.Text:=Check_Time; edt_Feedback.Text := Feedback; edt_Feedback_Time.Text := Feedback_Time; edt_Designer.Text:=Operator; edt_Designer_Time.Text:=Operate_Time; edt_Version.Text:=Version; mmo_Remark.Text:=Remark; mmoPDA.Text := PDARemark; mmoPDM.Text := PDMRemark; //填充工序到列表框中 FillOperationToAListControls(lst_Operationlist.Items); end; //显示CAD信息 with Sender as TSTDArtDtlInfo do CADInfo.OrgGFKeyValue:= StrUtils.ifthen(GF_NO = '', GF_ID, GF_NO); with CADInfo do begin edtGFID.Text := IntToStr(GF_ID); edt_Width.Text:=Width; edt_BR.Text:=BRUnitUsage; edt_Density.Text:=Density; cxbe_GFKeyValue.Text:=GF_NO; edt_Customer.Text:=Customer_Code; edt_Grey_Width.Text:=CADInfo.GreyWidth; edt_ReedWidth.Text:=CADInfo.Reed_Width; edt_GreyDensity.Text:=CADInfo.GreyDensity; edt_Anti_Fluorescence.Text:=FluorescencePercent; edtSpecialYarnRate.Text := SpecialYarnRate; if (edt_Anti_Fluorescence.Text = 'W:0%F:0%') and (cbb_FN_Art_NO2.ItemIndex = -1) then TGlobal.SetComboBoxValue(cbb_FN_Art_NO2, 'BP'); //缩水要求 if cbb_Shrinkage.Text = '' then cbb_Shrinkage.Text:=Shrinkage; //手感要求 if edt_HandFeel.Text = '' then edt_HandFeel.Text:=Handfeel; //门幅 if edt_ProductWidth.Text = '' then edt_ProductWidth.Text:=Width; end; OldFNArtNO2 := cbb_FN_Art_NO2.Text; //显示花型控件 AutoShowCADPicture(CADInfo.OrgGFKeyValue); //设置编辑控件可用 ChangeEditControlEnable(true); //工艺未确认则确认按钮可用. with Sender as TSTDArtDtlInfo do begin btn_CheckArtData.Enabled:=(Trim(Art_ID) <> '') and (Current_Department = Login.CurrentDepartment); if btn_CheckArtData.Enabled then begin if Trim(Checker) = '' then btn_CheckArtData.Caption:='确认(&V)' else btn_CheckArtData.Caption:='取消确认(&V)' end end; getRedio; //检查品名库是否已存在 liaogc 2015-12-21 if not CheckArtByHand(cxbe_GFKeyValue.Text) then begin chkArtByHand.Caption:='插入品名库' end else chkArtByHand.Caption:='更新品名库' end; procedure TStdArtInfoForm.ArtAfterClose(Sender: TObject); begin btn_SaveArt.Enabled:=False; btn_CheckArtData.Enabled:=False; ChangeEditControlEnable(false); end; procedure TStdArtInfoForm.FormCreate(Sender: TObject); begin btn_Exit.Glyph.LoadFromResourceName(HInstance, RES_EXIT); btn_SaveArt.Glyph.LoadFromResourceName(HInstance, RES_SAVE); btn_Help.Glyph.LoadFromResourceName(HInstance, RES_HELPABOUT); btn_Add_Operation.Glyph.LoadFromResourceName(HInstance, RES_LEFT); btn_CopyExistArt.Glyph.LoadFromResourceName(HInstance, RES_COPY); btn_Del_Operation.Glyph.LoadFromResourceName(HInstance, RES_DELETE); btn_RefrshGFNOList.Glyph.LoadFromResourceName(HInstance, RES_REFRESH); btn_MoveUP_Operation.Glyph.LoadFromResourceName(HInstance, RES_MOVEUP); btn_MoveDown_Operation.Glyph.LoadFromResourceName(HInstance, RES_MOVEDOWN); sbFeedback.Glyph.LoadFromResourceName(HInstance, RES_SAVE); cxbe_GFKeyValue.Properties.Buttons.Items[0].Glyph.LoadFromResourceName(HInstance, RES_QUERYSMALL); ChangeEditControlEnable(false); ChangeParameterEditMode(false); btn_CheckArtData.Enabled:=false; btn_SaveArt.Enabled:=false; (cbb_Operation_Name as TControl).Align:=alClient; //默认显示第一页 pgc_GFNOList.ActivePageIndex:=0; pgc_Operation.ActivePageIndex:=0; PageControl1.ActivePageIndex := 0; //ListView的双击事件 lv_CurNOCheckArt.OnDblClick:=TGlobal.DblClickAListview; lv_OtherNOCheckArt.OnDblClick:=TGlobal.DblClickAListview; lv_Feedback.OnDblClick:=TGlobal.DblClickAListview; //TWinControl的双击事件 cbb_Operation_Name.OnDblClick:=TGlobal.DblClickAWinControl; //构造标准工艺类 StdArtData:=TSTDArtDtlInfo.Create(Self); StdArtData.OrgDepartment:=Login.CurrentDepartment; StdArtData.OnAfterEdit:=ArtAfterEdit; StdArtData.OnBeforeSave:=ArtBeforeSave; StdArtData.OnAfterSave:=ArtAfterSave; StdArtData.OnAfterOpen:=ArtAfterOpen; StdArtData.OnAfterClose:=ArtAfterClose; //请求ID : 252770界面中的 “插入品名库”的权限只给到 fangy/ gaoyp, 其他用户权限封闭 tracy tan 2016-8-18 if (UpperCase(Login.LoginID) = UpperCase('fangy')) or (UpperCase(Login.LoginID) = UpperCase('gaoyp')) then begin chkartbyhand.Enabled:=true ; end else chkartbyhand.Enabled:=False ; end; procedure TStdArtInfoForm.KeyDownAControl(Sender: TObject; var Key: Word; Shift: TShiftState); //var Art_ID: Integer; begin //窗体KeyDown if Sender = Self then case Key of VK_F5: btn_RefrshGFNOList.Click; VK_F8: StdArtData.SaveArtToDataBase; end; //品名编辑框KeyDown if Sender = cxbe_GFKeyValue then case Key of VK_RETURN: cxbe_GFKeyValue.Properties.OnButtonClick(Sender, 0); end; //无工艺品名 或 待确认品名的ListView的KeyDown if Sender.ClassNameIs('TListView') then case Key of VK_RETURN: begin //工艺未保存则退出 if (Sender as TListView).Selected = nil then exit; if (Sender = lv_CurNOCheckArt) or (Sender = lv_OtherNOCheckArt) or (Sender = lv_Feedback)then begin OpenStdArt(StrToInt((Sender as TListView).Selected.SubItems.Strings[0]), 'Open'); if cdsFeedback.Active then cdsFeedback.EmptyDataSet; PageControl1.ActivePageIndex := 0; if (Sender = lv_Feedback) then begin PageControl1.ActivePageIndex := 1; cdsFeedback.Data := StdArtData.GetFeedbackInfo; GridDecorator.BindCxViewWithDataSource(cxGridDBTVFeedback,dsFeedback); end; end; end; end; //工艺拷贝品名编辑框KeyDown if Sender = edt_CopyExistArt then case Key of VK_RETURN: btn_CopyExistArt.Click; end; //工序列表 KeyDown if Sender = cbb_Operation_Name then case Key of VK_RETURN: btn_Add_Operation.Click; end; //工序列表KeyDown if Sender = lst_Operationlist then case Key of VK_RETURN, VK_UP, VK_DOWN: SelectAOperation; end; end; procedure TStdArtInfoForm.cxbe_PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var iGF_ID, iSTD_Art_ID: Integer; begin if Sender = cxbe_GFKeyValue then begin if cxbe_GFKeyValue.Text = '' then exit; //用户要求总是刷新数据 // if cxbe_GFKeyValue.Text = StdArtData.GF_NO then exit; //工艺关闭失败则退出 if not StdArtData.CloseArt then exit; //取品名ID或Std_Art_ID GetStdArtIDbyGFNO(cxbe_GFKeyValue.Text, Login.CurrentDepartment, iSTD_Art_ID, iGF_ID); //打开或建立工艺 if iSTD_Art_ID <> -1 then OpenStdArt(iSTD_Art_ID, 'Open') else OpenStdArt(iGF_ID, 'Create'); //定位到LISTVIEW FindItem(cxbe_GFKeyValue.Text,lv_OtherNOCheckArt); FindItem(cxbe_GFKeyValue.Text,lv_CurNOCheckArt); if StdArtData.Active then ////FindItem(cxbe_GFKeyValue.Text,lv_Feedback) and begin if cdsFeedback.Active then cdsFeedback.EmptyDataSet; cdsFeedback.Data := StdArtData.GetFeedbackInfo; GridDecorator.BindCxViewWithDataSource(cxGridDBTVFeedback,dsFeedback); end; pgc_GFNOList.OnChange(Self); end; end; procedure TStdArtInfoForm.btn_Add_OperationClick(Sender: TObject); var OperationID: Integer; begin if not btn_Add_Operation.Enabled then exit; with cbb_Operation_Name do if (Text = '') or (Items.IndexOf(Text) = -1)then exit; with cbb_Operation_Name do begin OperationID:=Integer(Items.Objects[Items.IndexOf(Text)]); Text:=''; end; //加入参数 StdArtData.AddAOperateStep(OperationID); //界面布置 StdArtData.FillOperationToAListControls(lst_Operationlist.Items); lst_Operationlist.ItemIndex:=lst_Operationlist.Count -1; SelectAOperation; end; procedure TStdArtInfoForm.btn_Operation(Sender: TObject); var ItemIndex, Step_NO: Integer; begin if Trim(StdArtData.Checker) <>'' then begin TMsgDialog.ShowMsgDialog('此品名工艺已经确认,请先取消确认再修改工艺',mtInformation); Exit; end; ItemIndex:=lst_Operationlist.ItemIndex; if ItemIndex = -1 then exit; Step_NO:=Integer(lst_Operationlist.Items.Objects[ItemIndex]); //用户按下btn_Del_Operation按钮 if Sender = btn_Del_Operation then begin StdArtData.MoveAOperateStep(Step_NO, ooDelete); ItemIndex:=ItemIndex-1; end; //用户按下btn_MoveDown_Operation按钮 if Sender = btn_MoveDown_Operation then begin if ItemIndex < lst_Operationlist.Count - 1 then begin StdArtData.MoveAOperateStep(Step_NO, ooMoveDown); ItemIndex:=ItemIndex+1; end; end; //用户按下btn_MoveUP_Operation按钮 if Sender = btn_MoveUP_Operation then begin if ItemIndex > 0 then begin StdArtData.MoveAOperateStep(Step_NO, ooMoveUP); ItemIndex:=ItemIndex-1; end; end; //界面布置 if ItemIndex <> lst_Operationlist.ItemIndex then begin StdArtData.FillOperationToAListControls(lst_Operationlist.Items); Vle_Operation_Parlist.Strings.Clear; if lst_Operationlist.Items.Count <> 0 then begin lst_Operationlist.ItemIndex:=ifthen(ItemIndex = -1, 0, ItemIndex); SelectAOperation; end; end; end; procedure TStdArtInfoForm.lst_OperationlistClick(Sender: TObject); begin SelectAOperation end; procedure TStdArtInfoForm.FormClose(Sender: TObject; var Action: TCloseAction); begin StdArtData.CloseArt; if StdArtData.Modify then Action:=caNone else begin StdArtData.Destroy; Action:=caFree; end; end; procedure TStdArtInfoForm.FormDestroy(Sender: TObject); begin StdArtInfoForm := nil; end; procedure TStdArtInfoForm.Vle_Operation_ParlistValidate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); var ItemValue: string; vData:OleVariant; sSql,sErrMsg:WideString; begin try Vle_Operation_Parlist.OnValidate:=nil; if KeyName = '' then Exit; if StdArtData.Active then begin ItemValue:=StdArtData.SetAOperateParameterValue(Vle_Operation_Parlist.Tag, Trim(KeyName), Trim(KeyValue)); //判断配方是否可用 --begin---- if Trim(KeyName) = '配方' then begin sSql := QuotedStr(Trim(KeyValue)); FNMServerObj.GetQueryData(vData,'CheckRecipe',sSql,sErrMsg); if sErrMsg <> '' then begin TMsgDialog.ShowMsgDialog(sErrMsg, mtError); Exit; end; cdsRecipe.Data := vData; if cdsRecipe.FieldByName('val').AsString <> '0' then begin ShowMessage('此配方' + Trim(KeyValue) + '不允许使用,请修改!'); end; end; //判断配方是否可用 --end---- Vle_Operation_Parlist.Cells[ACol, ARow]:=ItemValue; end; finally Vle_Operation_Parlist.OnValidate:=Vle_Operation_ParlistValidate; end; end; procedure TStdArtInfoForm.getRedio(); var sCondition,sErrorMsg:WideString; vData:OleVariant; begin //显示修改比例 //lblRadio.Caption := '10%'; if VarToStr(StdArtData.Art_ID) = '' then Exit; sCondition := IntToStr(StdArtData.Art_ID) + ',' + QuotedStr('') + ',' + QuotedStr('') + ',' + QuotedStr('') + ',' + '1'; FNMServerObj.GetQueryData(vData,'SaveParaChange',sCondition,sErrorMsg); if sErrorMsg <> '' then begin TMsgDialog.ShowMsgDialog('获取修改比例失败!',mtError); end; cdsRadio.Data := vData; lblRadio.Caption := cdsRadio.FieldByName('result').AsString ; end; procedure TStdArtInfoForm.SaveData(Index: Integer); var i: Integer; begin if chbPDA.Checked then StdArtData.PDARemark := mmoPDA.Lines.Text; if chbPDM.Checked then StdArtData.PDMRemark := mmoPDM.Lines.Text; if Index = 0 then //cuijf 2009-11-25 if not StdArtData.SaveArtToDataBase then Exit else StdArtData.SaveFeedbackInfo; //刷新反馈界面 with lv_Feedback.Items do begin for i := 0 to Count - 1 do if Item[i].Caption = StdArtData.GF_NO then begin Item[i].Delete; break; end; end; ts_Feedback.Caption := Login.CurrentDepartment + '工艺反馈['+ IntToStr(lv_Feedback.Items.Count)+']'; //显示修改比例 getRedio; if cdsFeedback.Active then cdsFeedback.EmptyDataSet; StdArtData.CloseArt; end; procedure TStdArtInfoForm.btn_SaveArtClick(Sender: TObject); begin SaveData(0); end; procedure TStdArtInfoForm.btn_CopyExistArtClick(Sender: TObject); var PopupPoint: TPoint; ClickButton: TSpeedButton; begin //PopuAMenu ClickButton:=(Sender as TSpeedButton); PopupPoint:=ClickButton.Parent.ClientToScreen(Point(ClickButton.Left, ClickButton.Top+ClickButton.Height)); ClickButton.PopupMenu.Popup(PopupPoint.X,PopupPoint.Y); end; procedure TStdArtInfoForm.KeyDownAComboBox(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Sender as TComboBox).DroppedDown then case Key of VK_TAB: begin Key:=0; PerForm(WM_NEXTDLGCTL, Ord(Shift = [ssShift]), 0); end end; end; procedure TStdArtInfoForm.pm_CopyExistArtPopup(Sender: TObject); begin if pm_CopyExistArt.Items.Count = 0 then StdArtData.InitializeDepartmentMenuItem(pm_CopyExistArt.Items, CopyStdArtClick); end; procedure TStdArtInfoForm.ChangeAEdit(Sender: TObject); begin StdArtData.Modify:=True; end; procedure TStdArtInfoForm.btn_RefrshGFNOListClick(Sender: TObject); var sDept, sErrorMsg : WideString; vData:OleVariant; begin sDept := Login.CurrentDepartment; FNMServerArtObj.GetNoCheckGFNO(sDept, vData, sErrorMsg); if sErrorMsg <> '' then raise Exception.Create(sErrorMsg); TempClientDataSet.Data:=vData; //填充数据(填充GF_ID到Items的Object对象列表) // 增加过滤条件 AND is_confirm>0 liaogc 20160421 TempClientDataSet.Filter:=Format('Current_Department = ''%s'' AND Type = ''%s'' AND is_confirm>0 ', [Login.CurrentDepartment,'待确认']); TempClientDataSet.Filtered:=True; FillListItemsFromDataSet(TempClientDataSet, 'GF_NO', '', ['STD_Art_ID', 'Construction','CADChange'], lv_CurNOCheckArt.Items); ts_NoCheck.Caption := Login.CurrentDepartment + '待确认['+ IntToStr(lv_CurNOCheckArt.Items.Count)+']'; TempClientDataSet.Filter:= Format('Current_Department <> ''%s'' AND Type <> ''%s'' AND is_confirm>0 ', [Login.CurrentDepartment ,'工艺反馈']); TempClientDataSet.Filtered:=True; FillListItemsFromDataSet(TempClientDataSet, 'GF_NO', '', ['STD_Art_ID', 'Construction','CADChange'], lv_OtherNOCheckArt.Items); ts_Other.Caption := '其他待确认['+ IntToStr(lv_OtherNOCheckArt.Items.Count)+']'; if Login.CurrentDepartment= 'FG' then TempClientDataSet.Filter:=Format('Current_Department = ''%s'' AND Type = ''%s'' AND is_confirm>0 ', [Login.CurrentDepartment ,'工艺反馈']) else TempClientDataSet.Filter:=Format('Current_Department = ''%s'' AND Type = ''%s'' AND is_confirm>0 ', [Login.CurrentDepartment ,'工艺反馈']); TempClientDataSet.Filtered:=True; FillListItemsFromDataSet(TempClientDataSet, 'GF_NO', '', ['STD_Art_ID', 'Construction','CADChange'], lv_Feedback.Items); ts_Feedback.Caption := Login.CurrentDepartment + '工艺反馈['+ IntToStr(lv_Feedback.Items.Count)+']'; //增加需调度确认数据 TempClientDataSet.Filter:= Format('is_confirm=0 ', [Login.CurrentDepartment ,'待确认']); TempClientDataSet.Filtered:=True; FillListItemsFromDataSet(TempClientDataSet, 'GF_NO', '', ['STD_Art_ID', 'Construction','CADChange'], lv_UNConfirm.Items); ts_UnConfirm.Caption := '待调度确认['+ IntToStr(lv_UNConfirm.Items.Count)+']'; TempClientDataSet.Filtered := False; end; procedure TStdArtInfoForm.Vle_Operation_ParlistEditButtonClick(Sender: TObject); var Item_Value: String; begin with Sender as TValueListEditor do begin if Pos('取样', Trim(Cells[0,Row])) > 0 then Item_Value:=GetSampleNo(Cells[1,Row]); if Pos('配方', Trim(Cells[0,Row])) > 0 then Item_Value:=GetStdPrescriptionNo(StdArtData.GetStepOperateCode(Tag), 'S', Cells[1,Row]); if (Item_Value <> '') and (Item_Value <> Cells[Col,Row]) then begin Cells[Col,Row] := Item_Value; (Sender as TValueListEditor).OnValidate(Sender, Col, Row, Cells[0, Row], Cells[Col,Row]); end; end; end; procedure TStdArtInfoForm.pgc_OperationChange(Sender: TObject); begin with Sender as TPageControl do begin btn_Add_Operation.Enabled:= (ActivePageIndex = 0) and (StdArtData.Active); if (ActivePageIndex = 2) and StdArtData.Active then mmoArtView.Lines.Text := StdArtData.ViewArtDtl(rgFilter.ItemIndex); end; end; procedure TStdArtInfoForm.Vle_Operation_ParlistKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Sender = Vle_Operation_Parlist then with Sender as TValueListEditor do case Key of VK_UP, VK_DOWN: begin if ssShift in Shift then begin lst_Operationlist.SetFocus; SendMessage(lst_Operationlist.Handle, WM_KEYDOWN, Key, 0); Key:=0; Vle_Operation_Parlist.SetFocus; end end; VK_RETURN: SendMessage(Vle_Operation_Parlist.Handle, WM_KEYDOWN, VK_DOWN, 0); end; end; procedure TStdArtInfoForm.btn_CheckArtDataClick(Sender: TObject); var i,j: Integer; sSQL,sErrorMsg : WideString; vData:OleVariant; sParam:array of string; begin if cbb_FN_Art_NO2.Text = '' then begin TMsgDialog.ShowMsgDialog('荧光属性为空,不能确认!',mtInformation); Exit; end; if (Login.LoginID <> 'liaogc') and (Login.UserLevelList = '') or (Pos('3',Login.UserLevelList)<0) then //3--有工艺确认和取消权限 begin TMsgDialog.ShowMsgDialog('你没有工艺确认和取消的权限,请联系你们的组长',mtInformation); Exit; end; cxbe_GFKeyValue.SetFocus; if btn_CheckArtData.Caption <> '确认(&V)' then begin StdArtData.CheckStdArt(0);//取消确认 btn_CheckArtData.Caption:='确认(&V)'; edt_Check.Text:=''; edt_Check_Time.Text:=''; with lv_CurNOCheckArt.Items.Add do begin Caption:=StdArtData.GF_NO; SubItems.Add(StdArtData.Art_ID); SubItems.Add(StdArtData.GF_ID); end; end else begin if not chk_Is_Active.Checked then begin TMsgDialog.ShowMsgDialog('此品名工艺无效,请先选择其有效后才能确认和取消确认',mtInformation); Exit; end; StdArtData.CheckStdArt(1); //确认 if chkArtByHand.Checked=True then SaveFnmArtbyHand; //确认,插入品名库工艺信息 liaogc 2015-12-25 getRedio(); btn_CheckArtData.Caption:='取消确认(&V)'; edt_Check.Text:=Login.LoginName; edt_Check_Time.Text:=DateTimeToStr(Now); with lv_CurNOCheckArt.Items do begin for i := 0 to Count - 1 do if Item[i].Caption = StdArtData.GF_NO then begin Item[i].Delete; break; end; end; end; if btn_CheckArtData.Caption ='取消确认(&V)' then begin SetLength(sParam,5); sParam[0] := '3'; // 213-8-12 检查是否是大花型 ,提示也放在这里 sParam[1] := '4'; // 213-8-15 检查CUSTOMER_ID ,提示也放在这里 sParam[2] := '0'; // 213-8-12 检查是否是大花型 ,提示也放在这里 sParam[3] := '5'; // 213-10-16 检查丝光定幅是否大于坯布幅宽 sParam[4] := '6'; // 213-10-18 检查 工艺备注 提示 for j:=0 to Length(sParam) - 1 do begin sSQL := QuotedStr(StdArtData.Art_ID) + ',' + sParam[j]; FNMServerObj.GetQueryData(vData, 'CheckRecipeRole', sSQL, sErrorMsg); if sErrorMsg<>'' then begin TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); end; cdsCheckRecipe.Data := vData; if cdsCheckRecipe.RecordCount > 0 then begin if cdsCheckRecipe.FieldByName('Alert_text').AsString <> '' then TMsgDialog.ShowMsgDialog(cdsCheckRecipe.FieldByName('Alert_text').AsString, mtWarning); end; end; end; // // 213-8-12 检查是否是大花型 ,提示也放在这里 // sSQL := QuotedStr(StdArtData.Art_ID) + ',3'; // FNMServerObj.GetQueryData(vData, 'CheckRecipeRole', sSQL, sErrorMsg); // if sErrorMsg<>'' then // begin // TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); // end; // cdsCheckRecipe.Data := vData; // if cdsCheckRecipe.RecordCount > 0 then // begin // if cdsCheckRecipe.FieldByName('Alert_text').AsString <> '' then // TMsgDialog.ShowMsgDialog(cdsCheckRecipe.FieldByName('Alert_text').AsString, mtWarning); // end; // // // 213-8-15 检查CUSTOMER_ID ,提示也放在这里 // sSQL := QuotedStr(StdArtData.Art_ID) + ',4'; // FNMServerObj.GetQueryData(vData, 'CheckRecipeRole', sSQL, sErrorMsg); // if sErrorMsg<>'' then // begin // TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); // end; // cdsCheckRecipe.Data := vData; // if cdsCheckRecipe.RecordCount > 0 then // begin // if cdsCheckRecipe.FieldByName('Alert_text').AsString <> '' then // TMsgDialog.ShowMsgDialog(cdsCheckRecipe.FieldByName('Alert_text').AsString, mtWarning); // end; // // // 检查配方 --- begin--------- // // 213-8-12 检查是否是大花型 ,提示也放在这里 // sSQL := QuotedStr(StdArtData.Art_ID) + ',0'; // FNMServerObj.GetQueryData(vData, 'CheckRecipeRole', sSQL, sErrorMsg); // if sErrorMsg<>'' then // begin // TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); // end; // cdsCheckRecipe.Data := vData; // if cdsCheckRecipe.RecordCount > 0 then // begin // if cdsCheckRecipe.FieldByName('Alert_text').AsString <> '' then // TMsgDialog.ShowMsgDialog(cdsCheckRecipe.FieldByName('Alert_text').AsString, mtWarning); // end; // // 检查配方 --- end--------- //显示修改比例 getRedio; StdArtData.CloseArt; PageControl1.ActivePageIndex := 0; ts_NoCheck.Caption := Login.CurrentDepartment + '待确认['+ IntToStr(lv_CurNOCheckArt.Items.Count)+']'; end; procedure TStdArtInfoForm.FormActivate(Sender: TObject); begin Application.ProcessMessages; //刷新界面数据 PostMessage(Handle, WM_KEYDOWN, VK_F5, 0); //加载后整工艺代号字典 FillArt_NOListToAComboBox('G', cbb_FN_Art_NO1); FillFN_Art_NOListToAComboBox('荧光属性', cbb_FN_Art_NO2); FillFN_Art_NOListToAComboBox('花型', cbb_FN_Art_NO4); //加载颜色字典 FillItemsFromDataSet(Dictionary.cds_ColorList, 'FN_Color_Code', 'FN_Color_Name', 'Iden','-', cbb_ColorCode.Items); cbb_ColorCode.DropDownCount:=cbb_ColorCode.Items.Count; //缩水要求字典 FillItemsFromDataSet(Dictionary.cds_ShrinkageList, 'Shrinkage', '', '','', cbb_Shrinkage.Items); //填充工序选择树 Dictionary.cds_OperationDtlList.Filter :='Use_Department LIKE ''%'+Login.CurrentDepartment + '%'''; Dictionary.cds_OperationDtlList.Filtered := True; FillItemsFromDataSet(Dictionary.cds_OperationDtlList, 'Operation_Code', 'Operation_CHN', 'Iden', '--', cbb_Operation_Name.Items); TabSheet2.Enabled := pgc_GFNOList.ActivePageIndex= 2; sbFeedback.Align := alBottom; GroupBox2.Align := alClient; OnActivate:=nil; end; procedure TStdArtInfoForm.btn_ExitClick(Sender: TObject); begin Close; end; procedure TStdArtInfoForm.btn_ViewArtDtlClick(Sender: TObject); begin StdArtData.ViewArtDtlInNewForm; end; procedure TStdArtInfoForm.cbb_FN_Art_NO2CloseUp(Sender: TObject); var OldIndex: Integer; begin OldIndex := cbb_FN_Art_NO2.Items.IndexOf(OldFNArtNO2); if edt_Anti_Fluorescence.Text = 'W:0.00%F:0.00%' then begin TMsgDialog.ShowMsgDialog('此布不含荧光,荧光属性只能设置为 [BP-漂白防荧光]', mtWarning); cbb_FN_Art_NO2.ItemIndex := 2 end else if cbb_FN_Art_NO2.ItemIndex = 2 then begin TMsgDialog.ShowMsgDialog('此布含荧光,荧光属性不能设置为 [BP-漂白防荧光]', mtWarning); cbb_FN_Art_NO2.ItemIndex := OldIndex; end; OldFNArtNO2 := cbb_FN_Art_NO2.Text; end; procedure TStdArtInfoForm.lv_CurNOCheckArtColumnClick(Sender: TObject; Column: TListColumn); begin TGlobal.SortListView(lv_CurNOCheckArt,Column); end; procedure TStdArtInfoForm.lv_OtherNOCheckArtColumnClick(Sender: TObject; Column: TListColumn); begin TGlobal.SortListView(lv_OtherNOCheckArt,Column); end; procedure TStdArtInfoForm.chbPDAClick(Sender: TObject); begin mmoPDA.Enabled := chbPDA.Checked; if mmoPDA.Enabled then mmoPDA.Color := clWindow else mmoPDA.Color := clBtnFace; end; procedure TStdArtInfoForm.chbPDMClick(Sender: TObject); begin mmoPDM.Enabled := chbPDM.Checked; if mmoPDM.Enabled then mmoPDM.Color := clWindow else mmoPDM.Color := clBtnFace; end; procedure TStdArtInfoForm.lv_FeedbackColumnClick(Sender: TObject; Column: TListColumn); begin TGlobal.SortListView(lv_Feedback,Column); end; procedure TStdArtInfoForm.lv_CurNOCheckArtCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Item.SubItems[2] <> '0' then Sender.Canvas.Font.Color := clBlue; end; procedure TStdArtInfoForm.lv_OtherNOCheckArtCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Item.SubItems[2] <> '0' then Sender.Canvas.Font.Color := clBlue; end; procedure TStdArtInfoForm.lv_FeedbackCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); begin if Item.SubItems[2] <> '0' then Sender.Canvas.Font.Color := clBlue; end; procedure TStdArtInfoForm.cxGridDBTVFeedbackCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); var col:Integer; begin col := TcxGridDBTableView(Sender).GetColumnByFieldName('Is_OK').Index; if not AViewInfo.GridRecord.Values[col] then ACanvas.Font.Color := clRed; end; procedure TStdArtInfoForm.pgc_GFNOListChange(Sender: TObject); begin if pgc_GFNOList.ActivePageIndex = 2 then PageControl1.ActivePageIndex := 1 else PageControl1.ActivePageIndex := 0; TabSheet2.Enabled := pgc_GFNOList.ActivePageIndex= 2; end; procedure TStdArtInfoForm.rgFilterClick(Sender: TObject); begin if (pgc_Operation.ActivePageIndex = 2) and StdArtData.Active then mmoArtView.Lines.Text := StdArtData.ViewArtDtl(rgFilter.ItemIndex); end; procedure TStdArtInfoForm.sbFeedbackClick(Sender: TObject); begin SaveData(1); end; procedure TStdArtInfoForm.SaveFnmArtbyHand; var sql_text,sErrorMsg: WideString; vData:OleVariant; begin if cxbe_GFKeyValue.Text='' then begin showmessage('请先输入查询品名'); exit; end; sql_text:='exec usp_UpdateFnmArtByHand 1,' +QuotedStr(cxbe_GFKeyValue.Text)+','+QuotedStr(login.CurrentDepartment) +','+QuotedStr(login.LoginName); FNMServerObj.GetQueryBySQL(vData,sql_text,sErrorMsg); if sErrorMsg <> '' then begin raise ExceptionEx.CreateResFmt(@SaveCheckArtDataError, [sErrorMsg]); end else TMsgDialog.ShowMsgDialog(chkArtByHand.Caption+'成功',mtInformation); end; procedure TStdArtInfoForm.btnDeleteArtByHandClick(Sender: TObject); var sql_text,sErrorMsg: WideString; vData:OleVariant; begin if cxbe_GFKeyValue.Text='' then begin showmessage('请先输入查询品名'); exit; end; sql_text:='exec usp_UpdateFnmArtByHand 2,' +QuotedStr(cxbe_GFKeyValue.Text); FNMServerObj.GetQueryBySQL(vData,sql_text,sErrorMsg); if sErrorMsg <> '' then begin raise ExceptionEx.CreateResFmt(@SaveCheckArtDataError, [sErrorMsg]); end else TMsgDialog.ShowMsgDialog('已删除品名 '+cxbe_GFKeyValue.Text,mtInformation); end; function TStdArtInfoForm.CheckArtByHand(gf_no: string):Boolean; var sql_text,sErrorMsg: WideString; vData:OleVariant; begin if cxbe_GFKeyValue.Text='' then begin showmessage('请先输入查询品名'); exit; end; sql_text:='exec usp_UpdateFnmArtByHand 3,' +QuotedStr(cxbe_GFKeyValue.Text); FNMServerObj.GetQueryBySQL(vData,sql_text,sErrorMsg); if sErrorMsg <> '' then begin raise ExceptionEx.CreateResFmt(@SaveCheckArtDataError, [sErrorMsg]); end ; cdsArtbyHand.Data:=vData; if cdsArtbyHand.FieldByName('gf_id').AsInteger>0 then Result:=True else Result:=False; end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_EXTRASYMBOL_TABLE.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} unit PAXCOMP_EXTRASYMBOL_TABLE; interface uses {$I uses.def} TypInfo, SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_SYS, PAXCOMP_BASESYMBOL_TABLE, PAXCOMP_SYMBOL_TABLE, PAXCOMP_SYMBOL_REC, PAXCOMP_MAP, PAXCOMP_STDLIB; type TExtraSymbolTable = class(TSymbolTable) private LocalSymbolTable: TSymbolTable; protected function GetRecord(I: Integer): TSymbolRec; override; public constructor Create(kernel: Pointer; ALocalSymbolTable: TSymbolTable); procedure Reset; override; property Records[I: Integer]: TSymbolRec read GetRecord; default; end; implementation constructor TExtraSymbolTable.Create(kernel: Pointer; ALocalSymbolTable: TSymbolTable); begin inherited Create(kernel); LocalSymbolTable := ALocalSymbolTable; IsExtraTable := true; end; procedure TExtraSymbolTable.Reset; var I: Integer; begin for I:=A.Count - 1 downto 0 do {$IFDEF ARC} A[I] := nil; {$ELSE} TSymbolRec(A[I]).Free; {$ENDIF} A.Clear; Card := LocalSymbolTable.Card; ResultId := LocalSymbolTable.ResultId; TrueId := LocalSymbolTable.TrueId; FalseId := LocalSymbolTable.FalseId; NilId := LocalSymbolTable.NilId; EventNilId := LocalSymbolTable.EventNilId; CurrExceptionObjectId := LocalSymbolTable.CurrExceptionObjectId; EmptySetId := LocalSymbolTable.EmptySetId; EmptyStringId := LocalSymbolTable.EmptyStringId; LastShiftValue := LocalSymbolTable.LastShiftValue; LastClassIndex := LocalSymbolTable.LastClassIndex; // GlobalST_LastShiftValue := GlobalST.LastShiftValue; FreeAndNil(HashArray); HashArray := LocalSymbolTable.HashArray.Clone; FreeAndNil(GuidList); GuidList := LocalSymbolTable.GuidList.Clone; FreeAndNil(SomeTypeList); SomeTypeList := LocalSymbolTable.SomeTypeList.Clone; // ExternList.Free; // ExternList := GlobalST.ExternList.Clone; // CompileCard := Card; end; function TExtraSymbolTable.GetRecord(I: Integer): TSymbolRec; begin if I <= LocalSymbolTable.Card then result := LocalSymbolTable[I] else result := TSymbolRec(A[I - LocalSymbolTable.Card - 1]); end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFResolveCallback; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefResolveCallbackOwn = class(TCefBaseRefCountedOwn, ICefResolveCallback) protected procedure OnResolveCompleted(result: TCefErrorCode; const resolvedIps: TStrings); virtual; abstract; public constructor Create; virtual; end; TCefCustomResolveCallback = class(TCefResolveCallbackOwn) protected FChromiumBrowser : TObject; procedure OnResolveCompleted(result: TCefErrorCode; const resolvedIps: TStrings); override; public constructor Create(const aChromiumBrowser : TObject); reintroduce; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFChromium; procedure cef_resolve_callback_on_resolve_completed(self: PCefResolveCallback; result: TCefErrorCode; resolved_ips: TCefStringList); stdcall; var TempSL : TStringList; i, j : Integer; str: TCefString; begin TempSL := nil; try try TempSL := TStringList.Create; i := 0; j := cef_string_list_size(resolved_ips); while (i < j) do begin FillChar(str, SizeOf(str), 0); cef_string_list_value(resolved_ips, i, @str); TempSL.Add(CefStringClearAndGet(str)); inc(i); end; TCefResolveCallbackOwn(CefGetObject(self)).OnResolveCompleted(result, TempSL); except on e : exception do if CustomExceptionHandler('cef_resolve_callback_on_resolve_completed', e) then raise; end; finally if (TempSL <> nil) then FreeAndNil(TempSL); end; end; // TCefResolveCallbackOwn constructor TCefResolveCallbackOwn.Create; begin CreateData(SizeOf(TCefResolveCallback)); with PCefResolveCallback(FData)^ do on_resolve_completed := cef_resolve_callback_on_resolve_completed; end; // TCefCustomResolveCallback constructor TCefCustomResolveCallback.Create(const aChromiumBrowser : TObject); begin inherited Create; FChromiumBrowser := aChromiumBrowser; end; procedure TCefCustomResolveCallback.OnResolveCompleted(result: TCefErrorCode; const resolvedIps: TStrings); begin if (FChromiumBrowser <> nil) and (FChromiumBrowser is TChromium) then TChromium(FChromiumBrowser).Internal_ResolvedHostAvailable(result, resolvedIps); end; end.
unit uHashTableXML; interface uses Classes, RTLConsts, uHashTable, OmniXML, JclStrings, SysUtils; const UNIT_NAME = 'uHashTableXML'; type TFileName = string; THashStringTableXML = class(THashStringTable) private FRootNode : String; protected function XMLToHashTable( const XMLString : string; ht : THashStringTable ) : boolean; public property RootNode : string read FRootNode write FRootNode; function LoadFromFile( const FileName : TFileName ) : boolean; function SaveToFile( const FileName : TFileName ) : boolean; function AsXML() : string; constructor Create; override; constructor Create( const initialCapacity : Cardinal ); override; destructor Destroy; override; end; implementation { THashStringTableXML } constructor THashStringTableXML.Create; begin inherited Create(); FRootNode := 'THashStringTable'; end; function THashStringTableXML.AsXML: string; Var sb : TStringBuilder; i : integer; arrKeyList : TKeyList; sKeyName : string; Begin try sb := TStringbuilder.Create; sb.Append( '<' ); sb.Append( FRootNode ); sb.Append( '>' ); arrKeyList := self.Keys; for i := 0 to Length(arrKeyList) - 1 do begin sKeyName := arrKeyList[i]; sb.Append( '<' ); sb.Append( sKeyName ); sb.Append( '>' ); sb.Append( self.Items[ sKeyName ] ); sb.Append( '</' ); sb.Append( sKeyName ); sb.Append( '>' ); end; sb.Append( '</' ); sb.Append( FRootNode ); sb.Append( '>' ); Result := sb.ToString; finally FreeAndNil( sb ); end; End; constructor THashStringTableXML.Create(const initialCapacity: Cardinal); begin inherited Create(initialCapacity); end; destructor THashStringTableXML.Destroy; begin inherited; end; function THashStringTableXML.LoadFromFile(const FileName: TFileName): boolean; var xmlDoc: IXMLDocument; Begin Result := false; try xmlDoc := CreateXMLDoc; if ( xmlDoc.Load( fileName ) ) then begin Result := XMLToHashTable( xmlDoc.XML, self ); end else begin raise Exception.Create('Could not load XML from file ' + fileName + '. Are you sure it exists and is it well formed?'); end; finally end; End; function THashStringTableXML.SaveToFile(const FileName: TFileName): boolean; var xmlDoc: IXMLDocument; str : string; Begin Result := false; try xmlDoc := CreateXMLDoc; str := AsXML(); if ( xmlDoc.LoadXML( AsXML() ) ) then begin xmlDoc.Save( fileName ); Result := true; end else begin raise Exception.Create('File ' + fileName + ' could not be saved.'); end; finally end; End; function THashStringTableXML.XMLToHashTable(const XMLString: string; ht: THashStringTable): boolean; var xmlDoc: IXMLDocument; ele: IXMLElement; nod : IXMLNode; xmlNodeList : IXMLNodeList; iImageIdx : integer; Begin ht.Clear; try xmlDoc := CreateXMLDoc; if ( xmlDoc.LoadXML( XMLString ) ) then begin xmlNodeList := xmldoc.DocumentElement.ChildNodes; for iImageIdx := 0 to xmlNodeList.length - 1 do begin nod := xmlNodeList.Item[iImageIdx]; if ( nod.HasChildNodes() ) then ht.Add( nod.NodeName, nod.FirstChild.XML ) else if ( nod.nodeType = ELEMENT_NODE ) then begin ele := IXMLElement(xmlNodeList.Item[iImageIdx]); ht.Add( ele.NodeName, ele.Text ); end; end; end else begin raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?'); end; finally end; End; END.
unit AvgHolPayment_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, StdCtrls, ExtCtrls, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, IBase, z_dmCommonStyles, cxSplitter, cxTextEdit, Unit_ZGlobal_Consts, cxContainer, cxCheckBox, cxCalendar, Math, Menus, PFibStoredProc, frxClass, dxBar, dxBarExtItems, frxDBSet; type TfmHolAvg = class(TForm) DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; DSet1: TpFIBDataSet; DSet2: TpFIBDataSet; DSource1: TDataSource; DSource2: TDataSource; Panel1: TPanel; Grid1: TcxGrid; Grid1DBTableView1: TcxGridDBTableView; cmnGrid1DateBeg: TcxGridDBColumn; cmnGrid1DateEnd: TcxGridDBColumn; cmnGrid1Days: TcxGridDBColumn; Grid1Level1: TcxGridLevel; Grid2: TcxGrid; Grid2DBTableView: TcxGridDBTableView; cmnGrid2DateBeg: TcxGridDBColumn; cmnGrid2Days: TcxGridDBColumn; cmnGrid2Summa: TcxGridDBColumn; cmnGrid2Koeff: TcxGridDBColumn; cmnGrid2AvgSum: TcxGridDBColumn; HospitalTableView: TcxGridDBTableView; HospitalDateBegColumn: TcxGridDBColumn; HospitalTotalDaysColumn: TcxGridDBColumn; HospitalTotalSumColumn: TcxGridDBColumn; HospitalTotalHoursColumn: TcxGridDBColumn; Grid2Level: TcxGridLevel; Grid3: TcxGrid; Grid3DBTableView: TcxGridDBTableView; cmnGrid3VO: TcxGridDBColumn; cmnGrid3VoName: TcxGridDBColumn; cmnGrid3KodSmeta: TcxGridDBColumn; cmnGrid3Summa: TcxGridDBColumn; cmnGrid3SummaForCount: TcxGridDBColumn; cxGridDBTableView2: TcxGridDBTableView; cxGridDBColumn6: TcxGridDBColumn; cxGridDBColumn7: TcxGridDBColumn; cxGridDBColumn8: TcxGridDBColumn; cxGridDBColumn9: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; DSet3: TpFIBDataSet; DSource3: TDataSource; pmGetAvgPopupMenu: TPopupMenu; N1: TMenuItem; WriteTransaction: TpFIBTransaction; dxBarManager1: TdxBarManager; btnPrint: TdxBarLargeButton; Report: TfrxReport; frxDSetGlobalData: TfrxDBDataset; frxDBDataset1: TfrxDBDataset; frxDBDataset2: TfrxDBDataset; DSetGlobalData: TpFIBDataSet; frxUserDataSet: TfrxUserDataSet; procedure Grid2DBTableViewDataControllerSummaryAfterSummary( ASender: TcxDataSummary); procedure N1Click(Sender: TObject); procedure btnPrintClick(Sender: TObject); private { Private declarations } pLanguageIndex:Byte; pStylesDM:TStylesDM; LRmoving:Int64; public { Public declarations } constructor Create(AOwner:TComponent); overload; procedure PrepareHolAvg(ADB_Handle:TISC_DB_HANDLE;IdHol:Integer); procedure PrepareAvg(ADB_Handle:TISC_DB_HANDLE;Rmoving:Integer;KOD_SETUP_B:Integer); end; implementation uses ZProc, Dates, UAvgEdit; const FullNameReport = 'Reports\Zarplata\AvgZarplata.fr3'; {$R *.dfm} constructor TfmHolAvg.Create(AOwner:TComponent); begin inherited Create(AOwner); pLanguageIndex:=LanguageIndex; //****************************************************************************** cmnGrid1DateBeg.Caption := GridClBegPeriod_Caption[pLanguageIndex]; cmnGrid1DateEnd.Caption := GridClEndPeriod_Caption[pLanguageIndex]; cmnGrid1Days.Caption := GridClNday_Caption[pLanguageIndex]; cmnGrid2Days.Caption := GridClNday_Caption[pLanguageIndex]; cmnGrid2Summa.Caption := GridClSumma_Caption[pLanguageIndex]; cmnGrid2Koeff.Caption := GridClKoefficicent_Caption[pLanguageIndex]; cmnGrid2AvgSum.Caption := GridClCount_Caption[pLanguageIndex]; cmnGrid2DateBeg.Caption := GridClTerm_Caption[pLanguageIndex]; //****************************************************************************** cmnGrid3VO.Caption := GridClKodVidOpl_Caption[pLanguageIndex]; cmnGrid3VoName.Caption := GridClNameVidOpl_Caption[pLanguageIndex]; cmnGrid3KodSmeta.Caption := GridClKodSmeta_Caption[pLanguageIndex]; cmnGrid3Summa.Caption := GridClSumma_Caption[pLanguageIndex]; cmnGrid3SummaForCount.Caption := GridClCount_Caption[pLanguageIndex]; //****************************************************************************** pStylesDM:=TStylesDM.Create(Self); Grid1DBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; Grid2DBTableView.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; Grid3DBTableView.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; end; procedure TfmHolAvg.PrepareHolAvg(ADB_Handle:TISC_DB_HANDLE;IdHol:Integer); begin DB.Handle:=ADB_Handle; ReadTransaction.Active:=True; //****************************************************************************** DSet1.SQLs.SelectSQL.Text:='SELECT * FROM Z_COUNT_HOL_TERMS('+IntToStr(IdHol)+')'; DSet1.Open; if Dset1.RecordCount>0 then LRmoving:=DSet1['RMOVING']; DSet2.SQLs.SelectSQL.Text:='SELECT * FROM Z_COUNT_AVARAGE_PAYMENT_UNIVER('''+ VarToStr(DSet1['HOLIDAY_BEG'])+''',12,'+ VarToStr(DSet1['RMOVING'])+',?KOD_SETUP,''F'')'; DSet2.Open; DSet3.SQLs.SelectSQL.Text:='Select * FROM Z_COUNT_GET_DATA_FOR_AVG_HOL(?ID_ACCOUNT,NULL,'+VarToStr(DSet1['RMOVING'])+',?KS)'; DSet3.Open; DSetGlobalData.close; DSetGlobalData.SQLs.SelectSQL.Text:='Select * FROM Z_MAN_MOVINGS_BY_R('+ VarToStr(DSet1['RMOVING'])+', '+ VarToStr(DSet1['KOD_SETUP'])+')'; DSetGlobalData.Open; end; procedure TfmHolAvg.PrepareAvg(ADB_Handle:TISC_DB_HANDLE;Rmoving:Integer;KOD_SETUP_B:Integer); begin DB.Handle:=ADB_Handle; ReadTransaction.Active:=True; LRmoving:=Rmoving; //****************************************************************************** Grid1.Visible := False; DSet1.SQLs.SelectSQL.Text:='SELECT * FROM Z_AVARAGE_HOLIDAY('+IntToStr(Rmoving)+','+ IntToStr(KOD_SETUP_B)+',12)'; DSet1.Open; DSet2.SQLs.SelectSQL.Text:='SELECT * FROM Z_COUNT_AVARAGE_PAYMENT_UNIVER('''+ VarToStr(DSet1['DATE_BEG'])+''',12,'+ IntToStr(Rmoving)+','+IntToStr(KOD_SETUP_B)+',''F'')'; DSet2.Open; DSet3.SQLs.SelectSQL.Text:='Select * FROM Z_COUNT_GET_DATA_FOR_AVG_HOL(?ID_ACCOUNT,NULL,'+IntToStr(Rmoving)+','+IntToStr(KOD_SETUP_B)+')'; DSet3.Open; end; procedure TfmHolAvg.Grid2DBTableViewDataControllerSummaryAfterSummary( ASender: TcxDataSummary); var TotalDays:Variant; TotalSum:Variant; begin try TotalSum:=Grid2DBTableView.DataController.Summary.FooterSummaryValues[0]; TotalDays:=Grid2DBTableView.DataController.Summary.FooterSummaryValues[1]; if (not VarIsNull(TotalSum)) then ASender.DataController.Summary.FooterSummaryValues[2]:= 'Середнє = '+FloatToStr(SimpleRoundTo(VarAsType(TotalSum, varDouble)/varAsType(TotalDays,varDouble),-2)); except on E:Exception do begin end; end; end; procedure TfmHolAvg.N1Click(Sender: TObject); var InsertSP:TPFibStoredProc; ks:Integer; dcount:string; T: TfrmAvgEdit; begin if (DSet2.RecordCount>0) then begin if (DSet2.FieldByName('BEFORE_START').Value=1) then begin T:=TfrmAvgEdit.Create(self, DB.Handle); case YearMonthFromKodSetup(DSet2.FieldByName('ks').value, false) of 1, 3, 5, 7, 8, 10, 12: T.NumDays.EditValue:=31; 4, 6, 9, 11 : T.NumDays.EditValue:=30; 2:T.NumDays.EditValue:=28; end; if T.ShowModal=mrYes then begin InsertSP:=TPFibStoredProc.Create(self); InsertSP.Database:=DB; InsertSP.Transaction:=WriteTransaction; WriteTransaction.StartTransaction; InsertSP.StoredProcName:='Z_OLD_PERIOD_DATA2_IU'; InsertSP.Prepare; ks:=DSet2.FieldByName('ks').value; InsertSP.ParamByName('kod_setup').AsInteger:=ks; //od_Caption[pLanguageIndex]; //****************************************************************************** //cmnGrid2DateBeg.Caption.Value:=DSet2.FieldByName('ks').value; InsertSP.ParamByName('num_days').Value :=T.NumDays.EditValue; InsertSP.ParamByName('summa').Value :=T.SummaNar.EditValue; InsertSP.ParamByName('kod_smet').Value :=T.FidSmeta; InsertSP.ParamByName('rmoving').asInt64:=LRmoving; InsertSP.ExecProc; WriteTransaction.Commit; InsertSP.Close; InsertSP.Free; DSet2.CloseOpen(true); DSet2.Locate('ks',ks,[]); DSet3.CloseOpen(true); end; end else ShowMessage('Не можна корегувати середнє для місяця в якому зроблено розрахунок!'); end; end; procedure TfmHolAvg.btnPrintClick(Sender: TObject); var TotalDays:Variant; TotalSum:Variant; Total_AVG_SUMMA:Variant; begin TotalSum:=Grid2DBTableView.DataController.Summary.FooterSummaryValues[0]; TotalDays:=Grid2DBTableView.DataController.Summary.FooterSummaryValues[1]; Total_AVG_SUMMA:=Grid2DBTableView.DataController.Summary.FooterSummaryValues[4]; Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+FullNameReport,True); Report.Variables.Clear; Report.Variables['AVG']:=''''+'Середнє = '+FloatToStr(SimpleRoundTo(VarAsType(TotalSum, varDouble)/varAsType(TotalDays,varDouble),-2))+''''; Report.Variables['COUNT_DAYS']:=''''+FloatToStr(TotalDays)+''''; Report.Variables['SUM_SUMMA_N_KOEFF']:=''''+FloatToStr(TotalSum)+''''; Report.Variables['KOEFF']:='''===='''; Report.Variables['SUM_AVG_SUMMA']:=''''+FloatToStr(Total_AVG_SUMMA)+''''; Report.Variables['AVG_TEXT']:=''''+FloatToStr(SimpleRoundTo(VarAsType(TotalSum, varDouble)/varAsType(TotalDays,varDouble),-2))+''''; DSet1.First; Report.Variables['PERIOD_BEG']:=''''+DateToStr(DSet1['DATE_BEG'])+''''; DSet1.Last; Report.Variables['PERIOD_END']:=''''+DateToStr(DSet1['DATE_END'])+''''; DSet1.First; if zDesignReport then Report.DesignReport else Report.ShowReport; end; end.
unit EanAce; interface uses Classes, Windows, SysUtils,EanKod, Graphics, Messages, Controls,Dialogs,EanSpecs, SctCtrl, AceOut; {$I EAN.INC} type TAceCustomEan = class(TSctLabel) private FCharWidthMM : Double; FOnBeforePrint, FOnAfterPrint : TNotifyEvent; procedure SetBarCode(Value:String); procedure SetShowLabels(Value:Boolean); procedure SetTransparent(Value:Boolean); procedure SetStartStopLines(Value:Boolean); procedure SetLinesColor(Value:TColor); procedure SetBackgroundColor(Value:TColor); procedure SetSecurity(Value:Boolean); procedure SetDemoVersion(Value:Boolean); procedure SetEan13AddUp(Value:Boolean); procedure SetFontAutoSize(Value:Boolean); Function GetBarCode :String; Function GetShowLabels :Boolean; Function GetTransparent :Boolean; Function GetStartStopLines:Boolean; Function GetLinesColor :TColor; Function GetBackgroundColor :TColor; Function GetEan13AddUp :Boolean; Function GetFontAutoSize :Boolean; Function GetSecurity :Boolean; Function GetDemoVersion :Boolean; Function GetTypBarCode :TTypBarCode; Function GetLAstPaintError :TLastPaintError; Function GetAngle :integer; Procedure SetAngle(Value:Integer); Function GetLabelMask:String; Procedure SetLabelMask(Value:String); Procedure SetCharWidthMM(Value:Double); function GetCaption:TBarcodeCaption; function GetCaptionBottom:TBarcodeCaption; Procedure SetAutoSize(Value:Boolean); Function GetAutoSize:Boolean; Procedure SetDisableEditor(Value:Boolean); Function GetDisableEditor:Boolean; procedure RekalkWidthMM; {$ifdef PSOFT_PDF417} function GetPDF417:TpsPDF417; {$endif} procedure DoChange(Sender:TObject); protected FEan : TCustomEan; constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure LoadEanProperty(Stream:TStream); procedure StoreEanProperty(Stream:TStream); procedure DefineProperties(Filer: TFiler); override; procedure Paint; override; procedure SetTypBarCode(Value:TTypBarCode); virtual; property DemoVersion : Boolean Read GetDemoVersion Write SetDemoVersion; property OnBeforePrint : TNotifyEvent Read FOnBeforePrint Write FOnBeforePrint; property OnAfterPrint : TNotifyEvent Read FOnAfterPrint Write FOnAfterPrint; public procedure Next; function GetSetOfChars:string; function GetSetOfCharsVisible:String; function CheckBarCode(var S:String):Boolean; // procedure Print(OfsX,OfsY:Integer); override; procedure PrintLabel( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer); override; function LastPaintErrorText:String; procedure ActiveSetupWindow; procedure Copyright; function DigitVisible(idx:integer):Boolean; function Ean : TCustomEan; procedure DblClick; override; procedure Loaded; override; property BackgroundColor : TColor Read GetBackgroundColor Write SetBackgroundColor; property Transparent : Boolean Read GetTransparent Write SetTransparent; property ShowLabels : Boolean Read GetShowLabels Write SetShowLabels; property StartStopLines : Boolean Read GetStartStopLines Write SetStartStopLines; property TypBarCode : TTypBarCode Read GetTypBarCode Write SetTypBarCode; property LinesColor : TColor Read GetLinesColor Write SetLinesColor; property Ean13AddUp : Boolean Read GetEan13AddUp Write SetEan13AddUp; property FontAutoSize : Boolean Read GetFontAutoSize Write SetFontAutoSize; property Security : Boolean Read GetSecurity Write SetSecurity; property Font; property BarCode : string Read GetBarCode Write SetBarCode; property LastPaintError : TLastPaintError Read GetLastPaintError; property Angle : Integer Read GetAngle Write SetAngle; property LabelMask : string Read GetLabelMask Write SetLabelMask; property CharWidthMM : Double Read FCharWidthMM Write SetCharWidthMM; property Caption : TBarcodeCaption Read GetCaption; property CaptionBottom : TBarcodeCaption Read GetCaptionBottom; property AutoSize : Boolean Read GetAutoSize Write SetAutoSize; property DisableEditor : Boolean Read GetDisableEditor Write SetDisableEditor; {$ifdef PSOFT_PDF417} property PDF417:TpsPDF417 Read GetPDF417; {$endif} published property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; TAceEan = class(TAceCustomEan) published property BackgroundColor; property Transparent; property ShowLabels; property StartStopLines; property TypBarCode; property LinesColor; property Ean13AddUp; property FontAutoSize; property Security; property DemoVersion; property Font; property LastPaintError; property BarCode; property Angle; property LabelMask; property CharWidthMM; property Caption; property CaptionBottom; property AutoSize; property DisableEditor; // property Size; property OnBeforePrint; property OnAfterPrint; {$ifdef PSOFT_PDF417} property PDF417; {$endif} end; implementation uses Forms, EanFmt2 ; constructor TAceCustomEan.Create(AOwner:TComponent); var i:Integer; begin inherited Create(AOwner); FEan := TEan.Create(self); FEan.Security := False; FEan.PDF417.OnChange := DoChange; i:=FEan.MinWidth; if Width<i then Width:=i; Height := FEan.Height; Width := FEan.Width; FCharWidthMM := 0; end; destructor TAceCustomEan.Destroy; begin inherited Destroy; end; procedure TAceCustomEan.LoadEanProperty(Stream:TStream); begin Stream.ReadComponent(FEan); end; procedure TAceCustomEan.StoreEanProperty(Stream:TStream); begin Stream.WriteComponent(FEan); end; procedure TAceCustomEan.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Ean', LoadEanProperty, StoreEanProperty, True ); end; {$ifdef PSOFT_PDF417} function TAceCustomEan.GetPDF417:TpsPDF417; begin Result := FEan.PDF417; end; {$endif} procedure TAceCustomEan.RekalkWidthMM; var SizeMM : Double; begin{ if CharWidthMM<>0 then begin SizeMM:=CharWidthMM*Length(FEan.Barcode); case Self.ParentReport.Units of Characters : ; MM : Size.Width := Round(SizeMM); Inches : Size.Width := Round(SizeMM/25.4); Native : Size.Width := Round(10*SizeMM); Pixels : ; end; end; } end; procedure TAceCustomEan.SetBarCode(Value:String); begin if FEan.BarCode<>Value then begin FEan.BarCode:=Value; RekalkWidthMM; Invalidate; end; end; procedure TAceCustomEan.SetShowLabels(Value:Boolean); begin if FEan.ShowLabels<>Value then begin FEan.ShowLabels:=Value; Invalidate; end; end; procedure TAceCustomEan.SetTransparent(Value:Boolean); begin if FEan.Transparent<>Value then begin FEan.Transparent:=Value; Invalidate; end; end; procedure TAceCustomEan.SetStartStopLines(Value:Boolean); begin if FEan.StartStopLines<>Value then begin FEan.StartStopLines:=Value; Invalidate; end; end; procedure TAceCustomEan.SetLinesColor(Value:TColor); begin if FEan.LinesColor<>Value then begin FEan.LinesColor:=Value; Invalidate; end; end; procedure TAceCustomEan.SetBackgroundColor(Value:TColor); begin if FEan.BackgroundColor<>Value then begin FEan.BackgroundColor:=Value; Invalidate; end; end; procedure TAceCustomEan.SetEan13AddUp(Value:Boolean); begin if FEan.Ean13AddUp<>Value then begin FEan.Ean13AddUp:=Value; Invalidate; end; end; procedure TAceCustomEan.SetFontAutoSize(Value:Boolean); begin if FEan.FontAutoSize<>Value then begin FEan.FontAutoSize:=Value; Invalidate; end; end; procedure TAceCustomEan.SetSecurity(Value:Boolean); begin if FEan.Security<>Value then begin FEan.Security:=Value; Invalidate; end; end; procedure TAceCustomEan.SetDemoVersion(Value:Boolean); begin if FEan.DemoVersion<>Value then begin FEan.DemoVersion:=Value; Invalidate; end; end; procedure TAceCustomEan.SetTypBarCode(Value:TTypBarCode); var i:Integer; begin if FEan.TypBarCode<>Value then begin FEan.TypBarCode:=Value; RekalkWidthMM; i:=fEan.MinWidth; if Width<i then Width := i; Invalidate; end; end; Function TAceCustomEan.GetBarCode :String; begin Result:=FEan.BarCode; end; Function TAceCustomEan.GetShowLabels :Boolean; begin Result:=FEan.ShowLabels; end; Function TAceCustomEan.GetTransparent :Boolean; begin Result:=FEan.Transparent; end; Function TAceCustomEan.GetStartStopLines:Boolean; begin Result:=FEan.StartStopLines; end; Function TAceCustomEan.GetLinesColor :TColor; begin Result:=FEan.LinesColor; end; Function TAceCustomEan.GetBackgroundColor :TColor; begin Result:=FEan.BackgroundColor; end; Function TAceCustomEan.GetEan13AddUp :Boolean; begin Result:=FEan.Ean13AddUp; end; Function TAceCustomEan.GetFontAutoSize :Boolean; begin Result:=FEan.FontAutoSize; end; Function TAceCustomEan.GetSecurity :Boolean; begin Result:=FEan.Security; end; Function TAceCustomEan.GetDemoVersion:Boolean; begin Result:=FEan.DemoVersion; end; Function TAceCustomEan.GetTypBarCode :TTypBarCode; begin Result:=fEan.TypBarCode; end; Function TAceCustomEan.GetLastPaintError :TLastPaintError; begin Result:=fEan.LastPaintError; end; procedure TAceCustomEan.Paint; begin RekalkWidthMM; PaintBarCode(Canvas,Rect(0,0,Width,Height),FEan); end; procedure TAceCustomEan.Next; begin FEan.Next; end; function TAceCustomEan.GetSetOfChars:string; begin Result:=FEan.GetSetOfChars; end; function TAceCustomEan.GetSetOfCharsVisible:String; begin Result:=FEan.GetSetOfCharsVisible; end; function TAceCustomEan.CheckBarCode(var S:String):Boolean; begin Result:=FEan.CheckBarCode(S); end; procedure TAceCustomEan.PrintLabel( AceCanvas: TAceCanvas; Rect: TRect; Space: Integer); var R : TRect; Bitmap : TBitmap; begin if Assigned(FOnBeforePrint) then FOnBeforePrint(Self); RekalkWidthMM; bitmap:=TBitmap.Create; try Bitmap.PixelFormat := pf4Bit; Bitmap.Height := Height; Bitmap.Width := FEan.MinWidth; R.Left := 0; R.Top := 0; R.Right := Bitmap.Width; R.Bottom := Rect.Bottom - Rect.Top; PaintBarCode(Bitmap.Canvas, R,FEan); AceCanvas.Draw(Rect.Left, Rect.Top, Bitmap); finally Bitmap.Free; end; if Assigned(FOnAfterPrint) then FOnAfterPrint(Self); end; function TAceCustomEan.Ean : TCustomEan; begin Result := FEan; end; function TAceCustomEan.LastPaintErrorText:String; begin Result:=FEan.LastPaintErrorText; end; Function TAceCustomEan.GetAngle:integer; begin Result := FEan.Angle; end; Procedure TAceCustomEan.SetAngle(Value:Integer); begin FEan.Angle := Value; Invalidate; end; procedure TAceCustomEAN.ActiveSetupWindow; begin FEan.ActiveSetupWindow(''); end; procedure TAceCustomEAN.Copyright; begin FEan.Copyright; end; function TAceCustomEAN.DigitVisible(idx:integer):Boolean; begin Result := True; if Length(LabelMask)>=idx then if LabelMask[idx]<>'_' then Result:=False; end; procedure TAceCustomEan.DblClick; begin if not Assigned(OnDblClick) then ActiveSetupWindow else inherited DblClick; end; Function TAceCustomEan.GetLabelMask:String; begin Result := FEan.LabelMask; end; Procedure TAceCustomEan.SetLabelMask(Value:String); begin FEan.LabelMask := Value; end; Procedure TAceCustomEan.SetCharWidthMM(Value:Double); var s:String; begin FCharWidthMM := Value; RekalkWidthMM; end; function TAceCustomEan.GetCaption:TBarcodeCaption; begin Result := FEan.Caption; end; function TAceCustomEan.GetCaptionBottom:TBarcodeCaption; begin Result := FEan.CaptionBottom; end; Procedure TAceCustomEan.SetAutoSize(Value:Boolean); var i:Integer; begin FEan.AutoSize := Value; i:=FEan.MinWidth; if Width<i then Width := i; end; Function TAceCustomEan.GetAutoSize:Boolean; begin Result := FEan.AutoSize; end; Procedure TAceCustomEan.SetDisableEditor(Value:Boolean); begin FEan.DisableEditor:=Value; end; Function TAceCustomEan.GetDisableEditor:Boolean; begin Result := FEan.DisableEditor; end; procedure TAceCustomEan.Loaded; begin inherited Loaded; RekalkWidthMM; end; procedure TAceCustomEan.DoChange(Sender:TObject); begin Invalidate; end; end.
unit StringUtilClass; { 字符串工具类 } interface uses SysUtils, Variants, Classes; function ChnToPY(Value: string): string; //取拼音首字母 implementation const py: array[216..247] of string = ( {216}'CJWGNSPGCGNESYPB' + 'TYYZDXYKYGTDJNMJ' + 'QMBSGZSCYJSYYZPG' + {216}'KBZGYCYWYKGKLJSW' + 'KPJQHYZWDDZLSGMR' + 'YPYWWCCKZNKYDG', {217}'TTNJJEYKKZYTCJNM' + 'CYLQLYPYQFQRPZSL' + 'WBTGKJFYXJWZLTBN' + {217}'CXJJJJZXDTTSQZYC' + 'DXXHGCKBPHFFSSYY' + 'BGMXLPBYLLLHLX', {218}'SPZMYJHSOJNGHDZQ' + 'YKLGJHXGQZHXQGKE' + 'ZZWYSCSCJXYEYXAD' + {218}'ZPMDSSMZJZQJYZCD' + 'JEWQJBDZBXGZNZCP' + 'WHKXHQKMWFBPBY', {219}'DTJZZKQHYLYGXFPT' + 'YJYYZPSZLFCHMQSH' + 'GMXXSXJJSDCSBBQB' + {219}'EFSJYHXWGZKPYLQB' + 'GLDLCCTNMAYDDKSS' + 'NGYCSGXLYZAYBN', {220}'PTSDKDYLHGYMYLCX' + 'PYCJNDQJWXQXFYYF' + 'JLEJBZRXCCQWQQSB' + {220}'ZKYMGPLBMJRQCFLN' + 'YMYQMSQYRBCJTHZT' + 'QFRXQHXMJJCJLX', {221}'QGJMSHZKBSWYEMYL' + 'TXFSYDSGLYCJQXSJ' + 'NQBSCTYHBFTDCYZD' + {221}'JWYGHQFRXWCKQKXE' + 'BPTLPXJZSRMEBWHJ' + 'LBJSLYYSMDXLCL', {222}'QKXLHXJRZJMFQHXH' + 'WYWSBHTRXXGLHQHF' + 'NMCYKLDYXZPWLGGS' + {222}'MTCFPAJJZYLJTYAN' + 'JGBJPLQGDZYQYAXB' + 'KYSECJSZNSLYZH', {223}'ZXLZCGHPXZHZNYTD' + 'SBCJKDLZAYFMYDLE' + 'BBGQYZKXGLDNDNYS' + {223}'KJSHDLYXBCGHXYPK' + 'DQMMZNGMMCLGWZSZ' + 'XZJFZNMLZZTHCS', {224}'YDBDLLSCDDNLKJYK' + 'JSYCJLKOHQASDKNH' + 'CSGANHDAASHTCPLC' + {224}'PQYBSDMPJLPCJOQL' + 'CDHJJYSPRCHNKNNL' + 'HLYYQYHWZPTCZG', {225}'WWMZFFJQQQQYXACL' + 'BHKDJXDGMMYDJXZL' + 'LSYGXGKJRYWZWYCL' + {225}'ZMSSJZLDBYDCPCXY' + 'HLXCHYZJQSQQAGMN' + 'YXPFRKSSBJLYXY', {226}'SYGLNSCMHCWWMNZJ' + 'JLXXHCHSYD CTXRY' + 'CYXBYHCSMXJSZNPW' + {226}'GPXXTAYBGAJCXLYS' + 'DCCWZOCWKCCSBNHC' + 'PDYZNFCYYTYCKX', {227}'KYBSQKKYTQQXFCWC' + 'HCYKELZQBSQYJQCC' + 'LMTHSYWHMKTLKJLY' + {227}'CXWHEQQHTQHZPQSQ' + 'SCFYMMDMGBWHWLGS' + 'LLYSDLMLXPTHMJ', {228}'HWLJZYHZJXHTXJLH' + 'XRSWLWZJCBXMHZQX' + 'SDZPMGFCSGLSXYMJ' + {228}'SHXPJXWMYQKSMYPL' + 'RTHBXFTPMHYXLCHL' + 'HLZYLXGSSSSTCL', {229}'SLDCLRPBHZHXYYFH' + 'BBGDMYCNQQWLQHJJ' + 'ZYWJZYEJJDHPBLQX' + {229}'TQKWHLCHQXAGTLXL' + 'JXMSLXHTZKZJECXJ' + 'CJNMFBYCSFYWYB', {230}'JZGNYSDZSQYRSLJP' + 'CLPWXSDWEJBJCBCN' + 'AYTWGMPABCLYQPCL' + {230}'ZXSBNMSGGFNZJJBZ' + 'SFZYNDXHPLQKZCZW' + 'ALSBCCJXJYZHWK', {231}'YPSGXFZFCDKHJGXD' + 'LQFSGDSLQWZKXTMH' + 'SBGZMJZRGLYJBPML' + {231}'MSXLZJQQHZSJCZYD' + 'JWBMJKLDDPMJEGXY' + 'HYLXHLQYQHKYCW', {232}'CJMYYXNATJHYCCXZ' + 'PCQLBZWWYTWBQCML' + 'PMYRJCCCXFPZNZZL' + {232}'JPLXXYZTZLGDLDCK' + 'LYRLZGQTGJHHGJLJ' + 'AXFGFJZSLCFDQZ', {233}'LCLGJDJCSNCLLJPJ' + 'QDCCLCJXMYZFTSXG' + 'CGSBRZXJQQCTZHGY' + {233}'QTJQQLZXJYLYLBCY' + 'AMCSTYLPDJBYREGK' + 'JZYZHLYSZQLZNW', {234}'CZCLLWJQJJJKDGJZ' + 'OLBBZPPGLGHTGZXY' + 'GHZMYCNQSYCYHBHG' + {234}'XKAMTXYXNBSKYZZG' + 'JZLQJDFCJXDYGJQJ' + 'JPMGWGJJJPKQSB', {235}'GBMMCJSSCLPQPDXC' + 'DYYKYWCJDDYYGYWR' + 'HJRTGZNYQLDKLJSZ' + {235}'ZGZQZJGDYKSHPZMT' + 'LCPWNJAFYZDJCNMW' + 'ESCYGLBTZCGMSS', {236}'LLYXQSXSBSJSBBGG' + 'GHFJLYPMZJNLYYWD' + 'QSHZXTYYWHMCYHYW' + {236}'DBXBTLMSYYYFSXJC' + 'SDXXLHJHF SXZQHF' + 'ZMZCZTQCXZXRTT', {237}'DJHNNYZQQMNQDMMG' + 'LYDXMJGDHCDYZBFF' + 'ALLZTDLTFXMXQZDN' + {237}'GWQDBDCZJDXBZGSQ' + 'QDDJCMBKZFFXMKDM' + 'DSYYSZCMLJDSYN', {238}'SPRSKMKMPCKLGDBQ' + 'TFZSWTFGGLYPLLJZ' + 'HGJJGYPZLTCSMCNB' + {238}'TJBQFKTHBYZGKPBB' + 'YMTDSSXTBNPDKLEY' + 'CJNYCDYKZDDHQH', {239}'SDZSCTARLLTKZLGE' + 'CLLKJLQJAQNBDKKG' + 'HPJTZQKSECSHALQF' + {239}'MMGJNLYJBBTMLYZX' + 'DCJPLDLPCQDHZYCB' + 'ZSCZBZMSLJFLKR', {240}'ZJSNFRGJHXPDHYJY' + 'BZGDLJCSEZGXLBLH' + 'YXTWMABCHECMWYJY' + {240}'ZLLJJYHLGBDJLSLY' + 'GKDZPZXJYYZLWCXS' + 'ZFGWYYDLYHCLJS', {241}'CMBJHBLYZLYCBLYD' + 'PDQYSXQZBYTDKYYJ' + 'YYCNRJMPDJGKLCLJ' + {241}'BCTBJDDBBLBLCZQR' + 'PPXJCGLZCSHLTOLJ' + 'NMDDDLNGKAQHQH', {242}'JHYKHEZNMSHRP QQ' + 'JCHGMFPRXHJGDYCH' + 'GHLYRZQLCYQJNZSQ' + {242}'TKQJYMSZSWLCFQQQ' + 'XYFGGYPTQWLMCRNF' + 'KKFSYYLQBMQAMM', {243}'MYXCTPSHCPTXXZZS' + 'MPHPSHMCLMLDQFYQ' + 'XSZYJDJJZZHQPDSZ' + {243}'GLSTJBCKBXYQZJSG' + 'PSXQZQZRQTBDKYXZ' + 'KHHGFLBCSMDLDG', {244}'DZDBLZYYCXNNCSYB' + 'ZBFGLZZXSWMSCCMQ' + 'NJQSBDQSJTXXMBLT' + {244}'XZCLZSHZCXRQJGJY' + 'LXZFJPHYXZQQYDFQ' + 'JJLZZNZJCDGZYG', {245}'CTXMZYSCTLKPHTXH' + 'TLBJXJLXSCDQXCBB' + 'TJFQZFSLTJBTKQBX' + {245}'XJJLJCHCZDBZJDCZ' + 'JDCPRNPQCJPFCZLC' + 'LZXBDMXMPHJSGZ', {246}'GSZZQLYLWTJPFSYA' + 'SMCJBTZYYCWMYTCS' + 'JJLQCQLWZMALBXYF' + {246}'BPNLSFHTGJWEJJXX' + 'GLLJSTGSHJQLZFKC' + 'GNNDSZFDEQFHBS', {247}'AQTGYLBXMMYGSZLD' + 'YDQMJJRGBJTKGDHG' + 'KBLQKBDMBYLXWCXY' + {247}'TTYBKMRTJZXQJBHL' + 'MHMJJZMQASLDCYXY' + 'QDLQCAFYWYXQHZ' ); function ChnPy(Value: array of char): Char; begin Result := #0; case Byte(Value[0]) of 176: case Byte(Value[1]) of 161..196: Result := 'A'; 197..254: Result := 'B'; end; {case} 177: Result := 'B'; 178: case Byte(Value[1]) of 161..192: Result := 'B'; 193..205: Result := 'C'; 206: Result := 'S'; 207..254: Result := 'C'; end; {case} 179: Result := 'C'; 180: case Byte(Value[1]) of 161..237: Result := 'C'; 238..254: Result := 'D'; end; {case} 181: Result := 'D'; 182: case Byte(Value[1]) of 161..233: Result := 'D'; 234..254: Result := 'E'; end; {case} 183: case Byte(Value[1]) of 161: Result := 'E'; 162..254: Result := 'F'; end; {case} 184: case Byte(Value[1]) of 161..192: Result := 'F'; 193..254: Result := 'G'; end; {case} 185: case Byte(Value[1]) of 161..253: Result := 'G'; 254: Result := 'H'; end; {case} 186: Result := 'H'; 187: case Byte(Value[1]) of 161..246: Result := 'H'; 247..254: Result := 'J'; end; {case} 188..190: Result := 'J'; 191: case Byte(Value[1]) of 161..165: Result := 'J'; 166..254: Result := 'K'; end; {case} 192: case Byte(Value[1]) of 161..171: Result := 'K'; 172..254: Result := 'L'; end; {case} 193: Result := 'L'; 194: case Byte(Value[1]) of 161..231: Result := 'L'; 232..254: Result := 'M'; end; {case} 195: Result := 'M'; 196: case Byte(Value[1]) of 161..194: Result := 'M'; 195..254: Result := 'N'; end; {case} 197: case Byte(Value[1]) of 161..181: Result := 'N'; 182..189: Result := 'O'; 190..254: Result := 'P'; end; {case} 198: case Byte(Value[1]) of 161..217: Result := 'P'; 218..254: Result := 'Q'; end; {case} 199: Result := 'Q'; 200: case Byte(Value[1]) of 161..186: Result := 'Q'; 187..245: Result := 'R'; 246..254: Result := 'S'; end; {case} 201..202: Result := 'S'; 203: case Byte(Value[1]) of 161..249: Result := 'S'; 250..254: Result := 'T'; end; {case} 204: Result := 'T'; 205: case Byte(Value[1]) of 161..217: Result := 'T'; 218..254: Result := 'W'; end; {case} 206: case Byte(Value[1]) of 161..243: Result := 'W'; 244..254: Result := 'X'; end; {case} 207..208: Result := 'X'; 209: case Byte(Value[1]) of 161..184: Result := 'X'; 185..254: Result := 'Y'; end; {case} 210..211: Result := 'Y'; 212: case Byte(Value[1]) of 161..208: Result := 'Y'; 209..254: Result := 'Z'; end; {case} 213..215: Result := 'Z'; 216..247: Result := py[Byte(Value[0])][Byte(Value[1]) - 160]; end; {case} end; function ChnToPY(Value: string): string; var I, L: Integer; C: array[0..1] of char; R: Char; begin Result := ''; L := Length(Value); I := 1; while I <= (L - 1) do begin if Value[I] < #160 then begin Result := Result + Value[I]; Inc(I); end else begin C[0] := Value[I]; C[1] := Value[I + 1]; R := ChnPY(C); if r <> #0 then Result := Result + R; Inc(I, 2); end; end; if I = L then Result := Result + Value[L]; end; end.
{ Modifications: ============== ie01: OnChange delayed for 500 ms. ie02: No usage of BrowseDirectory component ie03: Resume suspended thread when terminating the thread } // ==================== DISC DRIVE MONITOR ===================================== // // Class and Component to encapsulate the FindXXXXChangeNotification API calls // // The FindXXXXChangeNotification API calls set up a disc contents change // notification handle. You can set a filter to control which change types // are notified, the directory which is monitored and set whether subdirectories // from the monitored directory are monitored as well. // //------------------------------------------------------------------------------ // This file contains a class derived from TThread which undertakes the disc // monitoring and a simple component which encapsulates the thread to make // a non-visual VCL component. This component works at design time, monitoring // and notifying changes live if required. // // Version 1.00 - Grahame Marsh 14 January 1997 // Version 1.01 - Grahame Marsh 30 December 1997 // Bug fix - really a Win 95 bug but only surfaces in D3, not D2 // - see notes in execute method // Version 1.02 - Grahame Marsh 30 January 1998 // - adapted to work with version 2.30 TBrowseDirectoryDlg // // Freeware - you get it for free, I take nothing, I make no promises! // // Please feel free to contact me: grahame.s.marsh@courtaulds.com unit DiscMon; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ShlObj{, BrowseDr, DsgnIntf ie02}; //=== DISC MONITORING THREAD =================================================== // This thread will monitor a given directory and subdirectories (if required) // for defined filtered changes. When a change occurs the OnChange event will // be fired, if an invalid condition is found (eg non-existent path) then // the OnInvalid event is fired. Each event is called via the Sychronize method // and so are VCL thread safe. // // The thread is created suspended, so after setting the required properties // you must call the Resume method. type TDiscMonitorThread = class(TThread) private FOnChange : TNotifyEvent; FOnInvalid : TNotifyEvent; FDirectory : string; FFilters : integer; FDestroyEvent, FChangeEvent : THandle; FSubTree : boolean; fChangeDelay : Integer; {ie01} procedure InformChange; procedure InformInvalid; procedure SetDirectory (const Value : string); procedure SetFilters (Value : integer); procedure SetSubTree (Value : boolean); protected procedure Execute; override; procedure Update; public constructor Create; destructor Destroy; override; // The directory to monitor property Directory : string read FDirectory write SetDirectory; // Filter condition, may be any of the FILE_NOTIFY_CHANGE_XXXXXXX constants // ORed together. Zero is invalid. property Filters : integer read FFilters write SetFilters; // Event called when change noted in directory property OnChange : TNotifyEvent read FOnChange write FOnChange; // Event called for invalid parameters property OnInvalid : TNotifyEvent read FOnInvalid write FOnInvalid; // Include subdirectories below specified directory. property SubTree : boolean read FSubTree write SetSubTree; // specify, how long the thread should wait, before the event OnChange is fired: Property ChangeDelay : Integer Read fChangeDelay Write fChangeDelay {ie01} Default 500; {ie01} end; //===================== DISC MONITORING COMPONENT ============================== // specify directory string as type string so we can have our own property editor TDiscMonitorDirStr = type string; // enumerated type for filter conditions (not directly usable in thread class) // see the SetFilters procedure for the translation of these filter conditions // into FILE_NOTIFY_CHANGE_XXXXXX constants. TMonitorFilter = (moFilename, moDirName, moAttributes, moSize, moLastWrite, moSecurity); // set of filter conditions TMonitorFilters = set of TMonitorFilter; TDiscMonitor = class(TComponent) private FActive : boolean; FMonitor : TDiscMonitorThread; FFilters : TMonitorFilters; FOnChange : TNotifyEvent; FOnInvalid : TNotifyEvent; FShowMsg : boolean; function GetDirectory : TDiscMonitorDirStr; function GetSubTree : boolean; procedure SetActive (Value : boolean); procedure SetDirectory (Value : TDiscMonitorDirStr); procedure SetFilters (Value : TMonitorFilters); procedure SetSubTree (Value : boolean); Function GetChangeDelay : Integer; {ie01} Procedure SetChangeDelay(Value : Integer); {ie01} protected procedure Change (Sender : TObject); procedure Invalid (Sender : TObject); public constructor Create (AOwner : TComponent); Override; destructor Destroy; override; // stop the monitoring thread running procedure Close; // start the monitoring thread running procedure Open; // read-only property to access the thread directly property Thread : TDiscMonitorThread read FMonitor; procedure Update; published // the directory to monitor property Directory : TDiscMonitorDirStr read GetDirectory write SetDirectory; // control the appearance of information messages at design time (only) property ShowDesignMsg : boolean read FShowMsg write FShowMsg default false; // event called when a change is notified property OnChange : TNotifyEvent read FOnChange write FOnChange; // event called if an invalid condition is found property OnInvalid : TNotifyEvent read FOnInvalid write FOnInvalid; // notification filter conditions property Filters : TMonitorFilters read FFilters write SetFilters default [moFilename]; // include subdirectories below the specified directory property SubTree : boolean read GetSubTree write SetSubTree default true; // specify if the monitoring thread is active property Active : boolean read FActive write SetActive default false; // specify, how long the thread should wait, before the event OnChange is fired: Property ChangeDelay : Integer Read GetChangeDelay Write SetChangeDelay {ie01} Default 500; {ie01} end; procedure Register; implementation //=== MONITOR THREAD =========================================================== // Create the thread suspended. Create two events, each are created using // standard security, in the non-signalled state, with auto-reset and without // names. The FDestroyEvent will be used to signal the thread that it is to close // down. The FChangeEvent will be used to signal the thread when the monitoring // conditions (directory, filters or sub-directory search) have changed. // OnTerminate is left as false, so the user must Free the thread. constructor TDiscMonitorThread.Create; begin inherited Create (true); FDestroyEvent := CreateEvent (nil, true, false, NIL); FChangeEvent := CreateEvent (nil, false, false, NIL); end; // close OnXXXXX links, signal the thread that it is to close down destructor TDiscMonitorThread.Destroy; begin FOnChange := nil; FOnInvalid := nil; IF Suspended Then {ie03} Resume; {ie03} SetEvent (FDestroyEvent); FDirectory := ''; inherited Destroy end; // called by the Execute procedure via Synchronize. So this is VCL thread safe procedure TDiscMonitorThread.InformChange; begin if Assigned (FOnChange) then FOnChange (Self) end; // called by the Execute procedure via Synchronize. So this is VCL thread safe procedure TDiscMonitorThread.InformInvalid; begin if Assigned (FOnInvalid) then FOnInvalid (Self) end; // Change the current directory procedure TDiscMonitorThread.SetDirectory (const Value : string); begin if Value <> FDirectory then begin FDirectory := Value; Update end end; // Change the current filters procedure TDiscMonitorThread.SetFilters (Value : integer); begin if Value <> FFilters then begin FFilters := Value; Update end end; // Change the current sub-tree condition procedure TDiscMonitorThread.SetSubTree (Value : boolean); begin if Value <> FSubTree then begin FSubtree := Value; Update end end; Function TDiscMonitor.GetChangeDelay : Integer; {ie01} begin Result := FMonitor.ChangeDelay; end; Procedure TDiscMonitor.SetChangeDelay(Value : Integer); {ie01} begin FMonitor.ChangeDelay := Value; end; // On any of the above three changes, if the thread is running then // signal it that a change has occurred. procedure TDiscMonitorThread.Update; begin if not Suspended then SetEvent (FChangeEvent) end; // The EXECUTE procedure // ------- // Execute needs to: // 1. Call FindFirstChangeNotification and use the Handle in a WaitFor... // to wait until the thread become signalled that a notification has occurred. // The OnChange event is called and then the FindNextChangeNotification is // the called and Execute loops back to the WaitFor // 2. If an invalid handle is obtained from the above call, the the OnInvalid // event is called and then Execute waits until valid conditions are set. // 3. If a ChangeEvent is signalled then FindCloseChangeNotification is called, // followed by a new FindFirstChangeNotification to use the altered // conditions. // 4. If a DestroyEvent is signalled then FindCloseChangeNotification is // called and the two events are closed and the thread terminates. // // In practice WaitForMultipleObjects is used to wait for any of the conditions // to be signalled, and the returned value used to determine which event occurred. procedure TDiscMonitorThread.Execute; // There appears to be a bug in win 95 where the bWatchSubTree parameter // of FindFirstChangeNotification which is a BOOL only accepts values of // 0 and 1 as valid, rather than 0 and any non-0 value as it should. In D2 // BOOL was defined as 0..1 so the code worked, in D3 it is 0..-1 so // fails. The result is FindF... produces and error message. This fix (bodge) is // needed to produce a 0,1 bool pair, rather that 0,-1 as declared in D3 const R : array [false..true] of BOOL = (BOOL (0), BOOL (1)); var A : array [0..2] of THandle; // used to give the handles to WaitFor... B : boolean; // set to true when the thread is to terminate begin B := false; A [0] := FDestroyEvent; // put DestroyEvent handle in slot 0 A [1] := FChangeEvent; // put ChangeEvent handle in slot 1 // make the first call to the change notification system and put the returned // handle in slot 2. A [2] := FindFirstChangeNotification (PChar(FDirectory), R[fSubTree], FFilters); repeat // if the change notification handle is invalid then: if A [2] = INVALID_HANDLE_VALUE then begin // call the OnInvalid event Synchronize (InformInvalid); // wait until either DestroyEvent or the ChangeEvents are signalled case WaitForMultipleObjects (2, PWOHandleArray (@A), false, INFINITE) - WAIT_OBJECT_0 of // DestroyEvent - close down by setting B to true 0 : B := true; // try new conditions and loop back to the invalid handle test 1 : A [2] := FindFirstChangeNotification (PChar(FDirectory), R[fSubTree], FFilters) end end else // handle is valid so wait for any of the change notification, destroy or // change events to be signalled case WaitForMultipleObjects (3, PWOHandleArray (@A), false, INFINITE) - WAIT_OBJECT_0 of 0 : begin // DestroyEvent signalled so use FindClose... and close down by setting B to true FindCloseChangeNotification (A [2]); B := true end; 1 : begin // ChangeEvent signalled so close old conditions by FindClose... and start // off new conditions. Loop back to invalid test in case new conditions are // invalid FindCloseChangeNotification (A [2]); A [2] := FindFirstChangeNotification (PChar(FDirectory), R[fSubTree], FFilters) end; 2 : begin // Notification signalled, so fire the OnChange event and then FindNext.. // loop back to re-WaitFor... the thread Sleep(fChangeDelay); {ie01 ins} Synchronize (InformChange); FindNextChangeNotification (A [2]) end; end until B Or Self.Terminated; // closing down so chuck the two events CloseHandle (FChangeEvent); CloseHandle (FDestroyEvent) end; //=== MONITOR COMPONENT ======================================================== // This component encapsulates the above thread. It has properties for // directory, sub-directory conditions, filters, whether information messages // should be given at design time and if the thread is active. constructor TDiscMonitor.Create (AOwner : TComponent); begin inherited Create (AOwner); FMonitor := TDiscMonitorThread.Create; // create a monitor thread FMonitor.ChangeDelay := 500; {ie01} FMonitor.OnChange := Change; // hook into its event handlers FMonitor.OnInvalid := Invalid; Filters := [moFilename]; // default filters to moFilename SubTree := true // default sub-tree search to on end; destructor TDiscMonitor.Destroy; begin FMonitor.Free; // chuck the thread inherited Destroy end; // Change notification from the thread has occurred. Call the component's event // handler and then, if in design mode, and if desired, put up a simple // notification message procedure TDiscMonitor.Change; begin if Assigned (FOnChange) then FOnChange (Self) else if (csDesigning in ComponentState) and FShowMsg then ShowMessage ('Change signalled') end; // Invalid notification from the thread has occurred. Call the component's event // handler and then, if in design mode, and if desired, put up a simple // notification message procedure TDiscMonitor.Invalid; begin if Assigned (FOnInvalid) then FOnInvalid (Self) else if (csDesigning in ComponentState) and FShowMsg then ShowMessage ('Invalid parameter signalled') end; // Stop the monitor running procedure TDiscMonitor.Close; begin Active := false end; // Run the monitor procedure TDiscMonitor.Open; begin Active := true end; // Control the thread by using it's resume and suspend methods procedure TDiscMonitor.SetActive (Value : boolean); begin if Value <> FActive then begin FActive := Value; if Active then begin FMonitor.Resume; FMonitor.Update end else FMonitor.Suspend end end; // get the current directory from the thread function TDiscMonitor.GetDirectory : TDiscMonitorDirStr; begin Result := FMonitor.Directory end; // get the current sub-tree status from the thread function TDiscMonitor.GetSubTree : boolean; begin Result := FMonitor.SubTree end; // set the directory to monitor procedure TDiscMonitor.SetDirectory (Value : TDiscMonitorDirStr); begin FMonitor.Directory := Value end; procedure TDiscMonitor.Update; begin FMonitor.Update; end; // Change the filter conditions. The thread uses the raw windows constants // (FILE_NOTIFY_CHANGE_XXXX) but the components uses a set of enumurated type. // It is therefore necessary to translate from the component format into // an integer value for the thread. procedure TDiscMonitor.SetFilters (Value : TMonitorFilters); const XlatFileNotify : array [moFilename..moSecurity] of integer = (FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY); var L : TMonitorFilter; I : integer; begin if Value <> FFilters then if Value = [] then ShowMessage ('Some filter condition must be set.') else begin FFilters := Value; I := 0; for L := moFilename to moSecurity do if L in Value then I := I or XlatFileNotify [L]; FMonitor.Filters := I; end end; // set the sub-tree status in the thread procedure TDiscMonitor.SetSubTree (Value : boolean); begin FMonitor.SubTree := Value end; {ie02 TBrowseDirectoryDlg deleted.} procedure Register; begin RegisterComponents ('Tools', [TDiscMonitor]); {RegisterPropertyEditor (TypeInfo (TDiscMonitorDirStr), nil, '', TDiscMonitorDirStrProperty);} end; end.
unit uDwm.NoBorderForm; interface uses Windows, Classes, Messages, SysUtils, Forms, UxTheme, Dwmapi; type TDwmAero = class(TObject) public class function OSMajorVersion: Cardinal; class function IsAeroEnabled: Boolean; class procedure SetShadow(Handle: THandle); class procedure SetFramesSize(Handle: Cardinal; Left, Top, Width, Height: Integer; var FrameSize: Integer); end; TDwmNoBorderForm = class(TComponent) private FParent: TForm; FOldWndProc: TWndMethod; FOSMajorVersion: Cardinal; FAeroEnabled: Boolean; FEnabledShadow: Boolean; FEnabledNoBorder: Boolean; protected procedure WndProc(var Msg: TMessage); virtual; procedure SetEnabledShadow(const Value: Boolean); procedure SetEnabledNoBorder(const Value: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property EnabledShadow: Boolean read FEnabledShadow write SetEnabledShadow default True; property EnabledNoBorder: Boolean read FEnabledNoBorder write SetEnabledNoBorder default True; end; implementation class function TDwmAero.OSMajorVersion: Cardinal; begin Result := Win32MajorVersion; end; class function TDwmAero.IsAeroEnabled: Boolean; begin Result := DwmCompositionEnabled; end; class procedure TDwmAero.SetShadow(Handle: THandle); const dwAttribute = 2; cbAttribute = 4; var pvAttribute: Integer; pMarInset: TMargins; begin pvAttribute := 2; DwmSetWindowAttribute(Handle, dwAttribute, @pvAttribute, cbAttribute); pMarInset.cxLeftWidth := 1; pMarInset.cxRightWidth := 1; pMarInset.cyTopHeight := 1; pMarInset.cyBottomHeight := 1; DwmExtendFrameIntoClientArea(Handle, pMarInset); end; class procedure TDwmAero.SetFramesSize(Handle: Cardinal; Left, Top, Width, Height: Integer; var FrameSize: Integer); var R: TRect; begin SetRectEmpty(R); AdjustWindowRectEx(R, GetWindowLong(Handle, GWL_STYLE), False, GetWindowLong(Handle, GWL_EXSTYLE)); FrameSize := R.Right; SetWindowPos(Handle, 0, Left, Top, Width, Height, SWP_FRAMECHANGED); end; constructor TDwmNoBorderForm.Create(AOwner: TComponent); begin inherited; Assert(AOwner.InheritsFrom(TForm)); FParent := TForm(AOwner); FOldWndProc := FParent.WindowProc; FParent.WindowProc := WndProc; FOSMajorVersion := TDwmAero.OSMajorVersion; FAeroEnabled := TDwmAero.IsAeroEnabled; FEnabledShadow := True; FEnabledNoBorder := True; SetEnabledShadow(FEnabledShadow); SetEnabledNoBorder(FEnabledNoBorder); end; destructor TDwmNoBorderForm.Destroy; begin inherited; FParent.WindowProc := FOldWndProc; end; procedure TDwmNoBorderForm.SetEnabledShadow(const Value: Boolean); begin if FEnabledShadow <> Value then begin FEnabledShadow := Value; end; if FEnabledShadow and (FOSMajorVersion < 6) then begin SetClassLong(FParent.Handle, GCL_STYLE, GetClassLong(FParent.Handle, GCL_STYLE) or CS_DROPSHADOW); end; end; procedure TDwmNoBorderForm.SetEnabledNoBorder(const Value: Boolean); begin if FEnabledNoBorder <> Value then begin FEnabledNoBorder := Value; end; if FEnabledNoBorder and (FOSMajorVersion < 6) then begin FParent.BorderStyle := bsNone; end; end; procedure TDwmNoBorderForm.WndProc(var Msg: TMessage); var BorderSpace: Integer; WMNCCalcSize: TWMNCCalcSize; begin if csDesigning in ComponentState then begin if Assigned(FOldWndProc) then FOldWndProc(Msg); end else begin if Msg.Msg = WM_NCCALCSIZE then begin if FOSMajorVersion >= 6 then begin if FEnabledNoBorder then begin Msg.Result := 0; if FParent.WindowState = wsMaximized then begin WMNCCalcSize := TWMNCCalcSize(Msg); BorderSpace := GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER); Inc(WMNCCalcSize.CalcSize_Params.rgrc[0].Top, BorderSpace); Inc(WMNCCalcSize.CalcSize_Params.rgrc[0].Left, BorderSpace); Dec(WMNCCalcSize.CalcSize_Params.rgrc[0].Right, BorderSpace); Dec(WMNCCalcSize.CalcSize_Params.rgrc[0].Bottom, BorderSpace); end; end else begin if Assigned(FOldWndProc) then FOldWndProc(Msg); end; end else begin if Assigned(FOldWndProc) then FOldWndProc(Msg); end; end else if Msg.Msg = WM_PAINT then begin if Assigned(FOldWndProc) then FOldWndProc(Msg); if FEnabledShadow and FAeroEnabled then begin TDwmAero.SetShadow(FParent.Handle); end; end else begin if Assigned(FOldWndProc) then FOldWndProc(Msg); end; end; end; end.
unit uConfigFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentModalForm, XiButton, ExtCtrls, StdCtrls, ComCtrls, DB, DBClient, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, uMRSQLParam; const CON_DCOM = 0; CON_SOCKET = 1; CON_WEB = 2; TYPE_TAB_CONFIG = 0; TYPE_TAB_PETCENTER = 1; type TConfigFrm = class(TParentModalForm) pgConfig: TPageControl; tsConnection: TTabSheet; Label1: TLabel; lbHost: TLabel; lbPort: TLabel; Label2: TLabel; cbxConnectionType: TComboBox; edtHost: TEdit; edtPort: TEdit; edtClientID: TEdit; tsPetCenter: TTabSheet; pgPetCenter: TPageControl; tsBreeder: TTabSheet; scEntityType: TmrSuperCombo; tsInventory: TTabSheet; lbBreederInfo: TLabel; scMicrochip: TmrSuperCombo; scPet: TmrSuperCombo; scKitPet: TmrSuperCombo; tsStore: TTabSheet; scStore: TmrSuperCombo; tsWarrantyRep: TTabSheet; btnEditReport: TXiButton; Label3: TLabel; chkPreview: TCheckBox; cbxDefaultPrint: TcxComboBox; lbPrinter: TLabel; tsPrintServer: TTabSheet; Label4: TLabel; edtPrintIP: TcxTextEdit; Label5: TLabel; edtPrintPort: TcxTextEdit; tsKey: TTabSheet; Label6: TLabel; lbKey: TLabel; btnKey: TXiButton; Label7: TLabel; lbExpiration: TLabel; procedure scEntityTypeBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); procedure scMicrochipBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); procedure scPetBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); procedure scKitPetBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); procedure btnEditReportClick(Sender: TObject); procedure btnKeyClick(Sender: TObject); private FType : Integer; procedure GetConfigFile; procedure SetConfigFile; procedure GetPetCenterProperty; procedure SetPetCenterProperty; procedure RefreshConType; procedure RefreshTab; protected procedure ConfirmFrm; override; procedure CancelFrm; override; public function Start(AType : Integer):Boolean; end; implementation uses uDMPet, uDMGlobalNTier, uDMMaintenance, uParentPrintForm, uClasseFunctions, Printers, uMainRetailKeyConst, mrMsgBox; {$R *.dfm} { TConfigFrm } procedure TConfigFrm.GetConfigFile; var sConType : String; begin sConType := DMPet.GetAppProperty('Connection', 'Type'); if sConType = CON_TYPE_SOCKET then cbxConnectionType.ItemIndex := CON_SOCKET else if sConType = CON_TYPE_DCOM then cbxConnectionType.ItemIndex := CON_DCOM else if sConType = CON_TYPE_WEB then cbxConnectionType.ItemIndex := CON_WEB; RefreshConType; edtClientID.Text := DMPet.GetAppProperty('Connection', 'ClientID'); edtHost.Text := DMPet.GetAppProperty('Connection', 'Host'); edtPort.Text := DMPet.GetAppProperty('Connection', 'Port'); chkPreview.Checked := (StrToIntDef(DMPet.GetAppProperty('WarrantyRep', 'Preview'), 1) = 1); cbxDefaultPrint.Text := DMPet.GetAppProperty('WarrantyRep', 'PrinterName'); edtPrintIP.Text := DMPet.GetAppProperty('PrintServer', 'ServerIP'); edtPrintPort.Text := DMPet.GetAppProperty('PrintServer', 'ServerPort'); end; procedure TConfigFrm.RefreshConType; var fPort : Boolean; begin inherited; fPort := False; case cbxConnectionType.ItemIndex of CON_DCOM : fPort := False; CON_SOCKET : fPort := True; CON_WEB : fPort := False; end; lbPort.Visible := fPort; edtPort.Visible := fPort; end; procedure TConfigFrm.SetConfigFile; begin case cbxConnectionType.ItemIndex of CON_SOCKET : DMPet.SetAppProperty('Connection', 'Type', CON_TYPE_SOCKET); CON_DCOM : DMPet.SetAppProperty('Connection', 'Type', CON_TYPE_DCOM); CON_WEB : DMPet.SetAppProperty('Connection', 'Type', CON_TYPE_WEB); end; DMPet.SetAppProperty('Connection', 'ClientID', edtClientID.Text); DMPet.SetAppProperty('Connection', 'Host', edtHost.Text); DMPet.SetAppProperty('Connection', 'Port', edtPort.Text); if chkPreview.Checked then DMPet.SetAppProperty('WarrantyRep', 'Preview', '1') else DMPet.SetAppProperty('WarrantyRep', 'Preview', '0'); DMPet.SetAppProperty('WarrantyRep', 'PrinterName', cbxDefaultPrint.Text); DMPet.SetAppProperty('PrintServer', 'ServerIP', edtPrintIP.Text); DMPet.SetAppProperty('PrintServer', 'ServerPort', edtPrintPort.Text); end; function TConfigFrm.Start(AType : Integer): Boolean; begin FType := AType; RefreshTab; ShowModal; Result := (ModalResult = mrOK); end; procedure TConfigFrm.CancelFrm; begin inherited; end; procedure TConfigFrm.ConfirmFrm; begin inherited; SetConfigFile; Case FType of TYPE_TAB_CONFIG : ; TYPE_TAB_PETCENTER : SetPetCenterProperty; end; end; procedure TConfigFrm.RefreshTab; begin tsConnection.TabVisible := False; tsPetCenter.TabVisible := False; cbxDefaultPrint.Properties.Items := Printer.Printers; GetConfigFile; Case FType of TYPE_TAB_CONFIG : begin tsConnection.TabVisible := True; end; TYPE_TAB_PETCENTER : begin tsPetCenter.TabVisible := True; GetPetCenterProperty; lbKey.Caption := Copy(DMPet.MRKey, 1, 10) + ' ... ' + Copy(DMPet.MRKey, Length(DMPet.MRKey)-10, Length(DMPet.MRKey)); lbExpiration.Caption := FormatDateTime('ddddd', DMPet.DataSetControl.SoftwareExpirationDate); end; end; end; procedure TConfigFrm.SetPetCenterProperty; begin DMPet.SetPropertyDomain('PctBreederDefaultEntityType', scEntityType.EditValue); DMPet.SetPropertyDomain('PctBreederDefaultEntityTypePath', scEntityType.GetFieldValue('Path')); DMPet.SetPropertyDomain('PctMicrochipCategory', scMicrochip.EditValue); DMPet.SetPropertyDomain('PctPetCategory', scPet.EditValue); DMPet.SetPropertyDomain('PctPetKitCategory', scKitPet.EditValue); DMPet.SetPropertyDomain('PctDefaultStore', scStore.EditValue); DMPet.ApplyUpdatePropertyDomain; end; procedure TConfigFrm.GetPetCenterProperty; begin scEntityType.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, 'MenuDisplay=Entity Type;'); scMicrochip.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, 'MenuDisplay=Microchip;'); scPet.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, ''); scKitPet.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, ''); scStore.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, ''); scEntityType.EditValue := DMPet.GetPropertyDomain('PctBreederDefaultEntityType'); scMicrochip.EditValue := DMPet.GetPropertyDomain('PctMicrochipCategory'); scPet.EditValue := DMPet.GetPropertyDomain('PctPetCategory'); scKitPet.EditValue := DMPet.GetPropertyDomain('PctPetKitCategory'); scStore.EditValue := DMPet.GetPropertyDomain('PctDefaultStore'); end; procedure TConfigFrm.scEntityTypeBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); begin inherited; with TMRSQLParam.Create do try AddKey('Path').AsString := PT_PATH_MANUFACTURE; KeyByName('Path').Condition := tcLikeStartWith; AddKey('Desativado').AsBoolean := False; KeyByName('Desativado').Condition := tcEquals; OwnerData := ParamString; finally Free; end; end; procedure TConfigFrm.scMicrochipBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); begin inherited; with TMRSQLParam.Create do try AddKey('SizeAndColor').AsBoolean := False; KeyByName('SizeAndColor').Condition := tcEquals; AddKey('PackModel').AsBoolean := False; KeyByName('PackModel').Condition := tcEquals; AddKey('Service').AsBoolean := False; KeyByName('Service').Condition := tcEquals; AddKey('Credit').AsBoolean := False; KeyByName('Credit').Condition := tcEquals; AddKey('GiftCard').AsBoolean := False; KeyByName('GiftCard').Condition := tcEquals; AddKey('Hidden').AsBoolean := False; KeyByName('Hidden').Condition := tcEquals; AddKey('Desativado').AsBoolean := False; KeyByName('Desativado').Condition := tcEquals; OwnerData := ParamString; finally Free; end; end; procedure TConfigFrm.scPetBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); begin inherited; with TMRSQLParam.Create do try AddKey('SizeAndColor').AsBoolean := False; KeyByName('SizeAndColor').Condition := tcEquals; AddKey('PackModel').AsBoolean := False; KeyByName('PackModel').Condition := tcEquals; AddKey('Service').AsBoolean := False; KeyByName('Service').Condition := tcEquals; AddKey('Credit').AsBoolean := False; KeyByName('Credit').Condition := tcEquals; AddKey('GiftCard').AsBoolean := False; KeyByName('GiftCard').Condition := tcEquals; AddKey('PuppyTracker').AsBoolean := True; KeyByName('PuppyTracker').Condition := tcEquals; AddKey('Hidden').AsBoolean := False; KeyByName('Hidden').Condition := tcEquals; AddKey('Desativado').AsBoolean := False; KeyByName('Desativado').Condition := tcEquals; OwnerData := ParamString; finally Free; end; end; procedure TConfigFrm.scKitPetBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant); begin inherited; with TMRSQLParam.Create do try AddKey('SizeAndColor').AsBoolean := False; KeyByName('SizeAndColor').Condition := tcEquals; AddKey('PackModel').AsBoolean := True; KeyByName('PackModel').Condition := tcEquals; AddKey('Service').AsBoolean := False; KeyByName('Service').Condition := tcEquals; AddKey('Credit').AsBoolean := False; KeyByName('Credit').Condition := tcEquals; AddKey('GiftCard').AsBoolean := False; KeyByName('GiftCard').Condition := tcEquals; AddKey('Hidden').AsBoolean := False; KeyByName('Hidden').Condition := tcEquals; AddKey('Desativado').AsBoolean := False; KeyByName('Desativado').Condition := tcEquals; OwnerData := ParamString; finally Free; end; end; procedure TConfigFrm.btnEditReportClick(Sender: TObject); var Form : TForm; begin inherited; Form := CreateForm(Self, 'TPctWarrantyPrintForm'); try TParentPrintForm(Form).DesignReport; finally FreeAndNil(Form); end; end; procedure TConfigFrm.btnKeyClick(Sender: TObject); begin inherited; DMPet.ActiveConnection.AppServer.SoftwareDelete(SOFTWARE_PC); MsgBox('License Updated. Close Pet Center and reopen it to use your new license.', vbInformation + vbOKOnly); end; end.
unit PlugShare; interface uses Windows, Classes, EngineType; resourcestring sDBHeaderDesc = '自定义魔法数据库 程序制作:http://www.IGEM2.com.cn'; m_sDBFileName='UserMagic.db'; type TDBHeader = packed record //Size 12 sDesc: string[49]; //0x00 36 nLastIndex: Integer; //0x5C nMagicCount: Integer; //0x68 dCreateDate: TDateTime; //创建时间 end; pTDBHeader = ^TDBHeader; TRecordHeader = packed record //Size 12 boDeleted: Boolean; dCreateDate: TDateTime; //创建时间 end; pTRecordHeader = ^TRecordHeader; TMagicConfig = packed record nSelMagicID: Integer; //使用某个魔法的效果 nMagicCount: Integer; nAttackRange: Integer; //攻击范围 nAttackWay: Integer; //攻击方式 nNeed: Integer; //使用魔法需要物品 boHP: Boolean; boMP: Boolean; boAC: Boolean; boMC: Boolean; boAbil: Boolean; end; pTMagicConfig = ^TMagicConfig; TMagicRcd = packed record RecordHeader: TRecordHeader; Magic: _TMAGIC; MagicConfig: TMagicConfig; end; pTMagicRcd = ^TMagicRcd; var PlugHandle: Integer; PlugClass: string = 'Config'; g_MagicList: Classes.TList; nSelMagicID: Integer; m_nFileHandle:Integer; m_Header:TDBHeader; implementation end.
unit VirtualScrollingWinControl; interface uses SysUtils,Windows,Messages,Classes,Controls,Graphics; type TScrollBarUpdateStateItem=(sbuPage,sbuPosition,sbuRange); TScrollBarUpdateState=set of TScrollBarUpdateStateItem; TVirtualScrollBar=class private FWND:HWND; FVertical:Boolean; FPageSize,FPosition,FRange,FUpdateCount:Integer; FUpdateState:TScrollBarUpdateState; function GetPageSize: Integer; function GetPosition: Integer; function GetRange: Integer; procedure SetPageSize(const Value: Integer); procedure SetPosition(const Value: Integer); procedure SetRange(const Value: Integer); procedure SetWNDHandle(const Value: HWND); protected function GetBarFlag:Cardinal; procedure DoUpdate; property WNDHandle:HWND read FWND write SetWNDHandle; public constructor Create(AVertical:Boolean); procedure BeginUpdate; procedure EndUpdate; procedure Repaint; property Vertical:Boolean read FVertical; property Position:Integer read GetPosition write SetPosition; property Range:Integer read GetRange write SetRange; property PageSize:Integer read GetPageSize write SetPageSize; end; TVirtualScrollingWinControl=class(TWinControl) private FHorzScrollBar: TVirtualScrollBar; FVertScrollBar: TVirtualScrollBar; procedure DoUpdateScrollBars; procedure WMPaint(var Message:TWMPaint);message WM_PAINT; procedure WMDestroy(var Message:TMessage);message WM_DESTROY; procedure WMVScroll(var Message:TWMVScroll);message WM_VSCROLL; procedure WMHScroll(var Message:TWMHScroll);message WM_HSCROLL; procedure WMSize(var Message:TWMSize);message WM_SIZE; procedure WMNCPaint(var Message:TWMNCPaint);message WM_NCPAINT; protected property HorzScrollBar:TVirtualScrollBar read FHorzScrollBar; property VertScrollBar:TVirtualScrollBar read FVertScrollBar; procedure CreateHandle;override; procedure ScrollPosChanged;virtual; procedure UpdateScrollBars;virtual; public constructor Create(AOwner:TComponent);override; procedure UpdateScrollState; destructor Destroy;override; end; implementation uses Themes; { TVirtualScrollBar } procedure TVirtualScrollBar.BeginUpdate; begin Inc(FUpdateCount); end; constructor TVirtualScrollBar.Create(AVertical: Boolean); begin inherited Create; FVertical:=AVertical; end; procedure TVirtualScrollBar.DoUpdate; var SI:TScrollInfo; i:TScrollBarUpdateStateItem; const T:array[sbuPage..sbuRange] of Cardinal=(SIF_PAGE,SIF_POS,SIF_RANGE); begin if (FUpdateState=[]) or (FWND=0) then Exit; ZeroMemory(@SI,SizeOf(SI)); with SI do begin cbSize:=SizeOf(SI); if FPageSize<0 then FPageSize:=0; nPage:=FPageSize; nPos:=FPosition; nMax:=FRange; for i:=sbuPage to sbuRange do if i in FUpdateState then fMask:=fMask or T[i]; end; SetScrollInfo(FWND,GetBarFlag,SI,True); SI.fMask:=SIF_ALL; GetScrollInfo(FWND,GetBarFlag,SI); with SI do begin FPageSize:=nPage; FPosition:=nPos; FRange:=nMax; end; FUpdateState:=[]; end; procedure TVirtualScrollBar.EndUpdate; begin Assert(FUpdateCount>0,'Negative update count'); Dec(FUpdateCount); if FUpdateCount=0 then DoUpdate; end; function TVirtualScrollBar.GetBarFlag: Cardinal; begin if FVertical then Result:=SB_VERT else Result:=SB_HORZ; end; function TVirtualScrollBar.GetPageSize: Integer; begin DoUpdate; Result:=FPageSize; end; function TVirtualScrollBar.GetPosition: Integer; begin DoUpdate; Result:=FPosition; end; function TVirtualScrollBar.GetRange: Integer; begin DoUpdate; Result:=FRange; end; procedure TVirtualScrollBar.Repaint; var SI:TScrollInfo; begin ZeroMemory(@SI,SizeOf(SI)); SI.cbSize:=Sizeof(SI); SetScrollInfo(FWND,GetBarFlag,SI,True); end; procedure TVirtualScrollBar.SetPageSize(const Value: Integer); begin BeginUpdate; if FPageSize<>Value then begin Include(FUpdateState,sbuPage); FPageSize:=Value; end; EndUpdate; end; procedure TVirtualScrollBar.SetPosition(const Value: Integer); begin BeginUpdate; if FPosition<>Value then begin Include(FUpdateState,sbuPosition); FPosition:=Value; end; EndUpdate; end; procedure TVirtualScrollBar.SetRange(const Value: Integer); begin BeginUpdate; if FRange<>Value then begin Include(FUpdateState,sbuRange); FRange:=Value; end; EndUpdate; end; procedure TVirtualScrollBar.SetWNDHandle(const Value: HWND); begin FWND := Value; if Value<>0 then begin FUpdateState:=[sbuPage,sbuPosition,sbuRange]; DoUpdate; end; end; { TVirtualScrollingWinControl } constructor TVirtualScrollingWinControl.Create(AOwner: TComponent); begin FHorzScrollBar:=TVirtualScrollBar.Create(False); FVertScrollBar:=TVirtualScrollBar.Create(True); inherited; end; procedure TVirtualScrollingWinControl.CreateHandle; begin inherited; FHorzScrollBar.WNDHandle:=Handle; FVertScrollBar.WNDHandle:=Handle; DoUpdateScrollBars; end; destructor TVirtualScrollingWinControl.Destroy; begin inherited Destroy; FHorzScrollBar.Destroy; FVertScrollBar.Destroy; end; procedure TVirtualScrollingWinControl.DoUpdateScrollBars; begin FVertScrollBar.BeginUpdate; FHorzScrollBar.BeginUpdate; try UpdateScrollBars; finally FVertScrollBar.EndUpdate; FHorzScrollBar.EndUpdate; end; end; procedure TVirtualScrollingWinControl.ScrollPosChanged; begin Invalidate; end; procedure TVirtualScrollingWinControl.UpdateScrollBars; begin ScrollPosChanged; end; procedure TVirtualScrollingWinControl.UpdateScrollState; begin if HandleAllocated then DoUpdateScrollBars; end; procedure TVirtualScrollingWinControl.WMDestroy(var Message: TMessage); begin FVertScrollBar.WNDHandle:=0; FHorzScrollBar.WNDHandle:=0; inherited; end; procedure TVirtualScrollingWinControl.WMHScroll(var Message: TWMHScroll); var SI:TScrollInfo; begin with HorzScrollBar do case Message.ScrollCode of SB_LINEDOWN:Position:=Position+1; SB_LINEUP:Position:=Position-1; SB_PAGEDOWN:Position:=Position+PageSize; SB_PAGEUP:Position:=Position-PageSize; SB_THUMBTRACK:begin ZeroMemory(@Si,SizeOf(SI)); SI.cbSize:=SizeOf(SI); SI.fMask:=SIF_TRACKPOS; if GetScrollInfo(Handle,SB_HORZ,SI) then Position:=SI.nTrackPos else Position:=Message.Pos; end; else inherited; Exit; end; Message.Result:=0; ScrollPosChanged; end; procedure TVirtualScrollingWinControl.WMNCPaint(var Message: TWMNCPaint); //another fix of Delphi VCL... const InnerStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENINNER, BDR_RAISEDINNER, 0); OuterStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENOUTER, BDR_RAISEDOUTER, 0); EdgeStyles: array[TBevelKind] of Integer = (0, 0, BF_SOFT, BF_FLAT); Ctl3DStyles: array[Boolean] of Integer = (BF_MONO, 0); var DC: HDC; RC, RW, RWH, RWV, SaveRW: TRect; EdgeSize: Integer; WinStyle: Longint; begin { Get window DC that is clipped to the non-client area } inherited; if (BevelKind <> bkNone) or (BorderWidth > 0) then begin DC := GetWindowDC(Handle); try Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw borders in non-client area } SaveRW := RW; InflateRect(RC, BorderWidth, BorderWidth); RW := RC; WinStyle := GetWindowLong(Handle, GWL_STYLE); if BevelKind <> bkNone then begin EdgeSize := 0; if BevelInner <> bvNone then Inc(EdgeSize, BevelWidth); if BevelOuter <> bvNone then Inc(EdgeSize, BevelWidth); with RW do begin if beLeft in BevelEdges then Dec(Left, EdgeSize); if beTop in BevelEdges then Dec(Top, EdgeSize); if beRight in BevelEdges then Inc(Right, EdgeSize); if (WinStyle and WS_VSCROLL) <> 0 then Inc(Right, GetSystemMetrics(SM_CYVSCROLL)); if beBottom in BevelEdges then Inc(Bottom, EdgeSize); if (WinStyle and WS_HSCROLL) <> 0 then Inc(Bottom, GetSystemMetrics(SM_CXHSCROLL)); DrawEdge(DC, RW, InnerStyles[BevelInner] or OuterStyles[BevelOuter], Byte(BevelEdges) or EdgeStyles[BevelKind] or Ctl3DStyles[Ctl3D] or BF_ADJUST); end; IntersectClipRect(DC, RW.Left, RW.Top, RW.Right, RW.Bottom); RW := SaveRW; end; RWH:=Rect(2*BevelWidth+BorderWidth,RW.Bottom,RW.Right,RW.Bottom); RWV:=Rect(RW.Right,2*BevelWidth+BorderWidth,RW.Right,RW.Bottom); if (WinStyle and WS_VSCROLL) <> 0 then begin Dec(RWH.Right, GetSystemMetrics(SM_CXVSCROLL)); Dec(RWV.Left, GetSystemMetrics(SM_CXVSCROLL)); end; if (WinStyle and WS_HSCROLL) <> 0 then begin Dec(RWH.Top, GetSystemMetrics(SM_CYHSCROLL)); Dec(RWV.Bottom, GetSystemMetrics(SM_CYHSCROLL)); end; with RWH do ExcludeClipRect(DC,Left,Top,Right,Bottom); with RWV do ExcludeClipRect(DC,Left,Top,Right,Bottom); { Erase parts not drawn } OffsetRect(RW, -RW.Left, -RW.Top); Windows.FillRect(DC, RW, Brush.Handle); finally ReleaseDC(Handle, DC); end; end; if ThemeServices.ThemesEnabled and (csNeedsBorderPaint in ControlStyle) then ThemeServices.PaintBorder(Self, False); end; procedure TVirtualScrollingWinControl.WMPaint(var Message: TWMPaint); begin inherited; end; procedure TVirtualScrollingWinControl.WMSize(var Message: TWMSize); begin inherited; DoUpdateScrollBars; end; procedure TVirtualScrollingWinControl.WMVScroll(var Message: TWMVScroll); var SI:TScrollInfo; begin with VertScrollBar do case Message.ScrollCode of SB_LINEDOWN:Position:=Position+1; SB_LINEUP:Position:=Position-1; SB_PAGEDOWN:Position:=Position+PageSize; SB_PAGEUP:Position:=Position-PageSize; SB_THUMBTRACK:begin ZeroMemory(@Si,SizeOf(SI)); SI.cbSize:=SizeOf(SI); SI.fMask:=SIF_TRACKPOS; if GetScrollInfo(Handle,SB_VERT,SI) then Position:=SI.nTrackPos else Position:=Message.Pos; end; else inherited; // Exit; end; Message.Result:=0; ScrollPosChanged; end; end.
unit VirtualSendToMenu; // Version 1.3.0 // // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the // specific language governing rights and limitations under the License. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Menus, Registry, ShlObj, ShellAPI, ActiveX, VirtualShellUtilities, ImgList, CommCtrl, VirtualResources, VirtualWideStrings, VirtualSystemImageLists, VirtualShellContainers, VirtualUtilities, {$IFDEF TOOLBAR_2000} TB2Item, {$ENDIF TOOLBAR_2000} {$IFDEF TBX} TB2Item, TBX, {$ENDIF TBX} VirtualUnicodeDefines; type TVirtualSendToMenu = class; // Forward TSendToMenuOptions = class(TPersistent) private FImages: Boolean; FLargeImages: Boolean; FImageBorder: Integer; FMaxWidth: Integer; FEllipsisPlacement: TShortenStringEllipsis; public constructor Create; published property EllipsisPlacement: TShortenStringEllipsis read FEllipsisPlacement write FEllipsisPlacement default sseMiddle; property Images: Boolean read FImages write FImages default True; property LargeImages: Boolean read FLargeImages write FLargeImages default False; property ImageBorder: Integer read FImageBorder write FImageBorder default 1; property MaxWidth: Integer read FMaxWidth write FMaxWidth default -1; end; TVirtualSendToEvent = procedure(Sender: TVirtualSendToMenu; SendToTarget: TNamespace; var SourceData: IDataObject) of object; TVirtualSendToGetImageEvent = procedure(Sender: TVirtualSendToMenu; NS: TNamespace; var ImageList: TImageList; var ImageIndex: Integer) of object; TVirtualSendToMenuItem = class(TMenuItem) private FNamespace: TNamespace; protected property Namespace: TNamespace read FNamespace write FNamespace; public destructor Destroy; override; procedure Click; override; end; {$IFDEF TBX_OR_TB2K} {$IFDEF TBX} TVirtualSendToMenuItem_TB2000 = class(TTBXItem) {$ELSE} TVirtualSendToMenuItem_TB2000 = class(TTBItem) {$ENDIF TBX} private FNamespace: TNamespace; protected property Namespace: TNamespace read FNamespace write FNamespace; public destructor Destroy; override; procedure Click; override; end; {$ENDIF TBX_OR_TB2K} TVirtualSendToMenu = class(TPopupMenu) private FSendToItems: TVirtualNameSpaceList; FSendToEvent: TVirtualSendToEvent; FOptions: TSendToMenuOptions; FOnGetImage: TVirtualSendToGetImageEvent; protected procedure DoGetImage(NS: TNamespace; var ImageList: TImageList; var ImageIndex: Integer); procedure DoSendTo(SendToTarget: TNamespace; var SourceData: IDataObject); virtual; function EnumSendToCallback(APIDL: PItemIDList; AParent: TNamespace; Data: Pointer; var Terminate: Boolean): Boolean; procedure OnMenuItemDraw(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); virtual; procedure OnMenuItemMeasure(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Populate(MenuItem: TMenuItem); virtual; {$IFDEF TBX_OR_TB2K} procedure Populate_TB2000(MenuItem: TTBCustomItem); virtual; {$ENDIF TBX_OR_TB2K} procedure Popup(X, Y: Integer); override; property SendToItems: TVirtualNameSpaceList read FSendToItems; published property SendToEvent: TVirtualSendToEvent read FSendToEvent write FSendToEvent; property OnGetImage: TVirtualSendToGetImageEvent read FOnGetImage write FOnGetImage; property Options: TSendToMenuOptions read FOptions write FOptions; end; implementation function SendToMenuSort(Item1, Item2: Pointer): Integer; begin if Assigned(Item1) and Assigned(Item2) then Result := TNamespace(Item2).ComparePIDL(TNamespace(Item1).RelativePIDL, False) else Result := 0 end; { TVirtualSendToMenuItem } procedure TVirtualSendToMenuItem.Click; var Menu: TVirtualSendToMenu; DataObject: IDataObject; DropTarget: IDropTarget; DropEffect: Longint; begin inherited; Menu := Owner as TVirtualSendToMenu; Menu.DoSendTo(Namespace, DataObject); if Assigned(DataObject) then begin DropEffect := DROPEFFECT_COPY or DROPEFFECT_MOVE or DROPEFFECT_LINK; DropTarget := Namespace.DropTargetInterface; if Assigned(DropTarget) then if Succeeded(DropTarget.DragEnter(DataObject, MK_LBUTTON, Point(0, 0), DropEffect)) then (DropTarget.Drop(DataObject, MK_LBUTTON, Point(0, 0), DropEffect)) end end; destructor TVirtualSendToMenuItem.Destroy; begin Namespace.Free; inherited; end; {$IFDEF TBX_OR_TB2K} { TVirtualSendToMenuItem_TB2000 } procedure TVirtualSendToMenuItem_TB2000.Click; var Menu: TVirtualSendToMenu; DataObject: IDataObject; DropTarget: IDropTarget; DropEffect: Longint; begin inherited; Menu := Owner as TVirtualSendToMenu; Menu.DoSendTo(Namespace, DataObject); if Assigned(DataObject) then begin DropEffect := DROPEFFECT_COPY or DROPEFFECT_MOVE or DROPEFFECT_LINK; DropTarget := Namespace.DropTargetInterface; if Assigned(DropTarget) then if Succeeded(DropTarget.DragEnter(DataObject, MK_LBUTTON, Point(0, 0), DropEffect)) then (DropTarget.Drop(DataObject, MK_LBUTTON, Point(0, 0), DropEffect)) end end; destructor TVirtualSendToMenuItem_TB2000.Destroy; begin Namespace.Free; inherited; end; {$ENDIF TBX_OR_TB2K} { TVirtualSendToMenu } constructor TVirtualSendToMenu.Create(AOwner: TComponent); begin inherited; FSendToItems := TVirtualNameSpaceList.Create(False); FOptions := TSendToMenuOptions.Create; end; destructor TVirtualSendToMenu.Destroy; begin SendToItems.Free; FOptions.Free; inherited; end; procedure TVirtualSendToMenu.DoGetImage(NS: TNamespace; var ImageList: TImageList; var ImageIndex: Integer); begin if Assigned(OnGetImage) then OnGetImage(Self, NS, ImageList, ImageIndex); end; procedure TVirtualSendToMenu.DoSendTo(SendToTarget: TNamespace; var SourceData: IDataObject); begin SourceData := nil; if Assigned(SendToEvent) then SendToEvent(Self, SendToTarget, SourceData); end; function TVirtualSendToMenu.EnumSendToCallback(APIDL: PItemIDList; AParent: TNamespace; Data: Pointer; var Terminate: Boolean): Boolean; var NS: TNamespace; begin if AParent.IsMyComputer then begin NS := TNamespace.Create(PIDLMgr.AppendPIDL(AParent.AbsolutePIDL, APIDL), nil); if NS.Removable then TVirtualNameSpaceList(Data).Add(NS) else NS.Free end else TVirtualNameSpaceList(Data).Add(TNamespace.Create(PIDLMgr.AppendPIDL(AParent.AbsolutePIDL, APIDL), nil)); Result := True end; procedure TVirtualSendToMenu.OnMenuItemDraw(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); var WS: WideString; S: string; i, Border: integer; ImageRect: TRect; TargetImageIndex: Integer; TargetImageList: TImageList; RTL: Boolean; // Left to Right reading OldMode: Longint; MenuItem: TVirtualSendToMenuItem; begin if Sender is TMenuItem then begin RTL := Application.UseRightToLeftReading; i := TMenuItem(Sender).MenuIndex; if IsWinXP and Selected then begin ACanvas.Brush.Color := clHighlight; ACanvas.Font.Color := clBtnHighlight; ACanvas.FillRect(ARect); end else begin ACanvas.Brush.Color := clMenu; ACanvas.Font.Color := clMenuText; ACanvas.FillRect(ARect); end; MenuItem := TVirtualSendToMenuItem( Items[i]); if i > -1 then WS := MenuItem.Namespace.NameInFolder else WS := TMenuItem(Sender).Caption; if Options.Images then begin TargetImageIndex := -1; Border := Options.ImageBorder; if Options.LargeImages then begin TargetImageList := LargeSysImages; if i > -1 then TargetImageIndex := MenuItem.Namespace.GetIconIndex(False, icLarge) end else begin TargetImageList := SmallSysImages; if i > -1 then TargetImageIndex := MenuItem.Namespace.GetIconIndex(False, icSmall); end; // Allow custom icons if i > -1 then DoGetImage(MenuItem.Namespace, TargetImageList, TargetImageIndex); if RTL then ImageRect := Rect(ARect.Right - (TargetImageList.Width + 2 * Border), ARect.Top, ARect.Right, ARect.Bottom) else ImageRect := Rect(ARect.Left, ARect.Top, ARect.Left + TargetImageList.Width + 2 * Border, ARect.Bottom); if Selected and not IsWinXP then DrawEdge(ACanvas.Handle, ImageRect, BDR_RAISEDINNER, BF_RECT); OffsetRect(ImageRect, Border, ((ImageRect.Bottom - ImageRect.Top) - TargetImageList.Height) div 2); ImageList_Draw(TargetImageList.Handle, TargetImageIndex, ACanvas.Handle, ImageRect.Left, ImageRect.Top, ILD_TRANSPARENT); if RTL then ARect.Right := ARect.Right - (TargetImageList.Width + (2 * Border) + 1) else ARect.Left := ARect.Left + TargetImageList.Width + (2 * Border) + 1 end; if Selected and not IsWinXP then begin ACanvas.Brush.Color := clHighlight; ACanvas.Font.Color := clBtnHighlight; ACanvas.FillRect(ARect); end; Inc(ARect.Left, 2); if TextExtentW(WS, ACanvas).cx > ARect.Right-ARect.Left then WS := ShortenStringEx(ACanvas.Handle, WS, ARect.Right-ARect.Left, RTL, Options.EllipsisPlacement); OldMode := SetBkMode(ACanvas.Handle, TRANSPARENT); // The are WideString compatible //Note: it seems that DrawTextW doesn't draw the prefix. i := Pos('&', WS); System.Delete(WS, i, 1); if IsUnicode then DrawTextW_VST(ACanvas.handle, PWideChar(WS), StrLenW(PWideChar(WS)), ARect, DT_SINGLELINE or DT_VCENTER) else begin S := WS; DrawText(ACanvas.handle, PChar(S), Length(S), ARect, DT_SINGLELINE or DT_VCENTER) end; SetBkMode(ACanvas.Handle, OldMode); end; end; procedure TVirtualSendToMenu.OnMenuItemMeasure(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); var WS: WideString; i: integer; Border: Integer; begin if Sender is TMenuItem then begin i := TMenuItem(Sender).MenuIndex; if i > -1 then begin WS := TVirtualSendToMenuItem( Items[i]).Namespace.NameInFolder; Width := TextExtentW(WS, ACanvas).cx; end else Width := TextExtentW(TMenuItem(Sender).Caption, ACanvas).cx; if Options.Images then begin Border := 2 * Options.ImageBorder; if Options.LargeImages then begin Inc(Width, LargeSysImages.Width + Border); if LargeSysImages.Height + Border > Height then Height := LargeSysImages.Height + Border end else begin Inc(Width, SmallSysImages.Width + Border); if SmallSysImages.Height + Border > Height then Height := SmallSysImages.Height + Border end end; end; if Options.MaxWidth > 0 then begin if Width > Options.MaxWidth then Width := Options.MaxWidth; end; if Width > Screen.Width then Width := Screen.Width - 12 // Purely imperical value seen on XP for the unaccessable borders end; procedure TVirtualSendToMenu.Populate(MenuItem: TMenuItem); var NS: TNamespace; M: TVirtualSendToMenuItem; i: integer; OldErrorMode: integer; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS or SEM_NOOPENFILEERRORBOX); try SendToItems.Clear; NS := CreateSpecialNamespace(CSIDL_SENDTO); NS.EnumerateFolder(False, True, False, EnumSendToCallback, SendToItems); SendToItems.Sort(SendToMenuSort); for i := 0 to SendToItems.Count - 1 do begin M := TVirtualSendToMenuItem.Create(Self); M.Namespace := SendToItems[i]; M.Caption := M.Namespace.NameNormal; M.ImageIndex := M.Namespace.GetIconIndex(False, icSmall); MenuItem.Add(M); end; SendToItems.Clear; NS.Free; DrivesFolder.EnumerateFolder(False, False, False, EnumSendToCallback, SendToItems); SendToItems.Sort(SendToMenuSort); for i := 0 to SendToItems.Count - 1 do begin M := TVirtualSendToMenuItem.Create(Self); M.Namespace := SendToItems[i]; M.Caption := M.Namespace.NameNormal; M.ImageIndex := M.Namespace.GetIconIndex(False, icSmall); MenuItem.Add(M); end; SendToItems.Clear; finally SetErrorMode(OldErrorMode); end; end; {$IFDEF TBX_OR_TB2K} procedure TVirtualSendToMenu.Populate_TB2000(MenuItem: TTBCustomItem); var NS: TNamespace; M: TVirtualSendToMenuItem_TB2000; i: integer; begin {$IFDEF TBX} if MenuItem is TTBXSubmenuItem then TTBXSubmenuItem(MenuItem).SubMenuImages := SmallSysImages; {$ELSE} if MenuItem is TTBSubmenuItem then TTBSubmenuItem(MenuItem).SubMenuImages := SmallSysImages; {$ENDIF TBX} MenuItem.Clear; SendToItems.Clear; NS := CreateSpecialNamespace(CSIDL_SENDTO); NS.EnumerateFolder(False, True, False, EnumSendToCallback, SendToItems); SendToItems.Sort(SendToMenuSort); for i := 0 to SendToItems.Count - 1 do begin M := TVirtualSendToMenuItem_TB2000.Create(Self); M.Namespace := SendToItems[i]; M.Caption := M.Namespace.NameNormal; M.ImageIndex := M.Namespace.GetIconIndex(False, icSmall); MenuItem.Add(M); end; SendToItems.Clear; NS.Free; DrivesFolder.EnumerateFolder(False, False, False, EnumSendToCallback, SendToItems); SendToItems.Sort(SendToMenuSort); for i := 0 to SendToItems.Count - 1 do begin M := TVirtualSendToMenuItem_TB2000.Create(Self); M.Namespace := SendToItems[i]; M.Caption := M.Namespace.NameNormal; M.ImageIndex := M.Namespace.GetIconIndex(False, icSmall); MenuItem.Add(M); end; SendToItems.Clear; end; {$ENDIF TBX_OR_TB2K} procedure TVirtualSendToMenu.Popup(X, Y: Integer); begin Images := SmallSysImages; {$IFNDEF DELPHI_5_UP} ClearMenuItems(Self); {$ELSE} Items.Clear; {$ENDIF DELPHI_5_UP} Populate(Items); inherited; end; { TSendToMenuOptions } constructor TSendToMenuOptions.Create; begin Images := True; LargeImages := False; ImageBorder := 1; FEllipsisPlacement := sseMiddle; MaxWidth := -1; end; end.
unit uspQuery; interface uses System.Classes, FireDAC.Comp.Client, FireDAC.DApt; type TNotifyEvent = procedure(Sender: TObject) of Object; TspQuery = class(TFDQuery) private FspColunas: TStringList; FspTabelas: TStringList; FspCondicoes: TStringList; FStatus: TNotifyEvent; procedure SetspColunas(const Value: TStringList); procedure SetspTabelas(const Value: TStringList); procedure SetspCondicoes(const Value: TStringList); procedure SetStatus(const Value: TNotifyEvent); Public Function GeraSQL: TStringList; procedure OnStatus; published property spColunas: TStringList read FspColunas write SetspColunas; property spTabelas: TStringList read FspTabelas write SetspTabelas; property spCondicoes: TStringList read FspCondicoes write SetspCondicoes; property Status: TNotifyEvent read FStatus write SetStatus; end; implementation { TspQuery } Function TspQuery.GeraSQL: TStringList; var campos, Script: String; i: Integer; SqlQuery: TStringList; begin SqlQuery := TStringList.Create; try for i := 0 to spColunas.Count - 1 do campos := campos + spColunas.Strings[i] + ','; Script := ' Select ' + #13 + Copy(campos, 1, (length(campos) - 1)) + ' From ' + spTabelas.Text + '' + #13 + ' Where ' + spCondicoes.Text; SqlQuery.Add(Script); SQL := SqlQuery; finally Result := SqlQuery; OnStatus; SqlQuery.Free; end; end; procedure TspQuery.OnStatus; begin if Assigned(Status) then Status(Self); end; procedure TspQuery.SetspColunas(const Value: TStringList); begin FspColunas := Value; end; procedure TspQuery.SetspCondicoes(const Value: TStringList); begin FspCondicoes := Value; end; procedure TspQuery.SetspTabelas(const Value: TStringList); begin FspTabelas := Value; end; procedure TspQuery.SetStatus(const Value: TNotifyEvent); begin FStatus := Value; end; end.
{**************************************************************************************************} { } { Unit uHSLUtils } { unit for the VCL Styles Utils } { http://code.google.com/p/vcl-styles-utils/ } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); } { you may not use this file except in compliance with the License. You may obtain a copy of the } { License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is uHSLUtils.pas. } { } { The Initial Developer of the Original Code is Rodrigo Ruz V. } { Portions created by Rodrigo Ruz V. are Copyright (C) 2012 Rodrigo Ruz V. } { All Rights Reserved. } { } {**************************************************************************************************} unit uHSLUtils; interface uses Windows, Graphics, Classes, SysUtils; const MaxHue = 180; MinHue = -180; DefHue = 0; MaxSat = 255; MinSat = 0; DefSat = 0; MaxLig = 255; MinLig = -255; DefLig = 0; function _HSLtoRGB(HueValue, SaturationValue, LightValue: Double): TColor; procedure _RGBtoHSL(RGB: TColor; var HueValue, SaturationValue, LightValue: Double); procedure _Hue(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _Hue24(var ABitMap: TBitmap; Value: integer); procedure _Hue32(const ABitMap: TBitmap; Value: integer); procedure _Sepia(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _Sepia24(const ABitMap: TBitmap;Value : Byte=32); procedure _Sepia32(const ABitMap: TBitmap;Value : Byte=32); procedure _BlendMultiply(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendMultiply24(const ABitMap: TBitmap;Value: Integer); procedure _BlendMultiply32(const ABitMap: TBitmap;Value: Integer); procedure _Lightness(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _Lightness24(var ABitMap: TBitmap; Value: integer); procedure _Lightness32(const ABitMap: TBitmap; Value: integer); procedure _Darkness(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _Darkness24(var ABitMap: TBitmap; Value: integer); procedure _Darkness32(const ABitMap: TBitmap; Value: integer); procedure _Saturation(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _Saturation24(var ABitMap: TBitmap; Value: integer); procedure _Saturation32(const ABitMap: TBitmap; Value: integer); procedure _SetRComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _SetGComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _SetBComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _SetRGB24(const ABitMap: TBitmap; DR,DG,DB: Integer); procedure _SetRGB32(const ABitMap: TBitmap; DR,DG,DB: Integer); procedure _BlendBurn(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendBurn24(const ABitMap: TBitmap;Value: Integer); procedure _BlendBurn32(const ABitMap: TBitmap;Value: Integer); procedure _BlendAdditive(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendAdditive24(const ABitMap: TBitmap;Value: Integer); procedure _BlendAdditive32(const ABitMap: TBitmap;Value: Integer); procedure _BlendDodge(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendDodge24(const ABitMap: TBitmap;Value: Integer); procedure _BlendDodge32(const ABitMap: TBitmap;Value: Integer); procedure _BlendOverlay(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendOverlay24(const ABitMap: TBitmap;Value: Integer); procedure _BlendOverlay32(const ABitMap: TBitmap;Value: Integer); procedure _BlendDifference(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendDifference24(const ABitMap: TBitmap;Value: Integer); procedure _BlendDifference32(const ABitMap: TBitmap;Value: Integer); procedure _BlendLighten(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendLighten24(const ABitMap: TBitmap;Value: Integer); procedure _BlendLighten32(const ABitMap: TBitmap;Value: Integer); procedure _BlendDarken(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendDarken24(const ABitMap: TBitmap;Value: Integer); procedure _BlendDarken32(const ABitMap: TBitmap;Value: Integer); procedure _BlendScreen(const AColor: TColor;Value: Integer; out NewColor:TColor); procedure _BlendScreen24(const ABitMap: TBitmap;Value: Integer); procedure _BlendScreen32(const ABitMap: TBitmap;Value: Integer); Type TColorFilter=class private FValue : Integer; public constructor Create(AValue:Integer); property Value : Integer read FValue Write FValue; function ProcessColor(AColor: TColor):TColor;virtual;abstract; end; TBitmapFilter=class(TColorFilter) public procedure ProcessBitmap(ABitMap: TBitmap);virtual;abstract; end; TBitmap32HueFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32SaturationFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32LightnessFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32SepiaFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32RedFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32GreenFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlueFilter=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendBurn=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendMultiply=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendAdditive=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendDodge=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendOverlay=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendDifference=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendLighten=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendDarken=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; TBitmap32BlendScreen=class(TBitmapFilter) public procedure ProcessBitmap(ABitMap: TBitmap);override; function ProcessColor(AColor: TColor):TColor;override; end; implementation Uses Math; type PRGB24 = ^TRGB24; TRGB24 = record B, G, R: byte; end; PRGBArray24 = ^TRGBArray24; TRGBArray24 = array[0..0] of TRGB24; PRGB32 = ^TRGB32; TRGB32 = record B, G, R, A: byte; end; PRGBArray32 = ^TRGBArray32; TRGBArray32 = array[0..0] of TRGB32; TFilterCallback = procedure (const AColor: TColor;Value: Integer; out NewColor:TColor); function RoundIntToByte(i: integer): byte; begin if i > 255 then Result := 255 else if i < 0 then Result := 0 else Result := i; end; procedure GetRGB(Col: TColor; var R, G, B: byte); var Color: $0..$FFFFFFFF; begin Color := ColorToRGB(Col); R := ($000000FF and Color); G := ($0000FF00 and Color) shr 8; B := ($00FF0000 and Color) shr 16; end; procedure _ProcessBitmap32(const ABitMap: TBitmap;Value: Integer;_Process:TFilterCallback); var r, g, b, a : byte; x, y: integer; ARGB: TColor; Line, Delta: NativeInt; begin Line := NativeInt(ABitMap.ScanLine[0]); Delta := NativeInt(ABitMap.ScanLine[1]) - Line; for y := 0 to ABitMap.Height - 1 do begin for x := 0 to ABitMap.Width - 1 do begin r := PRGBArray32(Line)[x].R; g := PRGBArray32(Line)[x].G; b := PRGBArray32(Line)[x].B; a := PRGBArray32(Line)[x].A; _Process(RGB(r,g,b), Value, ARGB); GetRGB(ARGB, r, g, b); PRGBArray32(Line)[x].R := r; PRGBArray32(Line)[x].G := g; PRGBArray32(Line)[x].B := b; PRGBArray32(Line)[x].A := a; end; Inc(Line, Delta); end; end; procedure _ProcessBitmap24(const ABitMap: TBitmap;Value: Integer;_Process:TFilterCallback); var r, g, b : byte; x, y: integer; ARGB: TColor; Line, Delta: NativeInt; begin Line := NativeInt(ABitMap.ScanLine[0]); Delta := NativeInt(ABitMap.ScanLine[1]) - Line; for y := 0 to ABitMap.Height - 1 do begin for x := 0 to ABitMap.Width - 1 do begin r := PRGBArray24(Line)[x].R; g := PRGBArray24(Line)[x].G; b := PRGBArray24(Line)[x].B; _Process(RGB(r,g,b), Value, ARGB); GetRGB(ARGB, r, g, b); PRGBArray24(Line)[x].R := r; PRGBArray24(Line)[x].G := g; PRGBArray24(Line)[x].B := b; end; Inc(Line, Delta); end; end; procedure _Sepia(const AColor: TColor;Value: Integer; out NewColor:TColor); var ARGB : TColor; r, g, b : byte; begin GetRGB(AColor, r,g, b); ARGB:=(r+g+b) div 3; r:=ARGB+(Value*2); g:=ARGB+(Value*1); b:=ARGB+(Value*1); if r <= ((Value*2)-1) then r:=255; if g <= (Value-1) then g:=255; NewColor:= RGB(r, g, b); end; procedure _Sepia24(const ABitMap: TBitmap;Value : Byte); begin _ProcessBitmap24(ABitMap, Value, _Sepia); end; procedure _Sepia32(const ABitMap: TBitmap;Value : Byte); begin _ProcessBitmap32(ABitMap, Value, _Sepia); end; procedure _Hue(const AColor: TColor;Value: Integer; out NewColor:TColor); var ARGB : TColor; H, S, L : double; begin _RGBtoHSL(AColor, H, S, L); H := H + Value / 360; ARGB := _HSLtoRGB(H, S, L); NewColor:= ARGB; end; procedure _Hue24(var ABitMap: TBitmap; Value: integer); begin _ProcessBitmap24(ABitMap, Value, _Hue); end; procedure _Hue32(const ABitMap: TBitmap; Value: integer); begin _ProcessBitmap32(ABitMap, Value, _Hue); end; { if b = 0 then result := 0 else begin c := 255 - (((255-a) SHL 8) DIV b); if c < 0 then result := 0 else result := c; end; } procedure _BlendBurn(const AColor: TColor;Value: Integer; out NewColor:TColor); var ARGB : TColor; r, g, b : byte; br, bg, bb : byte; c : Integer; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); if br=0 then r:=0 else begin c:=RoundIntToByte(255-(((255-r) SHL 8) DIV br)); r:=c; end; if bg=0 then g:=0 else begin c:=RoundIntToByte(255-(((255-g) SHL 8) DIV bg)); g:=c; end; if bb=0 then b:=0 else begin c:=RoundIntToByte(255-(((255-b) SHL 8) DIV bb)); b:=c; end; NewColor:=RGB(r, g, b); end; procedure _BlendBurn24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendBurn); end; procedure _BlendBurn32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendBurn); end; {result := (a*b) SHR 8;} procedure _BlendMultiply(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; begin ARGB := Value; GetRGB(AColor, r,g, b); GetRGB(ARGB , br,bg, bb); r:=(r*br) shr 8; g:=(g*bg) shr 8; b:=(b*bb) shr 8; NewColor:= RGB(r,g,b); end; procedure _BlendMultiply24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendMultiply); end; procedure _BlendMultiply32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendMultiply); end; { c := a+b; if c > 255 then result := 255 else result := c; } procedure _BlendAdditive(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; c : Integer; begin ARGB := Value; GetRGB(AColor, r,g, b); GetRGB(ARGB, br,bg, bb); c:=RoundIntToByte(r+br); r:=c; c:=RoundIntToByte(g+bg); g:=c; c:=RoundIntToByte(b+bb); b:=c; NewColor:= RGB(r,g,b); end; procedure _BlendAdditive24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendAdditive); end; procedure _BlendAdditive32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendAdditive); end; { if b = 255 then result := 255 else begin c := (a SHL 8) DIV (255-b); if c > 255 then result := 255 else result := c; end; } procedure _BlendDodge(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; c : Integer; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); if br=255 then r:=255 else begin c := RoundIntToByte((r SHL 8) DIV (255-br)); r := c; end; if bg=255 then g:=255 else begin c := RoundIntToByte((g SHL 8) DIV (255-bg)); g := c; end; if bb=255 then b:=255 else begin c := RoundIntToByte((b SHL 8) DIV (255-bb)); b := c; end; NewColor:= RGB(r,g,b); end; procedure _BlendDodge24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendDodge); end; procedure _BlendDodge32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendDodge); end; { if a < 128 then result := (a*b) SHR 7 else result := 255 - ((255-a) * (255-b) SHR 7); } procedure _BlendOverlay(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; c : Integer; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); if r<128 then r:=RoundIntToByte((r*br) shr 7) else begin c := RoundIntToByte(255 - ((255-r) * (255-br) SHR 7)); r := c; end; if g<128 then g:=RoundIntToByte((g*bg) shr 7) else begin c := RoundIntToByte(255 - ((255-g) * (255-bg) SHR 7)); g := c; end; if b<128 then b:=RoundIntToByte((r*bb) shr 7) else begin c := RoundIntToByte(255 - ((255-b) * (255-bb) SHR 7)); b := c; end; NewColor:= RGB(r,g,b); end; procedure _BlendOverlay24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendOverlay); end; procedure _BlendOverlay32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendOverlay); end; { result := abs(a-b); } procedure _BlendDifference(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); r:=abs(r-br); g:=abs(g-bg); b:=abs(b-bb); NewColor:= RGB(r,g,b); end; procedure _BlendDifference24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendDifference); end; procedure _BlendDifference32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendDifference); end; { if a > b then result := a else result := b; } procedure _BlendLighten(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); r:=IfThen(r>br, r, br); g:=IfThen(g>bg, g, bg); b:=IfThen(b>bb, b, bb); NewColor:= RGB(r,g,b); end; procedure _BlendLighten24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendLighten); end; procedure _BlendLighten32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendLighten); end; { if a < b then result := a else result := b; } procedure _BlendDarken(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); r:=IfThen(r<br, r, br); g:=IfThen(g<bg, g, bg); b:=IfThen(b<bb, b, bb); NewColor:= RGB(r,g,b); end; procedure _BlendDarken24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendDarken); end; procedure _BlendDarken32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendDarken); end; { result := 255 - ((255-a) * (255-b) SHR 8); } procedure _BlendScreen(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; ARGB : TColor; br, bg, bb : byte; c : Integer; begin GetRGB(AColor, r,g, b); ARGB := Value; GetRGB(ARGB, br,bg, bb); c := RoundIntToByte(255 - ((255-r) * (255-br) SHR 8)); r := c; c := RoundIntToByte(255 - ((255-g) * (255-bg) SHR 8)); g := c; c := RoundIntToByte(255 - ((255-b) * (255-bb) SHR 8)); b := c; NewColor:= RGB(r,g,b); end; procedure _BlendScreen24(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap24(ABitMap, Value, _BlendScreen); end; procedure _BlendScreen32(const ABitMap: TBitmap;Value: Integer); begin _ProcessBitmap32(ABitMap, Value, _BlendScreen); end; procedure _SetRComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; begin GetRGB(AColor, r,g, b); r:=RoundIntToByte(r+Value); NewColor:= RGB(r,g,b); end; procedure _SetGComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; begin GetRGB(AColor, r,g, b); g:=RoundIntToByte(g+Value); NewColor:= RGB(r,g,b); end; procedure _SetBComponent(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; begin GetRGB(AColor, r,g, b); b:=RoundIntToByte(b+Value); NewColor:= RGB(r,g,b); end; procedure _SetRGB24(const ABitMap: TBitmap; DR,DG,DB: Integer); var r, g, b : byte; x, y: integer; Line, Delta: NativeInt; begin Line := NativeInt(ABitMap.ScanLine[0]); Delta := NativeInt(ABitMap.ScanLine[1]) - Line; for y := 0 to ABitMap.Height - 1 do begin for x := 0 to ABitMap.Width - 1 do begin r := PRGBArray24(Line)[x].R; g := PRGBArray24(Line)[x].G; b := PRGBArray24(Line)[x].B; PRGBArray24(Line)[x].R := RoundIntToByte(r+DR); PRGBArray24(Line)[x].G := RoundIntToByte(g+DG); PRGBArray24(Line)[x].B := RoundIntToByte(b+DB); end; Inc(Line, Delta); end; end; procedure _SetRGB32(const ABitMap: TBitmap; DR,DG,DB: Integer); var r, g, b, a: byte; x, y: integer; Line, Delta: NativeInt; begin Line := NativeInt(ABitMap.ScanLine[0]); Delta := NativeInt(ABitMap.ScanLine[1]) - Line; for y := 0 to ABitMap.Height - 1 do begin for x := 0 to ABitMap.Width - 1 do begin r := PRGBArray32(Line)[x].R; g := PRGBArray32(Line)[x].G; b := PRGBArray32(Line)[x].B; a := PRGBArray32(Line)[x].A; PRGBArray32(Line)[x].R := RoundIntToByte(r+DR); PRGBArray32(Line)[x].G := RoundIntToByte(g+DG); PRGBArray32(Line)[x].B := RoundIntToByte(b+DB); PRGBArray32(Line)[x].A := a; end; Inc(Line, Delta); end; end; procedure _Saturation(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; Gray : Integer; begin GetRGB(AColor, r,g, b); Gray := (r + g + b) div 3; r := RoundIntToByte(Gray + (((r - Gray) * Value) div 255)); g := RoundIntToByte(Gray + (((g - Gray) * Value) div 255)); b := RoundIntToByte(Gray + (((b - Gray) * Value) div 255)); NewColor:= RGB(r,g,b); end; procedure _Saturation24(var ABitMap: TBitmap; Value: integer); begin _ProcessBitmap24(ABitMap, Value, _Saturation); end; procedure _Saturation32(const ABitMap: TBitmap; Value: integer); begin _ProcessBitmap32(ABitMap, Value, _Saturation); end; procedure _Lightness(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; begin GetRGB(AColor, r,g, b); r := RoundIntToByte(r + ((255 - r) * Value) div 255); g := RoundIntToByte(g + ((255 - g) * Value) div 255); b := RoundIntToByte(b + ((255 - b) * Value) div 255); NewColor:= RGB(r,g,b); end; procedure _Lightness24(var ABitMap: TBitmap; Value: integer); begin _ProcessBitmap24(ABitMap, Value, _Lightness); end; procedure _Lightness32(const ABitMap: TBitmap; Value: integer); begin _ProcessBitmap32(ABitMap, Value, _Lightness); end; procedure _Darkness(const AColor: TColor;Value: Integer; out NewColor:TColor); var r, g, b : byte; begin GetRGB(AColor, r,g, b); r := RoundIntToByte(r - ((r) * Value) div 255); g := RoundIntToByte(g - ((g) * Value) div 255); b := RoundIntToByte(b - ((b) * Value) div 255); NewColor:= RGB(r,g,b); end; procedure _Darkness24(var ABitMap: TBitmap; Value: integer); begin _ProcessBitmap24(ABitMap, Value, _Darkness); end; procedure _Darkness32(const ABitMap: TBitmap; Value: integer); begin _ProcessBitmap32(ABitMap, Value, _Darkness); end; function _HSLtoRGB(HueValue, SaturationValue, LightValue: double): TColor; var M1, M2: double; function HueToColourValue(Hue: double): byte; var V: double; begin if Hue < 0 then Hue := Hue + 1 else if Hue > 1 then Hue := Hue - 1; if 6 * Hue < 1 then V := M1 + (M2 - M1) * Hue * 6 else if 2 * Hue < 1 then V := M2 else if 3 * Hue < 2 then V := M1 + (M2 - M1) * (2 / 3 - Hue) * 6 else V := M1; Result := round(255 * V); end; var R, G, B: byte; begin if SaturationValue = 0 then begin R := round(255 * LightValue); G := R; B := R; end else begin if LightValue <= 0.5 then M2 := LightValue * (1 + SaturationValue) else M2 := LightValue + SaturationValue - LightValue * SaturationValue; M1 := 2 * LightValue - M2; R := HueToColourValue(HueValue + 1 / 3); G := HueToColourValue(HueValue); B := HueToColourValue(HueValue - 1 / 3); end; Result := RGB(R, G, B); end; procedure _RGBtoHSL(RGB: TColor; var HueValue, SaturationValue, LightValue: double); function Max(a, b: double): double; begin if a > b then Result := a else Result := b; end; function Min(a, b: double): double; begin if a < b then Result := a else Result := b; end; var R, G, B, D, Cmax, Cmin: double; begin R := GetRValue(RGB) / 255; G := GetGValue(RGB) / 255; B := GetBValue(RGB) / 255; Cmax := Max(R, Max(G, B)); Cmin := Min(R, Min(G, B)); LightValue := (Cmax + Cmin) / 2; if Cmax = Cmin then begin HueValue := 0; SaturationValue := 0; end else begin D := Cmax - Cmin; if LightValue < 0.5 then SaturationValue := D / (Cmax + Cmin) else SaturationValue := D / (2 - Cmax - Cmin); if R = Cmax then HueValue := (G - B) / D else if G = Cmax then HueValue := 2 + (B - R) / D else HueValue := 4 + (R - G) / D; HueValue := HueValue / 6; if HueValue < 0 then HueValue := HueValue + 1; end; end; { TBitmap32Filter } { TBitmap32HueFilter } procedure TBitmap32HueFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _Hue) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _Hue); end; function TBitmap32HueFilter.ProcessColor(AColor: TColor): TColor; begin _Hue(AColor, Value, Result); end; { TBitmap32SaturationFilter } procedure TBitmap32SaturationFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _Saturation) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _Saturation); end; function TBitmap32SaturationFilter.ProcessColor(AColor: TColor): TColor; begin _Saturation(AColor, Value, Result); end; { TBitmap32LightnessFilter } procedure TBitmap32LightnessFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then begin if Value >= 0 then _ProcessBitmap32(ABitMap, Value, _Lightness) else _ProcessBitmap32(ABitMap, Abs(Value), _Darkness); end else if ABitMap.PixelFormat=pf24bit then begin if Value >= 0 then _ProcessBitmap24(ABitMap, Value, _Lightness) else _ProcessBitmap24(ABitMap, Abs(Value), _Darkness); end; end; function TBitmap32LightnessFilter.ProcessColor(AColor: TColor): TColor; begin if Value >= 0 then _Lightness(AColor, Value, Result) else _Darkness(AColor, Abs(Value), Result); end; { TBitmap32SepiaFilter } procedure TBitmap32SepiaFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _Sepia) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _Sepia); end; function TBitmap32SepiaFilter.ProcessColor(AColor: TColor): TColor; begin _Sepia(AColor, Value, Result); end; { TColorFilter } constructor TColorFilter.Create(AValue: Integer); begin inherited Create; FValue:=AValue; end; { TBitmap32BlueFilter } procedure TBitmap32BlueFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _SetRGB32(ABitMap,0,0,Value) else if ABitMap.PixelFormat=pf24bit then _SetRGB24(ABitMap,0,0,Value); end; function TBitmap32BlueFilter.ProcessColor(AColor: TColor): TColor; begin _SetBComponent(AColor, Value, Result); end; { TBitmap32RedFilter } procedure TBitmap32RedFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _SetRGB32(ABitMap,Value,0,0) else if ABitMap.PixelFormat=pf24bit then _SetRGB24(ABitMap,Value,0,0); end; function TBitmap32RedFilter.ProcessColor(AColor: TColor): TColor; begin _SetRComponent(AColor, Value, Result); end; { TBitmap32GreenFilter } procedure TBitmap32GreenFilter.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _SetRGB32(ABitMap,0,Value,0) else if ABitMap.PixelFormat=pf24bit then _SetRGB24(ABitMap,0,Value,0); end; function TBitmap32GreenFilter.ProcessColor(AColor: TColor): TColor; begin _SetGComponent(AColor, Value, Result); end; { TBitmap32BlendBurn } procedure TBitmap32BlendBurn.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendBurn) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendBurn); end; function TBitmap32BlendBurn.ProcessColor(AColor: TColor): TColor; begin _BlendBurn(AColor, Value, Result); end; { TBitmap32BlendMultiply } procedure TBitmap32BlendMultiply.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendMultiply) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendMultiply); end; function TBitmap32BlendMultiply.ProcessColor(AColor: TColor): TColor; begin _BlendMultiply(AColor, Value, Result); end; { TBitmap32BlendAdditive } procedure TBitmap32BlendAdditive.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendAdditive) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendAdditive); end; function TBitmap32BlendAdditive.ProcessColor(AColor: TColor): TColor; begin _BlendAdditive(AColor, Value, Result); end; { TBitmap32BlendDodge } procedure TBitmap32BlendDodge.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendDodge) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendDodge); end; function TBitmap32BlendDodge.ProcessColor(AColor: TColor): TColor; begin _BlendDodge(AColor, Value, Result); end; { TBitmap32BlendOverlay } procedure TBitmap32BlendOverlay.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendOverlay) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendOverlay); end; function TBitmap32BlendOverlay.ProcessColor(AColor: TColor): TColor; begin _BlendOverlay(AColor, Value, Result); end; { TBitmap32BlendLighten } procedure TBitmap32BlendLighten.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendLighten) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendLighten); end; function TBitmap32BlendLighten.ProcessColor(AColor: TColor): TColor; begin _BlendLighten(AColor, Value, Result); end; { TBitmap32BlendDarken } procedure TBitmap32BlendDarken.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendDarken) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendDarken); end; function TBitmap32BlendDarken.ProcessColor(AColor: TColor): TColor; begin _BlendDarken(AColor, Value, Result); end; { TBitmap32BlendScreen } procedure TBitmap32BlendScreen.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendScreen) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendScreen); end; function TBitmap32BlendScreen.ProcessColor(AColor: TColor): TColor; begin _BlendScreen(AColor, Value, Result); end; { TBitmap32BlendDifference } procedure TBitmap32BlendDifference.ProcessBitmap(ABitMap: TBitmap); begin if ABitMap.PixelFormat=pf32bit then _ProcessBitmap32(ABitMap, Value, _BlendDifference) else if ABitMap.PixelFormat=pf24bit then _ProcessBitmap24(ABitMap, Value, _BlendDifference); end; function TBitmap32BlendDifference.ProcessColor(AColor: TColor): TColor; begin _BlendDifference(AColor, Value, Result); end; end.
unit uFrmPromoItem; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, Buttons, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, Mask, SuperComboADO, ADODB, PowerADOQuery, uFrmBarcodeSearch, DBClient; type TFrmPromoItem = class(TFrmParent) Panel4: TPanel; lbSearch: TLabel; grdPromoPrizeItem: TcxGrid; grdPromoPrizeItemDB: TcxGridDBTableView; grdPromoPrizeItemDBModel: TcxGridDBColumn; grdPromoPrizeItemDBDescription: TcxGridDBColumn; grdPromoPrizeItemLevel: TcxGridLevel; pnlComand: TPanel; btSearch: TSpeedButton; btRemove: TSpeedButton; Panel6: TPanel; btSave: TButton; quSearchItem: TADODataSet; quSearchItemIDModel: TIntegerField; quSearchItemModel: TStringField; quSearchItemDescription: TStringField; lbVendor: TLabel; cbTypeSearch: TComboBox; edSearch: TEdit; scVendor: TSuperComboADO; cdsPromoItems: TClientDataSet; cdsPromoItemsIDPRomo: TIntegerField; cdsPromoItemsIDPromoItem: TIntegerField; cdsPromoItemsModel: TStringField; cdsPromoItemsDescription: TStringField; cdsPromoItemsIDModel: TIntegerField; dsPromoItems: TDataSource; btNewItem: TSpeedButton; procedure btSearchClick(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure btSaveClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure cbTypeSearchChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure edSearchKeyPress(Sender: TObject; var Key: Char); procedure cdsPromoItemsAfterOpen(DataSet: TDataSet); procedure btNewItemClick(Sender: TObject); private IDPromo :Integer; IDPromoItem: Integer; procedure CreatePromoItem; function ExistPromoItem(pIDModel : String): Boolean; { Funções que serão utilizadas para não permitir que um produto que esteja cadastrado em Promo Items(X) seja cadastrado no Discount Items(Y) e Vice-Versa. } function ExistInDiscountItems(pIDModel : String): Boolean; function ExistInPromoItems(pIDModel : String): Boolean; function VerifyModelCondition(pIDModel : String): Boolean; procedure LoadImages; Procedure ChangedTypeSearch; Procedure PopulatePromoItems; Procedure InsertPromoItems(IDPromo, IDPromoItem, IDModel : Integer; Model, Description : String); Procedure SearchItem; public function Start(AID, AIDPromoItem, APromoType :Integer): Boolean; end; implementation uses uDM, uMsgBox, uMsgConstant, StrUtils, uSystemConst, uFrmPromoPrizeItem, uFrmModelQuickEntry, uContentClasses, ufrmModelAdd; {$R *.dfm} procedure TFrmPromoItem.btSearchClick(Sender: TObject); var FFrmPromoProzeItem: TFrmPromoPrizeItem; begin FFrmPromoProzeItem := TFrmPromoPrizeItem.Create(self); with FFrmPromoProzeItem do if Start(IDPromoItem) then begin FFrmPromoProzeItem.cdsResult.First; while not FFrmPromoProzeItem.cdsResult.Eof do begin if not ExistPromoItem(FFrmPromoProzeItem.cdsResult.FieldByName('IDModel').AsString) then InsertPromoItems(IDPromo, IDPromoItem, FFrmPromoProzeItem.cdsResult.FieldByName('IDModel').Value, FFrmPromoProzeItem.cdsResult.FieldByName('Model').Value, FFrmPromoProzeItem.cdsResult.FieldByName('Description').Value); FFrmPromoProzeItem.cdsResult.Next; end; end; FreeAndNil(FFrmPromoProzeItem); end; procedure TFrmPromoItem.btRemoveClick(Sender: TObject); begin if (MsgBox(MSG_QST_DELETE, vbYesNo + vbQuestion) = vbYes) then try Screen.Cursor := crHourGlass; try cdsPromoItems.Delete; except MsgBox(MSG_CRT_NO_DEL_RECORD, vbCritical + vbOKOnly); end; finally Screen.Cursor := crDefault; end; end; procedure TFrmPromoItem.CreatePromoItem; var NewID : Integer; begin if not cdsPromoItems.IsEmpty then begin cdsPromoItems.DisableControls; cdsPromoItems.First; while not cdsPromoItems.Eof do begin if IDPromoItem = 0 then begin NewID := DM.GetNextID('Sal_PromoItem.IDPromoItem'); DM.RunSQL('INSERT INTO Sal_PromoItem (IDPromoItem, IDPromo, IDModel) VALUES ( ' + InttoStr(NewID) + ' , ' + InttoStr(IDPromo) + ' , ' + cdsPromoItemsIDModel.AsString + ')'); end else begin NewID := DM.GetNextID('Sal_PromoPrizeItem.IDPromoPrizeItem'); DM.RunSQL('INSERT INTO Sal_PromoPrizeItem (IDPromoPrizeItem, IDPromoItem, IDModel) VALUES ( ' + InttoStr(NewID) + ' , ' + InttoStr(IDPromoItem) + ' , ' + cdsPromoItemsIDModel.AsString + ')'); end; cdsPromoItems.Next; end; end; end; function TFrmPromoItem.Start(AID, AIDPromoItem, APromoType :Integer): Boolean; begin IDPromo := AID; IDPromoItem := AIDPromoItem; { IDPromoItem = 0 -> PROMO ITEMS(X) IDPromoItem <> 0 -> DISCOUNT ITEMS(Y) } cdsPromoItems.CreateDataSet; ShowModal; if (ModalResult = mrOk) then begin CreatePromoItem; Result := True; end else Result := false; cdsPromoItems.Close; end; procedure TFrmPromoItem.btSaveClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TFrmPromoItem.btCloseClick(Sender: TObject); begin inherited; cdsPromoItems.Close; Close; end; function TFrmPromoItem.ExistPromoItem(pIDModel : String) : Boolean; var sSelect : String; bInDiscountItems, bInPromoItems : Boolean; begin bInDiscountItems := False; bInPromoItems := False; if IDPromoItem = 0 then begin sSelect := 'SELECT IDModel FROM Sal_PromoItem (NOLOCK) WHERE IDPromo = ' + InttoStr(IDPromo) + ' AND IDModel = ' + pIDModel; bInDiscountItems := ExistInDiscountItems(pIDModel); end else begin sSelect := 'SELECT IDModel FROM Sal_PromoPrizeItem (NOLOCK) WHERE IDPromoItem = ' + InttoStr(IDPromoItem) + ' AND IDModel = ' + pIDModel; bInPromoItems := ExistInPromoItems(pIDModel); end; if ((not bInDiscountItems) and (not bInPromoItems)) then begin with DM.quFreeSQL do try if Active then Close; SQL.Text := sSelect; Open; if ((DM.quFreeSQL.IsEmpty) and (not cdsPromoItems.Locate('IDModel', pIDModel, []))) then Result := False else Result := True; finally Close; end; end else Result := True; end; procedure TFrmPromoItem.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; quSearchItem.Close; end; procedure TFrmPromoItem.LoadImages; begin DM.imgSmall.GetBitmap(BTN18_SEARCH, btSearch.Glyph); DM.imgSmall.GetBitmap(BTN18_DELETE, btRemove.Glyph); DM.imgSmall.GetBitmap(BTN18_NEW, btNewItem.Glyph); end; procedure TFrmPromoItem.FormCreate(Sender: TObject); begin inherited; LoadImages; end; function TFrmPromoItem.VerifyModelCondition(pIDModel : String): Boolean; begin if ExistPromoItem(pIDModel) then begin MsgBox(MSG_EXC_MODEL_EXISTE, vbOKOnly + vbInformation); ModalResult := mrNone; Result := False; Exit; end; Result := True; end; procedure TFrmPromoItem.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_F4 : begin //Remove Button if (btRemove.Enabled) then btRemoveClick(nil); end; end; end; procedure TFrmPromoItem.FormDestroy(Sender: TObject); begin inherited; // FreeAndNil(fFrmBarcodeSearch); end; procedure TFrmPromoItem.ChangedTypeSearch; begin edSearch.Clear; edSearch.SetFocus; if cbTypeSearch.ItemIndex <> 2 then begin scVendor.Enabled := False; scVendor.Text := ''; end else scVendor.Enabled := True; end; procedure TFrmPromoItem.cbTypeSearchChange(Sender: TObject); begin inherited; ChangedTypeSearch; end; procedure TFrmPromoItem.PopulatePromoItems; begin { quPromoPrizeItem.First; while not quPromoPrizeItem.Eof do begin cdsPromoItems.Append; cdsPromoItemsIDPRomo.value := IDPromo; cdsPromoItemsIDPromoItem.Value := IDPromoItem; cdsPromoItemsIDModel.value := quPromoPrizeItemIDModel.value; cdsPromoItemsModel.value := quPromoPrizeItemModel.value; cdsPromoItemsDescription.value := quPromoPrizeItemDescription.value; quPromoPrizeItem.Next; end; } end; procedure TFrmPromoItem.FormShow(Sender: TObject); begin inherited; ChangedTypeSearch; end; procedure TFrmPromoItem.SearchItem; var sSQL, sWhere, sJoin : String; begin quSearchItem.Close; sSQL := 'SELECT '+ 'M.IDModel, '+ 'M.Model, '+ 'M.Description '+ 'FROM Model M (NOLOCK) '; if cbTypeSearch.ItemIndex = 0 then sWhere := 'WHERE M.Model = '+ QuotedStr(edSearch.Text) else if cbTypeSearch.ItemIndex = 1 then begin sJoin := 'JOIN Barcode B (NOLOCK) ON (B.IDModel = M.IDModel) '; sWhere := 'WHERE B.IDBarcode = '+ QuotedStr(edSearch.Text); end else if cbTypeSearch.ItemIndex = 2 then begin sJoin := 'INNER JOIN Inv_ModelVendor IMV (NOLOCK) '+ 'ON (M.IDModel = IMV.IDModel) ' + 'AND IMV.IDPessoa = ' + scVendor.LookUpValue+ ' INNER JOIN Pet P (NOLOCK) ON M.IDModel = P.IDModel '; sWhere := 'WHERE P.SKU = ' + QuotedStr(edSearch.Text); end; quSearchItem.CommandText := sSQL + sJoin + sWhere; quSearchItem.Open; end; procedure TFrmPromoItem.InsertPromoItems(IDPromo, IDPromoItem, IDModel: Integer; Model, Description: String); begin cdsPromoItems.Append; cdsPromoItemsIDPRomo.value := IDPromo; cdsPromoItemsIDPromoItem.Value := IDPromoItem; cdsPromoItemsIDModel.value := IDModel; cdsPromoItemsModel.value := Model; cdsPromoItemsDescription.value := Description; cdsPromoItems.Post; end; procedure TFrmPromoItem.edSearchKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then begin if ((cbTypeSearch.ItemIndex = 2) and (scVendor.LookUpValue = '')) then MsgBox(MSG_EXC_SELECT_A_VENDOR, vbOkOnly + vbExclamation) else begin SearchItem; If not quSearchItem.IsEmpty then begin if VerifyModelCondition(quSearchItemIDModel.AsString) then InsertPromoItems(IDPromo, IDPromoItem, quSearchItemIDModel.value, quSearchItemModel.value, quSearchItemDescription.Value); end; edSearch.Clear; end; end; end; procedure TFrmPromoItem.cdsPromoItemsAfterOpen(DataSet: TDataSet); begin inherited; btRemove.Enabled := cdsPromoItems.RecordCount > 0; end; procedure TFrmPromoItem.btNewItemClick(Sender: TObject); var ABarcode: TBarcode; FFrmModelQuickEntry : TfrmModelAdd; key : Char; begin inherited; try //FFrmModelQuickEntry := TFrmModelQuickEntry.Create(Self); //amfsouza 11.22.2011 FFrmModelQuickEntry := TfrmModelAdd.Create(self); ABarcode := FFrmModelQuickEntry.Start(False, True, True, ''); if ABarcode.Model.IDModel <> -1 then begin if not ExistPromoItem(ABarcode.Model.Model) then InsertPromoItems(IDPromo, IDPromoItem, ABarcode.Model.IDModel, ABarcode.Model.Model, ABarcode.Model.Description); end; finally FreeAndNil(FFrmModelQuickEntry); end; end; function TFrmPromoItem.ExistInDiscountItems(pIDModel: String): Boolean; begin with DM.quFreeSQL do try if Active then Close; SQL.Text := 'SELECT PP.IDModel'+ ' FROM Sal_PromoPrizeItem PP (NOLOCK)'+ ' JOIN Sal_PromoItem P (NOLOCK)'+ ' ON PP.IDPromoItem = P.IDPromoItem'+ ' AND P.IDPromo = '+InttoStr(IDPromo)+ ' WHERE PP.IDModel = '+pIDModel; Open; if (DM.quFreeSQL.IsEmpty) then Result := False else Result := True; finally Close; end; end; function TFrmPromoItem.ExistInPromoItems(pIDModel: String): Boolean; begin with DM.quFreeSQL do try if Active then Close; SQL.Text := 'SELECT P.IDModel'+ ' FROM Sal_PromoItem P (NOLOCK)'+ ' WHERE P.IDPromo = '+InttoStr(IDPromo)+ ' AND P.IDModel = '+pIDModel; Open; if (DM.quFreeSQL.IsEmpty) then Result := False else Result := True; finally Close; end; end; end.
unit FCM; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,DW.PushClient, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,System.PushNotification; type TForm3 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); private FPushClient: TPushClient; procedure PushClientChangeHandler(Sender: TObject; AChange: TPushService.TChanges); procedure PushClientReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification); public { Public declarations } end; var Form3: TForm3; implementation {$R *.fmx} const cFCMSenderID = '1037658936759'; cFCMServerKey = 'AIzaSyCRuEMYS7zYnKjTwLHWRS0MJEG8EVbTQ0E'; cFCMBundleID = 'com.embarcadero.push'; procedure TForm3.FormCreate(Sender: TObject); begin FPushClient := TPushClient.Create; FPushClient.GCMAppID := cFCMSenderID; FPushClient.ServerKey := cFCMServerKey; FPushClient.BundleID := cFCMBundleID; FPushClient.UseSandbox := True; // Change this to False for production use! FPushClient.OnChange := PushClientChangeHandler; FPushClient.OnReceiveNotification := PushClientReceiveNotificationHandler; FPushClient.Active := True; end; procedure TForm3.PushClientChangeHandler(Sender: TObject; AChange: TPushService.TChanges); begin if TPushService.TChange.DeviceToken in AChange then begin Memo1.Lines.Add('DeviceID = ' + FPushClient.DeviceID); Memo1.Lines.Add('DeviceToken = ' + FPushClient.DeviceToken); end; end; procedure TForm3.PushClientReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification); begin Memo1.Lines.Add('Notification: ' + ANotification.DataObject.ToString); end; end.
unit DSA.Tree.LinkedListMap; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Rtti, DSA.Interfaces.Comparer, DSA.Interfaces.DataStructure, DSA.Utils; type { TLinkedListMap } generic TLinkedListMap<K, V, TKeyComparer> = class(TInterfacedObject, specialize IMap<K, V>) private type { TNode } TNode = class public Key: K; Value: V; Next: TNode; constructor Create(newKey: K; newValue: V; newNext: TNode); overload; constructor Create(newKey: K); overload; constructor Create; overload; function ToString: string; override; end; TPtrV = specialize TPtr_V<V>; var __dummyHead: TNode; __size: integer; __comparer: specialize IDSA_Comparer<K>; function __getNode(Key: K): TNode; public constructor Create; function Contains(Key: K): boolean; function Get(Key: K): TPtrV; function GetSize: integer; function IsEmpty: boolean; function Remove(Key: K): TPtrV; procedure Add(Key: K; Value: V); procedure Set_(Key: K; Value: V); end; procedure Main(); implementation type TLinkedListMap_str_int = specialize TLinkedListMap<string, integer, TComparer_str>; procedure Main(); var words: TArrayList_str; map: TLinkedListMap_str_int; i, n: integer; begin words := TArrayList_str.Create(); if TDsaUtils.ReadFile(FILE_PATH + A_FILE_NAME, words) then begin Writeln('Total words: ', words.GetSize); end; map := TLinkedListMap_str_int.Create; for i := 0 to words.GetSize - 1 do begin if map.Contains(words[i]) then begin n := map.Get(words[i]).PValue^; map.Set_(words[i], n + 1); end else map.Add(words[i], 1); end; Writeln('Total different words: ', map.GetSize); TDsaUtils.DrawLine; Writeln('Frequency of pride: ', map.Get('pride').PValue^); Writeln('Frequency of prejudice: ', map.Get('prejudice').PValue^); end; { TLinkedListMap } constructor TLinkedListMap.Create; begin __comparer := TKeyComparer.Default; __dummyHead := TNode.Create(); __size := 0; end; function TLinkedListMap.Contains(Key: K): boolean; begin Result := __getNode(Key) <> nil; end; function TLinkedListMap.Get(Key: K): TPtrV; var node: TNode; begin node := __getNode(Key); if node = nil then Result.PValue := nil else Result.PValue := @node.Value; end; function TLinkedListMap.GetSize: integer; begin Result := __size; end; function TLinkedListMap.__getNode(Key: K): TNode; var cur: TNode; begin cur := __dummyHead.Next; while cur <> nil do begin if __comparer.Compare(cur.Key, Key) = 0 then Exit(cur); cur := cur.Next; end; Result := nil; end; function TLinkedListMap.IsEmpty: boolean; begin Result := __size = 0; end; function TLinkedListMap.Remove(Key: K): TPtrV; var prev, delNode: TNode; begin prev := __dummyHead; while prev.Next <> nil do begin if __comparer.Compare(prev.Key, key) = 0 then Break; prev := prev.Next; end; if prev.Next <> nil then begin delNode := prev.Next; prev.Next := delNode.Next; Dec(__size); Result.PValue := @delNode.Value; FreeAndNil(delNode); end else begin Result.PValue := nil; end; end; procedure TLinkedListMap.Add(Key: K; Value: V); var node: TNode; begin node := __getNode(Key); if node = nil then begin __dummyHead.Next := TNode.Create(Key, Value, __dummyHead.Next); Inc(__size); end else begin node.Value := Value; end; end; procedure TLinkedListMap.Set_(Key: K; Value: V); var node: TNode; Val: Tvalue; begin node := __getNode(Key); if node = nil then begin TValue.Make(@Key, TypeInfo(K), Val); raise Exception.Create(Val.ToString + ' doesn''t exist!'); end; node.Value := Value; end; { TLinkedListMap.TNode } constructor TLinkedListMap.TNode.Create(newKey: K; newValue: V; newNext: TNode); begin Self.Key := newKey; Self.Value := newValue; Self.Next := newNext; end; constructor TLinkedListMap.TNode.Create(newKey: K); begin Self.Create(newKey, default(V), nil); end; constructor TLinkedListMap.TNode.Create; begin Self.Create(default(K)); end; function TLinkedListMap.TNode.ToString: string; var value_key, value_value: TValue; str_key, str_value: string; begin value_key := TValue.From(Key); value_value := TValue.From(Value); if not (value_key.IsObject) then str_key := value_key.ToString else str_key := value_key.AsObject.ToString; if not (value_value.IsObject) then str_value := value_value.ToString else str_value := value_value.AsObject.ToString; Result := str_key + ' : ' + str_value; end; end.
unit InflatablesList_Item_Search; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses InflatablesList_Types, InflatablesList_ItemShop, InflatablesList_Item_Comp; type TILItem_Search = class(TILItem_Comp) protected Function SearchField(const SearchSettings: TILAdvSearchSettings; Field: TILAdvItemSearchResult): Boolean; virtual; public Function FindPrev(const Text: String; From: TILItemSearchResult = ilisrNone): TILItemSearchResult; virtual; Function FindNext(const Text: String; From: TILItemSearchResult = ilisrNone): TILItemSearchResult; virtual; Function FindAll(const SearchSettings: TILAdvSearchSettings; out SearchResult: TILAdvSearchResult): Boolean; virtual; end; implementation uses SysUtils, InflatablesList_Utils, InflatablesList_LocalStrings; Function TILItem_Search.SearchField(const SearchSettings: TILAdvSearchSettings; Field: TILAdvItemSearchResult): Boolean; var SelShop: TILItemShop; i: Integer; Function GetFlagsString: String; var Flag: TILItemFlag; begin Result := ''; For Flag := Low(TILItemFlag) to High(TILItemFlag) do If Flag in fFlags then begin If Length(Result) > 0 then Result := Result + ' ' + fDataProvider.GetItemFlagString(Flag) else Result := fDataProvider.GetItemFlagString(Flag); end; end; begin case Field of ilaisrListIndex: Result := SearchSettings.CompareFunc(IntToStr(fIndex),False,False,False); ilaisrUniqueID: Result := SearchSettings.CompareFunc(GUIDToString(fUniqueID),False,False,False); ilaisrTimeOfAdd: Result := SearchSettings.CompareFunc(IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',fTimeOfAddition),False,False,False); ilaisrDescriptor: Result := SearchSettings.CompareFunc(Descriptor,True,False,True); ilaisrTitleStr: Result := SearchSettings.CompareFunc(TitleStr,True,False,True); ilaisrPictures: begin Result := False; For i := fPictures.LowIndex to fPictures.HighIndex do If SearchSettings.CompareFunc(fPictures[i].PictureFile,True,False,False) then begin Result := True; Break{For i}; end; end; ilaisrMainPictureFile: If fPictures.CheckIndex(fPictures.IndexOfItemPicture) then Result := SearchSettings.CompareFunc(fPictures[fPictures.IndexOfItemPicture].PictureFile,True,False,False) else Result := False; ilaisrPackagePictureFile: If fPictures.CheckIndex(fPictures.IndexOfPackagePicture) then Result := SearchSettings.CompareFunc(fPictures[fPictures.IndexOfPackagePicture].PictureFile,True,False,False) else Result := False; ilaisrCurrSecPictureFile: If fPictures.CheckIndex(fPictures.CurrentSecondary) then Result := SearchSettings.CompareFunc(fPictures[fPictures.CurrentSecondary].PictureFile,True,False,False) else Result := False; ilaisrType: Result := SearchSettings.CompareFunc(fDataProvider.GetItemTypeString(fItemType),False,True,False); ilaisrTypeSpec: Result := SearchSettings.CompareFunc(fItemTypeSpec,True,True,False); ilaisrTypeStr: Result := SearchSettings.CompareFunc(TypeStr,True,False,True); ilaisrPieces: Result := SearchSettings.CompareFunc(IntToStr(fPieces),False,True,False,'pcs'); ilaisrUserID: Result := SearchSettings.CompareFunc(fUserID,True,True,False); ilaisrManufacturer: Result := SearchSettings.CompareFunc(fDataProvider.ItemManufacturers[fManufacturer].Str,False,True,False); ilaisrManufacturerStr: Result := SearchSettings.CompareFunc(fManufacturerStr,True,True,False); ilaisrManufacturerTag: Result := SearchSettings.CompareFunc(fDataProvider.ItemManufacturers[fManufacturer].Tag ,True,False,False); ilaisrTextID: Result := SearchSettings.CompareFunc(fTextID,True,True,False); ilaisrNumID: Result := SearchSettings.CompareFunc(IntToStr(fNumID),False,True,False); ilaisrIDStr: Result := SearchSettings.CompareFunc(IDStr,True,False,False); ilaisrFlags: Result := SearchSettings.CompareFunc(GetFlagsString,False,True,True); ilaisrFlagOwned: Result := (ilifOwned in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifOwned),False,True,False); ilaisrFlagWanted: Result := (ilifWanted in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifWanted),False,True,False); ilaisrFlagOrdered: Result := (ilifOrdered in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifOrdered),False,True,False); ilaisrFlagBoxed: Result := (ilifBoxed in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifBoxed),False,True,False); ilaisrFlagElsewhere: Result := (ilifElsewhere in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifElsewhere),False,True,False); ilaisrFlagUntested: Result := (ilifUntested in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifUntested),False,True,False); ilaisrFlagTesting: Result := (ilifTesting in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifTesting),False,True,False); ilaisrFlagTested: Result := (ilifTested in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifTested),False,True,False); ilaisrFlagDamaged: Result := (ilifDamaged in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifDamaged),False,True,False); ilaisrFlagRepaired: Result := (ilifRepaired in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifRepaired),False,True,False); ilaisrFlagPriceChange: Result := (ilifPriceChange in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifPriceChange),False,True,False); ilaisrFlagAvailChange: Result := (ilifAvailChange in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifAvailChange),False,True,False); ilaisrFlagNotAvailable: Result := (ilifNotAvailable in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifNotAvailable),False,True,False); ilaisrFlagLost: Result := (ilifLost in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifLost),False,True,False); ilaisrFlagDiscarded: Result := (ilifDiscarded in fFlags) and SearchSettings.CompareFunc(fDataProvider.GetItemFlagString(ilifDiscarded),False,True,False); ilaisrTextTag: Result := SearchSettings.CompareFunc(fTextTag,True,True,False); ilaisrNumTag: Result := SearchSettings.CompareFunc(IntToStr(fNumTag),True,True,False); ilaisrWantedLevel: Result := SearchSettings.CompareFunc(IntToStr(fWantedLevel),False,True,False); ilaisrVariant: Result := SearchSettings.CompareFunc(fVariant,True,True,False); ilaisrVariantTag: Result := SearchSettings.CompareFunc(fVariantTag,True,True,False); ilaisrSurfaceFinish: Result := SearchSettings.CompareFunc(fDataProvider.GetItemSurfaceFinishString(fSurfaceFinish),False,True,False); ilaisrMaterial: Result := SearchSettings.CompareFunc(fDataProvider.GetItemMaterialString(fMaterial),False,True,False); ilaisrThickness: Result := SearchSettings.CompareFunc(IntToStr(fThickness),False,True,False,'um'); ilaisrSizeX: Result := SearchSettings.CompareFunc(IntToStr(fSizeX),False,True,False,'mm'); ilaisrSizeY: Result := SearchSettings.CompareFunc(IntToStr(fSizeY),False,True,False,'mm'); ilaisrSizeZ: Result := SearchSettings.CompareFunc(IntToStr(fSizeZ),False,True,False,'mm'); ilaisrTotalSize: Result := SearchSettings.CompareFunc(IntToStr(TotalSize),False,False,True,'mm^3'); ilaisrSizeStr: Result := SearchSettings.CompareFunc(SizeStr,False,False,True); ilaisrUnitWeight: Result := SearchSettings.CompareFunc(IntToStr(fUnitWeight),False,True,False,'g'); ilaisrTotalWeight: Result := SearchSettings.CompareFunc(IntToStr(TotalWeight),False,False,True,'g'); ilaisrTotalWeightStr: Result := SearchSettings.CompareFunc(TotalWeightStr,True,False,True); ilaisrNotes: Result := SearchSettings.CompareFunc(fNotes,True,True,False); ilaisrReviewURL: Result := SearchSettings.CompareFunc(fReviewURL,True,True,False); ilaisrUnitPriceDefault: Result := SearchSettings.CompareFunc(IntToStr(fUnitPriceDefault),False,True,False,IL_CURRENCY_SYMBOL); ilaisrRating: Result := SearchSettings.CompareFunc(IntToStr(fRating),False,True,False,'%'); ilaisrRatingDetails: Result := SearchSettings.CompareFunc(fRatingDetails,True,True,False); ilaisrUnitPrice: Result := SearchSettings.CompareFunc(IntToStr(UnitPrice),False,False,True,IL_CURRENCY_SYMBOL); ilaisrUnitPriceLowest: Result := SearchSettings.CompareFunc(IntToStr(fUnitPriceLowest),False,False,True,IL_CURRENCY_SYMBOL); ilaisrTotalPriceLowest: Result := SearchSettings.CompareFunc(IntToStr(TotalPriceLowest),False,False,True,IL_CURRENCY_SYMBOL); ilaisrUnitPriceHighest: Result := SearchSettings.CompareFunc(IntToStr(fUnitPriceHighest),False,False,True,IL_CURRENCY_SYMBOL); ilaisrTotalPriceHighest: Result := SearchSettings.CompareFunc(IntToStr(TotalPriceHighest),False,False,True,IL_CURRENCY_SYMBOL); ilaisrUnitPriceSel: Result := SearchSettings.CompareFunc(IntToStr(fUnitPriceSelected),False,False,False,IL_CURRENCY_SYMBOL); ilaisrTotalPriceSel: Result := SearchSettings.CompareFunc(IntToStr(TotalPriceSelected),False,False,True,IL_CURRENCY_SYMBOL); ilaisrTotalPrice: Result := SearchSettings.CompareFunc(IntToStr(TotalPrice),False,False,True,IL_CURRENCY_SYMBOL); ilaisrAvailableLowest: Result := SearchSettings.CompareFunc(IntToStr(fAvailableLowest),False,False,True,'pcs'); ilaisrAvailableHighest: Result := SearchSettings.CompareFunc(IntToStr(fAvailableHighest),False,False,True,'pcs'); ilaisrAvailableSel: Result := SearchSettings.CompareFunc(IntToStr(fAvailableSelected),False,False,False,'pcs'); ilaisrShopCount: Result := SearchSettings.CompareFunc(IntToStr(fShopCount),False,False,False); ilaisrShopCountStr: Result := SearchSettings.CompareFunc(ShopsCountStr,True,False,True); ilaisrUsefulShopCount: Result := SearchSettings.CompareFunc(IntToStr(ShopsUsefulCount),False,False,True); ilaisrUsefulShopRatio: Result := SearchSettings.CompareFunc(IL_Format('%f',[ShopsUsefulRatio]),False,False,True); ilaisrSelectedShop: If ShopsSelected(SelShop) then Result := SearchSettings.CompareFunc(SelShop.Name,True,True,False) else Result := False; ilaisrWorstUpdateResult: Result := SearchSettings.CompareFunc(fDataProvider.GetShopUpdateResultString(ShopsWorstUpdateResult),False,False,True); else Result := False; end; end; //============================================================================== Function TILItem_Search.FindPrev(const Text: String; From: TILItemSearchResult = ilisrNone): TILItemSearchResult; var i: TILItemSearchResult; begin Result := ilisrNone; If fDataAccessible then begin i := IL_WrapSearchResult(Pred(From)); while i <> From do begin If Contains(Text,i) then begin Result := i; Break{while...}; end; i := IL_WrapSearchResult(Pred(i)); end; end; end; //------------------------------------------------------------------------------ Function TILItem_Search.FindNext(const Text: String; From: TILItemSearchResult = ilisrNone): TILItemSearchResult; var i: TILItemSearchResult; begin Result := ilisrNone; If fDataAccessible then begin i := IL_WrapSearchResult(Succ(From)); while i <> From do begin If Contains(Text,i) then begin Result := i; Break{while...}; end; i := IL_WrapSearchResult(Succ(i)); end; end; end; //------------------------------------------------------------------------------ Function TILItem_Search.FindAll(const SearchSettings: TILAdvSearchSettings; out SearchResult: TILAdvSearchResult): Boolean; var Field: TILAdvItemSearchResult; i: Integer; ShopCntr: Integer; ShopField: TILAdvShopSearchResult; begin // init SearchResult.ItemIndex := -1; SearchResult.ItemValue := []; SetLength(SearchResult.Shops,0); // fields For Field := Low(TILAdvItemSearchResult) to High(TILAdvItemSearchResult) do If SearchField(SearchSettings,Field) then Include(SearchResult.ItemValue,Field); // shops If SearchSettings.SearchShops then begin ShopCntr := 0; SetLength(SearchResult.Shops,fShopCount); For i := ShopLowIndex to ShopHighIndex do begin For ShopField := Low(TILAdvShopSearchResult) to High(TILAdvShopSearchResult) do If fShops[i].SearchField(SearchSettings,i,ShopField) then Include(SearchResult.Shops[ShopCntr].ShopValue,ShopField); If SearchResult.Shops[ShopCntr].ShopValue <> [] then begin SearchResult.Shops[ShopCntr].ShopIndex := i; Inc(ShopCntr); end; end; SetLength(SearchResult.Shops,ShopCntr); end; // final touches If (SearchResult.ItemValue <> []) or (Length(SearchResult.Shops) > 0) then SearchResult.ItemIndex := fIndex; Result := SearchResult.ItemIndex >= 0; end; end.
//Contains all script commands used by the lua system //Note the command lual_argcheck will cause the procedure it is in to call exit; //So be aware of your code! unit LuaNPCCommands; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses LuaCoreRoutines, LuaTypes; function LoadNPCCommands(var ALua : TLua) : boolean; implementation uses //RTL SysUtils, Types, //Project Character, GameConstants, LuaNPCCore, LuaPas, Main, Math, Item, ItemInstance, NPC, PacketTypes, ZoneSend, LuaVarConstants, ZoneInterCommunication, Mob, Map ; //Forward declarations of delphi procedures that are added to the lua engine. function addnpc(ALua : TLua) : integer; cdecl; forward; function addwarp(ALua : TLua) : integer; cdecl; forward; function addhiddenwarp(ALua : TLua) : integer; cdecl; forward; //Standard NPC Commands function script_moveto(ALua : TLua) : integer; cdecl; forward; function script_dialog(ALua : TLua) : integer; cdecl; forward; function script_wait(ALua : TLua) : integer; cdecl; forward; function script_close(ALua : TLua) : integer; cdecl; forward; function script_checkpoint(ALua : TLua) : integer; cdecl; forward; function script_menu(ALua : TLua) : integer; cdecl; forward; function script_getcharavar(ALua : TLua) : integer; cdecl; forward; function script_setcharavar(ALua : TLua) : integer; cdecl; forward; function script_SetItem(ALua : TLua) : integer; cdecl; forward; function script_GetItem(ALua : TLua) : integer; cdecl; forward; function script_DropItem(ALua : TLua) : integer; cdecl; forward; function script_GetItemQuantity(ALua : TLua) : integer; cdecl; forward; function script_getgold(ALua : TLua) : integer; cdecl; forward; function script_dropgold(ALua : TLua) : Integer; cdecl; forward; function script_getexp(ALua : TLua) : integer; cdecl; forward; function script_getJexp(ALua : TLua) : integer; cdecl; forward; function script_ResetStat(ALua : TLua) : integer; cdecl; forward; function script_HpDrain(ALua : TLua) : integer; cdecl; forward; function script_HpHeal(ALua : TLua) : integer; cdecl; forward; function script_SpDrain(ALua : TLua) : integer; cdecl; forward; function script_SpHeal(ALua : TLua) : integer; cdecl; forward; function script_HPFullheal(ALua : TLua) : integer; cdecl; forward; function script_SPFullheal(ALua : TLua) : integer; cdecl; forward; function script_Compass(ALua : TLua) : integer; cdecl; forward; function script_ShowImage(ALua : TLua) : integer; cdecl; forward; function script_CompassCheck(ALua : TLua) : integer; cdecl; forward; function script_Emotion(ALua : TLua) : integer; cdecl; forward; function script_OpenMailBox(ALua : TLua) : integer; cdecl; forward; function script_CloseMailBox(ALua : TLua) : integer; cdecl; forward; function script_JobChange(ALua : TLua) : integer; cdecl; forward; function script_ResetLook(ALua :TLua) : Integer; cdecl; forward; function script_Input(ALua : TLua) : integer; cdecl; forward; function script_InputStr(ALua : TLua) : integer; cdecl; forward; function script_BroadcastInMap(ALua : TLua) : integer; cdecl; forward; function script_CreateInstanceMap(ALua : TLua) : integer; cdecl; forward; function script_PutMob(ALua : TLua) : integer; cdecl; forward; //Special Commands function script_get_charaname(ALua : TLua) : integer; cdecl; forward; function lua_print(ALua : TLua) : integer; cdecl; forward; const NPCCommandCount = 41; const //"Function name in lua" , Delphi function name //This assigns our procedures here, with the lua system NPCCommandList : array [1..NPCCommandCount] of lual_reg = ( //TNPC adding (name:'npc';func:addnpc), (name:'warp';func:addwarp), (name:'hiddenwarp';func:addhiddenwarp), //NPC Commands (name:'moveto';func:script_moveto), (name:'dialog';func:script_dialog), (name:'wait';func:script_wait), (name:'close';func:script_close), (name:'checkpoint';func:script_checkpoint), (name:'menu';func:script_menu), (name:'getvar';func:script_getcharavar), (name:'setvar';func:script_setcharavar), (name:'setitem';func:script_SetItem), (name:'getitem';func:script_GetItem), (name:'dropitem';func:script_DropItem), (name:'getitemquantity';func:script_GetItemQuantity), (name:'getgold';func:script_getgold), (name:'dropgold';func:script_dropgold), (name:'getexp';func:script_getexp), (name:'getJexp';func:script_getJexp), (name:'ResetStat';func:script_ResetStat), (name:'hpdrain';func:script_HpDrain), (name:'hpheal';func:script_HpHeal), (name:'spdrain';func:script_SpDrain), (name:'spheal';func:script_SpHeal), (name:'hpfullheal';func:script_HPFullHeal), (name:'spfullheal';func:script_SPFullHeal), (name:'compass';func:script_Compass), (name:'showimage';func:script_ShowImage), (name:'compass_check';func:script_CompassCheck), (name:'emotion';func:script_Emotion), (name:'OpenMailing';func:script_OpenMailBox), (name:'CloseMailing';func:script_CloseMailBox), (name:'JobChange';func:script_JobChange), (name:'ResetLook';func:script_ResetLook), (name:'input';func:script_Input), (name:'inputstr';func:script_InputStr), (name:'broadcastinmap';func:script_BroadcastInMap), (name:'createinstancemap';func:script_CreateInstanceMap), (name:'putmob';func:script_PutMob), //Special Variable retrieving functions (name:'PcName';func:script_get_charaname), //Misc tools. (name:'print';func:lua_print) ); //[2007/04/23] Tsusai - Added result //Registers all the NPC Commands into the Lua instance function LoadNPCCommands(var ALua : TLua) : boolean; var idx : integer; begin for idx := 1 to NPCCommandCount do begin lua_register( ALua, NPCCommandList[idx].name, NPCCommandList[idx].func ); end; Result := true; end; //npc("new_1-1","Bulletin Board",spr_HIDDEN_NPC,66,114,4,0,0,"new_1-1_Bulletin_Board_66114"[,"optional ontouch"]) //[2008/10/18] Tsusai - Implemented lua argchecks function CheckLuaNPCSyntax(ALua : TLua) : boolean; var ParamCount : word; begin //Assume false Result := false; ParamCount := lua_gettop(ALua); //Check parameter count if not ParamCount in [9..10] then lual_error(ALua,'Invalid number of NPC Script parameters'); //Check parameters lual_argcheck(ALua,Lua_isNonNumberString(ALua,1),1,'NPC Map parameter must be a string'); lual_argcheck(ALua,lua_isNonNumberString(ALua,2),2,'NPC Name parameter must be a string'); lual_argcheck(ALua,lua_isposnumber(ALua,3),3,'NPC Sprite parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,4),4,'NPC X Coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,5),5,'NPC Y Coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,6),6,'NPC Direction parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,7),7,'NPC X Radius parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,8),8,'NPC Y Radius parameter must be a integer'); lual_argcheck(ALua,Lua_isNonNumberString(ALua,9),9,'NPC Function Name parameter must be a string'); //Optional Ontouch if ParamCount = 10 then lual_argcheck(ALua,Lua_isNonNumberString(ALua,10),10,'NPC OnTouch Function Name parameter must be a string'); //Made it through, set to true Result := not Result; end; //[2007/04/23] Tsusai - Added result //[2007/05/28] Tsusai - Fixed npc point reading //npc("new_1-1","Bulletin Board",spr_HIDDEN_NPC,66,114,4,0,0,"new_1-1_Bulletin_Board_66114"[,"optional ontouch"]) function addnpc(ALua : TLua) : integer; cdecl; var ANPC : TScriptNPC; OnTouch : String; Index : Integer; begin OnTouch := ''; if CheckLuaNPCSyntax(ALua) then begin if lua_gettop(ALua) = 10 then begin OnTouch := lua_tostring(ALua,10); end; ANPC := TSCriptNPC.Create(lua_tostring(ALua,9),OnTouch); ANPC.Map := lua_tostring(ALua,1); ANPC.Name := lua_tostring(ALua,2); ANPC.JID := lua_tointeger(ALua,3); ANPC.Position := Point(lua_tointeger(ALua,4) , lua_tointeger(ALua,5)); ANPC.Direction := lua_tointeger(ALua,6); ANPC.OnTouchXRadius := lua_tointeger(ALua,7); ANPC.OnTouchYRadius := lua_tointeger(ALua,8); Index := MainProc.ZoneServer.MapList.IndexOf(ANPC.Map); if Index > -1 then begin MainProc.ZoneServer.MapList.Items[Index].NPCList.AddObject(ANPC.ID,ANPC); end; MainProc.ZoneServer.NPCList.AddObject(ANPC.ID,ANPC); end; Result := 0; end; //Verifies all lua information on the warp syntax //(hidden)warp("map","name",x,y,xradius,yradius) //[2008/10/18] Tsusai - Implemented lua argchecks function CheckLuaWarpSyntax( ALua : TLua ) : boolean; var ParamCount : word; begin //Assume false, since argchecks will cause Exit; to happen....somehow Result := False; //Validate ParamCount := lua_gettop(ALua); if not ParamCount = 6 then lual_error(ALua,'Invalid number of NPC Warp parameters'); lual_argcheck(ALua,Lua_isNonNumberString(ALua,1),1,'Warp Map parameter must be a string'); lual_argcheck(ALua,Lua_isNonNumberString(ALua,2),2,'Warp Name parameter must be a string'); lual_argcheck(ALua,lua_isposnumber(ALua,3),3,'Warp X Coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,4),4,'Warp Y Coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,5),5,'Warp X Radius parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,6),6,'Warp Y Radius parameter must be a integer'); //Made it through, set true Result := NOT Result; end; //Takes lua information and makes the warp procedure MakeNPCWarp( ALua : TLua; const JID : Word ); var Index : Integer; AWarpNPC : TWarpNPC; begin AWarpNPC := TWarpNPC.Create(lua_tostring(ALua,2)); AWarpNPC.Map := lua_tostring(ALua,1); AWarpNPC.Name := AWarpNPC.TouchFunction; AWarpNPC.JID := JID; AWarpNPC.Position := Point( lua_tointeger(ALua,3), lua_tointeger(ALua,4) ); AWarpNPC.OnTouchXRadius := lua_tointeger(ALua,5); AWarpNPC.OnTouchYRadius := lua_tointeger(ALua,6); Index := MainProc.ZoneServer.MapList.IndexOf(AWarpNPC.Map); if Index > -1 then begin MainProc.ZoneServer.MapList.Items[Index].NPCList.AddObject(AWarpNPC.ID,AWarpNPC); end; MainProc.ZoneServer.NPCList.AddObject(AWarpNPC.ID,AWarpNPC); end; //[2007/04/23] Tsusai - Added result //warp("new_1-1","novicetraining1warp001",148,112,2,3) function addwarp(ALua : TLua) : integer; cdecl; begin Result := 0; //Check Syntax if CheckLuaWarpSyntax(ALua) then begin //Make the warp MakeNPCWarp(ALua,NPC_WARPSPRITE); end; end; //[2007/05/03] Tsusai - Added //hiddenwarp("new_1-1","novicetraining1warp001",148,112,2,3) function addhiddenwarp(ALua : TLua) : integer; cdecl; begin Result := 0; //Check Syntax if CheckLuaWarpSyntax(ALua) then begin //Make the warp MakeNPCWarp(ALua,NPC_INVISIBLE); end; end; //moveto("map",x,y) //Warps the character to the given destination function script_moveto(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; //Validate if not ParamCount = 3 then lual_error(ALua,'Invalid number of NPC moveto parameters'); lual_argcheck(ALua,Lua_isNonNumberString(ALua,1),1,'NPC moveto map parameter must be a string'); lual_argcheck(ALua,lua_isposnumber(ALua,2),2,'NPC moveto X coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,3),3,'NPC moveto Y coord parameter must be a integer'); //Run if validated if GetCharaFromLua(ALua,AChara) then begin ZoneSendWarp( AChara^, lua_tostring(ALua,1), lua_tointeger(ALua,2), lua_tointeger(ALua,3) ); end; //Tsusai Oct 11 2008: We can't end the script. There are some stupid Aegis //scripts that still continue doing behind the scenes stuff after warping. //The script maker must verify it ends on its own. However, we warked, so, //assume we aren't running a script. The previous script should end quickly //anyways //lua_yield(ALua,0);//end the script AChara^.ScriptStatus := SCRIPT_NOTRUNNING; end; //dialog "this is my text" //NPC Dialog to the character function script_dialog(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if not (lua_gettop(ALua) = 1) then luaL_error(ALua,'NPC Dialog parameter count error'); lual_argcheck(ALua,lua_isstring(ALua,1),1,'NPC Dialog must be string with quotes'); if GetCharaFromLua(ALua,AChara) then begin SendNPCDialog(AChara^,AChara^.ScriptBeing.ID,lua_tostring(ALua,1)); end; end; //wait() //Sends the next button to the client function script_wait(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if not (lua_gettop(ALua) = 0) then luaL_error(ALua,'NPC wait must not have any parameters'); if GetCharaFromLua(ALua,AChara) then begin //Send the next button SendNPCNext(AChara^,AChara^.ScriptBeing.ID); //Pause lua. Tell it to wait on 0 parameters in return. AChara^.ScriptStatus := SCRIPT_YIELD_WAIT; Result := lua_yield(ALua,0); end; end; //close() //Sends the close button to the client and flags the script user as not running. function script_close(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if not lua_gettop(ALua) = 0 then luaL_error(ALua,'Close command error'); if GetCharaFromLua(ALua,AChara) then begin SendNPCClose(AChara^,AChara^.ScriptBeing.ID); //Make lua stop AChara^.ScriptStatus := SCRIPT_NOTRUNNING; TerminateLuaThread(AChara^.LuaInfo); end; end; //checkpoint("map",x,y) //Sets the specified save point to the character function script_checkpoint(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; //Validate if not ParamCount = 3 then lual_error(ALua,'Invalid number of NPC checkpoint parameters'); lual_argcheck(ALua,Lua_isNonNumberString(ALua,1),1,'NPC checkpoint map parameter must be a string'); lual_argcheck(ALua,lua_isposnumber(ALua,2),2,'NPC checkpoint X coord parameter must be a integer'); lual_argcheck(ALua,lua_isposnumber(ALua,3),3,'NPC checkpoint Y coord parameter must be a integer'); //Save data if GetCharaFromLua(ALua,AChara) then begin AChara^.SaveMap := lua_tostring(ALua,1); AChara^.SavePoint := Point( lua_tointeger(ALua,2), lua_tointeger(ALua,3)); end; end; //menu("choice1","choice2","choice3",etc) //Sets the specified save point to the character //R 00b7 <len>.w <ID>.l <str>.?B //Each menu choice is delimited by ":" function script_menu(ALua : TLua) : integer; cdecl; var AChara : PCharacter; ParamCount : word; MenuString : string; idx : word; begin Result := 0; MenuString := ''; //Validate ParamCount := lua_gettop(ALua); if not (ParamCount > 0) then lual_error(ALua,'NPC Menu needs at least one parameter'); for idx := 1 to ParamCount do lual_argcheck(ALua,lua_isString(ALua,idx),idx,'NPC Menu parameter must be a integer or string'); //Run if GetCharaFromLua(ALua,AChara) then begin for idx := 1 to ParamCount do begin if idx = 1 then begin MenuString := lua_tostring(Alua,idx); end else begin MenuString := MenuString + ':' + lua_tostring(Alua,idx); end; end; SendNPCMenu(AChara^,AChara^.ScriptBeing.ID,MenuString); AChara^.ScriptStatus := SCRIPT_YIELD_MENU; Result := lua_yield(ALua,1); end; end; //getvar(key) //Returns a character variable. function script_getcharavar(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Value : String; Key : string; KeyConst : Integer; VarType : Byte; begin //Returns 1 result Result := 1; if (lua_gettop(ALua) = 1) and //1 parameter count (lua_isString(ALua,1)) then //first param is a string begin if GetCharaFromLua(ALua,AChara) then begin Key := lua_tostring(ALua, 1); if lua_isNumber(ALua, 1) then begin KeyConst := lua_toInteger(ALua, 1); case KeyConst of VAR_ASPD: begin lua_pushinteger(ALua, AChara^.ASpeed); end; VAR_CURXPOS: begin lua_pushinteger(ALua, AChara^.Position.X); end; VAR_CURYPOS: begin lua_pushinteger(ALua, AChara^.Position.Y); end; VAR_CLEVEL: begin lua_pushinteger(ALua, AChara^.BaseLV); end; VAR_EXP: begin lua_pushinteger(ALua, AChara^.BaseEXP); end; VAR_HAIRCOLOR: begin lua_pushinteger(ALua, AChara^.HairColor); end; VAR_HP: begin lua_pushinteger(ALua, AChara^.HP); end; VAR_JOB: begin lua_pushinteger(ALua, AChara^.JID); end; VAR_JOBEXP: begin lua_pushinteger(ALua, AChara^.JobEXP); end; VAR_JOBLEVEL: begin lua_pushinteger(ALua, AChara^.JobLV); end; VAR_MAXHP: begin lua_pushinteger(ALua, AChara^.MaxHP); end; VAR_MAXSP: begin lua_pushinteger(ALua, AChara^.MaxSP); end; VAR_MAXWEIGHT: begin lua_pushinteger(ALua, AChara^.MaxWeight); end; VAR_MONEY : begin lua_pushinteger(ALua, AChara^.Zeny); end; VAR_POINT: begin lua_pushinteger(ALua, AChara^.StatusPts); end; VAR_SEX : begin lua_pushinteger(ALua, TClientLink(AChara^.ClientInfo.Data).AccountLink.GenderNum); end; VAR_SP: begin lua_pushinteger(ALua, AChara^.SP); end; VAR_SPEED: begin lua_pushinteger(ALua, AChara^.Speed); end; VAR_SPPOINT: begin lua_pushinteger(ALua, AChara^.SkillPts); end; VAR_WEIGHT: begin lua_pushinteger(ALua, AChara^.Weight); end; //Ismarried Variable //Implemented by Spre 2007/12/31 //Comment Here Incase changes need to be made, easily Identifiable VAR_ISMARRIED: begin lua_pushinteger(ALua, Byte(AChara^.IsMarried)); end; VAR_STR: begin lua_pushinteger(ALua, AChara^.ParamBase[STR] + AChara^.ParamBonus[STR]); end; VAR_AGI: begin lua_pushinteger(ALua, AChara^.ParamBase[AGI] + AChara^.ParamBonus[AGI]); end; VAR_VIT: begin lua_pushinteger(ALua, AChara^.ParamBase[VIT] + AChara^.ParamBonus[VIT]); end; VAR_INT: begin lua_pushinteger(ALua, AChara^.ParamBase[INT] + AChara^.ParamBonus[INT]); end; VAR_DEX: begin lua_pushinteger(ALua, AChara^.ParamBase[DEX] + AChara^.ParamBonus[DEX]); end; VAR_LUK: begin lua_pushinteger(ALua, AChara^.ParamBase[LUK] + AChara^.ParamBonus[LUK]); end; VAR_STANDARD_STR: begin lua_pushinteger(ALua, AChara^.ParamBase[STR]); end; VAR_STANDARD_AGI: begin lua_pushinteger(ALua, AChara^.ParamBase[AGI]); end; VAR_STANDARD_VIT: begin lua_pushinteger(ALua, AChara^.ParamBase[VIT]); end; VAR_STANDARD_INT: begin lua_pushinteger(ALua, AChara^.ParamBase[INT]); end; VAR_STANDARD_DEX: begin lua_pushinteger(ALua, AChara^.ParamBase[DEX]); end; VAR_STANDARD_LUK: begin lua_pushinteger(ALua, AChara^.ParamBase[LUK]); end; VAR_CURDIR: begin lua_pushinteger(ALua, AChara^.Direction); end; VAR_CHARACTERID: begin lua_pushinteger(ALua, AChara^.ID); end; VAR_ACCOUNTID: begin lua_pushinteger(ALua, AChara^.AccountID); end; VAR_MAPNAME: begin lua_pushstring(ALua, PChar(AChara^.Map)); end; VAR_ACCOUNTNAME: begin Value := TClientLink(AChara^.ClientInfo.Data).AccountLink.Name; lua_pushstring(ALua, PChar(Value)); end; VAR_CHARACTERNAME: begin lua_pushstring(ALua, PChar(AChara^.Name)); end; VAR_HEADPALETTE: begin lua_pushinteger(ALua, AChara^.HairColor); end; VAR_BODYPALETTE: begin lua_pushinteger(ALua, AChara^.ClothesColor); end; end; end else begin Value := TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Character.GetVariable(AChara^,Key, VarType); //Check variable type and push appropriate type back to script. case VarType of CHARAVAR_STRING : begin lua_pushstring(ALua, PChar(Value)); end; else begin lua_pushinteger(ALua, StrToIntDef(Value, 0)); end; end; end; end; end else begin luaL_error(ALua,'script getvar syntax error'); end; end; //setvar(key,value) //Sets a character variable function script_setcharavar(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Key : string; Value : String; AType : Byte; begin //Returns 0 results Result := 0; if (lua_gettop(ALua) = 2) and (lua_isString(ALua,1)) then begin if GetCharaFromLua(ALua,AChara) then begin Key := lua_tostring(ALua, 1); if lua_isnumber(ALua, 2) then begin AType := CHARAVAR_INTEGER; end else begin AType := CHARAVAR_STRING; end; Value := lua_tostring(ALua, 2); TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Character.SetVariable(AChara^,Key,Value, AType); end; end else begin luaL_error(ALua,'script setvar syntax error'); end; end; //SetItem - Apparently is set variable.. //so I just made it wrapper of setvar function script_SetItem(ALua : TLua) : Integer; begin Result := script_setcharavar(ALua); end; //gives the character an item of quantity function script_GetItem(ALua : TLua) : Integer; var AChara : PCharacter; AnItem : TItemInstance; ItemID : Word; begin Result := 0; //check number of parameters if lua_gettop(ALua) = 2 then begin //check to make sure it was a character who executed this script if GetCharaFromLua(ALua,AChara) then begin ItemID := 0; //type check first parameter to see if we're dealing with an item id or name if lua_isnumber(ALua, 1) then begin //if we're dealing with an id, we try to find the item. if TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find( lua_tointeger(ALua, 1) ) then begin ItemID := lua_tointeger(ALua, 1); end; //else, if we're dealing with a name, we try to find the id. end else begin ItemID := TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find(lua_tostring(ALua, 1)); end; //if an id was found, we check the second parameter if ItemID > 0 then begin //type check the second parameter, quantity if lua_isnumber(ALua, 2) then begin //since we passed all checks, create the item instance and add it to the inventory. AnItem := TItemInstance.Create; AnItem.Item := TItem.Create; AnItem.Item.ID := ItemID; AnItem.Quantity := EnsureRange(lua_tointeger(ALua, 2), 1, High(Word)); AnItem.Identified := true; TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Load(AnItem.Item); AChara^.Inventory.Add(AnItem); end else begin luaL_error(ALua,'script getitem syntax error, second parameter should be numeric'); end; end else begin luaL_error(ALua,'script getitem syntax error, item not found'); end; end; end else begin luaL_error(ALua,'script getitem syntax error, incorrect number of parameters'); end; end; function script_GetItemQuantity(ALua : TLua) : Integer; var AChara : PCharacter; ItemID : Word; begin Result := 0; //check number of parameters if lua_gettop(ALua) = 1 then begin //check to make sure it was a character who executed this script if GetCharaFromLua(ALua,AChara) then begin ItemID := 0; //type check first parameter to see if we're dealing with an item id or name if lua_isnumber(ALua, 1) then begin //if we're dealing with an id, we try to find the item. if TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find( lua_tointeger(ALua, 1) ) then begin ItemID := lua_tointeger(ALua, 1); end; //else, if we're dealing with a name, we try to find the id. end else begin ItemID := TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find(lua_tostring(ALua, 1)); end; //if an id was found, we check the second parameter if ItemID > 0 then begin lua_pushinteger(ALua, AChara^.Inventory.AmountOf(ItemId)); end else begin luaL_error(ALua,'script getitemquantity syntax error, item not found'); end; end; end else begin luaL_error(ALua,'script getitemquantity syntax error, incorrect number of parameters'); end; end; function script_DropItem(ALua : TLua) : Integer; var AChara : PCharacter; ItemID : Word; Quantity : Word; begin Result := 0; //check number of parameters if lua_gettop(ALua) = 2 then begin //check to make sure it was a character who executed this script if GetCharaFromLua(ALua,AChara) then begin ItemID := 0; //type check first parameter to see if we're dealing with an item id or name if lua_isnumber(ALua, 1) then begin //if we're dealing with an id, we try to find the item. if TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find( lua_tointeger(ALua, 1) ) then begin ItemID := lua_tointeger(ALua, 1); end; //else, if we're dealing with a name, we try to find the id. end else begin ItemID := TThreadLink(AChara^.ClientInfo.Data).DatabaseLink.Items.Find(lua_tostring(ALua, 1)); end; //if an id was found, we check the second parameter if ItemID > 0 then begin //type check the second parameter, quantity if lua_isnumber(ALua, 2) then begin Quantity := EnsureRange(lua_toInteger(ALua, 2), 1, High(Word)); //since we passed all checks, create the item instance and add it to the inventory. AChara^.Inventory.Remove(ItemID, Quantity); end else begin luaL_error(ALua,'script dropitem syntax error, second parameter should be numeric'); end; end else begin luaL_error(ALua,'script dropitem syntax error, item not found'); end; end; end else begin luaL_error(ALua,'script dropitem syntax error, incorrect number of parameters'); end; end; //getgold(value) //Gives or takes money/zeny to/from the character function script_getgold(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Zeny : LongInt; begin //Returns 0 results Result := 0; //Validate if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC getgold error, there must be one parameter'); lual_argcheck(ALua, lua_isposnumber(ALua,1), 1, 'NPC getgold parameter must be a positive integer.'); //Run if GetCharaFromLua(ALua,AChara) then begin //combining signed and unsigned types warning. Ignoring {$WARNINGS OFF} Zeny := EnsureRange(lua_tointeger(ALua, 1),Low(LongInt),High(LongInt)); AChara^.Zeny := EnsureRange(AChara^.Zeny + Zeny, Low(AChara^.Zeny), High(AChara^.Zeny) ); {$WARNINGS ON} end; end; //dropgold function script_dropgold(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Zeny : LongInt; begin //Returns 0 results Result := 0; //Validate if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC dropgold error, there must be one parameter'); lual_argcheck(ALua, lua_isposnumber(ALua,1), 1, 'NPC dropgold parameter must be a positive integer.'); //Run if GetCharaFromLua(ALua,AChara) then begin {$WARNINGS OFF} Zeny := EnsureRange(lua_tointeger(ALua, 1),Low(LongInt),High(LongInt)); AChara^.Zeny := EnsureRange(AChara^.Zeny - Zeny, Low(AChara^.Zeny), High(AChara^.Zeny) ); {$WARNINGS ON} end; end; //getexp(value) //Gives or takes base exp to/from the character function script_getexp(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin //Returns 0 results Result := 0; if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC getexp error, there must be one parameter'); lual_argcheck(ALua, lua_isnumber(ALua,1), 1, 'NPC getexp parameter must be a integer.'); if GetCharaFromLua(ALua,AChara) then begin AChara^.BaseEXP := AChara^.BaseEXP + Cardinal(EnsureRange(lua_tointeger(ALua, 1),0,High(Integer))); end; end; //getJexp(value) //Gives or takes job exp to/from the character function script_getJexp(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin //Returns 0 results Result := 0; if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC getjexp error, there must be one parameter'); lual_argcheck(ALua, lua_isnumber(ALua,1), 1, 'NPC getjexp parameter must be a integer.'); if GetCharaFromLua(ALua,AChara) then begin AChara^.JobEXP := AChara^.JobEXP + Cardinal(EnsureRange(lua_tointeger(ALua, 1),0,High(Integer))); end; end; //ResetStat //Reset character's status function script_ResetStat(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if GetCharaFromLua(ALua,AChara) then begin AChara^.ResetStats; end; end; // Lose some % hp for player function script_HpDrain(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Percentage : Byte; begin Result := 0; if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC HPDrain error, there must be one parameter'); lual_argcheck(ALua, lua_isposnumber(ALua,1), 1, 'NPC HPDrain parameter must be a positive integer.'); if GetCharaFromLua(ALua,AChara) then begin Percentage := EnsureRange(lua_tointeger(ALua, 1),0,100); if AChara^.HP > 0 then AChara^.HPPercent := AChara^.HPPercent - Percentage; end; end; //Gain some % HP for player function script_HpHeal(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Percentage : Byte; begin Result := 0; if not (lua_gettop(ALua) = 1) then lual_error(ALua, 'NPC HPHeal error, there must be one parameter'); lual_argcheck(ALua, lua_isposnumber(ALua,1), 1, 'NPC HPHeal parameter must be a positive integer.'); if GetCharaFromLua(ALua,AChara) then begin Percentage := EnsureRange(lua_tointeger(ALua, 1),0,100); if AChara^.HP > 0 then AChara^.HPPercent := AChara^.HPPercent + Percentage; end; end; // Lose some sp for player function script_SpDrain(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Percentage : Byte; begin Result := 0; if lua_gettop(ALua) = 1 then begin if GetCharaFromLua(ALua,AChara) then begin Percentage := EnsureRange(lua_tointeger(ALua, 1),0,100); if AChara^.SP > 0 then AChara^.SPPercent := AChara^.SPPercent - Percentage; end; end; end; //Gain some % SP for player function script_SpHeal(ALua : TLua) : integer; cdecl; var AChara : PCharacter; Percentage : Byte; begin Result := 0; if lua_gettop(ALua) = 1 then begin if GetCharaFromLua(ALua,AChara) then begin Percentage := EnsureRange(lua_tointeger(ALua, 1),0,100); if AChara^.SP > 0 then AChara^.SPPercent := AChara^.SPPercent + Percentage; end; end; end; //Full heal player's HP function script_HPFullHeal(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if lua_gettop(ALua) = 0 then begin if GetCharaFromLua(ALua,AChara) then begin AChara^.HP := AChara^.MaxHP; end; end else begin luaL_error(ALua,'script hpfullheal syntax error'); end; end; //Full heal player's SP function script_SPFullHeal(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if lua_gettop(ALua) = 0 then begin if GetCharaFromLua(ALua,AChara) then begin AChara^.SP := AChara^.MaxSP; end; end else begin luaL_error(ALua,'script spfullheal syntax error'); end; end; //Compass - mark on mini map function script_Compass(ALua : TLua) : integer; cdecl; var AChara : PCharacter; PointType : Byte; begin Result := 0; if lua_gettop(ALua) = 5 then begin if lua_isnumber(ALua, 1) AND lua_isnumber(ALua, 2) AND lua_isnumber(ALua, 3) AND lua_isnumber(ALua, 4) then begin if GetCharaFromLua(ALua,AChara) then begin PointType := EnsureRange(lua_tointeger(ALua, 4),0,255); if PointType = 0 then PointType := 2; SendCompass( AChara^.ClientInfo, AChara^.ScriptBeing.ID, lua_tointeger(ALua, 1), lua_tointeger(ALua, 2), lua_tointeger(ALua, 3), PointType, Lua_toLongWord(ALua, 5) ); end; end; end; end; //Show cutin thingy function script_ShowImage(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if lua_gettop(ALua) = 2 then begin if lua_isString(ALua, 1) AND lua_isNumber(ALua, 2) then begin if GetCharaFromLua(ALua,AChara) then begin SendCutin( AChara^.ClientInfo, lua_toString(ALua, 1), EnsureRange(lua_toInteger(ALua, 2),0,255) ); end; end; end; end; //Compass Check - I have no idea what it does.. function script_CompassCheck(ALua : TLua) : integer; cdecl; begin Result := 0; if lua_gettop(ALua) = 2 then begin // Do nothing... end; end; //Trigger emotion function script_Emotion(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 0; if lua_gettop(ALua) = 1 then begin if GetCharaFromLua(ALua,AChara) then begin AChara^.ScriptBeing.ShowEmotion(lua_tointeger(ALua,1)); end; end; end; //Open Mailbox function script_OpenMailBox(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if GetCharaFromLua(ALua,AChara) then begin ToggleMailWindow( AChara^, True ); end; end; //Close Mailbox function script_CloseMailBox(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if GetCharaFromLua(ALua,AChara) then begin ToggleMailWindow( AChara^, False ); end; end; //Change Jobs //Change Job script code [Spre] function script_JobChange(ALua : TLua) : integer; var AChara : PCharacter; begin if (lua_gettop(ALua) = 1) then begin if GetCharaFromLua(ALua,AChara) then begin AChara^.ChangeJob(EnsureRange(lua_tointeger(ALua, 1), 0, high(word))); end; end else begin luaL_error(ALua,'script ChangeJob syntax error'); end; Result := 0; end; //Reset Look //Code I am working on to reset ones look to 0 [Spre] function script_ResetLook(ALua :TLua) : Integer; cdecl; var AChara : PCharacter; begin Result := 0; if GetCharaFromLua(ALua,AChara) then begin // AChara^.ResetLook; end; luaL_error(ALua,'script Reset Look syntax error'); end; //Special commands here function script_get_charaname(ALua : TLua) : integer; cdecl; var AChara : PCharacter; begin Result := 1; //we are going to return 1 result if (lua_gettop(ALua) = 0) then begin if GetCharaFromLua(ALua,AChara) then begin lua_pushstring(ALua,PChar(AChara^.Name)); end; end else begin luaL_error(ALua,'script PcName syntax error'); end; end; //Random usage for testing. Will take its string and output it on //the console. function lua_print(ALua : TLua) : integer; cdecl; var i, n: Integer; begin n := lua_gettop(ALua); for i := 1 to n do begin if i > 1 then Write(#9); try//if lua_isstring(ALua, i) then Write(lua_tostring(ALua, i)); write(lua_typename(ALua, i)); except//else //Write(Format('%s:%p', [lua_type(ALua, i), lua_topointer(ALua, i)])); end; end; WriteLn; Result := 0; end; //Input a number function script_Input(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if (lua_gettop(ALua) = 0) then begin if GetCharaFromLua(ALua,AChara) then begin SendNPCInput( AChara^, AChara^.ScriptBeing.ID ); AChara^.ScriptStatus := SCRIPT_YIELD_INPUT; Result := lua_yield(ALua,1); end; end else begin luaL_error(ALua,'script Input syntax error'); end; end; //Input of a string function script_InputStr(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if (lua_gettop(ALua) = 0) then begin if GetCharaFromLua(ALua,AChara) then begin SendNPCInputStr( AChara^, AChara^.ScriptBeing.ID ); AChara^.ScriptStatus := SCRIPT_YIELD_INPUT; Result := lua_yield(ALua,1); end; end else begin luaL_error(ALua,'script Inputstr syntax error'); end; end; //Broadcast in current map function script_BroadcastInMap(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if (lua_gettop(ALua) = 1) then begin if GetCharaFromLua(ALua,AChara) then begin ZoneSendGMCommandtoInter( MainProc.ZoneServer.ToInterTCPClient, AChara^.AccountID, AChara^.ID, '#BroadCastLN ' + lua_tostring(ALua,1) ); end; end else begin luaL_error(ALua,'script Inputstr syntax error'); end; end; function script_CreateInstanceMap(ALua : TLua) : integer; var AChara : PCharacter; begin Result := 0; if (lua_gettop(ALua) = 2) then begin if GetCharaFromLua(ALua,AChara) then begin if lua_isnumber(ALua, 1) then ZoneSendCreateInstanceMapRequest ( MainProc.ZoneServer.ToInterTCPClient, IntToStr(lua_tointeger(ALua, 1)), lua_tostring(ALua, 2), AChara^.ID, AChara^.ScriptBeing.ID ) else ZoneSendCreateInstanceMapRequest ( MainProc.ZoneServer.ToInterTCPClient, lua_tostring(ALua, 1), lua_tostring(ALua, 2), AChara^.ID, AChara^.ScriptBeing.ID ); AChara^.ScriptStatus := SCRIPT_YIELD_INSTANCEREQUEST; Result := lua_yield(ALua,1); end; end else begin luaL_error(ALua,'script CreateInstanceMap syntax error'); end; end; function script_PutMob(ALua : TLua) : integer; var MapName : String; Position:TPoint; RadiusX,RadiusY:Word; Amount:Word; MobName : String; // TimerMin,TimerMax:LongWord; AMob : TMob; MapIndex:Integer; AMap:TMap; Index : Word; begin Result := 0; if (lua_gettop(ALua) = 10) then begin MapName := lua_tostring(ALua, 1); Position.X := EnsureRange(lua_tointeger(ALua, 2),0,High(Word)); Position.Y := EnsureRange(lua_tointeger(ALua, 3),0,High(Word)); RadiusX := EnsureRange(lua_tointeger(ALua, 4),0,High(Word)); RadiusY := EnsureRange(lua_tointeger(ALua, 5),0,High(Word)); Amount := EnsureRange(lua_tointeger(ALua, 6),1,High(Word)); MobName := lua_tostring(ALua, 7); // TimerMin := lua_tolongword(ALua,7); // TimerMax := lua_tolongword(ALua,8); MapIndex := MainProc.ZoneServer.MapList.IndexOf(MapName); if MapIndex > -1 then begin AMap := MainProc.ZoneServer.MapList.Items[MapIndex]; for Index := 1 to Amount do begin AMob := TMob.Create; AMob.SpriteName := MobName; AMob.Position := Position; AMob.InitPosition := Position; AMob.RadiusX := RadiusX; AMob.RadiusY := RadiusY; if NOT MainProc.ZoneServer.Database.Mob.Load(AMob) then begin AMob.Free; luaL_error(ALua,'Monster cannot found'); end else begin AMob.MapInfo := AMap; AMob.SummonType := stREPEAT; AMob.AddToList; AMob.Initiate; end; end; end else begin luaL_error(ALua,'Map cannot found'); end; end else begin luaL_error(ALua,'script PutMob syntax error'); end; end; end.
unit uLinkListEditorFolders; interface uses Generics.Collections, Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Graphics, Dmitry.Controls.WatermarkedEdit, Dmitry.Controls.WebLink, Dmitry.PathProviders, UnitDBDeclare, uMemory, uDBForm, uVCLHelpers, uFormInterfaces, uShellIntegration, uProgramStatInfo, uIconUtils; type TLinkInfo = class(TDataObject) public Title: string; Path: string; Icon: string; SortOrder: Integer; constructor Create(Title: string; Path: string; Icon: string; SortOrder: Integer); function Clone: TDataObject; override; procedure Assign(Source: TDataObject); override; end; TLinkListEditorFolder = class(TInterfacedObject, ILinkEditor) private FOwner: TDBForm; FCurrentPath: string; FForm: IFormLinkItemEditorData; procedure LoadIconForLink(Link: TWebLink; Path, Icon: string); procedure OnPlaceIconClick(Sender: TObject); procedure OnChangePlaceClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public constructor Create(Owner: TDBForm; CurrentPath: string); procedure SetForm(Form: IFormLinkItemEditorData); virtual; procedure CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); procedure CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); function OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; function OnApply(Sender: ILinkItemSelectForm): Boolean; end; implementation const CHANGE_PLACE_ICON = 1; CHANGE_PLACE_EDIT = 2; CHANGE_PLACE_CHANGE_PATH = 3; CHANGE_PLACE_INFO = 4; { TLinkInfo } procedure TLinkInfo.Assign(Source: TDataObject); var SI: TLinkInfo; begin SI := Source as TLinkInfo; if SI <> nil then begin Title := SI.Title; Path := SI.Path; Icon := SI.Icon; SortOrder := SI.SortOrder; end; end; function TLinkInfo.Clone: TDataObject; begin Result := TLinkInfo.Create(Title, Path, Icon, SortOrder); end; constructor TLinkInfo.Create(Title, Path, Icon: string; SortOrder: Integer); begin Self.Title := Title; Self.Path := Path; Self.Icon := Icon; Self.SortOrder := SortOrder; end; { TLinkListEditorFolder } constructor TLinkListEditorFolder.Create(Owner: TDBForm; CurrentPath: string); begin FOwner := Owner; FCurrentPath := CurrentPath; end; procedure TLinkListEditorFolder.CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var LI: TLinkInfo; WlIcon: TWebLink; WlChangeLocation: TWebLink; WedCaption: TWatermarkedEdit; LbInfo: TLabel; Editor: TPanel; begin Editor := EditorData.EditorPanel; LI := TLinkInfo(Data); WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_PLACE_ICON); WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_PLACE_EDIT); WlChangeLocation := Editor.FindChildByTag<TWebLink>(CHANGE_PLACE_CHANGE_PATH); LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_PLACE_INFO); if WedCaption = nil then begin WedCaption := TWatermarkedEdit.Create(Editor); WedCaption.Parent := Editor; WedCaption.Tag := CHANGE_PLACE_EDIT; WedCaption.Top := 8; WedCaption.Left := 35; WedCaption.Width := 200; WedCaption.OnKeyDown := FormKeyDown; end; if WlIcon = nil then begin WlIcon := TWebLink.Create(Editor); WlIcon.Parent := Editor; WlIcon.Tag := CHANGE_PLACE_ICON; WlIcon.Width := 16; WlIcon.Height := 16; WlIcon.Left := 8; WlIcon.Top := 8 + WedCaption.Height div 2 - WlIcon.Height div 2; WlIcon.OnClick := OnPlaceIconClick; end; if WlChangeLocation = nil then begin WlChangeLocation := TWebLink.Create(Editor); WlChangeLocation.Parent := Editor; WlChangeLocation.Tag := CHANGE_PLACE_CHANGE_PATH; WlChangeLocation.Height := 26; WlChangeLocation.Text := FOwner.L('Change location'); WlChangeLocation.RefreshBuffer(True); WlChangeLocation.Top := 8 + WedCaption.Height div 2 - WlChangeLocation.Height div 2; WlChangeLocation.Left := 240; WlChangeLocation.LoadFromResource('NAVIGATE'); WlChangeLocation.OnClick := OnChangePlaceClick; end; if LbInfo = nil then begin LbInfo := TLabel.Create(Editor); LbInfo.Parent := Editor; LbInfo.Tag := CHANGE_PLACE_INFO; LbInfo.Left := 35; LbInfo.Top := 35; end; LoadIconForLink(WlIcon, LI.Path, LI.Icon); WedCaption.Text := LI.Title; LbInfo.Caption := LI.Path; end; procedure TLinkListEditorFolder.CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); var LI: TLinkInfo; PI: TPathItem; Link: TWebLink; Info: TLabel; begin if Data = nil then begin PI := nil; try if Verb = 'Add' then begin if SelectLocationForm.Execute(FOwner.L('Select a directory'), '', PI, True) then Data := TLinkInfo.Create(PI.DisplayName, PI.Path, '', 0); end else begin PI := PathProviderManager.CreatePathItem(FCurrentPath); if PI <> nil then Data := TLinkInfo.Create(PI.DisplayName, PI.Path, '', 0); end; finally F(PI); end; Exit; end; LI := TLinkInfo(Data); Link := TWebLink(Elements[leWebLink]); Info := TLabel(Elements[leInfoLabel]); Link.Text := LI.Title; Info.Caption := LI.Path; Info.EllipsisPosition := epPathEllipsis; LoadIconForLink(Link, LI.Path, LI.Icon); end; procedure TLinkListEditorFolder.FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); var PI: TPathItem; begin AddActionProc(['Add', 'CurrentDirectory'], procedure(Action: string; WebLink: TWebLink) begin if Action = 'Add' then begin WebLink.Text := FOwner.L('Add directory'); WebLink.LoadFromResource('SERIES_EXPAND'); end; if Action = 'CurrentDirectory' then begin WebLink.Text := FOwner.L('Current directory'); PI := PathProviderManager.CreatePathItem(FCurrentPath); try if (PI <> nil) and PI.LoadImage(PATH_LOAD_FOR_IMAGE_LIST, 16) then WebLink.LoadFromPathImage(PI.Image) else WebLink.LoadFromResource('DIRECTORY'); finally F(PI); end; end; end ); end; procedure TLinkListEditorFolder.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then FForm.ApplyChanges; end; procedure TLinkListEditorFolder.LoadIconForLink(Link: TWebLink; Path, Icon: string); var Ico: HIcon; PI: TPathItem; begin if Icon <> '' then begin Ico := ExtractSmallIconByPath(Icon); try Link.LoadFromHIcon(Ico); finally DestroyIcon(Ico); end; end else begin PI := PathProviderManager.CreatePathItem(Path); try if (PI <> nil) and PI.LoadImage(PATH_LOAD_NORMAL or PATH_LOAD_FAST or PATH_LOAD_FOR_IMAGE_LIST, 16) and (PI.Image <> nil) then Link.LoadFromPathImage(PI.Image); finally F(PI); end; end; end; procedure TLinkListEditorFolder.UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var LI: TLinkInfo; WedCaption: TWatermarkedEdit; begin LI := TLinkInfo(Data); WedCaption := EditorData.EditorPanel.FindChildByTag<TWatermarkedEdit>(CHANGE_PLACE_EDIT); LI.Assign(EditorData.EditorData); LI.Title := WedCaption.Text; end; function TLinkListEditorFolder.OnApply(Sender: ILinkItemSelectForm): Boolean; begin ProgramStatistics.QuickLinksUsed; Result := True; end; procedure TLinkListEditorFolder.OnChangePlaceClick(Sender: TObject); var LI: TLinkInfo; LbInfo: TLabel; Editor: TPanel; PI: TPathItem; begin Editor := TPanel(TControl(Sender).Parent); LI := TLinkInfo(Editor.Tag); PI := nil; try if SelectLocationForm.Execute(FOwner.L('Select a directory'), LI.Path, PI, True) then begin LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_PLACE_INFO); LbInfo.Caption := PI.Path; LI.Path := PI.Path; end; finally F(PI); end; end; function TLinkListEditorFolder.OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; begin Result := True; end; procedure TLinkListEditorFolder.OnPlaceIconClick(Sender: TObject); var LI: TLinkInfo; Icon: string; Editor: TPanel; WlIcon: TWebLink; begin Editor := TPanel(TControl(Sender).Parent); LI := TLinkInfo(Editor.Tag); Icon := LI.Icon; if ChangeIconDialog(0, Icon) then begin LI.Icon := Icon; WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_PLACE_ICON); LoadIconForLink(WlIcon, LI.Path, LI.Icon); end; end; procedure TLinkListEditorFolder.SetForm(Form: IFormLinkItemEditorData); begin FForm := Form; end; end.
unit TpAuthenticator; interface uses SysUtils, Classes, ThHtmlDocument, ThHeaderComponent, ThTag, TpInterfaces, TpControls, TpDb, TpInput; type TTpCustomAuthenticator = class(TThHeaderComponent, ITpIncludeLister) private FAuto: Boolean; FFailureUrl: string; FLogoutUrl: string; FOnFailure: string; FOnLogout: string; FOnQueryFailure: string; FOnSuccess: string; FSuccessUrl: string; FLoginInput: TTpInput; FPasswordInput: TTpInput; protected procedure SetLoginInput(const Value: TTpInput); procedure SetPasswordInput(const Value: TTpInput); protected procedure ListPhpIncludes(inIncludes: TStringList); virtual; procedure Tag(inTag: TThTag); override; procedure UnassignComponent(AComponent: TComponent); override; public constructor Create(inOwner: TComponent); override; published property Auto: Boolean read FAuto write FAuto default true; property FailureUrl: string read FFailureUrl write FFailureUrl; property LoginInput: TTpInput read FLoginInput write SetLoginInput; property LogoutUrl: string read FLogoutUrl write FLogoutUrl; property PasswordInput: TTpInput read FPasswordInput write SetPasswordInput; property OnFailure: string read FOnFailure write FOnFailure; property OnLogout: string read FOnLogout write FOnLogout; property OnSuccess: string read FOnSuccess write FOnSuccess; property OnQueryFailure: string read FOnQueryFailure write FOnQueryFailure; property SuccessUrl: string read FSuccessUrl write FSuccessUrl; end; // TTpAuthenticator = class(TTpCustomAuthenticator) published property Auto; property FailureUrl; property LoginInput; property LogoutUrl; property PasswordInput; property OnFailure; property OnLogout; property OnSuccess; property OnQueryFailure; property SuccessUrl; end; // TTpDbAuthenticator = class(TTpCustomAuthenticator) private FDb: TTpDb; FUsersTable: string; protected procedure SetDb(const Value: TTpDb); protected procedure ListPhpIncludes(inIncludes: TStringList); override; procedure Tag(inTag: TThTag); override; procedure UnassignComponent(AComponent: TComponent); override; public constructor Create(inOwner: TComponent); override; published property Auto; property Db: TTpDb read FDb write SetDb; property FailureUrl; property LoginInput; property LogoutUrl; property PasswordInput; property OnFailure; property OnLogout; property OnSuccess; property OnQueryFailure; property UsersTable: string read FUsersTable write FUsersTable; property SuccessUrl; end; implementation { TTpCustomAuthenticator } constructor TTpCustomAuthenticator.Create(inOwner: TComponent); begin inherited; FAuto := true; end; procedure TTpCustomAuthenticator.Tag(inTag: TThTag); begin with inTag do begin Add(tpClass, 'TTpAuthenticator'); Add('tpName', Name); Attributes.Add('tpAuto', Auto); if Assigned(LoginInput) then Add('tpLoginInput', LoginInput.Name); if Assigned(PasswordInput) then Add('tpPasswordInput', PasswordInput.Name); Add('tpFailureUrl', FailureUrl); Add('tpFailureUrl', FailureUrl); Add('tpLogoutUrl', LogoutUrl); Add('tpSuccessUrl', SuccessUrl); Add('tpOnFailure', OnFailure); Add('tpOnSuccess', OnSuccess); Add('tpOnQueryFailure', OnQueryFailure); end; end; procedure TTpCustomAuthenticator.ListPhpIncludes(inIncludes: TStringList); begin inIncludes.Add('TpUserLib.php'); end; procedure TTpCustomAuthenticator.SetLoginInput(const Value: TTpInput); begin ChangeComponentProp(FLoginInput, Value); end; procedure TTpCustomAuthenticator.SetPasswordInput(const Value: TTpInput); begin ChangeComponentProp(FPasswordInput, Value); end; procedure TTpCustomAuthenticator.UnassignComponent(AComponent: TComponent); begin if AComponent = LoginInput then FLoginInput := nil; if AComponent = PasswordInput then FPasswordInput := nil; end; { TTpDbAuthenticator } constructor TTpDbAuthenticator.Create(inOwner: TComponent); begin inherited; end; procedure TTpDbAuthenticator.ListPhpIncludes(inIncludes: TStringList); begin inherited; inIncludes.Add('TpDb.php'); end; procedure TTpDbAuthenticator.SetDb(const Value: TTpDb); begin ChangeComponentProp(FDb, Value); end; procedure TTpDbAuthenticator.Tag(inTag: TThTag); begin inherited; with inTag do begin Attributes[tpClass] := 'TTpDbAuthenticator'; if Assigned(Db) then Add('tpDb', Db.Name); Add('tpUsersTbl', UsersTable); end; end; procedure TTpDbAuthenticator.UnassignComponent(AComponent: TComponent); begin inherited; if AComponent = Db then FDb := nil; end; end.
unit uDMImportTextFile; interface uses SysUtils, Classes, DBClient, DB, ADODB, uDMGlobal, Variants; type TDMImportTextFile = class(TDataModule) qryInsConfigImport: TADOQuery; qryUpdConfigImport: TADOQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FTextFile: TClientDataSet; FLinkedColumns: TStringList; FImpExpConfig : TStringList; FLog: TStringList; FSQLConnection : TADOConnection; function InsertConfigImport(AIDPessoa: Integer; ACaseCost : Boolean; AImportType: Smallint) : Boolean; function UpdadeConfigImport(AIDConfigImport: Integer; ACaseCost : Boolean) : Boolean; protected procedure BeforeImport; virtual; procedure ImportLine; virtual; procedure AfterImport; virtual; function GetParamValue(Value: String): Variant; function GetParamCurrency(Value: String) : Currency; function GetParamDateTime(Value: String) : TDateTime; function GetParamInteger(Value: String) : Integer; public property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection; property TextFile: TClientDataSet read FTextFile write FTextFile; property LinkedColumns: TStringList read FLinkedColumns write FLinkedColumns; property ImpExpConfig: TStringList read FImpExpConfig write FImpExpConfig; property Log: TStringList read FLog write FLog; procedure Import; function CreateConfigImport(AIDPessoa: Integer; ACaseCost : Boolean; AImportType: Smallint) : Boolean; function GetConfigImport(AIDPessoa: Integer; AImportType: Smallint; var ACrossColumn : WideString; var ACaseCost : WordBool) : WordBool; end; implementation uses uSystemConst, uDMCalcPrice, uDebugFunctions; {$R *.dfm} procedure TDMImportTextFile.AfterImport; begin // para ser herdado end; procedure TDMImportTextFile.BeforeImport; begin // para ser herdado end; procedure TDMImportTextFile.DataModuleCreate(Sender: TObject); begin FTextFile := TClientDataSet.Create(nil); FLinkedColumns := TStringList.Create; FImpExpConfig := TStringList.Create; FLog := TStringList.Create; end; procedure TDMImportTextFile.DataModuleDestroy(Sender: TObject); begin FreeAndNil(FTextFile); FreeAndNil(FLinkedColumns); FreeAndNil(FImpExpConfig); FreeAndNil(FLog); end; function TDMImportTextFile.GetParamValue(Value: String): Variant; begin if not(LinkedColumns.Values[Value] = '') then Result := TextFile.FieldByName(LinkedColumns.Values[Value]).AsString else Result := null; end; function TDMImportTextFile.GetParamCurrency(Value: String) : Currency; begin if not(LinkedColumns.Values[Value] = '') then Result := StrToCurrDef(TextFile.FieldByName(LinkedColumns.Values[Value]).AsString, 0) else Result := 0; end; function TDMImportTextFile.GetParamDateTime(Value: String) : TDateTime; begin if not(LinkedColumns.Values[Value] = '') then Result := StrToDateTimeDef(TextFile.FieldByName(LinkedColumns.Values[Value]).AsString, 0) else Result := 0; end; function TDMImportTextFile.GetParamInteger(Value: String) : Integer; begin if not(LinkedColumns.Values[Value] = '') then Result := StrToIntDef(TextFile.FieldByName(LinkedColumns.Values[Value]).AsString, 0) else Result := 0; end; procedure TDMImportTextFile.Import; var iLine: Integer; begin iLine := 0; BeforeImport; TextFile.First; while not TextFile.Eof do begin try Inc(iLine); if TextFile.FieldByName('Validation').AsBoolean then ImportLine; except on E: Exception do begin Log.Add('Line #' + IntToStr(iLine) + ' not imported. Error: ' + E.Message); end; end; TextFile.Next; end; AfterImport; end; procedure TDMImportTextFile.ImportLine; begin // para ser herdado end; function TDMImportTextFile.CreateConfigImport(AIDPessoa: Integer; ACaseCost: Boolean; AImportType: Smallint): Boolean; begin DMGlobal.qryFreeSQL.Connection := SQLConnection; with DMGlobal.qryFreeSQL do begin if Active then Close; if (AImportType = IMPORT_TYPE_PO) then begin debugtofile('ImportType = IMPORT_TYPE_PO'); SQL.Text := 'SELECT IDConfigImport '+ ' FROM Sis_ConfigImport '+ ' WHERE ImportType = ' + InttoStr(AImportType)+ ' and IDPessoa = ' + InttoStr(AIDPessoa) end else SQL.Text := 'SELECT IDConfigImport '+ ' FROM Sis_ConfigImport '+ ' WHERE ImportType = ' + InttoStr(AImportType); try debugtofile('SQL.Text = ' + SQL.text); Open; debugtofile('Open with success'); if IsEmpty then begin debugtofile('IsEmpty - InsertConfigImport'); Result := InsertConfigImport(AIDPessoa, ACaseCost, AImportType); debugtofile('Insert success'); end else begin debugtofile('IsEmpty - UpdateConfigImport'); Result := UpdadeConfigImport(FieldByName('IDConfigImport').AsInteger, ACaseCost); debugtofile('Insert success'); end; finally Close; end; end; end; function TDMImportTextFile.InsertConfigImport(AIDPessoa: Integer; ACaseCost: Boolean; AImportType: Smallint): Boolean; var NewId : integer; begin Result := True; qryInsConfigImport.Connection := SQLConnection; try NewId := DMGlobal.GetNextCode('Sis_ConfigImport', 'IDConfigImport',SQLConnection); with qryInsConfigImport do try Parameters.ParamByName('IDConfigImport').Value := NewId; if (AIDPessoa <> 0) then Parameters.ParamByName('IDPessoa').Value := AIDPessoa else Parameters.ParamByName('IDPessoa').Value := null; Parameters.ParamByName('ImportType').Value := AImportType; Parameters.ParamByName('CrossColumn').Value := LinkedColumns.Text; Parameters.ParamByName('CaseCost').Value := ACaseCost; ExecSQL; finally qryInsConfigImport.Close; end; except on E: Exception do begin Log.Add(Format('Error: %s', [E.Message])); Result := False; end; end; end; function TDMImportTextFile.UpdadeConfigImport(AIDConfigImport: Integer; ACaseCost: Boolean): boolean; begin Result := True; qryUpdConfigImport.Connection := SQLConnection; try with qryUpdConfigImport do try Parameters.ParamByName('CrossColumn').Value := LinkedColumns.Text; Parameters.ParamByName('CaseCost').Value := ACaseCost; Parameters.ParamByName('IDConfigImport').Value := AIDConfigImport; ExecSQL; finally qryUpdConfigImport.Close; end; except on E: Exception do begin Log.Add(Format('Error: %s', [E.Message])); Result := False; end; end; end; function TDMImportTextFile.GetConfigImport(AIDPessoa: Integer; AImportType: Smallint; var ACrossColumn: WideString; var ACaseCost: WordBool): WordBool; begin Result := False; DMGlobal.qryFreeSQL.Connection := SQLConnection; with DMGlobal.qryFreeSQL do begin if Active then Close; if (AImportType = IMPORT_TYPE_PO) then SQL.Text := 'SELECT CaseCost, CrossColumn '+ ' FROM Sis_ConfigImport '+ ' WHERE ImportType = ' + InttoStr(AImportType)+ ' and IDPessoa = ' + InttoStr(AIDPessoa) else SQL.Text := 'SELECT CaseCost, CrossColumn '+ ' FROM Sis_ConfigImport '+ ' WHERE ImportType = ' + InttoStr(AImportType); try Open; ACaseCost := False; ACrossColumn := ''; if not IsEmpty then begin ACaseCost := FieldByName('CaseCost').AsBoolean; ACrossColumn := FieldByName('CrossColumn').AsString; Result := True; end finally Close; end; end; end; end.
namespace Loops; interface uses System.Linq; type ConsoleApp = class public class method Main; method loopsTesting; method fillData : sequence of Country; var Countries : sequence of Country; end; type Country = public class public property Name : String; property Capital : String; constructor (setName : String; setCapital : String); end; implementation class method ConsoleApp.Main; begin Console.WriteLine('Loops example'); Console.WriteLine(); with myConsoleApp := new ConsoleApp() do myConsoleApp.loopsTesting; end; method ConsoleApp.loopsTesting; begin {---------------------------------} {"for" loop, taking every 5th item} for i : Int32 :=0 to 50 step 5 do begin Console.Write(i); Console.Write(' '); end; Console.WriteLine(); Console.WriteLine(); {---------------------------------} {"for" loop, going from high to low value} for i : Int32 := 10 downto 1 do begin Console.Write(i); Console.Write(' '); end; Console.WriteLine(); Console.WriteLine(); Countries := fillData; {---------------------------------} {loop with defined "index" variable, which will count from 0 through the number of elements looped} Console.WriteLine('Countries: '); for each c in Countries index num do Console.WriteLine(Convert.ToString(num + 1) + ') ' + c.Name); Console.WriteLine(); Console.WriteLine('Cities: '); var ind : Integer :=0; {---------------------------------} {simple "loop" construct that loops endlessly, until broken out of} loop begin Console.WriteLine(Countries.ElementAt(ind).Capital); inc(ind); if ind = Countries.Count then break; end; Console.WriteLine(); {---------------------------------} {the type of 'c' is inferred automatically} for each c in Countries do Console.WriteLine(c.Capital + ' is the capital of ' + c.Name); Console.WriteLine(); ind := 0; Console.WriteLine('Cities: '); {"repeat ... until" loop} repeat Console.WriteLine(Countries.ElementAt(ind).Capital); inc(ind); until ind = Countries.Count; Console.WriteLine(); ind := 0; Console.WriteLine('Countries: '); {---------------------------------} {"while ... do" loop} while ind < Countries.Count do begin Console.WriteLine(Countries.ElementAt(ind).Name); inc(ind); end; Console.ReadLine(); end; method ConsoleApp.fillData: sequence of Country; begin result := [new Country('UK', 'London'), new Country('USA', 'Washington'), new Country('Germany', 'Berlin'), new Country('Ukraine', 'Kyiv'), new Country('Russia', 'Moscow'), new Country('France', 'Paris')]; end; constructor Country (setName :String; setCapital: String); begin Name := setName; Capital := setCapital; end; end.
unit uPRK_SP_PERELIK_ISPIT_Edit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxMaskEdit, cxButtonEdit, ActnList, cxControls, cxContainer, cxEdit, cxLabel, StdCtrls, cxButtons, ExtCtrls, cxCheckBox,AArray, DB, FIBDataSet, pFIBDataSet, cxDropDownEdit, cxDBEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TFormPRK_SP_PERELIK_ISPIT_Edit = class(TForm) cxButtonOK: TcxButton; cxButtonCansel: TcxButton; cxLabelFormCaption: TcxLabel; cxButtonCloseForm: TcxButton; ActionListKlassSpravEdit: TActionList; ActionOK: TAction; ActionCansel: TAction; cxButtonEditNamePredm: TcxButtonEdit; cxButtonEditEKZ_FORM: TcxButtonEdit; cxLabelNamePredm: TcxLabel; cxLabelEKZ_FORM: TcxLabel; cxLabelEKZ_FORM_ORDER: TcxLabel; cxTextEditEKZ_FORM_ORDER: TcxTextEdit; cxCheckBoxIsSpivbesida: TcxCheckBox; cxLabelIsSpivbesida: TcxLabel; cxCheckBoxIsZalik: TcxCheckBox; cxLabelIsZalik: TcxLabel; cxCheckBoxIS_KOLVO_BALLOV: TcxCheckBox; cxLabelIS_KOLVO_BALLOV: TcxLabel; cxLabelIS_PROF_PREDMET: TcxLabel; cxLabellEKZFORM_PRB: TcxLabel; cxButtonEditlEKZFORM_PRB: TcxButtonEdit; ImageSpravEdit: TImage; cxCheckBoxIS_PROF_PREDMET: TcxCheckBox; cxLabelNAME_PREDM_DOP_TO: TcxLabel; DSetPREDM_DOP_TO: TpFIBDataSet; DSourcePREDM_DOP_TO: TDataSource; cxLookupComboBoxPREDM_DOP_TO: TcxLookupComboBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure cxLabelFormCaptionMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ActionCanselExecute(Sender: TObject); procedure ActionOKExecute(Sender: TObject); procedure cxButtonEditNamePredmPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButtonEditEKZ_FORMPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxButtonEditlEKZFORM_PRBPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); procedure cxTextEditEKZ_FORM_ORDERKeyPress(Sender: TObject; var Key: Char); private Layout: array[0.. KL_NAMELENGTH] of char; LangEdit :integer; DataPI: TAArray; procedure inicCaption;virtual; public constructor Create(aOwner: TComponent;aDataVL :TAArray);overload; end; var FormPRK_SP_PERELIK_ISPIT_Edit: TFormPRK_SP_PERELIK_ISPIT_Edit; implementation uses uPrK_Resources,uConstants,uPrK_Loader, uPRK_SP_PERELIK_ISPIT; {$R *.dfm} { TFormPRK_SP_PERELIK_ISPIT_Edit } constructor TFormPRK_SP_PERELIK_ISPIT_Edit.Create(aOwner: TComponent; aDataVL: TAArray); begin DataPI :=aDataVL; LangEdit :=SelectLanguage; inherited Create(aOwner); cxLabelFormCaption.Top :=0; inicCaption; DSetPREDM_DOP_TO.SQLs.SelectSQL.Text:='SELECT * FROM PRK_SP_PERELIK_ISPIT_OSN_PR_SEL(:ID_SP_SPEC,:ID_CN_SP_FORM_STUD,:ID_CN_SP_KAT_STUD,:ID_SP_GOD_NABORA)'; DSetPREDM_DOP_TO.ParamByName('ID_SP_SPEC').AsInt64 :=TFormPRK_SP_PERELIK_ISPIT(AOwner).DataSetPiLeft['ID_CN_SP_SPEC']; DSetPREDM_DOP_TO.ParamByName('ID_CN_SP_FORM_STUD').AsInt64 :=TFormPRK_SP_PERELIK_ISPIT(AOwner).DataSetPiLeft['ID_CN_SP_FORM_STUD']; DSetPREDM_DOP_TO.ParamByName('ID_CN_SP_KAT_STUD').AsInt64 :=TFormPRK_SP_PERELIK_ISPIT(AOwner).DataSetPiLeft['ID_CN_SP_KAT_STUD']; DSetPREDM_DOP_TO.ParamByName('ID_SP_GOD_NABORA').AsInt64 :=aDataVL['ID_SP_GOD_NABORA'].AsInt64; DSetPREDM_DOP_TO.Open; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.FormCreate(Sender: TObject); begin cxCheckBoxIsSpivbesida.EditValue :=DataPI['IS_SPIVBESIDA'].AsInteger; cxCheckBoxIsZalik.EditValue :=DataPI['IS_ZALIK'].AsInteger; cxCheckBoxIS_KOLVO_BALLOV.EditValue:=DataPI['IS_KOLVO_BALLOV'].AsInteger; cxCheckBoxIS_PROF_PREDMET.EditValue:=DataPI['IS_PROF_PREDMET'].AsInteger; if DataPI['IS_PROF_PREDMET'].AsInteger=1 then cxCheckBoxIS_PROF_PREDMET.Enabled:=false; cxButtonEditNamePredm.Text :=DataPI['SHORT_NAME_PREDM'].AsString; cxButtonEditEKZ_FORM.Text :=DataPI['SHORT_NAME_EKZFORM'].AsString; cxTextEditEKZ_FORM_ORDER.Text :=IntToStr(DataPI['EKZ_ORDER'].AsInteger); cxButtonEditlEKZFORM_PRB.Text :=DataPI['SHORT_NAME_EKZFORM_PRB'].AsString; if DSetPREDM_DOP_TO.Locate('ID_SP_PREDM',DataPI['ID_PREDM_DOP_TO'].AsInt64,[]) then cxLookupComboBoxPREDM_DOP_TO.Text:=DSetPREDM_DOP_TO['NAME']; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.FormShow(Sender: TObject); begin {422-урк, 409-англ, 419-рус} LoadKeyboardLayout( StrCopy(Layout,nLayoutLang[LangEdit]),KLF_ACTIVATE); end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.cxLabelFormCaptionMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); const SC_DragMove = $F012; begin ReleaseCapture; perform(WM_SysCommand, SC_DragMove, 0); end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.inicCaption; begin ActionOK.Caption :=nActiont_OK[LangEdit]; ActionCansel.Caption :=nActiont_Cansel[LangEdit]; ActionOK.Hint :=nHintActiont_OK[LangEdit]; ActionCansel.Hint :=nHintActiont_Cansel[LangEdit]; cxLabelNamePredm.Caption :=nLabelPredm[LangEdit]; cxLabelEKZ_FORM.Caption :=nLabelEKZ_FORM[LangEdit]; cxLabelEKZ_FORM_ORDER.Caption :=nLabelNpp[LangEdit]; cxLabellEKZFORM_PRB.Caption :=nLabelEKZFORM_PRB[LangEdit]; cxLabelIsSpivbesida.Caption :=nLabelIsSpivbesida[LangEdit]; cxLabelIsZalik.Caption :=nLabelIsZalik[LangEdit]; cxLabelIS_KOLVO_BALLOV.Caption :=nLabelIS_KOLVO_BALLOV[LangEdit]; cxLabelIS_PROF_PREDMET.Caption :=nLabelIS_PROF_PREDMET[LangEdit]; cxLabelNAME_PREDM_DOP_TO.Caption :=nLabelNAME_PREDM_DOP_TO[LangEdit]; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.ActionCanselExecute( Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.ActionOKExecute(Sender: TObject); var i: integer; begin if trim(cxButtonEditNamePredm.Text)='' then begin ShowMessage(nMsgEmptyPredm[LangEdit]); cxButtonEditNamePredm.SetFocus; exit; end; if trim(cxButtonEditEKZ_FORM.Text)='' then begin ShowMessage(nMsgEmptyEKZ_FORM[LangEdit]); cxButtonEditEKZ_FORM.SetFocus; exit; end; if trim(cxTextEditEKZ_FORM_ORDER.Text)='' then begin ShowMessage(nMsgEmptyNPP[LangEdit]); cxTextEditEKZ_FORM_ORDER.SetFocus; exit; end; for i:=0 to DataPI['All_EKZ_ORDER'].AsInteger do begin if (DataPI['EKZ_ORDER'].AsInteger<>StrToInt(cxTextEditEKZ_FORM_ORDER.Text)) then if (DataPI['All_EKZ_ORDER'][i].AsInteger=StrToInt(cxTextEditEKZ_FORM_ORDER.Text)) then begin ShowMessage(nMsgThisNppExist[LangEdit]+chr(13)+nMsgFreeNomer[LangEdit]+DataPI['EKZ_ORDER'].AsString); cxTextEditEKZ_FORM_ORDER.SetFocus; exit; end; end; if trim(cxButtonEditlEKZFORM_PRB.Text)='' then begin ShowMessage(nMsgEmptyEKZFORM_PRB[LangEdit]); cxButtonEditlEKZFORM_PRB.SetFocus; exit; end; DataPI['EKZ_ORDER'].AsInteger :=StrToInt(cxTextEditEKZ_FORM_ORDER.Text); DataPI['IS_SPIVBESIDA'].AsInteger :=cxCheckBoxIsSpivbesida.EditValue; DataPI['IS_ZALIK'].AsInteger :=cxCheckBoxIsZalik.EditValue; DataPI['IS_KOLVO_BALLOV'].AsInteger :=cxCheckBoxIS_KOLVO_BALLOV.EditValue; DataPI['IS_PROF_PREDMET'].AsInteger :=cxCheckBoxIS_PROF_PREDMET.EditValue; DataPI['ID_PREDM_DOP_TO'].AsInt64 :=cxLookupComboBoxPREDM_DOP_TO.EditValue; ModalResult:=mrOk; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.cxButtonEditNamePredmPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res: Variant; begin res := uPrK_Loader.ShowPrkSprav(self,TFormPRK_SP_PERELIK_ISPIT(Self.Owner).DataBasePrk.Handle, PrK_SP_PREDM_u,fsNormal); if VarArrayDimCount(res) > 0 then begin if res[0]<>NULL THEN begin DataPI['ID_SP_PREDM'].AsInt64 := Res[0]; DataPI['SHORT_NAME_PREDM'].AsString := Res[2]; cxButtonEditNamePredm.Text := DataPI['SHORT_NAME_PREDM'].AsString; cxButtonEditEKZ_FORM.SetFocus; end; end; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.cxButtonEditEKZ_FORMPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res: Variant; begin res := uPrK_Loader.ShowPrkSprav(self,TFormPRK_SP_PERELIK_ISPIT(Self.Owner).DataBasePrk.Handle, PrK_SP_EXZFORM,fsNormal); if VarArrayDimCount(res) > 0 then begin if res[0]<>NULL THEN begin DataPI['ID_SP_EKZ_FORM'].AsInt64 := Res[0]; DataPI['SHORT_NAME_EKZFORM'].AsString := Res[2]; cxButtonEditEKZ_FORM.Text := DataPI['SHORT_NAME_EKZFORM'].AsString; if trim(cxButtonEditlEKZFORM_PRB.Text)='' then begin DataPI['ID_SP_EKZFORM_PRB'].AsInt64 := Res[0]; DataPI['SHORT_NAME_EKZFORM_PRB'].AsString := Res[2]; cxButtonEditlEKZFORM_PRB.Text := DataPI['SHORT_NAME_EKZFORM_PRB'].AsString; end; cxTextEditEKZ_FORM_ORDER.SetFocus; end; end; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.cxButtonEditlEKZFORM_PRBPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var res: Variant; begin res := uPrK_Loader.ShowPrkSprav(self,TFormPRK_SP_PERELIK_ISPIT(Self.Owner).DataBasePrk.Handle, PrK_SP_EXZFORM,fsNormal); if VarArrayDimCount(res) > 0 then begin if res[0]<>NULL THEN begin DataPI['ID_SP_EKZFORM_PRB'].AsInt64 := Res[0]; DataPI['SHORT_NAME_EKZFORM_PRB'].AsString := Res[2]; cxButtonEditlEKZFORM_PRB.Text := DataPI['SHORT_NAME_EKZFORM_PRB'].AsString; cxCheckBoxIsSpivbesida.SetFocus; end; end; end; procedure TFormPRK_SP_PERELIK_ISPIT_Edit.cxTextEditEKZ_FORM_ORDERKeyPress( Sender: TObject; var Key: Char); begin if (Key = '.') or (Key=',') then Key := Chr(0); if ((Ord(Key) < 48) or (Ord(Key) > 57)) and (Ord(Key) <> 8) and (Ord(Key) <> VK_DELETE) then Key := Chr(0); end; end.
unit UnitOpenGLEnvMapDrawShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type TEnvMapDrawShader=class(TShader) public uTexture:glInt; uViewProjectionMatrix:glInt; public constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor TEnvMapDrawShader.Create; var f,v:ansistring; begin v:='#version 330'+#13#10+ 'out vec3 vPosition;'+#13#10+ 'uniform mat4 uViewProjectionMatrix;'+#13#10+ 'void main(){'+#13#10+ ' int vertexID = int(gl_VertexID),'+#13#10+ ' vertexIndex = vertexID % 3,'+#13#10+ ' faceIndex = vertexID / 3,'+#13#10+ ' stripVertexID = faceIndex + (((faceIndex & 1) == 0) ? (2 - vertexIndex) : vertexIndex),'+#13#10+ ' reversed = int(stripVertexID > 6),'+#13#10+ ' index = (reversed == 1) ? (13 - stripVertexID) : stripVertexID;'+#13#10+ ' vPosition = (vec3(ivec3(int((index < 3) || (index == 4)), reversed ^ int((index > 0) && (index < 4)), reversed ^ int((index < 2) || (index > 5)))) * 2.0) - vec3(1.0);'+#13#10+ ' gl_Position = (uViewProjectionMatrix * vec4(vPosition, 1.0)).xyww;'+#13#10+ '}'+#13#10; f:='#version 330'+#13#10+ 'in vec3 vPosition;'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'uniform samplerCube uTexture;'+#13#10+ 'void main(){'+#13#10+ ' oOutput = texture(uTexture, normalize(vPosition));'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor TEnvMapDrawShader.Destroy; begin inherited Destroy; end; procedure TEnvMapDrawShader.BindAttributes; begin inherited BindAttributes; end; procedure TEnvMapDrawShader.BindVariables; begin inherited BindVariables; uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture'))); uViewProjectionMatrix:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uViewProjectionMatrix'))); end; end.
unit uProcessMemMgr; { author: Michael Winter, delphi.net@gmx.net ver: 0.8, 2001-11-20 desc: Provides access to memory of other processes currently running on the same machine. Memory can be allocated and deallocated inside the context of the other process. Read and write operations supported, not limited to portions of memory allocated by the object. Works for the own process, too. notes: You need one TProcessMemMgr object for each process. Freeing the TProcessMemMgr frees all memory allocated for the appropriate process. The IPCThread unit, usually located in $(DELPHI)\Demos\Ipcdemos\ is neccessary to compile this. Please report any problems with this unit to the email address above. } interface uses Windows, Classes, IPCThrd; const MemMgrMemSize = 16*1024; type TProcessMemMgr = class(TObject) public function AllocMem(Bytes: Cardinal): Pointer; virtual; abstract; procedure FreeMem(P: Pointer); virtual; abstract; procedure Read(Source: Pointer; var Dest; Bytes: Cardinal); virtual; abstract; function ReadStr(Source: PChar): String; virtual; abstract; procedure Write(const Source; Dest: Pointer; Bytes: Cardinal); virtual; abstract; procedure WriteStr(const Str: String; Dest: Pointer); virtual; abstract; end; function CreateProcessMemMgr(ProcessID: Cardinal): TProcessMemMgr; function CreateProcessMemMgrForWnd(Wnd: HWND): TProcessMemMgr; implementation uses SysUtils, Contnrs; type EProcessMemMgr = class(Exception); TOwnProcessMemMgr = class(TProcessMemMgr) private FMemList: TThreadList; public constructor Create; destructor Destroy; override; function AllocMem(Bytes: Cardinal): Pointer; override; procedure FreeMem(P: Pointer); override; procedure Read(Source: Pointer; var Dest; Bytes: Cardinal); override; function ReadStr(Source: PChar): String; override; procedure Write(const Source; Dest: Pointer; Bytes: Cardinal); override; procedure WriteStr(const Str: String; Dest: Pointer); override; end; TForeignProcessMemMgr = class(TProcessMemMgr) private FProcess: THandle; FMemList: TThreadList; protected procedure NeedMoreMem(Bytes: Cardinal); virtual; abstract; public constructor Create(ProcessID: Cardinal); destructor Destroy; override; function AllocMem(Bytes: Cardinal): Pointer; override; procedure FreeMem(P: Pointer); override; procedure Read(Source: Pointer; var Dest; Bytes: Cardinal); override; function ReadStr(Source: PChar): String; override; procedure Write(const Source; Dest: Pointer; Bytes: Cardinal); override; procedure WriteStr(const Str: String; Dest: Pointer); override; end; TWin9xProcessMemMgr = class(TForeignProcessMemMgr) private FSharedList: TObjectList; protected procedure NeedMoreMem(Bytes: Cardinal); override; public constructor Create(ProcessID: Cardinal); destructor Destroy; override; end; TWinNTProcessMemMgr = class(TForeignProcessMemMgr) private FAllocList: TList; protected procedure NeedMoreMem(Bytes: Cardinal); override; public constructor Create(ProcessID: Cardinal); destructor Destroy; override; end; PMemRec = ^TMemRec; TMemRec = record Start: Pointer; Size: Cardinal; Group: Integer; Used: Boolean; end; { Win95 doesn't export these functions, thus we have to import them dynamically: } var VirtualAllocEx: function (hProcess: THandle; lpAddress: Pointer; dwSize, flAllocationType: DWORD; flProtect: DWORD): Pointer; stdcall = nil; VirtualFreeEx: function(hProcess: THandle; lpAddress: Pointer; dwSize, dwFreeType: DWORD): Pointer; stdcall = nil; procedure NeedVirtualAlloc; var H: HINST; begin if @VirtualFreeEx <> nil then exit; H := GetModuleHandle(kernel32); if H = 0 then RaiseLastWin32Error; @VirtualAllocEx := GetProcAddress(H, 'VirtualAllocEx'); if @VirtualAllocEx = nil then RaiseLastWin32Error; @VirtualFreeEx := GetProcAddress(H, 'VirtualFreeEx'); if @VirtualFreeEx = nil then RaiseLastWin32Error; end; { TOwnProcessMemMgr } function TOwnProcessMemMgr.AllocMem(Bytes: Cardinal): Pointer; begin Result := SysUtils.AllocMem(Bytes); FMemList.Add(Result); end; constructor TOwnProcessMemMgr.Create; begin inherited; FMemList := TThreadList.Create; end; destructor TOwnProcessMemMgr.Destroy; var i: Integer; begin with FMemList.LockList do try for i := 0 to Count - 1 do System.FreeMem(Items[i]); finally FMemList.UnlockList; end; FMemList.Free; inherited; end; procedure TOwnProcessMemMgr.FreeMem(P: Pointer); begin FMemList.Remove(P); System.FreeMem(P); end; procedure TOwnProcessMemMgr.Read(Source: Pointer; var Dest; Bytes: Cardinal); begin System.Move(Source^, Dest, Bytes); end; function TOwnProcessMemMgr.ReadStr(Source: PChar): String; begin Result := Source; end; procedure TOwnProcessMemMgr.Write(const Source; Dest: Pointer; Bytes: Cardinal); begin System.Move(Source, Dest^, Bytes); end; procedure TOwnProcessMemMgr.WriteStr(const Str: String; Dest: Pointer); begin StrPCopy(Dest, Str); end; { TForeignProcessMemMgr } function TForeignProcessMemMgr.AllocMem(Bytes: Cardinal): Pointer; var t: Integer; i: Integer; Rec, NewRec: PMemRec; Remain: Cardinal; begin Result := nil; with FMemList.LockList do try for t := 0 to 1 do begin for i := 0 to Count - 1 do begin Rec := Items[i]; if not Rec^.Used and (Rec^.Size >= Bytes) then begin Remain := Rec^.Size - Bytes; Rec^.Size := Bytes; Rec^.Used := true; Result := Rec^.Start; if Remain > 0 then begin New(NewRec); NewRec^.Start := Pointer(Cardinal(Result) + Cardinal(Bytes)); NewRec^.Size := Remain; NewRec^.Group := Rec^.Group; NewRec^.Used := false; Insert(i + 1, NewRec); end; exit; end; end; NeedMoreMem(Bytes); end; raise EProcessMemMgr.Create('ProcessMemMgr.AllocMem: not enough memory'); finally FMemList.UnlockList; end; end; constructor TForeignProcessMemMgr.Create(ProcessID: Cardinal); begin inherited Create; FProcess := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_READ or PROCESS_VM_WRITE, false, ProcessID); if FProcess = 0 then RaiseLastWin32Error; FMemList := TThreadList.Create; end; destructor TForeignProcessMemMgr.Destroy; begin FMemList.Free; CloseHandle(FProcess); inherited; end; procedure TForeignProcessMemMgr.FreeMem(P: Pointer); var i, j: Integer; Rec, NextRec: PMemRec; begin with FMemList.LockList do try for i := 0 to Count - 1 do begin Rec := Items[i]; if Rec^.Start = P then begin Rec^.Used := false; j := i + 1; while j < Count do begin NextRec := Items[j]; if NextRec^.Used then exit; if NextRec^.Group <> Rec^.Group then exit; inc(Rec^.Size, NextRec^.Size); Dispose(NextRec); Delete(j); end; exit; end; end; Assert(false, 'ProcessMemMgr.FreeMem: unknown pointer'); finally FMemList.UnlockList; end; end; procedure TForeignProcessMemMgr.Read(Source: Pointer; var Dest; Bytes: Cardinal); var BytesRead: Cardinal; begin if not ReadProcessMemory(FProcess, Source, @Dest, Bytes, BytesRead) then RaiseLastWin32Error; end; function TForeignProcessMemMgr.ReadStr(Source: PChar): String; var BytesRead: Cardinal; OldSz, DeltaSz, NewSz: Integer; Buf: PChar; i: Integer; Found: Integer; begin Result := ''; if Source = nil then exit; Buf := nil; OldSz := 0; DeltaSz := $1000 - (Cardinal(Source) and $FFF); Found := -1; try while Found < 0 do begin NewSz := OldSz + DeltaSz; System.ReallocMem(Buf, NewSz); if not ReadProcessMemory(FProcess, Source + OldSz, Buf + OldSz , DeltaSz, BytesRead) then RaiseLastWin32Error; for i := OldSz to NewSz - 1 do begin if Buf[i] = #0 then begin Found := i; break; end; end; DeltaSz := $1000; end; SetLength(Result, Found); if Found > 0 then System.Move(Buf^, Result[1], Found); finally System.FreeMem(Buf); end; end; procedure TForeignProcessMemMgr.Write(const Source; Dest: Pointer; Bytes: Cardinal); var BytesWritten: Cardinal; begin if not WriteProcessMemory(FProcess, Dest, @Source, Bytes, BytesWritten) then RaiseLastWin32Error; end; procedure TForeignProcessMemMgr.WriteStr(const Str: String; Dest: Pointer); begin Write(PChar(Str)^, Dest, Length(Str) + 1); end; { TWin9xProcessMemMgr } constructor TWin9xProcessMemMgr.Create(ProcessID: Cardinal); begin inherited; FSharedList := TObjectList.Create; end; destructor TWin9xProcessMemMgr.Destroy; begin FSharedList.Free; inherited; end; procedure TWin9xProcessMemMgr.NeedMoreMem(Bytes: Cardinal); var Ix: Integer; Share: TSharedMem; Rec: PMemRec; begin if Bytes < MemMgrMemSize then Bytes := MemMgrMemSize else Bytes := (Bytes + $FFF) and not $FFF; Ix := FSharedList.Count; Share := TSharedMem.Create('', Bytes); FSharedList.Add(Share); New(Rec); Rec^.Start := Share.Buffer; Rec^.Size := Bytes; Rec^.Group := Ix; Rec^.Used := false; FMemList.Add(Rec); end; { TWinNTProcessMemMgr } constructor TWinNTProcessMemMgr.Create(ProcessID: Cardinal); begin inherited; NeedVirtualAlloc; FAllocList := TList.Create; end; destructor TWinNTProcessMemMgr.Destroy; var i: Integer; begin for i := 0 to FAllocList.Count - 1 do VirtualFreeEx(FProcess, FAllocList[i], 0, MEM_RELEASE); FAllocList.Free; inherited; end; procedure TWinNTProcessMemMgr.NeedMoreMem(Bytes: Cardinal); var Ix: Integer; Alloc: Pointer; Rec: PMemRec; begin if Bytes < MemMgrMemSize then Bytes := MemMgrMemSize else Bytes := (Bytes + $FFF) and not $FFF; Ix := FAllocList.Count; Alloc := VirtualAllocEx(FProcess, nil, MemMgrMemSize, MEM_COMMIT, PAGE_READWRITE); if Alloc = nil then RaiseLastWin32Error; FAllocList.Add(Alloc); New(Rec); Rec^.Start := Alloc; Rec^.Size := Bytes; Rec^.Group := Ix; Rec^.Used := false; FMemList.Add(Rec); end; function CreateProcessMemMgr(ProcessID: Cardinal): TProcessMemMgr; begin if ProcessID = GetCurrentProcessId then begin Result := TOwnProcessMemMgr.Create; end else begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := TWinNTProcessMemMgr.Create(ProcessID) else Result := TWin9xProcessMemMgr.Create(ProcessID); end; end; function CreateProcessMemMgrForWnd(Wnd: HWND): TProcessMemMgr; var PID: Cardinal; begin PID := 0; GetWindowThreadProcessId(Wnd, @PID); Result := CreateProcessMemMgr(PID); end; end.
unit OTFECrossCrypt_DriverAPI; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows; type // ------------------------ // DELPHI FACING STRUCTURES // ------------------------ // !! DANGER !! // DO NOT UPDATE WITHOUT ALSO CHANGING BOTH "CROSSCRYPT_CIPHER_IDS" AND // "CROSSCRYPT_CIPHER_NAMES" TCROSSCRYPT_CIPHER_TYPE = ( cphrNone, cphrTwoFish, cphrAES256, cphrAES128, cphrAES192, cphrUnknown ); const CROSSCRYPT_CIPHER_NAMES: array [TCROSSCRYPT_CIPHER_TYPE] of string = ( 'None', 'TwoFish', 'AES256', 'AES128', 'AES192', 'Unknown' ); // The encryption algorithm IDs which must be passed to the driver CROSSCRYPT_CIPHER_IDS: array [TCROSSCRYPT_CIPHER_TYPE] of word = ( 0, 1, 2, 3, 4, $ffff ); // #define CTL_CODE( DeviceType, Function, Method, Access ) ( \ // ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ // ) // From winioctl.h (part of the MS DDK) const FILE_DEVICE_FILE_SYSTEM = $00000009; FILE_DEVICE_UNKNOWN = $00000022; FILE_DEVICE_MASS_STORAGE = $0000002d; FILE_ANY_ACCESS = 0; FILE_READ_ACCESS = $0001; // file & pipe FILE_WRITE_ACCESS = $0002; // file & pipe METHOD_BUFFERED = 0; // Extracted from CrossCrypt's filedisk.c: // The number of passwords required for a multikey password: MULTIKEY_PASSWORD_REQUIREMENT = 64; // From winioctl.h: const IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE; const CROSSCRYPT_REGISTRY_ROOT = HKEY_LOCAL_MACHINE; CROSSCRYPT_REGISTRY_KEY_MAIN = 'SYSTEM\CurrentControlSet\Services\FileDisk'; CROSSCRYPT_REGGISTRY_MAIN_NAME_START = 'Start'; CROSSCRYPT_REGISTRY_KEY_PARAM = CROSSCRYPT_REGISTRY_KEY_MAIN + '\Parameters'; CROSSCRYPT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES = 'NumberOfDevices'; CROSSCRYPT_DFLT_REGGISTRY_PARAM_NAME_NUMEROFDEVICES = 4; const IOCTL_STORAGE_MEDIA_REMOVAL = ((IOCTL_STORAGE_BASE) * $10000) OR ((FILE_READ_ACCESS) * $4000) OR (($0201) * $4) OR (METHOD_BUFFERED); // #define IOCTL_STORAGE_MEDIA_REMOVAL CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS) const IOCTL_STORAGE_EJECT_MEDIA = ((IOCTL_STORAGE_BASE) * $10000) OR ((FILE_READ_ACCESS) * $4000) OR (($0202) * $4) OR (METHOD_BUFFERED); // #define IOCTL_STORAGE_EJECT_MEDIA CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS) const FSCTL_LOCK_VOLUME = ((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((6) * $4) OR (METHOD_BUFFERED); // #define FSCTL_LOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_UNLOCK_VOLUME = ((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((7) * $4) OR (METHOD_BUFFERED); // #define FSCTL_UNLOCK_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_DISMOUNT_VOLUME = ((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((8) * $4) OR (METHOD_BUFFERED); // #define FSCTL_DISMOUNT_VOLUME CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS) const DEVICE_BASE_NAME = '\FileDisk'; DEVICE_DIR_NAME = '\Device'+DEVICE_BASE_NAME; DEVICE_NAME_PREFIX = DEVICE_DIR_NAME+DEVICE_BASE_NAME; FILE_DEVICE_FILE_DISK = $8000; USER_MODE_DEVICE_NAME_PREFIX = '\\.\FileDisk'; MAX_KEYS = 64; MAX_KEYHASH = 32; // This next one's from CrossCrypt's filedisk.c MAX_KEY_LENGTH = 500; // We have these as magic numbers as I was getting an "Overflow in conversion // or arithmetic operation" when they were expressed in the same way as the // "FSCTL_..." declarations above const IOCTL_FILE_DISK_OPEN_FILE = $8000e000; //#define IOCTL_FILE_DISK_OPEN_FILE CTL_CODE(FILE_DEVICE_FILE_DISK, 0x800, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) const IOCTL_FILE_DISK_CLOSE_FILE = $8000e004; //#define IOCTL_FILE_DISK_CLOSE_FILE CTL_CODE(FILE_DEVICE_FILE_DISK, 0x801, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) const IOCTL_FILE_DISK_QUERY_FILE = $80006008; //#define IOCTL_FILE_DISK_QUERY_FILE CTL_CODE(FILE_DEVICE_FILE_DISK, 0x802, METHOD_BUFFERED, FILE_READ_ACCESS) type // !! WARNING !! // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" POPEN_FILE_INFORMATION = ^TOPEN_FILE_INFORMATION; TOPEN_FILE_INFORMATION = record version: word; FileSize: LARGE_INTEGER; ReadOnly: boolean; KeyType: word; //0 None 1 2Fish 2 AES256 KeyNum: word; KeyLength: word; FileNameLength: word; Key: array [0..MAX_KEYS-1] of array [0..MAX_KEYHASH-1] of byte; DriveLetter: Ansichar; // This next one uses an artificially long buffer; DON'T USE // siezeof(TOPEN_FILE_INFORMATION) when passing one of these structs to the // device driver, as the fixed length of this buffer will screw things up FileName: array [0..MAX_PATH] of Ansichar; end; implementation END.
unit uAlertCore; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UtilsBase; type { Механизм оповещений } TAlertWindowEventType = (awetFeedBack, awetRMedication, awetMissedCall, awetPay, awetPayCheck, awetError, awetUser, awetPharmacy, awetNewPost, awetCall); TAlertWindowShowMethod = (fmAAWShowLeftToRight,fmAAWShowCenter,fmAAWShowTopDown); TAlertWindowFadeMethod = (fmAAWFadeTimer, fmAAWFadeRightToLeft, fmAAWFadeCenter, fmAAWFadeDowmUp); PAlertPopupWindowOptions = ^TAlertPopupWindowOptions; TAlertPopupWindowOptions = record NRN_AlertUser : int64; Enumereator : byte; EventTime : TDateTime; EventType : TAlertWindowEventType; WShowMetod : TAlertWindowShowMethod; WFadeMetod : TAlertWindowFadeMethod; WColor : TColor; TextColor : TColor; AlertMessage : string; AlertType : string; AlertUser : string; AlertTypeUser : string; IconIndex : integer; Content : string; end; TAlertPopupWindowControl = class private procedure UpdateWindowPos(PWH : HWND); public AWList : TList; procedure RegisterAlertPopupWindow(PWH: HWND); procedure UnRegisterAlertPopupWindow(PWH: HWND); constructor Create; destructor Destroy; end; TWndRec = record Handle: HWND; Id: Integer; end; PWndRec = ^TWndRec; TAlertManager = class private FList: TList; FWList: TList; FLeft: Integer; FTop: Integer; FDeltaX: Integer; FDeltaY: Integer; FMaxCnt: Integer; FCurrId: Integer; procedure UpdateWindowPos(Handle: HWND); public procedure RegisterWindow(Handle: HWND); procedure UnRegisterWindow(Handle: HWND); constructor Create; destructor Destroy; override; end; var g_AlertManager: TAlertManager; implementation procedure TAlertPopupWindowControl.UpdateWindowPos(PWH : HWND); const IndentY = 100; var rAW : TRect; TopAW : integer; LeftAW : integer; i : integer; BErr : boolean; ScreenY : integer; ScreenX : integer; begin ScreenY := screen.WorkAreaHeight-100; ScreenX := screen.WorkAreaWidth; TopAW := ScreenY - IndentY - 2; for i := 0 to AWList.Count - 1 do begin GetWindowRect(HWND(AWList[i]),rAW); LeftAW := ScreenX - (rAW.Right-rAW.Left) - 2; BErr := SetWindowPos(HWND(AWList[i]), HWND_TOPMOST, LeftAW, TopAW, rAW.Right-rAW.Left, rAW.Bottom-rAW.Top, SWP_SHOWWINDOW or SWP_NOACTIVATE); (* case TfrmDepED_WAlert(popupList[i]).AlertWOptions.WShowMetod of fmAAWShowLeftToRight : AnimateWindow(HWND(popupList[i]), 300, AW_SLIDE or AW_HOR_POSITIVE ); { слева на право } fmAAWShowCenter : AnimateWindow(HWND(popupList[i]), 300, AW_SLIDE or AW_CENTER ); fmAAWShowTopDown : AnimateWindow(HWND(popupList[i]), 300, AW_SLIDE or AW_VER_POSITIVE ); { сверху вниз } else AnimateWindow(HWND(popupList[i]), 300, AW_SLIDE or AW_HOR_POSITIVE ); { слева на право } end; *) TopAW := TopAW - (rAW.Bottom - rAW.Top) - 2; end; end; constructor TAlertPopupWindowControl.Create; begin AWList := TList.Create; end; procedure TAlertPopupWindowControl.RegisterAlertPopupWindow(PWH: HWND); var IndexAW : integer; begin IndexAW := AWList.IndexOf(Pointer(PWH)); if IndexAW < 0 then AWList.Add(Pointer(PWH)); UpdateWindowPos(PWH); end; procedure TAlertPopupWindowControl.UnRegisterAlertPopupWindow(PWH: HWND); var IndexAW : integer; begin IndexAW := AWList.IndexOf(Pointer(PWH)); if IndexAW >= 0 then begin AWList.Remove(Pointer(PWH)); UpdateWindowPos(PWH); end; end; destructor TAlertPopupWindowControl.Destroy; begin AWList.Free; end; { TAlertManager } constructor TAlertManager.Create; begin inherited; FList := TList.Create; FWList := TList.Create; FLeft := 30; FTop := screen.WorkAreaHeight - 380; FDeltaX := 0; FDeltaY := 100; FMaxCnt := 5; FCurrId := 1; end; destructor TAlertManager.Destroy; begin FList.Free; FWList.Free; inherited; end; procedure TAlertManager.RegisterWindow(Handle: HWND); var Idx : integer; vWnd: TWndRec; begin Idx := FList.IndexOf(Pointer(Handle)); if Idx < 0 then begin FList.Add(Pointer(Handle)); vWnd.Handle := Handle; vWnd.Id := FCurrId; FWList.Add(@vWnd); Inc(FCurrId); if FCurrId > FMaxCnt then FCurrId := 1; end; UpdateWindowPos(Handle); end; procedure TAlertManager.UnRegisterWindow(Handle: HWND); var Idx : integer; begin Idx := FList.IndexOf(Pointer(Handle)); if Idx >= 0 then begin FList.Delete(Idx); FWList.Delete(Idx); if FList.Count = 0 then FCurrId := 1; //UpdateWindowPos(PWH); end; end; procedure TAlertManager.UpdateWindowPos(Handle: HWND); var vRect: TRect; vTop: integer; vLeft: integer; I: Integer; vPWnd: PWndRec; begin if FWList.Count > 0 then begin vPWnd := PWndRec(FWList.Items[FWList.Count - 1]); I := vPWnd^.Id; end else I := 1; vTop := FTop - (I - 1)* FDeltaY; vLeft := FLeft + (I - 1) * FDeltaX; GetWindowRect(Handle ,vRect); SetWindowPos(Handle, HWND_TOPMOST, vLeft, vTop, vRect.Right - vRect.Left, vRect.Bottom - vRect.Top, SWP_SHOWWINDOW or SWP_NOACTIVATE); end; initialization g_AlertManager := TAlertManager.Create; finalization FreeAndNil(g_AlertManager); end.
unit MediaPlayer.StateConversion; interface uses System.Classes, System.SysUtils, Data.Bind.Components, System.Bindings.Helper, System.Generics.Collections, FMX.Types, FMX.Media; implementation uses System.Bindings.EvalProtocol, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Consts; const sMediaPlayerStateToString = 'MediaPlayerStateToString'; sThisUnit = 'MediaPlayer.StateConversion'; sMediaPlayerStateToStringDesc = 'Assigns a Media Player State to a String'; procedure RegisterOutputConversions; begin // Assign String from State TValueRefConverterFactory.RegisterConversion(TypeInfo(TMediaState), TypeInfo(string), TConverterDescription.Create( procedure(const InValue: TValue; var OutValue: TValue) begin Assert(InValue.IsType(TypeInfo(TMediaState)), 'Input needs to be MediaState'); case TMediaState(InValue.AsOrdinal) of TMediaState.Unavailable: OutValue := TValue.From<string>('Unavailable'); TMediaState.Playing: OutValue := TValue.From<string>('Playing'); TMediaState.Stopped: OutValue := TValue.From<string>('Stopped'); else OutValue := TValue.From<string>('UNKNOW!'); end; end, sMediaPlayerStateToString, sMediaPlayerStateToString, sThisUnit, True, sMediaPlayerStateToStringDesc, FMX.Types.TStyledControl) // fmx only ); end; procedure UnregisterOutputConversions; begin TValueRefConverterFactory.UnRegisterConversion( TypeInfo(TMediaState), TypeInfo(string)); end; initialization RegisterOutputConversions; finalization UnregisterOutputConversions; end.
// Imprimir la media de los elementos que se encuentran en las posiciones pares //y la media de los elementos que se encuentran en las posiciones impares de un vector numérica. Program TP7E9; uses crt; const n=1000; type t_vector=array[1..n] of real; var vector:t_vector; lim:integer; Procedure inicializar (var v:t_vector); var i:integer; begin i:=0; for i:=1 to n do begin v[i]:=0; end; end; procedure cargar (var v:t_vector;var l:integer); var aux:char; num:real; begin l:=0; aux:='s'; while ((aux<>'n') and (l<=n)) do begin writeln('ingrese un numero.'); readln(num); l:=l+1; v[l]:=num; writeln('Para finalizar presione "n".'); readln(aux); end; end; procedure media(var v:t_vector;l:integer); var mp,mi,cp,ci:real; i:integer; begin mp:=0; mi:=0; ci:=0; cp:=0; for i:=1 to l do begin if ((i mod 2)=0) then begin mp:=mp+v[i]; cp:=cp+1; end else begin mi:=mi+v[i]; ci:=ci+1; end; end; writeln('La media de los numeros de posicion par en el vector es: ',(mp/cp):2:2); writeln('La media de los numeros de posicion impar en el vector es: ',(mi/ci):2:2); end; begin inicializar(vector); cargar(vector,lim); media(vector,lim); readkey; end.
// // Generated by JavaToPas v1.4 20140515 - 180839 //////////////////////////////////////////////////////////////////////////////// unit org.apache.http.impl.conn.LoggingSessionOutputBuffer; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.apache.http.io.SessionOutputBuffer, org.apache.http.impl.conn.Wire, org.apache.http.util.CharArrayBuffer, org.apache.http.io.HttpTransportMetrics; type JLoggingSessionOutputBuffer = interface; JLoggingSessionOutputBufferClass = interface(JObjectClass) ['{D309EBBF-FAE8-430E-AA43-D37FEDC91472}'] function getMetrics : JHttpTransportMetrics; cdecl; // ()Lorg/apache/http/io/HttpTransportMetrics; A: $1 function init(&out : JSessionOutputBuffer; wire : JWire) : JLoggingSessionOutputBuffer; cdecl;// (Lorg/apache/http/io/SessionOutputBuffer;Lorg/apache/http/impl/conn/Wire;)V A: $1 procedure &write(b : Integer) ; cdecl; overload; // (I)V A: $1 procedure &write(b : TJavaArray<Byte>) ; cdecl; overload; // ([B)V A: $1 procedure &write(b : TJavaArray<Byte>; off : Integer; len : Integer) ; cdecl; overload;// ([BII)V A: $1 procedure flush ; cdecl; // ()V A: $1 procedure writeLine(buffer : JCharArrayBuffer) ; cdecl; overload; // (Lorg/apache/http/util/CharArrayBuffer;)V A: $1 procedure writeLine(s : JString) ; cdecl; overload; // (Ljava/lang/String;)V A: $1 end; [JavaSignature('org/apache/http/impl/conn/LoggingSessionOutputBuffer')] JLoggingSessionOutputBuffer = interface(JObject) ['{A5B7B7C9-5632-47D3-9750-B55CAC395AD2}'] function getMetrics : JHttpTransportMetrics; cdecl; // ()Lorg/apache/http/io/HttpTransportMetrics; A: $1 procedure &write(b : Integer) ; cdecl; overload; // (I)V A: $1 procedure &write(b : TJavaArray<Byte>) ; cdecl; overload; // ([B)V A: $1 procedure &write(b : TJavaArray<Byte>; off : Integer; len : Integer) ; cdecl; overload;// ([BII)V A: $1 procedure flush ; cdecl; // ()V A: $1 procedure writeLine(buffer : JCharArrayBuffer) ; cdecl; overload; // (Lorg/apache/http/util/CharArrayBuffer;)V A: $1 procedure writeLine(s : JString) ; cdecl; overload; // (Ljava/lang/String;)V A: $1 end; TJLoggingSessionOutputBuffer = class(TJavaGenericImport<JLoggingSessionOutputBufferClass, JLoggingSessionOutputBuffer>) end; implementation end.
{ ************************************* * Crossing Bridge game engine * *-----------------------------------* * Version : 1.0 * * Coder : David Eleazar * * Prog. Lang : Pascal * * Compiler : Free Pascal 3.0.4 * * Date Added : December 15th, 2019 * * Last Modif. : December 16th, 2019 * ************************************* Definition : 1. People/person is the entity/ies who want to cross the river using designated bridge 2. Source is the starting place a.k.a person initial standing point 3. Destination is the target place where the people want to cross with the bridge 3. Lamp is the lighting helper to cross the bridge in the night. The lamp has its own time-to-blown, so after several minutes, it will blew, render player to lose the game Changelog : 1.0 : Initial release } unit CBProcessor; interface uses CRT, SysUtils; type TPerson = record timeCost: integer; isCrossed: boolean; end; TState = record data: array [0..4] of TPerson; lampPosition: char; //lamp position in [S]ource or [D]estination timeLeft: integer; end; TVertex = record //record untuk menyimpan data tiap simpul selfPosition, parentPosition, depthLevel: integer; //memuat posisi array parent, dirinya sendiri dan tingkatan turunan content: TState; //isi state childPosition: array of integer; //menyimpan posisi anak dalam generated list isVisited: boolean; //penanda jika sudah dikunjungi end; var //globar vars errEnterBack: String = 'Tekan ENTER untuk kembali . . '; strEnterContinue: String = 'Tekan ENTER untuk melanjutkan . . .'; strAnyKeyExit: String = 'Tekan sembarang tombol untuk keluar . . .'; generatedList: array of TVertex; //array untuk menyimpan anakan hasil generate intInitState,intFinalState: TState; //initial state dan final state solutionFound: boolean; //jika solusi sudah ditemukan, maka bernilai TRUE solutionList: array of TState; //menyimpan solusi pergerakan dari initial state dan final state, jika solusi ditemukan //begin of procedure's prototypes procedure initialState; procedure copyContent (var origin,target: TState); procedure viewState (state: TState); function isIdenticalState(x, y : TState): boolean; procedure stepTracker (var x : array of TState); procedure runGameSimulation(method: char; level:integer); procedure crossTheBridge(a,b: integer; var state: TState); procedure nodeGenerator (var node : TVertex); procedure cbBFS (numOfLevel : integer); procedure cbDFS (var node : TVertex; numOfLevel : integer); //end of procedure's protoypes implementation procedure initialState; var tc: array [0..4] of integer = (1,3,6,8,12); //set person timing here lampRunningTime: integer = 30; //set max running time i: integer; begin for i:=Low(tc) to High(tc) do begin intInitState.data[i].timeCost := tc[i]; intInitState.data[i].isCrossed := FALSE; intFinalState.data[i].timeCost := tc[i]; intFinalState.data[i].isCrossed := TRUE; end; intInitState.lampPosition := 'S'; //lamp at the source intInitState.timeLeft := lampRunningTime; intFinalState.lampPosition := 'D'; //lamp at the destination intFinalState.timeLeft := 0; //for init only end; procedure copyContent (var origin,target: TState); var i: integer; begin for i:=Low(origin.data) to High(origin.data) do begin target.data[i].timeCost := origin.data[i].timeCost; target.data[i].isCrossed := origin.data[i].isCrossed; end; target.lampPosition := origin.lampPosition; target.timeLeft := origin.timeLeft; end; procedure viewState (state: TState); var i: integer; str: string = ''; peopleTime: string = ''; begin for i:=Low(state.data) to High(state.data) do begin peopleTime += IntToStr(state.data[i].timeCost); peopleTime += ' '; if state.data[i].isCrossed then str += '1 ' else str += '0 '; end; str += ': '; str += state.lampPosition; str += ' : '; str += IntToStr(state.timeLeft); //then print the state writeLn ('================================'); writeLn ('= People : Lamp : Rem. ='); writeLn ('= ' + peopleTime + ' ='); writeLn ('= ' + str + ' ='); writeLn ('================================'); end; function isIdenticalState(x, y : TState): boolean; var i: integer; begin isIdenticalState := TRUE; for i:=Low(x.data) to High(x.data) do begin if (x.data[i].isCrossed <> y.data[i].isCrossed) then begin isIdenticalState:=FALSE; break; end; end; if (x.lampPosition <> y.lampPosition) then isIdenticalState:=FALSE; end; { prosedur stepTracker berguna untuk menarik garis dari posisi final state di array hasil generate hingga ke initial state dari program } procedure stepTracker (var x : array of TState); var i,locParent : integer; begin locParent:=generatedList[High(generatedList)].selfPosition; //kopikan posisi diri sendiri terlebih dahulu for i:=High(x) downto Low(x) do begin copyContent(generatedList[locParent].content,x[i]); locParent:=generatedList[locParent].parentPosition; //kemudian untuk tiap loop, ganti posisi parent end; end; procedure runGameSimulation(method: char; level:integer); //method = [B]FS and [D]FS begin writeLn ('Initial state'); viewState(intInitState); readln; SetLength(generatedList,1); //siapkan tempat pertama untuk root parent copyContent(intInitState, generatedList[0].content); //posisi 0 sebagai root parent //set root parent attributes generatedList[0].parentPosition := 0; generatedList[0].selfPosition := 0; generatedList[0].depthLevel := 0; generatedList[0].isVisited := FALSE; if (method='B') then begin cbBFS(level); end else begin cbDFS(generatedList[0], level); end; if not solutionFound then begin TextColor (12); writeln ('Mohon maaf, solusi tidak ditemukan'); writeln (strAnyKeyExit); repeat until keypressed; //menunggu hingga sebuah tombol ditekan end; end; procedure crossTheBridge(a,b: integer; var state: TState); var oldLampPosition: char; timeDecreaseFactor: integer = 0; begin oldLampPosition := state.lampPosition; //toggle lamp position if (oldLampPosition = 'S') then state.lampPosition := 'D' else state.lampPosition := 'S'; //then toggle the person position if a >= 0 then state.data[a].isCrossed := not state.data[a].isCrossed; if b >= 0 then state.data[b].isCrossed := not state.data[b].isCrossed; //check time remaining by measuring maximum time from two people if ((a >= 0) and (b >= 0)) then begin if state.data[a].timeCost > state.data[b].timeCost then timeDecreaseFactor := state.data[a].timeCost else timeDecreaseFactor := state.data[b].timeCost; end else if ((a >= 0) and (b < 0)) then timeDecreaseFactor := state.data[a].timeCost else if ((a < 0) and (b >= 0)) then timeDecreaseFactor := state.data[b].timeCost; state.timeLeft -= timeDecreaseFactor; end; { prosedur nodeGenerator berfungsi untuk membangkitan child dari suatu node masukan, dan menyimpannya dalam variabel global bertipe array dinamis Defined rules in array 0-4 : person #1..#5 can move } procedure nodeGenerator (var node : TVertex); var currentSide : char; allowedRule : array [0..4] of boolean; i,j,k,tmpNodeLevel : integer; tmpStateStorage : TState; isIdentic,reachedFinal : boolean; //cek kesamaan isi matriks dan finalisasi begin //init tmpNodeLevel := 0; isIdentic := FALSE; reachedFinal := FALSE; clrscr; //bersihkan layar writeln ('Parent position : ',node.selfPosition); currentSide := node.content.lampPosition; //begin ruler init for i:=0 to 4 do begin // if the person doesn't match current lamp position, then it cannot cross the river if ((node.content.data[i].isCrossed and (currentSide = 'S')) xor (not node.content.data[i].isCrossed and (currentSide = 'D'))) then allowedRule[i] := FALSE else allowedRule[i] := TRUE; write (allowedRule[i]); write (' '); end; //end ruler init tmpNodeLevel := node.depthLevel; inc(tmpNodeLevel); for i:=Low(allowedRule) to High(allowedRule) do begin for j:=0 to i do begin copyContent(node.content, tmpStateStorage); //kopi konten node ke temp if (i <> j) then begin if (allowedRule[i] and allowedRule[j]) then crossTheBridge(i, j, tmpStateStorage); //move two people to the other side end else begin if (allowedRule[i]) then crossTheBridge(i, -1, tmpStateStorage); //move only one people to the other side end; for k:=Low(generatedList) to High(generatedList) do begin isIdentic := isIdenticalState(tmpStateStorage, generatedList[k].content); if isIdentic then break; //jika terdeteksi ada yang identik, hentikan looping end; if (not isIdentic and (allowedRule[i] or allowedRule[j]) and (tmpStateStorage.timeLeft >= 0)) then begin //jika tidak ada yang identik, kopikan hasil generate ke generatedList SetLength(generatedList, length(generatedList)+1); //siapkan tempat untuk generated matrix SetLength(node.childPosition, length(node.childPosition)+1); //siapkan tempat untuk posisi child pada array node.childPosition[length(node.childPosition)-1] := length(generatedList)-1; //masukkan posisi child pada array childPosition copyContent(tmpStateStorage,generatedList[length(generatedList)-1].content); //kopikan isi ke generated list generatedList[length(generatedList)-1].parentPosition := node.selfPosition; //posisi parent pada array generatedList[length(generatedList)-1].selfPosition := length(generatedList)-1; //posisi node yang baru digenerate berada pada posisi terakhir array yang baru diset generatedList[length(generatedList)-1].depthLevel := tmpNodeLevel; //kedalaman level = level node aktif + 1 generatedList[length(generatedList)-1].isVisited := FALSE; //set status node yang belum digenerate dengan FALSE reachedFinal := isIdenticalState(generatedList[length(generatedList)-1].content, intFinalState); if reachedFinal then begin //jika sudah ketemu final state SetLength(solutionList, generatedList[length(generatedList)-1].depthLevel+1); //menyiapkan array untuk menyimpan posisi langkah stepTracker(solutionList); //panggil prosedur tracker TextColor(14); clrscr; writeln ('Solusi ditemukan!'); solutionFound:=TRUE; end; writeLn ('i : ' + IntToStr(i) + ', j : ' + IntToStr(j)); writeln ('Current node position : ',node.childPosition[high(node.childPosition)]); writeln ('Child level : ',tmpNodeLevel); viewState(generatedList[length(generatedList)-1].content); //tampilkan node yang baru digenerate if solutionFound then begin writeln ('Posisi final state berada pada array ke-',High(generatedList)); writeln ('Langkah yang diperlukan dari initial state adalah ',generatedList[High(generatedList)].depthLevel,' langkah'); writeln ('Langkah langkahnya adalah : '); writeln; TextColor (10); for k:=Low(solutionList) to High(solutionList) do begin if k=Low(solutionList) then writeln ('Initial State') else if k=High(solutionList) then writeln ('Final State') else writeln ('Langkah ke-',k); viewState(solutionList[k]); readln; end; writeln ('Permainan selesai'); writeln (strAnyKeyExit); repeat until keypressed; //menunggu hingga sebuah tombol ditekan halt; //keluar dari program end; writeln; end; end; end; node.isVisited := TRUE; //tandai node yang sudah digenerate sebagai TRUE //delay(500); //just for debugging readln; //just for debugging end; procedure cbBFS (numOfLevel : integer); var bfsPosition : integer; begin bfsPosition := 0; //posisi awal BFS pada root parent while ((generatedList[bfsPosition].isVisited=FALSE) and (solutionFound=FALSE)) do begin if generatedList[bfsPosition].depthLevel<numOfLevel then begin nodeGenerator(generatedList[bfsPosition]); //generate hasil inc(bfsPosition); //generator akan bergerak secara mendatar end else exit; end; end; procedure cbDFS (var node : TVertex; numOfLevel : integer); var i : integer; begin if (node.isVisited=FALSE) then begin if node.depthLevel<numOfLevel then begin nodeGenerator(node); for i:=low(node.childPosition) to high(node.childPosition) do //generator akan melakukan pembangkitan anakan terlebih dahulu cbDFS(generatedList[node.childPosition[i]],numOfLevel); end; end else exit; end; initialization initialState; end.
unit TiMessages; interface uses Classes, SysUtils,Dialogs,Graphics,Forms,StdCtrls; function TiShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer; implementation const OkBtnCaption = 'Ок'; const CancelBtnCaption = 'Відмінити'; const YesBtnCaption = 'Так'; const NoBtnCaption = 'Ні'; const AbortBtnCaption = 'Прервати'; const RetryBtnCaption = 'Повторити'; const IgnoreBtnCaption = 'Продовжити'; const AllBtnCaption = 'Для усіх'; const HelpBtnCaption = 'Допомога'; const NoToAllBtnCaption = 'Ні для усіх'; const YesToAllBtnCaption = 'Так для усіх'; const AttentionBtnCaption = 'Увага'; function TiShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer; var ViewMessageForm:TForm; i:integer; begin if Pos(#13,Msg)=0 then Msg:=#13+Msg; ViewMessageForm:=CreateMessageDialog(Msg,DlgType,Buttons); ViewMessageForm.FormStyle := fsStayOnTop; with ViewMessageForm do begin for i:=0 to ComponentCount-1 do if (Components[i].ClassType=TButton) then begin if UpperCase((Components[i] as TButton).Caption)='OK' then (Components[i] as TButton).Caption := OkBtnCaption; if UpperCase((Components[i] as TButton).Caption)='CANCEL' then (Components[i] as TButton).Caption := CancelBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&YES' then (Components[i] as TButton).Caption := YesBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&NO' then (Components[i] as TButton).Caption := NoBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&ABORT' then (Components[i] as TButton).Caption := AbortBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&RETRY' then (Components[i] as TButton).Caption := RetryBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&IGNORE' then (Components[i] as TButton).Caption := IgnoreBtnCaption; if UpperCase((Components[i] as TButton).Caption) = '&ALL' then (Components[i] as TButton).Caption := AllBtnCaption; if UpperCase((Components[i] as TButton).Caption) = '&HELP' then (Components[i] as TButton).Caption := HelpBtnCaption; if UpperCase((Components[i] as TButton).Caption) = 'N&O TO ALL' then (Components[i] as TButton).Caption := NoToAllBtnCaption; if UpperCase((Components[i] as TButton).Caption) = 'YES TO &ALL' then (Components[i] as TButton).Caption := YesToAllBtnCaption; end; Caption:=Title; i:=ShowModal; Free; end; TiShowMessage:=i; end; end.
program Exercise1; Uses sysutils; var numbersString: String; numbersArray: Array of Integer; number: Integer; type ArrayOfInteger = array of Integer; { Counts the occurences of separator in str } function Occurs(CONST str, separator: string): Integer; var i, nSep: Integer; begin nSep:= 0; for i:= 1 to Length(str) do if str[i] = separator then Inc(nSep); Occurs:= nSep; end; { Splits string containing Integers separated by separator into array of Integer } function Split(const str, separator: string): ArrayOfInteger; var i, n: Integer; strline, strfield: string; begin { Number of occurences of the separator } n:= Occurs(str, separator); { Size of the array to be returned is the number of occurences of the separator } SetLength(Split, n + 1); i := 0; strline:= str; repeat if Pos(separator, strline) > 0 then begin strfield:= Copy(strline, 1, Pos(separator, strline) - 1); strline:= Copy(strline, Pos(separator, strline) + 1, Length(strline) - pos(separator,strline)); end else begin strfield:= strline; strline:= ''; end; Split[i]:= StrToInt(strfield); Inc(i); until strline= ''; end; { Exercise 1: Read numbers from STDIN, sort them using QuickSort and then build a binary tree } begin Write ('INPUT: Numbers separated by whitespace : '); ReadLn (numbersString); numbersArray := Split(numbersString, ' '); for number in numbersArray do WriteLn (number); end.
PROGRAM Serie; USES Crt; (*11100011b 9600 baudios 1 bit stop*) CONST COM1_Base = $3F8; COM2_Base = $2F8; LCR_Offset = $03; Latch_Low = $00; Latch_High = $01; VAR gbNoWait: boolean; gbStopArduino: boolean; gbBaud: longint; gbCadFile: string; gbDelayLine: word; gbCurrentTime: LONGINT ABSOLUTE $0040:$006C; gbBeforeTime: LONGINT; gbFile: Text; Ch: Char; auxByte: byte; contador: integer; gbTotalLineas: word; gbCurrentLinea: word; gbBuffer: ARRAY[1..16000] OF char; gbCurrentBuffer: word; i:word; {************************************************} procedure SetBaudRate(NewRate: longint); var DivisorLatch: Word; begin DivisorLatch := 115200 div NewRate; Port[COM1_Base + LCR_Offset] := Port[COM1_Base + LCR_Offset] or $80; {Set DLAB} Port[COM1_Base + Latch_High] := DivisorLatch shr 8; Port[COM1_Base + Latch_Low] := DivisorLatch and $FF; Port[COM1_Base + LCR_Offset] := Port[COM1_Base + LCR_Offset] and $7F; {Clear DLAB} end; {************************************************} (*function GetBaudRate: Integer; var DivisorLatch: Word; begin Port[COM1_Base + LCR_Offset] := Port[COM1_Base + LCR_Offset] or $80; {Set DLAB} DivisorLatch := (Port[COM1_Base + Latch_High] shl 8) + Port[COM1_Base + Latch_Low]; Port[COM1_Base + LCR_Offset] := Port[COM1_Base + LCR_Offset] and $7F; {Clear DLAB} GetBaudRate := 115200 div DivisorLatch; end;*) {************************************************} (*FUNCTION CharHexToDec(c: Char): byte; VAR aReturn: byte; a: integer; BEGIN contador:= 0; a:= ord(c); IF (a>=97) THEN aReturn:= a-87 ELSE IF (a>=65) THEN aReturn:= a-55 ELSE IF (a>=48) THEN aReturn:= a-48; CharHexToDec:= aReturn; END;*) {************************************************} PROCEDURE Prepara; BEGIN ASM mov dx,03FBh {Line Control Register} in al,dx and al,$7F {0111_1111b Set DLAB=0} out dx,al END; END; {************************************************} PROCEDURE SendSerial(ch: char); VAR contTimeOut,LSR_Reg: word; BEGIN contTimeOut:= 0; WHILE (contTimeOut< 100) DO BEGIN LSR_Reg:= port[$3FD]; IF (LSR_Reg = $60) THEN contTimeOut:= 1000; contTimeOut:= contTimeOut+1; END; port[$3F8]:= byte(Ch); END; {************************************************} FUNCTION GetLinesFile:word; VAR aReturn: word; BEGIN aReturn:= 0; Reset(gbFile); WHILE NOT EOF(gbFile) DO BEGIN Readln(gbFile); aReturn:= aReturn+1; END; Reset(gbFile); GetLinesFile:= aReturn; END; {************************************************} PROCEDURE Set9600baudios; BEGIN ASM {9600 baudios} mov ah,0 {mov al,11000111b} mov al,11100011b {9600 111 NoParity 00 StopBits 0 CharSize8bits 11} mov dx,0 {COM1} int 14h END; END; {************************************************} PROCEDURE GetParams; VAR code: integer; aux: string; BEGIN gbCadFile:= ParamStr(1); Val(ParamStr(2), gbDelayLine, code); gbDelayLine:= gbDelayLine DIV 55; {18.2 ticks} aux:= ParamStr(3); IF (aux='115200') THEN gbBaud:= 115200 ELSE gbBaud:= 9600; gbNoWait:= false; gbStopArduino:= false; IF (ParamCount>=4) THEN BEGIN IF ParamStr(4)='nowait' THEN gbNoWait:= true; IF (ParamStr(4)='stop') THEN gbStopArduino:= true; END; IF (ParamCount>=5) THEN BEGIN IF ParamStr(5)='nowait' THEN gbNoWait:= true; IF (ParamStr(5)='stop') THEN gbStopArduino:= true; END; END; {************************************************} PROCEDURE ShowHelp; BEGIN writeln(''); writeln('SEND PAD PSX ARDUINO Author: Ackerman'); writeln('----------------------------------------'); writeln('SEND frame.txt delay baud nowait stop'); writeln(''); writeln(' delay milliseconds'); writeln(' baud:'); writeln(' 9600 - 9600 bauds'); writeln(' 115200 - 115200 bauds'); writeln(' nowait: Not wait key press'); writeln(' stop: Start Stop arduino'); writeln(''); writeln('Example:'); writeln(' SEND frame.txt 1050 9600 stop'); END; {************************************************} PROCEDURE EnviaFichero; BEGIN gotoxy(1,1); Write('Delay ',ParamStr(2),' Baud ',gbBaud); IF (gbNoWait = false) THEN BEGIN IF (gbStopArduino = true) THEN BEGIN gotoxy(1,2);Write('ARDUINO STOP'); SendSerial('-'); {Paro ARDUINO} END; gotoxy(1,3);Write('Press key to begin'); WHILE NOT(keypressed) DO; readkey; IF (gbStopArduino = true) THEN BEGIN SendSerial('+'); {Arranco ARDUINO} gotoxy(1,2);Write('ARDUINO START'); gbBeforeTime:= gbCurrentTime; WHILE ((gbCurrentTime - gbBeforeTime) <= gbDelayLine) DO; END; END; Reset(gbFile); while not Eof(gbFile) do begin if keypressed then exit; IF (EOLN(gbFile)=TRUE) THEN BEGIN FOR i:= 1 TO gbCurrentBuffer DO SendSerial(gbBuffer[i]); SendSerial(chr($0D)); SendSerial(chr($0A)); gbCurrentLinea:= gbCurrentLinea+1; gotoxy(1,4); Write('Line ',gbTotalLineas,'/',gbCurrentLinea); gbBeforeTime:= gbCurrentTime; WHILE (((gbCurrentTime - gbBeforeTime) <= gbDelayLine) AND NOT Keypressed) DO; {Delay(1150);} gbCurrentBuffer:= 1; END; Read(gbFile, Ch); gbBuffer[gbCurrentBuffer]:= Ch; gbCurrentBuffer:= gbCurrentBuffer+1; end; END; {************************************************} BEGIN {Delay(2000);} IF (paramCount<3) THEN BEGIN ShowHelp; Exit END; GetParams; gbCurrentBuffer:=1; gbCurrentLinea:=0; Clrscr; IF (gbBaud=9600) THEN Set9600baudios ELSE SetBaudRate(gbBaud); Prepara; {Assign(F,'c:\tp\bin\serie\frame.txt');} Assign(gbFile,gbCadFile); gbTotalLineas:= GetLinesFile; EnviaFichero; Close(gbFile); END. {Sobra} {Write(Ch);} {port[$3F8]:= CharHexToDec(Ch);} {port[$3F8]:= byte(Ch);} {al,0010_0000b ;Use bit 5 to see if THR is empty} {WHILE ((port[$3FD] AND $20) = 0) DO;} (* auxByte:= byte(Ch); asm mov dx,0 mov al,'F' mov ah,1 int 14h end;*) {contador:= contador+1;} {if (contador>=60) then} (*Write(Ch);*) {Delay(1);} (* asm mov dx,03F8h mov ah,0 mov al,'F' out dx,al end;*) { Delay(50);} (* Write(Ch); { Descargar ficheros tipo texto }*) (*asm mov dx,03F8h mov ah,0 mov al,'F' out dx,al end;*)
unit InvModOpTest; interface uses DUnitX.TestFramework, uIntX; type [TestFixture] TInvModTest = class(TObject) public [Test] procedure IntXBothPositive(); end; implementation procedure TInvModTest.IntXBothPositive; var res: TIntX; begin res := TIntX.InvMod(123, 4567); Assert.IsTrue(res = 854); res := TIntX.InvMod(9876, 2457); Assert.IsTrue(res = 0); // zero means modular inverse does not exist. end; initialization TDUnitX.RegisterTestFixture(TInvModTest); end.
unit GoToForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TGoToEntry = class(TForm) MainPanel: TPanel; UrlEdit: TEdit; GoBtn: TBitBtn; CancelButton: TBitBtn; Panel1: TPanel; FormatLabel: TLabel; TitleLabel: TLabel; procedure UrlEditChange(Sender: TObject); private { Private declarations } public function GetUrl(var fUrl : string) : Boolean; end; var GoToEntry: TGoToEntry; implementation {$R *.dfm} function TGoToEntry.GetUrl(var fUrl : string) : Boolean; var fTemp : string; begin GoBtn.Enabled:=FALSE; Result:=ShowModal = mrOk; if Result then begin fUrl:=UrlEdit.Text; end; end; procedure TGoToEntry.UrlEditChange(Sender: TObject); begin GoBtn.enabled:=Trim(UrlEdit.Text) <> ''; end; end.
unit uDBIcons; interface uses System.Generics.Collections, System.SyncObjs, Winapi.Windows, Winapi.CommCtrl, Vcl.ImgList, Dmitry.Graphics.LayeredBitmap, uMemory, uVCLHelpers, uImageListUtils; const IconsCount = 133; const IconsVersion = '1_5'; type TDbKernelArrayIcons = array [1 .. IconsCount] of THandle; type TIconEx = class private FIcon: TLayeredBitmap; FGrayIcon: TLayeredBitmap; FIconIndex: Integer; function GetGrayIcon: TLayeredBitmap; public constructor Create(AIconIndex: Integer); destructor Destroy; override; property IconIndex: Integer read FIconIndex; property GrayIcon: TLayeredBitmap read GetGrayIcon; property Icon: TLayeredBitmap read FIcon; end; TDBIcons = class(TObject) private FIcons: TList<TIconEx>; FSync: TCriticalSection; FImageList: TCustomImageList; FDisabledImageList: TCustomImageList; FHIcons: TDbKernelArrayIcons; function GetIconByIndex(Index: Integer): HIcon; function IconsExByIndex(Index: Integer): TIconEx; public constructor Create; destructor Destroy; override; procedure LoadIcons; property ImageList: TCustomImageList read FImageList; property DisabledImageList: TCustomImageList read FDisabledImageList; property Icons[Index: Integer]: HIcon read GetIconByIndex; default; property IconsEx[index: Integer]: TIconEx read IconsExByIndex; end; function Icons: TDBIcons; implementation var FIcons: TDBIcons = nil; function Icons: TDBIcons; begin if FIcons = nil then FIcons := TDBIcons.Create; Result := FIcons; end; { TIconEx } constructor TIconEx.Create(AIconIndex: Integer); begin FIconIndex := AIconIndex; FGrayIcon := nil; FIcon := TLayeredBitmap.Create; FIcon.LoadFromHIcon(Icons[AIconIndex]); end; destructor TIconEx.Destroy; begin F(FIcon); F(FGrayIcon); inherited; end; function TIconEx.GetGrayIcon: TLayeredBitmap; begin if FGrayIcon = nil then begin FGrayIcon := TLayeredBitmap.Create; FGrayIcon.Load(FIcon); FGrayIcon.GrayScale; end; Result := FGrayIcon; end; { TDBIcons } constructor TDBIcons.Create; var I: Integer; begin FImageList := nil; FDisabledImageList := nil; FSync := TCriticalSection.Create; FIcons := TList<TIconEx>.Create; for I := 1 to IconsCount do FHIcons[I] := 0; end; destructor TDBIcons.Destroy; var I: Integer; begin for I := 1 to IconsCount do DestroyIcon(FHIcons[I]); F(FSync); FreeList(FIcons); F(FImageList); F(FDisabledImageList); inherited; end; function TDBIcons.GetIconByIndex(Index: Integer): HIcon; begin if FHIcons[Index + 1] <> 0 then Exit(FHIcons[Index + 1]); FHIcons[Index + 1] := ImageList_GetIcon(FImageList.Handle, Index, 0); Result := FHIcons[Index + 1]; end; function TDBIcons.IconsExByIndex(Index: Integer): TIconEx; var I: Integer; Item: TIconEx; begin FSync.Enter; try for I := 0 to FIcons.Count - 1 do begin Item := FIcons[I]; if Item.IconIndex = Index then begin Result := Item; Exit; end; end; Item := TIconEx.Create(Index); FIcons.Add(Item); Result := Item; finally FSync.Leave; end; end; procedure TDBIcons.LoadIcons; var I: Integer; Icons: TDbKernelArrayIcons; LB: TLayeredBitmap; function LoadIcon(Instance: HINST; ResName: string): HIcon; begin Result := LoadImage(Instance, PWideChar(ResName), IMAGE_ICON, 16, 16, 0); end; begin FImageList := TSIImageList.Create(nil); FImageList.Width := 16; FImageList.Height := 16; FImageList.ColorDepth := cd32Bit; FDisabledImageList := TSIImageList.Create(nil); FDisabledImageList.Width := 16; FDisabledImageList.Height := 16; FDisabledImageList.ColorDepth := cd32Bit; if not FImageList.LoadFromCache('Images' + IconsVersion) or not FDisabledImageList.LoadFromCache('ImGray' + IconsVersion) then begin Icons[1] := LoadIcon(HInstance,'SHELL'); Icons[2] := LoadIcon(HInstance,'SLIDE_SHOW'); Icons[3] := LoadIcon(HInstance,'REFRESH_THUM'); Icons[4] := LoadIcon(HInstance,'RATING_STAR'); Icons[5] := LoadIcon(HInstance,'DELETE_INFO'); Icons[6] := LoadIcon(HInstance,'DELETE_FILE'); Icons[7] := LoadIcon(HInstance,'COPY_ITEM'); Icons[8] := LoadIcon(HInstance,'PROPERTIES'); Icons[9] := LoadIcon(HInstance,'PRIVATE'); Icons[10] := LoadIcon(HInstance,'COMMON'); Icons[11] := LoadIcon(HInstance,'SEARCH'); Icons[12] := LoadIcon(HInstance,'EXIT'); Icons[13] := LoadIcon(HInstance,'FAVORITE'); Icons[14] := LoadIcon(HInstance,'DESKTOP'); Icons[15] := LoadIcon(HInstance,'RELOAD'); Icons[16] := LoadIcon(HInstance,'NOTES'); Icons[17] := LoadIcon(HInstance,'NOTEPAD'); Icons[18] := LoadIcon(HInstance,'TRATING_1'); Icons[19] := LoadIcon(HInstance,'TRATING_2'); Icons[20] := LoadIcon(HInstance,'TRATING_3'); Icons[21] := LoadIcon(HInstance,'TRATING_4'); Icons[22] := LoadIcon(HInstance,'TRATING_5'); Icons[23] := LoadIcon(HInstance,'Z_NEXT_NORM'); //NEXT //TODO: delete icon 'NEXT' Icons[24] := LoadIcon(HInstance,'Z_PREVIOUS_NORM'); //PREVIOUS //TODO: delete icon 'PREVIOUS' Icons[25] := LoadIcon(HInstance,'TH_NEW'); Icons[26] := LoadIcon(HInstance,'ROTATE_0'); Icons[27] := LoadIcon(HInstance,'ROTATE_90'); Icons[28] := LoadIcon(HInstance,'ROTATE_180'); Icons[29] := LoadIcon(HInstance,'ROTATE_270'); Icons[30] := LoadIcon(HInstance,'PLAY'); Icons[31] := LoadIcon(HInstance,'PAUSE'); Icons[32] := LoadIcon(HInstance,'COPY'); Icons[33] := LoadIcon(HInstance,'PASTE'); Icons[34] := LoadIcon(HInstance,'LOADFROMFILE'); Icons[35] := LoadIcon(HInstance,'SAVETOFILE'); Icons[36] := LoadIcon(HInstance,'PANEL'); Icons[37] := LoadIcon(HInstance,'SELECTALL'); Icons[38] := LoadIcon(HInstance,'OPTIONS'); Icons[39] := LoadIcon(HInstance,'ADMINTOOLS'); Icons[40] := LoadIcon(HInstance,'ADDTODB'); Icons[41] := LoadIcon(HInstance,'HELP'); Icons[42] := LoadIcon(HInstance,'RENAME'); Icons[43] := LoadIcon(HInstance,'EXPLORER'); Icons[44] := LoadIcon(HInstance,'SEND'); Icons[45] := LoadIcon(HInstance,'SENDTO'); Icons[46] := LoadIcon(HInstance,'NEW'); Icons[47] := LoadIcon(HInstance,'NEWDIRECTORY'); Icons[48] := LoadIcon(HInstance,'SHELLPREVIOUS'); Icons[49] := LoadIcon(HInstance,'SHELLNEXT'); Icons[50] := LoadIcon(HInstance,'SHELLUP'); Icons[51] := LoadIcon(HInstance,'KEY'); Icons[52] := LoadIcon(HInstance,'FOLDER'); Icons[53] := LoadIcon(HInstance,'ADDFOLDER'); Icons[54] := LoadIcon(HInstance,'BOX'); Icons[55] := LoadIcon(HInstance,'DIRECTORY'); Icons[56] := LoadIcon(HInstance,'THFOLDER'); Icons[57] := LoadIcon(HInstance,'CUT'); Icons[58] := LoadIcon(HInstance,'NEWWINDOW'); Icons[59] := LoadIcon(HInstance,'ADDSINGLEFILE'); Icons[60] := LoadIcon(HInstance,'MANYFILES'); Icons[61] := LoadIcon(HInstance,'MYCOMPUTER'); Icons[62] := LoadIcon(HInstance,'EXPLORERPANEL'); Icons[63] := LoadIcon(HInstance,'INFOPANEL'); Icons[64] := LoadIcon(HInstance,'SAVEASTABLE'); Icons[65] := LoadIcon(HInstance,'EDITDATE'); Icons[66] := LoadIcon(HInstance,'GROUPS'); Icons[67] := LoadIcon(HInstance,'WALLPAPER'); Icons[68] := LoadIcon(HInstance,'NETWORK'); Icons[69] := LoadIcon(HInstance,'WORKGROUP'); Icons[70] := LoadIcon(HInstance,'COMPUTER'); Icons[71] := LoadIcon(HInstance,'SHARE'); Icons[72] := LoadIcon(HInstance,'Z_ZOOMIN_NORM'); Icons[73] := LoadIcon(HInstance,'Z_ZOOMOUT_NORM'); Icons[74] := LoadIcon(HInstance,'Z_FULLSIZE_NORM'); Icons[75] := LoadIcon(HInstance,'Z_BESTSIZE_NORM'); Icons[76] := LoadIcon(HInstance,'E_MAIL'); Icons[77] := LoadIcon(HInstance,'CRYPTFILE'); Icons[78] := LoadIcon(HInstance,'DECRYPTFILE'); Icons[79] := LoadIcon(HInstance,'PASSWORD'); Icons[80] := LoadIcon(HInstance,'EXEFILE'); Icons[81] := LoadIcon(HInstance,'SIMPLEFILE'); Icons[82] := LoadIcon(HInstance,'CONVERT'); Icons[83] := LoadIcon(HInstance,'RESIZE'); Icons[84] := LoadIcon(HInstance,'REFRESHID'); Icons[85] := LoadIcon(HInstance,'DUPLICAT'); Icons[86] := LoadIcon(HInstance,'DELDUPLICAT'); Icons[87] := LoadIcon(HInstance,'UPDATING'); Icons[88] := LoadIcon(HInstance,'Z_FULLSCREEN_NORM'); Icons[89] := LoadIcon(HInstance,'MYDOCUMENTS'); Icons[90] := LoadIcon(HInstance,'MYPICTURES'); Icons[91] := LoadIcon(HInstance,'DESKTOPLINK'); Icons[92] := LoadIcon(HInstance,'IMEDITOR'); Icons[93] := LoadIcon(HInstance,'OTHER_TOOLS'); Icons[94] := LoadIcon(HInstance,'EXPORT_IMAGES'); Icons[95] := LoadIcon(HInstance,'PRINTER'); Icons[96] := LoadIcon(HInstance,'EXIF'); Icons[97] := LoadIcon(HInstance,'GET_USB'); Icons[98] := LoadIcon(HInstance,'USB'); Icons[99] := LoadIcon(HInstance,'TXTFILE'); Icons[100] := LoadIcon(HInstance,'DOWN'); Icons[101] := LoadIcon(HInstance,'UP'); Icons[102] := LoadIcon(HInstance,'CDROM'); Icons[103] := LoadIcon(HInstance,'TREE'); Icons[104] := LoadIcon(HInstance,'CANCELACTION'); Icons[105] := LoadIcon(HInstance,'XDB'); Icons[106] := LoadIcon(HInstance,'XMDB'); Icons[107] := LoadIcon(HInstance,'SORT'); Icons[108] := LoadIcon(HInstance,'FILTER'); Icons[109] := LoadIcon(HInstance,'CLOCK'); Icons[110] := LoadIcon(HInstance,'ATYPE'); Icons[111] := LoadIcon(HInstance,'MAINICON'); Icons[112] := LoadIcon(HInstance,'APPLY_ACTION'); Icons[113] := LoadIcon(HInstance,'RELOADING'); Icons[114] := LoadIcon(HInstance,'STENO'); Icons[115] := LoadIcon(HInstance,'DESTENO'); Icons[116] := LoadIcon(HInstance,'SPLIT'); Icons[117] := LoadIcon(HInstance,'CD_EXPORT'); Icons[118] := LoadIcon(HInstance,'CD_MAPPING'); Icons[119] := LoadIcon(HInstance,'CD_IMAGE'); Icons[120] := LoadIcon(HInstance,'MAGIC_ROTATE'); Icons[121] := LoadIcon(HInstance,'PERSONS'); Icons[122] := LoadIcon(HInstance,'CAMERA'); Icons[123] := LoadIcon(HInstance,'CROP'); Icons[124] := LoadIcon(HInstance,'PIC_IMPORT'); Icons[125] := LoadIcon(HInstance,'BACKUP'); Icons[126] := LoadIcon(HInstance,'MAP_MARKER'); Icons[127] := LoadIcon(HInstance,'SHELF'); Icons[128] := LoadIcon(HInstance,'PHOTO_SHARE'); Icons[129] := LoadIcon(HInstance,'EDIT_PROFILE'); Icons[130] := LoadIcon(HInstance,'AAA'); Icons[131] := LoadIcon(HInstance,'LINK'); Icons[132] := LoadIcon(HInstance,'VIEW_COUNT'); Icons[133] := LoadIcon(HInstance,'TRAIN'); //disabled items are bad for I := 1 to IconsCount do ImageList_ReplaceIcon(FImageList.Handle, -1, Icons[I]); for I := 1 to IconsCount do begin LB := TLayeredBitmap.Create; try LB.LoadFromHIcon(Icons[I]); LB.GrayScale; ImageList_Add(FDisabledImageList.Handle, LB.Handle, 0); finally F(LB); end; end; FImageList.SaveToCache('Images' + IconsVersion); FDisabledImageList.SaveToCache('ImGray' + IconsVersion); end; end; initialization finalization F(FIcons); end.
unit uFrmTrackPackage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ADODB, Mask, SuperComboADO; type TFrmTrackPackage = class(TFrmParentAll) pnlSearchSH: TPanel; Label1: TLabel; lbSelection: TLabel; lbTrack: TLabel; edtInvoiceNum: TEdit; btnSearchSH: TButton; cbSearchFor: TComboBox; edtParamText: TEdit; edtTracNum: TEdit; gdTrackPackge: TcxGrid; gdTrackPackgeDBTableView: TcxGridDBTableView; gdTrackPackgeLevel: TcxGridLevel; Label2: TLabel; quSHInvoice: TADODataSet; quSHInvoiceIDPreSale: TIntegerField; quSHInvoicePreSaleDate: TDateTimeField; quSHInvoiceSaleCode: TStringField; quSHInvoiceInvoiceCode: TStringField; quSHInvoiceInvoiceDate: TDateTimeField; quSHInvoiceNote: TStringField; quSHInvoicePessoaFirstName: TStringField; quSHInvoicePessoaLastName: TStringField; quSHInvoicePessoa: TStringField; quSHInvoiceIDPessoa: TIntegerField; quSHInvoiceTotInvoice: TBCDField; quSHInvoiceShipDate: TDateTimeField; quSHInvoiceTracking: TStringField; quSHInvoiceIDDeliverType: TIntegerField; quSHInvoiceAddressName: TStringField; quSHInvoiceAddress: TStringField; quSHInvoiceCity: TStringField; quSHInvoiceZIP: TStringField; quSHInvoiceIDEstado: TStringField; quSHInvoiceIDPais: TIntegerField; quSHInvoiceShipVia: TStringField; dsSHInvoice: TDataSource; gdTrackPackgeDBTableViewInvoiceCode: TcxGridDBColumn; gdTrackPackgeDBTableViewInvoiceDate: TcxGridDBColumn; gdTrackPackgeDBTableViewPessoa: TcxGridDBColumn; gdTrackPackgeDBTableViewTotInvoice: TcxGridDBColumn; gdTrackPackgeDBTableViewShipDate: TcxGridDBColumn; gdTrackPackgeDBTableViewTracking: TcxGridDBColumn; gdTrackPackgeDBTableViewAddressName: TcxGridDBColumn; gdTrackPackgeDBTableViewAddress: TcxGridDBColumn; gdTrackPackgeDBTableViewCity: TcxGridDBColumn; gdTrackPackgeDBTableViewZIP: TcxGridDBColumn; gdTrackPackgeDBTableViewIDEstado: TcxGridDBColumn; gdTrackPackgeDBTableViewIDPais: TcxGridDBColumn; gdTrackPackgeDBTableViewShipVia: TcxGridDBColumn; quSHInvoiceWebsite: TStringField; gdTrackPackgeDBTableViewWebsite: TcxGridDBColumn; scDeliverType: TSuperComboADO; btnDeliverClear: TButton; strepPredefined: TcxStyleRepository; cxWebLink: TcxStyle; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btCloseClick(Sender: TObject); procedure btnSearchSHClick(Sender: TObject); procedure btnDeliverClearClick(Sender: TObject); procedure gdTrackPackgeDBTableViewCellClick( Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); private { Private declarations } public function Start:Boolean; end; implementation uses uDM, uDMGlobal, uSystemConst, uCharFunctions, uSqlFunctions, uWebFunctions, ClipBrd; {$R *.dfm} { TFrmTrackPackage } function TFrmTrackPackage.Start: Boolean; begin ShowModal; end; procedure TFrmTrackPackage.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TFrmTrackPackage.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmTrackPackage.btnSearchSHClick(Sender: TObject); var sSQL, sWhere, sField, sName : String; begin inherited; sSQL := quSHInvoice.CommandText; sWhere := 'P.IDTipoPessoa = 1 AND I.IDInvoice IS NOT NULL AND I.Canceled = 0 '; if Trim(edtInvoiceNum.Text) <> '' then sWhere := sWhere + ' AND I.InvoiceCode like '+ QuotedStr('%'+edtInvoiceNum.Text+'%'); if Trim(edtParamText.Text) <> '' then begin Case cbSearchFor.ItemIndex of 0 : sField := 'P.Pessoa'; 1 : sField := 'P.PessoaFirstName'; 2 : sField := 'P.PessoaLastName'; 3 : sField := 'P.CustomerCard'; 4 : sField := 'P.Telefone'; 5 : sField := 'P.CEP'; end; sWhere := sWhere + ' AND ' + sField + ' Like ' + QuotedStr('%'+edtParamText.Text+'%'); end; if Trim(edtTracNum.Text) <> '' then sWhere := sWhere + ' AND S.Tracking like '+ QuotedStr('%'+edtTracNum.Text+'%'); if (scDeliverType.LookUpValue <> '') then sWhere := sWhere + ' AND D.IDDeliverType = '+ scDeliverType.LookUpValue; quSHInvoice.Close; quSHInvoice.CommandText := ChangeWhereClause(quSHInvoice.CommandText, sWhere, True); quSHInvoice.Open; end; procedure TFrmTrackPackage.btnDeliverClearClick(Sender: TObject); begin inherited; scDeliverType.LookUpValue := ''; end; procedure TFrmTrackPackage.gdTrackPackgeDBTableViewCellClick( Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; if ACellViewInfo.Item.Name = 'gdTrackPackgeDBTableViewWebsite' then if (ACellViewInfo.GridRecord.Values[gdTrackPackgeDBTableViewWebsite.Index] <> Null) then begin Clipboard.AsText := ACellViewInfo.GridRecord.Values[gdTrackPackgeDBTableViewTracking.Index]; OpenURL(ACellViewInfo.GridRecord.Values[gdTrackPackgeDBTableViewWebsite.Index]); end; end; end.
unit Nathan.JWT.Builder.Impl; interface uses Nathan.JWT.Service, Nathan.JWT.Builder.Intf; {$M+} type TNathanJwtWrapperBuilder = class(TInterfacedObject, INathanJwtWrapperBuilder) strict private class var FInstance: INathanJwtWrapperBuilder; FSecretKey: string; FPayload: string; public class function CreateInstance(): INathanJwtWrapperBuilder; function WithSecretKey(const Value: string): INathanJwtWrapperBuilder; function WithPayload(const Value: string): INathanJwtWrapperBuilder; function Build(): INathanJwtWrapper; end; {$M-} implementation uses System.SysUtils; class function TNathanJwtWrapperBuilder.CreateInstance: INathanJwtWrapperBuilder; begin if (not Assigned(FInstance)) then FInstance := TNathanJwtWrapperBuilder.Create(); Result := FInstance; end; function TNathanJwtWrapperBuilder.WithSecretKey(const Value: string): INathanJwtWrapperBuilder; begin FSecretKey := Value; Result := Self; end; function TNathanJwtWrapperBuilder.WithPayload(const Value: string): INathanJwtWrapperBuilder; begin FPayload := Value; Result := Self; end; function TNathanJwtWrapperBuilder.Build(): INathanJwtWrapper; begin Result := TNathanJwtWrapper.Create(); if (not FSecretKey.IsEmpty) then Result.Key := FSecretKey; if (not FPayload.IsEmpty) then Result.Payload := FPayload; end; end.
unit WR_PTX_TDXT_Color; interface uses Math, KromUtils; procedure DXT_RGB_Encode(R1,R2,R3,R4:Pointer; out OutDat:int64; out RMS:array of single); procedure DXT_RGB_Decode(InDat:Pointer; out OutDat:array of byte); implementation function ColTo16(c1,c2,c3:byte):word; begin if (c3 mod 8)>3 then Result := Math.min((c3 shr 3)+1,31) else Result:=(c3 shr 3); if (c2 mod 4)>1 then Result := Result+Math.min((c2 shr 2)+1,63)shl 5 else Result:=Result+(c2 shr 2)shl 5; if (c1 mod 8)>3 then Result := Result+Math.min((c1 shr 3)+1,31)shl 11 else Result:=Result+(c1 shr 3)shl 11; end; procedure ColFrom16(m:word; out c1,c2,c3:byte); begin c1 := m div 2048 * 8; c2 := m div 32 mod 64 * 4; c3 := m mod 32 * 8; end; procedure DXT_RGB_Encode(R1,R2,R3,R4:Pointer; out OutDat:int64; out RMS:array of single); var i,k,h:integer; Col:array[1..16,1..3]of byte; //Input colors c0:array[1..4,1..3]of byte; // c2:array[1..4,1..3]of byte; Crms:array[1..48]of byte; im:array[1..16]of word; m1,m2:word; tRMS:array[1..4]of integer; Trial:array[1..6]of record Dat:int64; tRMS:integer; end; procedure MakeBlock(id,mm1,mm2:word); var i:integer; begin with Trial[id] do begin Dat:=mm1+(mm2 shl 16); for i:=1 to 16 do Dat:=Dat+int64( int64(im[i] AND $03) shl ( 32 + (i-1)*2 )); end; end; begin FillChar(im,SizeOf(im),#0); FillChar(Trial,SizeOf(Trial),#0); FillChar(tRMS,SizeOf(tRMS),#0); for i:=0 to 3 do for h:=1 to 3 do col[i+1,h]:=byte(Char(Pointer((Integer(R1)+i*4+h-1))^)); for i:=0 to 3 do for h:=1 to 3 do col[i+1+4,h]:=byte(Char(Pointer((Integer(R2)+i*4+h-1))^)); for i:=0 to 3 do for h:=1 to 3 do col[i+1+8,h]:=byte(Char(Pointer((Integer(R3)+i*4+h-1))^)); for i:=0 to 3 do for h:=1 to 3 do col[i+1+12,h]:=byte(Char(Pointer((Integer(R4)+i*4+h-1))^)); for i:=1 to 16 do begin RMS[1] := 0; RMS[2] := 0; RMS[3] := 0; end; //Find minmax pair from existing colors; tRMS[1] := 65535; tRMS[2] := 0; for i:=1 to 16 do for h:=i+1 to 16 do begin if tRMS[2] <= GetLengthSQR(col[i,1]-col[h,1], col[i,2]-col[h,2], col[i,3]-col[h,3]) then begin tRMS[2] := GetLengthSQR(col[i,1]-col[h,1], col[i,2]-col[h,2], col[i,3]-col[h,3]); if ColTo16(col[i,1], col[i,2], col[i,3]) <= ColTo16(col[h,1], col[h,2], col[h,3]) then begin im[1] := i; im[2] := h; end else begin im[1] := h; im[2] := i; end; end; end; m1 := ColTo16(col[im[2],1], col[im[2],2], col[im[2],3]); m2 := ColTo16(col[im[1],1], col[im[1],2], col[im[1],3]); //Find another minmax pair from existing colors; { tRMS[1]:=65535; tRMS[2]:=0; for i:=1 to 16 do for h:=i+1 to 16 do if (im[1]<>i)and(im[2]<>h)and(im[2]<>i)and(im[1]<>h) then begin if tRMS[2]<=round(GetLength(col[i,1]-col[h,1],col[i,2]-col[h,2],col[i,3]-col[h,3])) then begin tRMS[2]:=round(GetLength(col[i,1]-col[h,1],col[i,2]-col[h,2],col[i,3]-col[h,3])); if ColTo16(col[i,1],col[i,2],col[i,3])<=ColTo16(col[h,1],col[h,2],col[h,3]) then begin im[3]:=i; im[4]:=h; end else begin im[3]:=h; im[4]:=i; end; end; end; m1:=ColTo16((col[im[2],1]+col[im[4],1])div 2,(col[im[2],2]+col[im[4],2])div 2,(col[im[2],3]+col[im[4],3])div 2); m2:=ColTo16((col[im[1],1]+col[im[3],1])div 2,(col[im[1],2]+col[im[3],2])div 2,(col[im[1],3]+col[im[3],3])div 2); //} {//Get minmax pair by luminance, produces rather poor results tRMS[1]:=65535; tRMS[2]:=0; for i:=1 to 16 do begin if tRMS[1]>=(col[i,1]*3+col[i,2]*6+col[i,3]*1) then begin tRMS[1]:=(col[i,1]*3+col[i,2]*6+col[i,3]*1); im[2]:=i; end; if tRMS[2]<=(col[i,1]*3+col[i,2]*6+col[i,3]*1) then begin tRMS[2]:=(col[i,1]*3+col[i,2]*6+col[i,3]*1); im[1]:=i; end; end; //} {//Find a middlepoint and build endpoints from it - incomplete idea FillChar(c1[1],SizeOf(c1[1]),#0); FillChar(c1[4],SizeOf(c1[4]),#255); for i:=1 to 16 do begin c1[1,1]:=max(c1[1,1],col[i,1]); c1[1,2]:=max(c1[1,2],col[i,2]); c1[1,3]:=max(c1[1,3],col[i,3]); c1[4,1]:=min(c1[4,1],col[i,1]); c1[4,2]:=min(c1[4,2],col[i,2]); c1[4,3]:=min(c1[4,3],col[i,3]); end; c1[2,1]:=(c1[1,1]+c1[4,1])div 2; c1[2,2]:=(c1[1,2]+c1[4,2])div 2; c1[2,3]:=(c1[1,3]+c1[4,3])div 2; } //for i:=1 to 16 do begin // if col[i,1] //} //These are input colors, 1=max and 4=min c0[1,1] := col[im[2],1]; c0[1,2] := col[im[2],2]; c0[1,3] := col[im[2],3]; c0[4,1] := col[im[1],1]; c0[4,2] := col[im[1],2]; c0[4,3] := col[im[1],3]; //Case1 Straight case, use 2 interpolated colors 1/3 and 2/3 ColFrom16(m1,c2[1,1],c2[1,2],c2[1,3]); ColFrom16(m2,c2[4,1],c2[4,2],c2[4,3]); c2[2,1]:=mix(c2[4,1],c2[1,1],1/3); c2[2,2]:=mix(c2[4,2],c2[1,2],1/3); c2[2,3]:=mix(c2[4,3],c2[1,3],1/3); c2[3,1]:=mix(c2[4,1],c2[1,1],2/3); c2[3,2]:=mix(c2[4,2],c2[1,2],2/3); c2[3,3]:=mix(c2[4,3],c2[1,3],2/3); for i:=1 to 16 do begin for h:=1 to 4 do tRMS[h]:=GetLengthSQR(col[i,1]-c2[h,1],col[i,2]-c2[h,2],col[i,3]-c2[h,3]); if tRMS[1]<tRMS[2] then h:=1 else h:=2; if tRMS[h]>tRMS[3] then h:=3; if tRMS[h]>tRMS[4] then h:=4; if h=1 then im[i]:=0; if h=2 then im[i]:=2; if h=3 then im[i]:=3; if h=4 then im[i]:=1; inc(Trial[1].tRMS,tRMS[h]); end; MakeBlock(1,m1,m2); //Case2 Straight case, use 1 interpolated color 1/2, other color should be avoided (it's black?) c2[2,1]:=(c2[1,1]+c2[4,1])div 2; c2[2,2]:=(c2[1,2]+c2[4,2])div 2; c2[2,3]:=(c2[1,3]+c2[4,3])div 2; for i:=1 to 16 do begin for h:=1 to 4 do tRMS[h]:=GetLengthSQR(col[i,1]-c2[h,1],col[i,2]-c2[h,2],col[i,3]-c2[h,3]); if tRMS[1]<tRMS[2] then h:=1 else h:=2; if tRMS[h]>tRMS[4]{=tRMS[3]} then h:=4; if h=1 then im[i]:=1; if h=2 then im[i]:=2; if h=3 then im[i]:=3; if h=4 then im[i]:=0; inc(Trial[2].tRMS,tRMS[h]); end; MakeBlock(2,m2,m1); //Case3 Enlarge range one direction to get better match for 1/3 or 2/3 interpolation for k:=0 to 1 do begin if k=0 then begin c2[1,1]:=EnsureRange(c0[1,1]+(c0[1,1]-c0[4,1])div 2,0,255); c2[1,2]:=EnsureRange(c0[1,2]+(c0[1,2]-c0[4,2])div 2,0,255); c2[1,3]:=EnsureRange(c0[1,3]+(c0[1,3]-c0[4,3])div 2,0,255); m1:=ColTo16(c2[1,1],c2[1,2],c2[1,3]); m2:=ColTo16(c0[4,1],c0[4,2],c0[4,3]); if m1<m2 then SwapInt(m1,m2); ColFrom16(m1,c2[1,1],c2[1,2],c2[1,3]); ColFrom16(m2,c2[4,1],c2[4,2],c2[4,3]); end; if k=1 then begin c2[4,1]:=EnsureRange(c0[4,1]-(c0[1,1]-c0[4,1])div 2,0,255); c2[4,2]:=EnsureRange(c0[4,2]-(c0[1,2]-c0[4,2])div 2,0,255); c2[4,3]:=EnsureRange(c0[4,3]-(c0[1,3]-c0[4,3])div 2,0,255); m1:=ColTo16(c0[1,1],c0[1,2],c0[1,3]); m2:=ColTo16(c2[4,1],c2[4,2],c2[4,3]); if m1<m2 then SwapInt(m1,m2); ColFrom16(m1,c2[1,1],c2[1,2],c2[1,3]); ColFrom16(m2,c2[4,1],c2[4,2],c2[4,3]); end; c2[2,1]:=mix(c2[4,1],c2[1,1],1/3); c2[2,2]:=mix(c2[4,2],c2[1,2],1/3); c2[2,3]:=mix(c2[4,3],c2[1,3],1/3); c2[3,1]:=mix(c2[4,1],c2[1,1],2/3); c2[3,2]:=mix(c2[4,2],c2[1,2],2/3); c2[3,3]:=mix(c2[4,3],c2[1,3],2/3); for i:=1 to 16 do begin for h:=1 to 4 do tRMS[h]:=GetLengthSQR(col[i,1]-c2[h,1],col[i,2]-c2[h,2],col[i,3]-c2[h,3]); if tRMS[1]<tRMS[2] then h:=1 else h:=2; if tRMS[h]>tRMS[3] then h:=3; if tRMS[h]>tRMS[4] then h:=4; if h=1 then im[i]:=0; if h=2 then im[i]:=2; if h=3 then im[i]:=3; if h=4 then im[i]:=1; inc(Trial[3+k].tRMS,tRMS[h]); end; MakeBlock(3+k,m1,m2); end; //Case4 Compute average block color and try to match it either by 1 or 2 interpolations, best for plaincolor matching // possibly can be split into R-G-B matching, but that involves triple the code.. tRMS[1]:=0; tRMS[2]:=0; tRMS[3]:=0; for i:=1 to 16 do begin inc(tRMS[1],col[i,1]); inc(tRMS[2],col[i,2]); inc(tRMS[3],col[i,3]); end; m1:=ColTo16( //rounded one step up EnsureRange((round(tRMS[1]/16)shr 3+1) * 8,0,255), EnsureRange((round(tRMS[2]/16)shr 2+1) * 4,0,255), EnsureRange((round(tRMS[3]/16)shr 3+1) * 8,0,255)); ColFrom16(m1,c2[1,1],c2[1,2],c2[1,3]); m2:=ColTo16( //rounded one step down EnsureRange((round(tRMS[1]/16)shr 3) * 8,0,255), EnsureRange((round(tRMS[2]/16)shr 2) * 4,0,255), EnsureRange((round(tRMS[3]/16)shr 3) * 8,0,255)); ColFrom16(m2,c2[4,1],c2[4,2],c2[4,3]); c2[2,1]:=(c2[4,1]+c2[1,1])div 2; c2[2,2]:=(c2[4,2]+c2[1,2])div 2; c2[2,3]:=(c2[4,3]+c2[1,3])div 2; for i:=1 to 16 do begin for h:=1 to 4 do tRMS[h]:=GetLengthSQR(col[i,1]-c2[h,1],col[i,2]-c2[h,2],col[i,3]-c2[h,3]); if tRMS[1]<tRMS[2] then h:=1 else h:=2; if tRMS[h]>tRMS[4]{=tRMS[3]} then h:=4; if h=1 then im[i]:=1; if h=2 then im[i]:=2; if h=3 then im[i]:=3; if h=4 then im[i]:=0; inc(Trial[5].tRMS,tRMS[h]); end; MakeBlock(5, m2, m1); c2[2,1] := mix(c2[4,1],c2[1,1],1/3); c2[2,2] := mix(c2[4,2],c2[1,2],1/3); c2[2,3] := mix(c2[4,3],c2[1,3],1/3); c2[3,1] := mix(c2[4,1],c2[1,1],2/3); c2[3,2] := mix(c2[4,2],c2[1,2],2/3); c2[3,3] := mix(c2[4,3],c2[1,3],2/3); for i:=1 to 16 do begin for h:=1 to 4 do tRMS[h]:=GetLengthSQR(col[i,1]-c2[h,1],col[i,2]-c2[h,2],col[i,3]-c2[h,3]); if tRMS[1]<tRMS[2] then h := 1 else h := 2; if tRMS[h]>tRMS[3] then h := 3; if tRMS[h]>tRMS[4] then h := 4; if h=1 then im[i] := 0; if h=2 then im[i] := 2; if h=3 then im[i] := 3; if h=4 then im[i] := 1; inc(Trial[6].tRMS,tRMS[h]); end; MakeBlock(6, m1, m2); // Trial[1].tRMS:=9999999; // Trial[2].tRMS:=9999999; // Trial[3].tRMS:=9999999; // Trial[4].tRMS:=9999999; // Trial[5].tRMS:=9999999; // Trial[6].tRMS:=9999999; { Trial[1].Dat:=ColTo16(255,0,0); //Red Trial[2].Dat:=ColTo16(255,255,0); //Yellow Trial[3].Dat:=ColTo16(0,255,0); //Green Trial[4].Dat:=ColTo16(0,255,255); //Cyan Trial[5].Dat:=ColTo16(0,0,255); //Blue Trial[6].Dat:=ColTo16(255,0,255); //Magenta} //Choose the result with least RMS error k := 99999; for i:=1 to 6 do if k>Trial[i].tRMS then begin k := Trial[i].tRMS; h := i; end; OutDat := Trial[h].Dat; // if Trial[h].tRMS>100 then // OutDat:=1023; DXT_RGB_Decode(@OutDat,Crms); //Carry out RMS error value for i:=1 to 16 do RMS[0] := RMS[0] + sqr(col[i,1] - Crms[i*3-2]); for i:=1 to 16 do RMS[1] := RMS[1] + sqr(col[i,2] - Crms[i*3-1]); for i:=1 to 16 do RMS[2] := RMS[2] + sqr(col[i,3] - Crms[i*3]); end; procedure DXT_RGB_Decode(InDat:Pointer; out OutDat:array of byte); var i,h,x:integer; c:array[1..8]of byte; Colors:array[1..4,1..3]of word; //4colors in R,G,B begin for i := 1 to 8 do //cast into array of byte c[i] := byte(Char(Pointer((cardinal(InDat)+i-1))^)); //Acquire min/max colors Colors[1,1] := (c[2]div 8)*8; //R1 Colors[1,2] := (c[2]mod 8)*32+(c[1]div 32)*4;//G1 Colors[1,3] := (c[1]mod 32)*8; //B1 Colors[2,1] := (c[4]div 8)*8; //R2 Colors[2,2] := (c[4]mod 8)*32+(c[3]div 32)*4;//G2 Colors[2,3] := (c[3]mod 32)*8; //B2 //Acquire average colors if (c[1]+c[2]*256) > (c[3]+c[4]*256) then begin Colors[3,1] := round((Colors[2,1] + Colors[1,1]*2)/3); Colors[3,2] := round((Colors[2,2] + Colors[1,2]*2)/3); Colors[3,3] := round((Colors[2,3] + Colors[1,3]*2)/3); Colors[4,1] := round((Colors[2,1]*2 + Colors[1,1])/3); Colors[4,2] := round((Colors[2,2]*2 + Colors[1,2])/3); Colors[4,3] := round((Colors[2,3]*2 + Colors[1,3])/3); end else begin Colors[3,1] := round((Colors[2,1] + Colors[1,1])/2); Colors[4,1] := 255; //This is in fact 1bit transparent Colors[3,2] := round((Colors[2,2] + Colors[1,2])/2); Colors[4,2] := 0; //but let's show it as purple Colors[3,3] := round((Colors[2,3] + Colors[1,3])/2); Colors[4,3] := 255; end; for h:=1 to 16 do begin x:=0; if h mod 4=1 then x := ord(c[1+(h-1)div 4+4])mod 4; //1,5, 9,13 if h mod 4=2 then x := (ord(c[1+(h-1)div 4+4])mod 16)div 4; //2,6,10,14 if h mod 4=3 then x := (ord(c[1+(h-1)div 4+4])mod 64)div 16;//3,7,11,15 if h mod 4=0 then x := ord(c[1+(h-1)div 4+4])div 64; //4,8,12,16 OutDat[(h-1)*3+0] := Colors[x+1,1]; //R OutDat[(h-1)*3+1] := Colors[x+1,2]; //G OutDat[(h-1)*3+2] := Colors[x+1,3]; //B end; end; end.
(*************************************************** * COMMANDER 64 (c)2018 by ir. Marc Dendooven * * El Dendo's Commodore 64 emulator Version II * * This file contains the cycle exact cpu emulation * ***************************************************) unit cpu; //------------------------------------------------- interface procedure cpu_execute_one_cycle; //------------------------------------------------- implementation uses memio; var A,X,Y,S: byte; IR: byte = 0; PC: word = 0; CC: 1..2 = 1; procedure error (s: string); begin writeln('--------------------------------------'); writeln('emulator error: ',s); writeln('PC=',hexstr(PC-1,4),' IR=',hexstr(IR,2)); writeln; writeln('Execution has been ended'); writeln('push return to exit'); writeln('--------------------------------------'); readln; halt end; procedure fetch_opcode_inc_PC; begin IR := peek(PC); inc(PC); inc(CC) end; procedure cycle0; begin writeln('instruction 00'); CC := 1 end; procedure cycle1; begin writeln('instruction 01'); CC := 1 end; procedure cycle2; begin writeln('instruction 02'); CC := 1 end; procedure err; begin error('unknown instruction ') end; type instruction = array[1..2] of procedure; const instructionSet: array[0..3] of instruction = ( //00 instr0 (@fetch_opcode_inc_PC, @cycle0), // 01 instr1 (@fetch_opcode_inc_PC, @cycle1), // 02 instr2 (@fetch_opcode_inc_PC, @cycle2), // 03 unknown instruction (@fetch_opcode_inc_PC, @err) ); //--------------------------------------------------------------------- procedure cpu_execute_one_cycle; begin instructionSet[IR,CC] end; end.
unit trl_ipersist; {$mode delphi}{$H+} interface uses Classes, SysUtils, trl_irttibroker; const cMemoStringType = 'TMemoString'; cIDStringType = 'TIDString'; type TMemoString = type string; TIDString = type string; { IPersistMoniker } IPersistMoniker = interface ['{84B31F57-E9FB-47C8-A4D5-2BB150985A9C}'] function GetData: IRBData; procedure SetData(AValue: IRBData); property Data: IRBData read GetData write SetData; end; { IPersistMany } IPersistMany = interface ['{2C47DA7F-FEA7-4E37-965C-82176B12A721}'] function GetAsInterface(AIndex: integer): IUnknown; function GetAsPersistData(AIndex: integer): IRBData; function GetAsObject(AIndex: integer): TObject; function GetAsPersistDataClass: IRBData; function GetAsPersist(AIndex: integer): string; function GetAsString(AIndex: integer): string; function GetClassName: string; function GetCount: integer; function GetEnumName(AValue: integer): string; function GetEnumNameCount: integer; function GetIsInterface: Boolean; function GetIsObject: Boolean; function GetIsMemo: Boolean; function GetIsID: Boolean; procedure SetAsInterface(AIndex: integer; AValue: IUnknown); procedure SetAsPersistData(AIndex: integer; AValue: IRBData); procedure SetAsObject(AIndex: integer; AValue: TObject); procedure SetCount(AValue: integer); procedure SetAsPersist(AIndex: integer; AValue: string); procedure SetAsString(AIndex: integer; AValue: string); property Count: integer read GetCount write SetCount; property AsPersist[AIndex: integer]: string read GetAsPersist write SetAsPersist; property AsString[AIndex: integer]: string read GetAsString write SetAsString; property AsObject[AIndex: integer]: TObject read GetAsObject write SetAsObject; property AsPersistData[AIndex: integer]: IRBData read GetAsPersistData write SetAsPersistData; property AsPersistDataClass: IRBData read GetAsPersistDataClass; property AsInterface[AIndex: integer]: IUnknown read GetAsInterface write SetAsInterface; procedure Delete(AIndex: integer); property EnumNameCount: integer read GetEnumNameCount; property EnumName[AValue: integer]: string read GetEnumName; property IsObject: Boolean read GetIsObject; property IsInterface: Boolean read GetIsInterface; property IsMemo: Boolean read GetIsMemo; property IsID: Boolean read GetIsID; property ClassName: string read GetClassName; end; { IPersistManyItems } IPersistManyItems<TItem> = interface(IPersistMany) ['{A08640F4-019D-4F1B-BAC2-6894CA5E0570}'] function GetItem(AIndex: integer): TItem; procedure SetItem(AIndex: integer; AValue: TItem); property Item[AIndex: integer]: TItem read GetItem write SetItem; default; end; { IPersistManyIntegers } IPersistManyIntegers = interface(IPersistManyItems<integer>) ['{E50D2C49-26BF-4ABB-92B9-7888A63B19A5}'] end; { IPersistManyStrings } IPersistManyStrings = interface(IPersistManyItems<string>) ['{E50D2C49-26BF-4ABB-92B9-7888A63B19A5}'] end; { TSID } TSID = record private fSID: integer; public procedure Clear; function IsClear: Boolean; class operator =(a, b: TSID): Boolean; class operator :=(a: integer): TSID; class operator :=(a: widestring): TSID; class operator Explicit(a: TSID): string; class operator Implicit(a: TSID): string; class operator Explicit(a: TSID): widestring; class operator Implicit(a: TSID): widestring; class operator Add(const A: string; const B: TSID): string; end; { ISIDList } ISIDList = interface ['{0F1BB78E-6627-43CC-8145-65E81D67AB6C}'] function GetCount: integer; function GetItems(AIndex: integer): TSID; procedure SetCount(AValue: integer); procedure SetItems(AIndex: integer; AValue: TSID); property Count: integer read GetCount write SetCount; property Items[AIndex: integer]: TSID read GetItems write SetItems; default; end; { IPersistFactory } IPersistFactory = interface ['{66F2248D-87D0-49D8-ACBF-DA19CC862A11}'] function CreateObject(const AClass: string): IRBData; function Create(const AClass: string; const AID: string = ''): TObject; overload; function Create(AInterface: TGUID; const AID: string = ''): IUnknown; overload; end; { IPersistStore } IPersistStore = interface ['{C306CCBC-5BF5-4109-969F-FFC96D6DDEF3}'] function New(const AClass: string): IRBData; procedure Load(AData: IRBData); overload; procedure Save(AData: IRBData); procedure Delete(AData: IRBData); function Load(const ASID: TSID): IRBData; overload; function GetSID(const AData: IRBData): TSID; property SID[const AData: IRBData]: TSID read GetSID; procedure Open; overload; procedure Open(const AFile: string); overload; procedure Open(const AStream: TStream); overload; procedure Close; overload; procedure Close(const AStream: TStream); overload; procedure Flush; end; { IPersistRef } IPersistRef = interface ['{9602E374-F6CE-4D2A-BB31-E2224B4BACE5}'] function GetClassName: string; function GetData: IRBData; function GetSID: TSID; function GetStore: IPersistStore; procedure SetClassName(AValue: string); procedure SetData(AValue: IRBData); procedure SetSID(AValue: TSID); procedure SetStore(AValue: IPersistStore); property Data: IRBData read GetData write SetData; property Store: IPersistStore read GetStore write SetStore; property SID: TSID read GetSID write SetSID; property ClassName: string read GetClassName write SetClassName; end; IPersistRef<TItem> = interface(IPersistRef) ['{62132B90-58C8-4E61-AE6A-D00953BAA7BD}'] function GetItem: TItem; procedure SetItem(AValue: TItem); property Item: TItem read GetItem write SetItem; end; { IPersistRefList } IPersistRefList = interface ['{0264926F-FC8E-4421-9001-0DD67E0E7373}'] function GetCount: integer; function GetData(AIndex: integer): IRBData; function GetItems(AIndex: integer): IPersistRef; function IndexOfData(const AData: IRBData): integer; procedure SetCount(AValue: integer); procedure SetItems(AIndex: integer; AValue: IPersistRef); procedure Delete(AIndex: integer); procedure Insert(AIndex: integer; const AData: IPersistRef); property Count: integer read GetCount write SetCount; property Items[AIndex: integer]: IPersistRef read GetItems write SetItems; default; property Data[AIndex: integer]: IRBData read GetData; end; { IPersistQuery } IPersistQuery = interface ['{4A8B3A3E-562B-4E61-9513-8DFBC3CB7BC6}'] function SelectClass(const AClass: string): IPersistRefList; end; IPersistStoreDevice = interface ['{32674407-3D99-4BF9-8BBE-99DABA186655}'] procedure Load(const ASID: TSID; AData: IRBData); procedure Save(const ASID: TSID; AData: IRBData); procedure Delete(const ASID: TSID); //function GetSIDSForClass(const AClass: string): array of ASID; function NewSID: TSID; function GetSIDClass(const ASID: TSID): string; procedure Open; overload; procedure Open(const AFile: string); overload; procedure Open(const AStream: TStream); overload; procedure Close; overload; procedure Close(const AStream: TStream); overload; procedure Flush; function GetSIDs(const AClass: string): ISIDList; end; { IPersistManyRefs } IPersistManyRefs = interface(IPersistManyItems<IPersistRef>) ['{55766680-2912-4680-8B30-8908573E263C}'] function GetFactory: IPersistFactory; procedure SetFactory(AValue: IPersistFactory); property Factory: IPersistFactory read GetFactory write SetFactory; end; IPersistManyRefs<TItem: TObject> = interface(IPersistManyRefs) ['{A276B6FA-D582-4071-90A0-EF2AFE861152}'] end; implementation { TSID } procedure TSID.Clear; begin fSID := -1; end; function TSID.IsClear: Boolean; begin Result := fSID = -1; end; class operator TSID. = (a, b: TSID): Boolean; begin Result := a.fSID = b.fSID; end; class operator TSID. := (a: integer): TSID; begin Result.fSID := a; end; class operator TSID. := (a: widestring): TSID; begin Result.fSID := StrToInt(a); end; class operator TSID.Explicit(a: TSID): string; begin Result := IntToStr(a.fSID); end; class operator TSID.Implicit(a: TSID): string; begin Result := IntToStr(a.fSID); end; class operator TSID.Explicit(a: TSID): widestring; begin Result := IntToStr(a.fSID); end; class operator TSID.Implicit(a: TSID): widestring; begin Result := IntToStr(a.fSID); end; class operator TSID.Add(const A: string; const B: TSID): string; begin Result := A + string(B); end; end.
unit uSuperUser; {$mode objfpc}{$H+} interface procedure WaitProcess(Process: UIntPtr); function AdministratorPrivileges: Boolean; inline; function TerminateProcess(Process: UIntPtr): Boolean; function ElevationRequired(LastError: Integer = 0): Boolean; function ExecCmdAdmin(const Exe: String; Args: array of String; sStartPath: String = ''): UIntPtr; implementation uses SysUtils {$IF DEFINED(MSWINDOWS)} , Types, Windows, DCOSUtils, ShellApi, DCConvertEncoding, uMyWindows {$ELSEIF DEFINED(UNIX)} , Classes, Unix, BaseUnix, DCUnix, Dialogs, SyncObjs, Process, un_process {$IF DEFINED(DARWIN)} , DCStrUtils {$ENDIF} {$ENDIF} ; var FAdministratorPrivileges: Boolean; procedure WaitProcess(Process: UIntPtr); {$IF DEFINED(MSWINDOWS)} begin WaitForSingleObject(Process, INFINITE); CloseHandle(Process); end; {$ELSE} var Status : cInt = 0; begin while (FpWaitPid(Process, @Status, 0) = -1) and (fpgeterrno() = ESysEINTR) do; end; {$ENDIF} function ElevationRequired(LastError: Integer = 0): Boolean; {$IF DEFINED(MSWINDOWS)} begin if FAdministratorPrivileges then Exit(False); if LastError = 0 then LastError:= GetLastError; Result:= (LastError = ERROR_ACCESS_DENIED) or (LastError = ERROR_PRIVILEGE_NOT_HELD) or (LastError = ERROR_INVALID_OWNER) or (LastError = ERROR_NOT_ALL_ASSIGNED); end; {$ELSE} begin if FAdministratorPrivileges then Exit(False); if LastError = 0 then LastError:= GetLastOSError; Result:= (LastError = ESysEPERM) or (LastError = ESysEACCES); end; {$ENDIF} function AdministratorPrivileges: Boolean; begin Result:= FAdministratorPrivileges; end; function TerminateProcess(Process: UIntPtr): Boolean; {$IF DEFINED(MSWINDOWS)} begin Result:= Windows.TerminateProcess(Process, 1); end; {$ELSE} begin Result:= fpKill(Process, SIGTERM) = 0; end; {$ENDIF} {$IF DEFINED(UNIX)} const SYS_PATH: array[0..1] of String = ('/usr/bin/', '/usr/local/bin/'); resourcestring rsMsgPasswordEnter = 'Please enter the password:'; type TSuperProgram = (spNone, spSudo, spPkexec); { TSuperUser } TSuperUser = class(TThread) private FPrompt: String; FCtl: TExProcess; FMessage: String; FArgs: TStringArray; FEvent: TSimpleEvent; private procedure Ready; procedure RequestPassword; procedure OnReadLn(Str: String); procedure OnQueryString(Str: String); protected procedure Execute; override; public constructor Create(Args: TStringArray; const StartPath: String); destructor Destroy; override; end; var SuperExe: String; SuperProgram: TSuperProgram; function ExecuteCommand(Command: String; Args: TStringArray; StartPath: String): UIntPtr; var ProcessId : TPid; begin ProcessId := fpFork; if ProcessId = 0 then begin { Set the close-on-exec flag to all } FileCloseOnExecAll; { Set child current directory } if Length(StartPath) > 0 then fpChdir(StartPath); { The child does the actual exec, and then exits } if FpExecLP(Command, Args) = -1 then Writeln(Format('Execute error %d: %s', [fpgeterrno, SysErrorMessage(fpgeterrno)])); { If the FpExecLP fails, we return an exitvalue of 127, to let it be known } fpExit(127); end else if ProcessId = -1 then { Fork failed } begin WriteLn('Fork failed: ' + Command, LineEnding, SysErrorMessage(fpgeterrno)); end; if ProcessId < 0 then Result := 0 else Result := ProcessId; end; function FindExecutable(const FileName: String; out FullName: String): Boolean; var Index: Integer; begin for Index:= Low(SYS_PATH) to High(SYS_PATH) do begin FullName:= SYS_PATH[Index] + FileName; if fpAccess(FullName, X_OK) = 0 then Exit(True); end; Result:= False; end; function ExecuteSudo(Args: TStringArray; const StartPath: String): UIntPtr; begin with TSuperUser.Create(Args, StartPath) do begin Start; FEvent.WaitFor(INFINITE); Result:= FCtl.Process.ProcessHandle; end; end; { TSuperUser } procedure TSuperUser.Ready; begin FEvent.SetEvent; Yield; FreeOnTerminate:= True; FCtl.OnOperationProgress:= nil; end; procedure TSuperUser.RequestPassword; var S: String = ''; begin if Length(FMessage) = 0 then begin FMessage:= rsMsgPasswordEnter end; if not InputQuery('Double Commander', FMessage, True, S) then FCtl.Stop else begin S:= S + LineEnding; FCtl.Process.Input.Write(S[1], Length(S)); end; FMessage:= EmptyStr; end; procedure TSuperUser.OnReadLn(Str: String); begin FMessage:= Str; end; procedure TSuperUser.OnQueryString(Str: String); begin Synchronize(@RequestPassword) end; procedure TSuperUser.Execute; var GUID : TGUID; Index: Integer; begin CreateGUID(GUID); FPrompt:= GUIDToString(GUID); FCtl.Process.Options:= FCtl.Process.Options + [poStderrToOutPut]; FCtl.Process.Executable:= SuperExe; FCtl.Process.Parameters.Add('-S'); FCtl.Process.Parameters.Add('-k'); FCtl.Process.Parameters.Add('-p'); FCtl.Process.Parameters.Add(FPrompt); for Index:= 0 to High(FArgs) do begin FCtl.Process.Parameters.Add(FArgs[Index]); end; FCtl.QueryString:= FPrompt; FCtl.OnQueryString:= @OnQueryString; FCtl.OnOperationProgress:= @Ready; fCtl.OnProcessExit:= @Ready; FCtl.OnReadLn:= @OnReadLn; FCtl.Execute; end; constructor TSuperUser.Create(Args: TStringArray; const StartPath: String); begin inherited Create(True); FCtl:= TExProcess.Create(EmptyStr); FCtl.Process.CurrentDirectory:= StartPath; FEvent:= TSimpleEvent.Create; FArgs:= Args; end; destructor TSuperUser.Destroy; begin inherited Destroy; FEvent.Free; FCtl.Free; end; {$ELSEIF DEFINED(MSWINDOWS)} function MaybeQuoteIfNotQuoted(const S: String): String; begin if (Pos(' ', S) <> 0) and (pos('"', S) = 0) then Result := '"' + S + '"' else Result := S; end; {$ENDIF} function ExecCmdAdmin(const Exe: String; Args: array of String; sStartPath: String): UIntPtr; {$IF DEFINED(MSWINDOWS)} var Index: Integer; AParams: String; lpExecInfo: TShellExecuteInfoW; begin AParams := EmptyStr; for Index := Low(Args) to High(Args) do AParams += MaybeQuoteIfNotQuoted(Args[Index]) + ' '; if sStartPath = EmptyStr then sStartPath:= mbGetCurrentDir; ZeroMemory(@lpExecInfo, SizeOf(lpExecInfo)); lpExecInfo.cbSize:= SizeOf(lpExecInfo); lpExecInfo.fMask:= SEE_MASK_NOCLOSEPROCESS; lpExecInfo.lpFile:= PWideChar(CeUtf8ToUtf16(Exe)); lpExecInfo.lpDirectory:= PWideChar(CeUtf8ToUtf16(sStartPath)); lpExecInfo.lpParameters:= PWideChar(CeUtf8ToUtf16(AParams)); lpExecInfo.lpVerb:= 'runas'; if ShellExecuteExW(@lpExecInfo) then Result:= lpExecInfo.hProcess else Result:= 0; end; {$ELSEIF DEFINED(DARWIN)} var Index: Integer; ACommand: String; AParams: TStringArray; begin ACommand:= EscapeNoQuotes(Exe); for Index := Low(Args) to High(Args) do ACommand += ' ' + EscapeNoQuotes(Args[Index]); SetLength(AParams, 7); AParams[0]:= '-e'; AParams[1]:= 'on run argv'; AParams[2]:= '-e'; AParams[3]:= 'do shell script (item 1 of argv) with administrator privileges'; AParams[4]:= '-e'; AParams[5]:='end run'; AParams[6]:= ACommand; Result:= ExecuteCommand('/usr/bin/osascript', AParams, sStartPath); end; {$ELSE} var Index: Integer; AParams: TStringArray; begin SetLength(AParams, Length(Args) + 1); for Index := Low(Args) to High(Args) do AParams[Index + 1]:= Args[Index]; AParams[0] := Exe; case SuperProgram of spSudo: Result:= ExecuteSudo(AParams, sStartPath); spPkexec: Result:= ExecuteCommand(SuperExe, AParams, sStartPath); end; end; {$ENDIF} initialization {$IF DEFINED(DARWIN)} FAdministratorPrivileges:= True; {$ELSEIF DEFINED(UNIX)} {$IFDEF LINUX} if FindExecutable('pkexec', SuperExe) then SuperProgram:= spPkexec else {$ENDIF} if FindExecutable('sudo', SuperExe) then SuperProgram:= spSudo else begin SuperProgram:= spNone; end; FAdministratorPrivileges:= (fpGetUID = 0) or (SuperProgram = spNone); {$ELSE} FAdministratorPrivileges:= (IsUserAdmin <> dupError); {$ENDIF} end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm2 = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; pbWithStatusText: TButton; pbNoStatusText: TButton; pbTestSDUWindowsProgressDialog: TButton; pbClose: TButton; procedure FormCreate(Sender: TObject); procedure pbWithStatusTextClick(Sender: TObject); procedure pbNoStatusTextClick(Sender: TObject); procedure pbTestSDUWindowsProgressDialogClick(Sender: TObject); procedure pbCloseClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} uses ComCtrls, SDUGeneral, SDUDialogs, SDUProgressDlg; procedure TForm2.FormCreate(Sender: TObject); begin self.Caption := Application.Title; end; procedure TForm2.pbCloseClick(Sender: TObject); begin Close(); end; procedure TForm2.pbNoStatusTextClick(Sender: TObject); var progressDlg: TSDUProgressDialog; i: integer; begin progressDlg := TSDUProgressDialog.Create(nil); try progressDlg.Min := 0; progressDlg.Max := 10; progressDlg.Title := 'Demo one...'; progressDlg.Show(); Application.ProcessMessages(); for i:=0 to 10 do begin progressDlg.Position := i; Application.ProcessMessages(); if progressDlg.Cancel then begin break; end; sleep(1000); end; finally progressDlg.Free(); end; end; procedure TForm2.pbWithStatusTextClick(Sender: TObject); var progressDlg: TSDUProgressDialog; i: integer; begin progressDlg := TSDUProgressDialog.Create(nil); try progressDlg.Min := 0; progressDlg.Max := 10; progressDlg.Title := 'Demo one...'; progressDlg.ShowStatusText := TRUE; progressDlg.Show(); Application.ProcessMessages(); for i:=0 to 10 do begin progressDlg.Position := i; progressDlg.StatusText := 'ABC '+inttostr(i)+' XYZ'; Application.ProcessMessages(); if progressDlg.Cancel then begin break; end; sleep(1000); end; finally progressDlg.Free(); end; end; procedure TForm2.pbTestSDUWindowsProgressDialogClick(Sender: TObject); const NUM_STEPS = 200; var progressDlg: TSDUWindowsProgressDialog; i: integer; userCancelled: boolean; begin userCancelled := FALSE; progressDlg:= TSDUWindowsProgressDialog.Create(); try progressDlg.Title := 'MY TITLE HERE'; progressDlg.LineText[1] := 'MY LINE 1 HERE'; progressDlg.LineText[2] := 'MY LINE 2 HERE'; //progressDlg.LineText[3] := 'MY LINE 3 HERE'; // Automatically overwritten with "time remaining" progressDlg.CommonAVI := aviCopyFile; progressDlg.CancelMsg := 'Please wait while the current operation is cleaned up...'; progressDlg.StartProgressDialog(); // Optionally perform time-consuming task to determine total here progressDlg.Total := NUM_STEPS; // In case the determination of what "Total" should be set to, prior to // setting it above, too awhile, we reset the progress dialog's internal // timer, so that the "time remaining" display is more accurate progressDlg.Timer(PDTIMER_RESET); // Important: DO NOT SET "progressDlg.Progress := 0;"! From the MSDN // documentation, this can confuse the "time remaining" timer // Carry out processing here, updating "progressDlg.Progress" as // progress is made - checking "progressDlg.HasUserCancelled" in case // the user's cancelled the operation. // LineText[1..3] may also be updated here. for i:=1 to NUM_STEPS do begin sleep(50); // Replace this line with processing. if progressDlg.HasUserCancelled then begin userCancelled := TRUE; break; end; progressDlg.Progress := i; progressDlg.LineText[2] := inttostr(i) + ' / ' + inttostr(NUM_STEPS); end; finally progressDlg.StopProgressDialog(); progressDlg.Free(); end; if userCancelled then begin SDUMessageDlg('User cancelled.', mtInformation, [mbOK], 0); end else begin SDUMessageDlg('Done!', mtInformation, [mbOK], 0); end; end; END.
unit ibSHServicesAPIEditors; interface uses SysUtils, Classes, DesignIntf, TypInfo, Dialogs, SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors; type // -> Component Editors // -> Property Editors TibSHServicesPropEditor = class(TibBTPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; end; IibSHServicesStopAfterPropEditor = interface ['{B7A20BFE-350B-4972-B472-027FB4492539}'] end; IibSHServicesShutdownModePropEditor = interface ['{FFB34663-CA86-44F5-AAE9-7BC3BB15FAE4}'] end; IibSHServicesPageSizePropEditor = interface ['{A94C6151-583F-48C7-B586-43E776D12CEB}'] end; IibSHServicesCharsetPropEditor = interface ['{7F24E38C-205B-4295-9188-2AF44625B79A}'] end; IibSHServicesSQLDialectPropEditor = interface ['{C24552AF-5CDE-481B-B552-2D167353D735}'] end; IibSHServicesGlobalActionPropEditor = interface ['{BE59E863-BC79-4586-BF7F-F944372D60BE}'] end; IibSHServicesFixLimboPropEditor = interface ['{3B153E64-1353-41A0-955E-15B83608F947}'] end; TibSHServicesStopAfterPropEditor = class(TibSHServicesPropEditor, IibSHServicesStopAfterPropEditor); TibSHServicesShutdownModePropEditor = class(TibSHServicesPropEditor, IibSHServicesShutdownModePropEditor); TibSHServicesPageSizePropEditor = class(TibSHServicesPropEditor, IibSHServicesPageSizePropEditor); TibSHServicesCharsetPropEditor = class(TibSHServicesPropEditor, IibSHServicesCharsetPropEditor); TibSHServicesSQLDialectPropEditor = class(TibSHServicesPropEditor, IibSHServicesSQLDialectPropEditor); TibSHServicesGlobalActionPropEditor = class(TibSHServicesPropEditor, IibSHServicesGlobalActionPropEditor); TibSHServicesFixLimboPropEditor = class(TibSHServicesPropEditor, IibSHServicesFixLimboPropEditor); implementation uses ibSHConsts, ibSHValues; { TibSHServicesPropEditor } function TibSHServicesPropEditor.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; if Supports(Self, IibSHServicesStopAfterPropEditor) then Result := [paValueList]; if Supports(Self, IibSHServicesShutdownModePropEditor) then Result := [paValueList]; if Supports(Self, IibSHServicesPageSizePropEditor) then if not Supports(Component, IibSHDatabaseProps) then Result := [paValueList]; if Supports(Self, IibSHServicesCharsetPropEditor) then Result := [paReadOnly]; if Supports(Self, IibSHServicesSQLDialectPropEditor) then Result := [paValueList]; if Supports(Self, IibSHServicesGlobalActionPropEditor) then Result := [paValueList]; if Supports(Self, IibSHServicesFixLimboPropEditor) then Result := [paReadOnly, paDialog]; end; function TibSHServicesPropEditor.GetValue: string; begin Result := inherited GetValue; if Supports(Self, IibSHServicesStopAfterPropEditor) then ; if Supports(Self, IibSHServicesShutdownModePropEditor) then ; if Supports(Self, IibSHServicesPageSizePropEditor) then ; if Supports(Self, IibSHServicesCharsetPropEditor) then ; if Supports(Self, IibSHServicesSQLDialectPropEditor) then ; if Supports(Self, IibSHServicesGlobalActionPropEditor) then ; if Supports(Self, IibSHServicesFixLimboPropEditor) then Result := '>>'; end; procedure TibSHServicesPropEditor.GetValues(AValues: TStrings); begin inherited GetValues(AValues); if Supports(Self, IibSHServicesStopAfterPropEditor) then AValues.Text := GetStopAfter; if Supports(Self, IibSHServicesShutdownModePropEditor) then AValues.Text := GetShutdownMode; if Supports(Self, IibSHServicesPageSizePropEditor) then if not Supports(Component, IibSHDatabaseProps) then AValues.Text := GetPageSize; if Supports(Self, IibSHServicesCharsetPropEditor) then ; if Supports(Self, IibSHServicesSQLDialectPropEditor) then AValues.Text := GetDialect(True); if Supports(Self, IibSHServicesGlobalActionPropEditor) then AValues.Text := GetGlobalAction; if Supports(Self, IibSHServicesFixLimboPropEditor) then ; end; procedure TibSHServicesPropEditor.SetValue(const Value: string); begin inherited SetValue(Value); if Supports(Self, IibSHServicesStopAfterPropEditor) then if Designer.CheckPropValue(Value, GetStopAfter) then inherited SetStrValue(Value); if Supports(Self, IibSHServicesShutdownModePropEditor) then if Designer.CheckPropValue(Value, GetShutdownMode) then inherited SetStrValue(Value); if Supports(Self, IibSHServicesPageSizePropEditor) then if Designer.CheckPropValue(Value, GetPageSize) then inherited SetStrValue(Value); if Supports(Self, IibSHServicesCharsetPropEditor) then ; if Supports(Self, IibSHServicesSQLDialectPropEditor) then if Designer.CheckPropValue(Value, GetDialect(True)) then inherited SetStrValue(Value); if Supports(Self, IibSHServicesGlobalActionPropEditor) then if Designer.CheckPropValue(Value, GetGlobalAction) then inherited SetStrValue(Value); end; procedure TibSHServicesPropEditor.Edit; begin inherited Edit; if Supports(Self, IibSHServicesStopAfterPropEditor) then ; if Supports(Self, IibSHServicesShutdownModePropEditor) then ; if Supports(Self, IibSHServicesFixLimboPropEditor) then Designer.ShowMsg(Format('No pending transactions were found', []), mtInformation); end; end.
Unit Un_PdfGrafico; Interface Uses Classes, System.Types, System.UITypes, FMX.Objects, FMX.Types; //------------------------------------------------------------------------ Type TPdfGrafico=Class(TObject) Private img_Pagina:TImage; //obj_EstadoCanvas:TCanvasSaveState; //obj_Caminho:TPathData; flt_Largura, flt_Zoom, flt_Inicio:Single; int_TipoBorda, int_TipoJuncao:Integer; arr_Tracos:Array Of Single; Function ObtemQtdComandosCaminho:Integer; Function ConverteCoordenada_X(flt_X,flt_Y:Double):Double; Function ConverteCoordenada_Y(flt_X,flt_Y:Double):Double; Public Procedure DefineLarguraLinha(flt_Largura:Double); Procedure DefineBordaLinha(int_TipoBorda:Integer); Procedure DefineJuncaoLinha(int_TipoJuncao:Integer); Procedure NovoCaminho(flt_X,flt_Y:Double); Procedure IncluiPontoCaminho(flt_X,flt_Y:Double); Procedure DefineArrayTracejado(flt_Inicio:Single;arr_Tracos:Array Of Single); Procedure PropositoRederizacao; Procedure DefineMaximoNivelamento; Procedure DefineEstadoGrafico; Procedure RestauraEstadoGrafico; Procedure SalvaEstadoGrafico; Procedure Matriz(flt_A,flt_B,flt_C,flt_D,flt_E,flt_F:Double); Procedure ConcatMatriz(flt_A,flt_B,flt_C,flt_D,flt_E,flt_F:Double); Procedure Linha(flt_X,flt_Y:Double); Procedure Curva(flt_X1,flt_Y1,flt_X2,flt_Y2,flt_X3,flt_Y3:Double); Procedure IncluiCurvaInicio; Procedure IncluiCurvaFinal; Procedure FechaSubCaminho; Procedure Retangulo(flt_X,flt_Y,flt_Altura,flt_Largura:Double); Procedure FechaQuebraCaminho; Procedure QuebraCaminho; Procedure Preenche; Procedure FechaCaminho; Procedure DefineCorLinhaCMYK(int_C,int_M,int_Y,int_K:Integer); Procedure DefineCorFundoCMYK(int_C,int_M,int_Y,int_K:Integer); Procedure DefineCorLinhaRGB(flt_R,flt_G,flt_B:Double); Procedure DefineCorFundoRGB(flt_R,flt_G,flt_B:Double); Procedure InicioObjetoInterno; Procedure InicioDadoInterno; Procedure FimImagemInterna; Procedure LimpaParam; Procedure InvocaObjeto; Constructor Create(Var img_Pagina:TImage;flt_Zoom:Double); Procedure Desenha; Property QtdComandosCaminho:Integer Read ObtemQtdComandosCaminho; End; Implementation Uses System.SysUtils, System.Math, System.StrUtils; //----------------------------------------------------------------------------- // TPdfGrafico //----------------------------------------------------------------------------- Function TPdfGrafico.ObtemQtdComandosCaminho:Integer; Begin // Result:=Self.obj_Caminho.Count; End; //----------------------------------------------------------------------------- Function TPdfGrafico.ConverteCoordenada_X(flt_X,flt_Y:Double):Double; Begin flt_X:=Self.flt_Zoom*flt_X; flt_Y:=Self.flt_Zoom*flt_Y; Result:=Self.img_Pagina.Bitmap.Canvas.Matrix.m11*flt_X+Self.img_Pagina.Bitmap.Canvas.Matrix.m21*flt_y+Self.img_Pagina.Bitmap.Canvas.Matrix.m31; End; //----------------------------------------------------------------------------- Function TPdfGrafico.ConverteCoordenada_Y(flt_X,flt_Y:Double):Double; Begin flt_X:=Self.flt_Zoom*flt_X; flt_Y:=Self.flt_Zoom*flt_Y; Result:=Self.img_Pagina.Bitmap.Canvas.Matrix.m12*flt_X+Self.img_Pagina.Bitmap.Canvas.Matrix.m22*flt_y+Self.img_Pagina.Bitmap.Canvas.Matrix.m32; Result:=Self.img_Pagina.Height-Result; End; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineLarguraLinha(flt_Largura:Double); Begin Self.flt_Largura:=flt_Largura; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineBordaLinha(int_TipoBorda:Integer); Begin Self.int_TipoBorda:=int_TipoBorda; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineJuncaoLinha(int_TipoJuncao:Integer); Begin Self.int_TipoJuncao:=int_TipoJuncao; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.NovoCaminho(flt_X,flt_Y:Double); Begin // Self.obj_Caminho.MoveTo(TPointF.Create(ConverteCoordenada_X(flt_X,flt_Y),ConverteCoordenada_Y(flt_X,flt_Y))); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.IncluiPontoCaminho(flt_X,flt_Y:Double); Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineArrayTracejado(flt_Inicio:Single;arr_Tracos:Array Of Single); Var I:Integer; Begin SetLength(Self.arr_Tracos,Length(arr_Tracos)); For I:=1 To Length(arr_Tracos) Do Self.arr_Tracos[I]:=arr_Tracos[I]; Self.flt_Inicio:=flt_Inicio; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.PropositoRederizacao; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineMaximoNivelamento; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineEstadoGrafico; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.RestauraEstadoGrafico; //Var obj_Matriz:TMatrix; Begin {obj_Matriz.m11:=1; //A obj_Matriz.m12:=0; //B obj_Matriz.m13:=0; obj_Matriz.m21:=0; //C obj_Matriz.m22:=1; //D obj_Matriz.m23:=0; obj_Matriz.m31:=0; //E obj_Matriz.m32:=0; //F obj_Matriz.m33:=1; Self.img_Pagina.Bitmap.Canvas.SetMatrix(obj_Matriz);} // Self.img_Pagina.Bitmap.Canvas.RestoreState(obj_EstadoCanvas); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.SalvaEstadoGrafico; Begin //obj_EstadoCanvas:=Self.img_Pagina.Bitmap.Canvas.SaveState; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Matriz(flt_A,flt_B,flt_C,flt_D,flt_E,flt_F:Double); //Var obj_Matriz:TMatrix; Begin { obj_Matriz.m11:=flt_A; obj_Matriz.m12:=flt_B; obj_Matriz.m13:=0; obj_Matriz.m21:=flt_C; obj_Matriz.m22:=flt_D; obj_Matriz.m23:=0; obj_Matriz.m31:=flt_E; obj_Matriz.m32:=flt_F; obj_Matriz.m33:=1; Self.img_Pagina.Bitmap.Canvas.SetMatrix(obj_Matriz);} End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.ConcatMatriz(flt_A,flt_B,flt_C,flt_D,flt_E,flt_F:Double); //Var obj_MatrizParam, // obj_MatrizResult:TMatrix; Begin { obj_MatrizParam.m11:=flt_A; obj_MatrizParam.m12:=flt_B; obj_MatrizParam.m13:=0; obj_MatrizParam.m21:=flt_C; obj_MatrizParam.m22:=flt_D; obj_MatrizParam.m23:=0; obj_MatrizParam.m31:=flt_E; obj_MatrizParam.m32:=flt_F; obj_MatrizParam.m33:=1; obj_MatrizResult.m11:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m11*obj_MatrizParam.m11)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m12*obj_MatrizParam.m21)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m13*obj_MatrizParam.m31); obj_MatrizResult.m12:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m11*obj_MatrizParam.m12)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m12*obj_MatrizParam.m22)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m13*obj_MatrizParam.m32); obj_MatrizResult.m13:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m11*obj_MatrizParam.m13)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m12*obj_MatrizParam.m23)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m13*obj_MatrizParam.m33); obj_MatrizResult.m21:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m21*obj_MatrizParam.m11)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m22*obj_MatrizParam.m21)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m23*obj_MatrizParam.m31); obj_MatrizResult.m22:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m21*obj_MatrizParam.m12)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m22*obj_MatrizParam.m22)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m23*obj_MatrizParam.m32); obj_MatrizResult.m23:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m21*obj_MatrizParam.m13)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m22*obj_MatrizParam.m23)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m23*obj_MatrizParam.m33); obj_MatrizResult.m31:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m31*obj_MatrizParam.m11)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m32*obj_MatrizParam.m21)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m33*obj_MatrizParam.m31); obj_MatrizResult.m32:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m31*obj_MatrizParam.m12)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m32*obj_MatrizParam.m22)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m33*obj_MatrizParam.m32); obj_MatrizResult.m33:=(Self.img_Pagina.Bitmap.Canvas.Matrix.m31*obj_MatrizParam.m13)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m32*obj_MatrizParam.m23)+(Self.img_Pagina.Bitmap.Canvas.Matrix.m33*obj_MatrizParam.m33); Self.img_Pagina.Bitmap.Canvas.SetMatrix(obj_MatrizResult); } End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Linha(flt_X,flt_Y:Double); Begin //Self.obj_Caminho.LineTo(TPointF.Create(ConverteCoordenada_X(flt_X,flt_Y),ConverteCoordenada_Y(flt_X,flt_Y))); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Curva(flt_X1,flt_Y1,flt_X2,flt_Y2,flt_X3,flt_Y3:Double); Begin //Self.obj_Caminho.CurveTo(TPointF.Create(ConverteCoordenada_X(flt_X1,flt_Y1),ConverteCoordenada_Y(flt_X1,flt_Y1)), // TPointF.Create(ConverteCoordenada_X(flt_X2,flt_Y2),ConverteCoordenada_Y(flt_X2,flt_Y2)), // TPointF.Create(ConverteCoordenada_X(flt_X3,flt_Y3),ConverteCoordenada_Y(flt_X3,flt_Y3))); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.IncluiCurvaInicio; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.IncluiCurvaFinal; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.FechaSubCaminho; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Retangulo(flt_X,flt_Y,flt_Altura,flt_Largura:Double); Var obj_PotoAnt:TPointF; Begin // obj_PotoAnt:=Self.obj_Caminho.LastPoint; // Self.obj_Caminho.MoveTo(TPointF.Create(ConverteCoordenada_X(flt_X,flt_Y),ConverteCoordenada_Y(flt_X,flt_Y))); // Self.obj_Caminho.LineTo(TPointF.Create(ConverteCoordenada_X(flt_X+flt_Largura,flt_Y),ConverteCoordenada_Y(flt_X+flt_Largura,flt_Y))); // Self.obj_Caminho.LineTo(TPointF.Create(ConverteCoordenada_X(flt_X+flt_Largura,flt_Y+flt_Altura),ConverteCoordenada_Y(flt_X+flt_Largura,flt_Y+flt_Altura))); // Self.obj_Caminho.LineTo(TPointF.Create(ConverteCoordenada_X(flt_X,flt_Y+flt_Altura),ConverteCoordenada_Y(flt_X,flt_Y+flt_Altura))); // Self.obj_Caminho.LineTo(TPointF.Create(ConverteCoordenada_X(flt_X,flt_Y),ConverteCoordenada_Y(flt_X,flt_Y))); // Self.obj_Caminho.MoveTo(obj_PotoAnt); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.FechaQuebraCaminho; Begin // Self.obj_Caminho.ClosePath; Self.Desenha; // Self.obj_Caminho.Clear; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.QuebraCaminho; Begin Self.Desenha; // Self.obj_Caminho.Clear; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Preenche; Begin // Self.img_Pagina.Bitmap.Canvas.FillPath(Self.obj_Caminho,200); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.FechaCaminho; Begin // Self.obj_Caminho.ClosePath; End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineCorLinhaCMYK(int_C,int_M,int_Y,int_K:Integer); Var int_R, int_G, int_B:Integer; Begin int_R:=1-int_C-int_K; int_G:=1-int_M-int_K; int_B:=1-int_Y-int_K; Self.img_Pagina.Bitmap.Canvas.Stroke.Color:=StrToInt('$FF'+IntToHex(int_B,2)+IntToHex(int_G,2)+IntToHex(int_R,2)); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineCorFundoCMYK(int_C,int_M,int_Y,int_K:Integer); Var int_R, int_G, int_B:Integer; Begin int_R:=1-int_C-int_K; int_G:=1-int_M-int_K; int_B:=1-int_Y-int_K; Self.img_Pagina.Bitmap.Canvas.Fill.Color:=StrToInt('$FF'+IntToHex(int_B,2)+IntToHex(int_G,2)+IntToHex(int_R,2)); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineCorLinhaRGB(flt_R,flt_G,flt_B:Double); Var str_R, str_G, str_B:String; Begin str_R:=IfThen(flt_R<=1,IntToHex(Trunc(0.5+flt_R*$FF),2),IntToHex(Trunc(0.5+flt_R),2)); str_G:=IfThen(flt_G<=1,IntToHex(Trunc(0.5+flt_G*$FF),2),IntToHex(Trunc(0.5+flt_G),2)); str_B:=IfThen(flt_B<=1,IntToHex(Trunc(0.5+flt_B*$FF),2),IntToHex(Trunc(0.5+flt_B),2)); Self.img_Pagina.Bitmap.Canvas.Stroke.Color:=StrToInt('$FF'+str_B+str_G+str_R); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.DefineCorFundoRGB(flt_R,flt_G,flt_B:Double); Var str_R, str_G, str_B:String; Begin str_R:=IfThen(flt_R<=1,IntToHex(Trunc(0.5+flt_R*$FF),2),IntToHex(Trunc(0.5+flt_R),2)); str_G:=IfThen(flt_G<=1,IntToHex(Trunc(0.5+flt_G*$FF),2),IntToHex(Trunc(0.5+flt_G),2)); str_B:=IfThen(flt_B<=1,IntToHex(Trunc(0.5+flt_B*$FF),2),IntToHex(Trunc(0.5+flt_B),2)); Self.img_Pagina.Bitmap.Canvas.Fill.Color:=StrToInt('$FF'+str_B+str_G+str_R); End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.InicioObjetoInterno; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.InicioDadoInterno; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.FimImagemInterna; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.LimpaParam; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.InvocaObjeto; Begin End; //----------------------------------------------------------------------------- Procedure TPdfGrafico.Desenha; Begin Self.img_Pagina.Bitmap.Canvas.BeginScene; // Case Self.int_TipoJuncao Of // 0:Self.img_Pagina.Bitmap.Canvas.StrokeJoin:=TStrokeJoin.sjMiter; // 1:Self.img_Pagina.Bitmap.Canvas.StrokeJoin:=TStrokeJoin.sjRound; // 2:Self.img_Pagina.Bitmap.Canvas.StrokeJoin:=TStrokeJoin.sjBevel; // End; // Case Self.int_TipoBorda Of // 0:Self.img_Pagina.Bitmap.Canvas.StrokeCap:=TStrokeCap.scFlat; // 1:Self.img_Pagina.Bitmap.Canvas.StrokeCap:=TStrokeCap.scRound; // 2:Self.img_Pagina.Bitmap.Canvas.StrokeCap:=TStrokeCap.scFlat; // End; If Length(Self.arr_Tracos)>0 Then Begin // Self.img_Pagina.Bitmap.Canvas.StrokeDash:=TStrokeDash.sdCustom; Self.img_Pagina.Bitmap.Canvas.SetCustomDash(Self.arr_Tracos,Self.flt_Inicio); End; Self.img_Pagina.Bitmap.Canvas.StrokeThickness:=Self.flt_Largura; // Self.img_Pagina.Bitmap.Canvas.DrawPath(Self.obj_Caminho,200); Self.img_Pagina.Bitmap.Canvas.EndScene; // Self.img_Pagina.Bitmap.BitmapChanged; End; //----------------------------------------------------------------------------- Constructor TPdfGrafico.Create(Var img_Pagina:TImage;flt_Zoom:Double); Var chr_Dado:AnsiChar; int_ContPonto, int_ContSinal, int_ContPar:Byte; Begin Inherited Create; Self.img_Pagina:=img_Pagina; Self.RestauraEstadoGrafico; // Self.obj_Caminho:=TPathData.Create; Self.flt_Zoom:=flt_Zoom; // Self.img_Pagina.Bitmap.Canvas.Fill.Color:=claWhite; // Self.img_Pagina.Bitmap.Canvas.Stroke.Color:=claBlack; // Self.img_Pagina.Bitmap.Canvas.StrokeJoin:=TStrokeJoin.sjMiter; // Self.img_Pagina.Bitmap.Canvas.StrokeCap:=TStrokeCap.scFlat; End; //----------------------------------------------------------------------------- End.
unit htColumnsPanel; interface uses Windows, SysUtils, Types, Messages, Classes, Controls, Graphics, htInterfaces, htMarkup, htControls, htPanel; type ThtCustomColumnsPanel = class(ThtCustomControl) private FClientPanel: ThtPanel; FLeftPanel: ThtPanel; FLeftWidth: Integer; protected procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure CMControlChange(var Message: TMessage); message CM_CONTROLCHANGE; procedure GenerateCtrls(inMarkup: ThtMarkup); procedure GenerateCtrl(inMarkup: ThtMarkup; const inContainer: string; inCtrl: TControl); procedure SetLeftWidth(const Value: Integer); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; procedure Generate(const inContainer: string; inMarkup: ThtMarkup); override; property LeftWidth: Integer read FLeftWidth write SetLeftWidth; end; // ThtColumnsPanel = class(ThtCustomColumnsPanel) published property Align; property LeftWidth; property Outline; property Style; property Transparent; property Visible; end; implementation uses LrVclUtils, LrControlIterator; { ThtCustomColumnsPanel } constructor ThtCustomColumnsPanel.Create(inOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; // FLeftPanel := ThtPanel.Create(Owner); FLeftPanel.Parent := Self; FLeftPanel.Align := alLeft; FLeftPanel.Outline := true; //FLeftPanel.SetSubcomponent(true); // FClientPanel := ThtPanel.Create(Self); FClientPanel.Align := alClient; FClientPanel.Parent := Self; //FClientPanel.SetSubcomponent(true); LeftWidth := 200; end; destructor ThtCustomColumnsPanel.Destroy; begin inherited; end; procedure ThtCustomColumnsPanel.SetLeftWidth(const Value: Integer); begin FLeftWidth := Value; FLeftPanel.Width := FLeftWidth; end; procedure ThtCustomColumnsPanel.GenerateCtrl(inMarkup: ThtMarkup; const inContainer: string; inCtrl: TControl); var c: IhtControl; begin if LrIsAs(inCtrl, IhtControl, c) then c.Generate(inContainer, inMarkup) else inMarkup.Add(inCtrl.Name); end; procedure ThtCustomColumnsPanel.GenerateCtrls(inMarkup: ThtMarkup); begin with TLrCtrlIterator.Create(Self) do try while Next do GenerateCtrl(inMarkup, Ctrl.Name, Ctrl); finally Free; end; end; procedure ThtCustomColumnsPanel.Generate(const inContainer: string; inMarkup: ThtMarkup); begin GenerateStyle('#' + Name, inMarkup); inMarkup.Styles.Add( Format('#%s { position: relative; margin-right: 0; height: %dpx; }', [ Name, Height ])); inMarkup.Add(Format('<div id="%s">', [ Name ])); GenerateCtrls(inMarkup); inMarkup.Add('</div>'); end; procedure ThtCustomColumnsPanel.AlignControls(AControl: TControl; var Rect: TRect); begin with TLrCtrlIterator.Create(Self) do try while Next do if (Ctrl <> FLeftPanel) and (Ctrl <> FClientPanel) then if Ctrl.Left < LeftWidth then Ctrl.Parent := FLeftPanel else begin Ctrl.Parent := FClientPanel; Ctrl.Left := Ctrl.Left - LeftWidth; end; finally Free; end; inherited; end; procedure ThtCustomColumnsPanel.CMControlChange(var Message: TMessage); begin { if not (csLoading in ComponentState) then with TCMControlChange(Message) do if Inserting and (Control.Parent = Self) and (Control <> FLeftPanel) and (Control <> FClientPanel) then begin if Control.Left < LeftWidth then Control.Parent := FLeftPanel else begin Control.Parent := FClientPanel; Control.Left := Control.Left - LeftWidth; end; end; } inherited; end; end.
unit uSM; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, generics.collections; type Tcliente = class private FID: integer; FNome: String; public property ID: integer read FID write FID; property Nome: String read FNome write FNome; end; TSM = class(TDSServerModule) private { Private declarations } public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; function retornaMeuNome(): string; function GetDateTime(): string; function GetClients(): TList<TCliente>; end; implementation {$R *.dfm} uses System.StrUtils; function TSM.EchoString(Value: string): string; begin Result := Value; end; function TSM.GetClients: TList<TCliente>; begin end; function TSM.GetDateTime: string; begin Result := DateTimeToStr(now); end; function TSM.retornaMeuNome: string; begin Result := 'Bruno'; end; function TSM.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
unit ThItemSelection; interface uses System.Classes, System.Types, FMX.Types, System.UITypes, FMX.Controls, System.Generics.Collections, System.Math.Vectors, FMX.Graphics, ThConsts, ThTypes; type TSpotTrackingEvent = procedure(SpotCorner: TSpotCorner; X, Y: Single; SwapHorz, SwapVert: Boolean) of object; TItemResizeSpot = class(TControl, IItemResizeSpot) private FMouseDownPos: TPointF; FDownItemRect: TRectF; FSpotCorner: TSpotCorner; FOnTracking: TTrackingEvent; FParentItem: IThItem; FDisabled: Boolean; procedure SetSpotCorner(const Value: TSpotCorner); procedure SetParentItem(const Value: IThItem); procedure SetDisabled(const Value: Boolean); protected function GetAbsoluteMatrix: TMatrix; override; procedure DoMouseEnter; override; procedure DoMouseLeave; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; public constructor Create(AOwner: TComponent; ASpotCorner: TSpotCorner); reintroduce; virtual; function PointInObject(X, Y: Single): Boolean; override; property SpotCorner: TSpotCorner read FSpotCorner write SetSpotCorner; property OnTracking: TTrackingEvent read FOnTracking write FOnTracking; property ParentItem: IThItem read FParentItem write SetParentItem; property Disabled: Boolean read FDisabled write SetDisabled; class function InflateSize: Integer; end; TThItemCircleResizeSpot = class(TItemResizeSpot) protected procedure Paint; override; function DoGetUpdateRect: TRectF; override; public constructor Create(AOwner: TComponent; ADirection: TSpotCorner); override; end; TThResizeSpots = TList<TItemResizeSpot>; TResizeSpotClass = class of TItemResizeSpot; DefaultResizeSpotClass = TThItemCircleResizeSpot; TThItemSelection = class(TInterfacedObject, IItemSelection) private FParent: IItemSelectionObject; FSpotClass: TResizeSpotClass; FParentControl: TControl; FSpots: TThResizeSpots; FOnTracking: TSpotTrackingEvent; function GetSpots(Index: Integer): IItemResizeSpot; function GetCount: Integer; function GetSpot(SpotCorner: TSpotCorner): TItemResizeSpot; procedure DoResizeSpotTrack(Sender: TObject; X, Y: Single); function GetIsMouseOver: Boolean; protected function GetSelectionRect: TRectF; virtual; procedure ResizeItemBySpot(ASpot: IItemResizeSpot); virtual; // Spot 이동 시 Item 크기 조정 procedure NormalizeSpotCorner(ASpot: IItemResizeSpot); virtual; // Spot의 SpotCorner 조정 procedure RealignSpot; virtual; public constructor Create(AParent: IItemSelectionObject); destructor Destroy; override; procedure SetResizeSpotClass(ASpotClass: TResizeSpotClass); procedure SetResizeSpots(Spots: array of TSpotCorner); function GetActiveSpotsItemRect(ASpot: IItemResizeSpot = nil): TRectF; virtual; property IsMouseOver: Boolean read GetIsMouseOver; procedure ShowSpots; procedure ShowDisableSpots; procedure HideSpots; procedure DrawSelection; virtual; property Spots[Index: Integer] : IItemResizeSpot read GetSpots; default; property Count: Integer read GetCount; property OnTracking: TSpotTrackingEvent read FOnTracking write FOnTracking; end; // 수직/수평선(Width, Height = 0) 예외처리 TThLineSelection = class(TThItemSelection) protected procedure NormalizeSpotCorner(ASpot: IItemResizeSpot); override; procedure RealignSpot; override; // Width, Height가 1인 경우 발생 public procedure DrawSelection; override; end; // 상하/좌우 크기만 변경되도록 예외 TThCircleSelection = class(TThItemSelection) protected procedure NormalizeSpotCorner(ASpot: IItemResizeSpot); override; public function GetActiveSpotsItemRect(ASpot: IItemResizeSpot = nil): TRectF; override; end; implementation uses System.UIConsts, SpotCornerUtils, System.Math, DebugUtils; { TItemResizeSpot } constructor TItemResizeSpot.Create(AOwner: TComponent; ASpotCorner: TSpotCorner); begin inherited Create(AOwner); AutoCapture := True; Opacity := 1; SpotCorner := ASpotCorner; end; procedure TItemResizeSpot.DoMouseEnter; begin inherited; TControl(Parent).Repaint; Repaint; end; procedure TItemResizeSpot.DoMouseLeave; begin inherited; TControl(Parent).Repaint; Repaint; end; function TItemResizeSpot.GetAbsoluteMatrix: TMatrix; begin Result := inherited GetAbsoluteMatrix; if not Assigned(Scale) then Exit; Result.m11 := Scale.X; Result.m22 := Scale.Y; end; class function TItemResizeSpot.InflateSize: Integer; begin Result := ItemResizeSpotRadius; end; procedure TItemResizeSpot.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if FDisabled then Exit; inherited; if Pressed then begin FMouseDownPos := PointF(X, Y); // Spot내의 마우스 위치 FDownItemRect := TControl(Parent).BoundsRect; // Item의 범위 FDownItemRect.Offset(TControl(Parent).Position.Point); end; end; procedure TItemResizeSpot.MouseMove(Shift: TShiftState; X, Y: Single); var Gap: TPointF; begin if FDisabled then Exit; inherited; if Pressed then begin Gap := PointF(X, Y) - FMouseDownPos; // Down and Move Gap Position.Point := Position.Point + Gap; if Assigned(FOnTracking) then FOnTracking(Self, Gap.X, Gap.Y); end; end; procedure TItemResizeSpot.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if FDisabled then Exit; inherited; if (FDownItemRect <> TControl(Parent).BoundsRect) then FParentItem.ItemResizeBySpot(Self, FDownItemRect); end; function TItemResizeSpot.PointInObject(X, Y: Single): Boolean; function _GetAbsoluteScale: Single; begin Result := TControl(Parent).AbsoluteScale.X; end; var P: TPointF; Raduis: Single; begin Result := False; P := AbsoluteToLocal(PointF(X, Y)); Raduis := ItemResizeSpotRadius / _GetAbsoluteScale; if (Abs(P.X) < Raduis) and (Abs(P.Y) < Raduis) then Result := True; end; procedure TItemResizeSpot.SetDisabled(const Value: Boolean); begin FDisabled := Value; if FDisabled then Cursor := crDefault else SetSpotCorner(FSpotCorner); end; procedure TItemResizeSpot.SetParentItem(const Value: IThItem); begin FParentItem := Value; // Parent := TFMXObject(Value); end; procedure TItemResizeSpot.SetSpotCorner(const Value: TSpotCorner); begin FSpotCorner := Value; case FSpotCorner of scTopLeft, scBottomRight: Cursor := crSizeNWSE; scTopRight, scBottomLeft: Cursor := crSizeNESW; scTop, scBottom: Cursor := crSizeNS; scLeft, scRight: Cursor := crSizeWE; end; end; { TItemSelection } constructor TThItemSelection.Create(AParent: IItemSelectionObject); begin FParent := AParent; FParentControl := TControl(AParent); FSpots := TThResizeSpots.Create; FSpotClass := DefaultResizeSpotClass; end; destructor TThItemSelection.Destroy; var I: Integer; begin for I := FSpots.Count - 1 downto 0 do FSpots[I].Free; inherited; end; procedure TThItemSelection.SetResizeSpots(Spots: array of TSpotCorner); var I: Integer; Spot: TItemResizeSpot; begin for I := FSpots.Count - 1 downto 0 do FSpots[I].Free; FSpots.Clear; Assert(Assigned(FSpotClass), 'Not assigned items Spot class'); for I := 0 to Length(Spots) - 1 do begin Spot := FSpotClass.Create(TControl(FParent), Spots[I]); Spot.ParentItem := FParent; Spot.Parent := TControl(FParent); Spot.OnTracking := DoResizeSpotTrack; Spot.Visible := False; FSpots.Add(Spot); end; end; procedure TThItemSelection.SetResizeSpotClass(ASpotClass: TResizeSpotClass); begin FSpotClass := ASpotClass; end; function TThItemSelection.GetCount: Integer; begin Result := FSpots.Count; end; function TThItemSelection.GetIsMouseOver: Boolean; var Spot: TItemResizeSpot; begin Result := False; for Spot in FSpots do begin if Spot.IsMouseOver then begin Result := True; Exit; end; end; end; function TThItemSelection.GetSelectionRect: TRectF; begin Result := TControl(FParent).ClipRect; InflateRect(Result, FSpotClass.InflateSize + 1, FSpotClass.InflateSize + 1); end; function TThItemSelection.GetSpot( SpotCorner: TSpotCorner): TItemResizeSpot; var I: Integer; begin for I := 0 to FSpots.Count - 1 do begin Result := FSpots[I]; if Result.SpotCorner = SpotCorner then Exit; end; Result := nil; end; function TThItemSelection.GetSpots(Index: Integer): IItemResizeSpot; begin if FSpots.Count > Index then Result := IItemResizeSpot(TItemResizeSpot(FSpots[Index])); end; procedure TThItemSelection.ShowSpots; var I: Integer; begin for I := 0 to FSpots.Count - 1 do begin FSpots[I].Disabled := False; FSpots[I].Visible := True; end; RealignSpot; end; procedure TThItemSelection.ShowDisableSpots; var I: Integer; begin for I := 0 to FSpots.Count - 1 do begin FSpots[I].Disabled := True; FSpots[I].Visible := True; end; RealignSpot; end; procedure TThItemSelection.HideSpots; var I: Integer; begin for I := 0 to FSpots.Count - 1 do TControl(FSpots[I]).Visible := False; end; procedure TThItemSelection.DoResizeSpotTrack(Sender: TObject; X, Y: Single); var ActiveSpot: TThItemCircleResizeSpot absolute Sender; SpotCorner: TSpotCorner; BeforeSize: TSizeF; SwapHorz, SwapVert: Boolean; begin SpotCorner := ActiveSpot.SpotCorner; BeforeSize := TControl(FParent).BoundsRect.Size; ResizeItemBySpot(ActiveSpot); NormalizeSpotCorner(ActiveSpot); RealignSpot; if Assigned(FOnTracking) then begin ////////////////////////////////////////////// /// 최소크기 및 반전(RightSpot -> LeftSpot)에 대한 예외사항 SwapHorz := False; SwapVert := False; if ChangeHorizonSpotCorner(SpotCorner, ActiveSpot.SpotCorner) then begin if ContainSpotCorner(ActiveSpot.SpotCorner, scLeft) then X := -TControl(FParent).Width else X := BeforeSize.Width; SwapHorz := True; end else if TControl(FParent).Width <= FParent.MinimumSize.Width then begin if BeforeSize.Width <= FParent.MinimumSize.Width then X := 0 else if ContainSpotCorner(ActiveSpot.SpotCorner, scLeft) then X := BeforeSize.Width - FParent.MinimumSize.Width; end; if ChangeVerticalSpotCorner(SpotCorner, ActiveSpot.SpotCorner) then begin if ContainSpotCorner(ActiveSpot.SpotCorner, scTop) then Y := -TControl(FParent).Height else Y := BeforeSize.Height; SwapVert := True; end else if TControl(FParent).Height <= FParent.MinimumSize.Height then begin if BeforeSize.Height <= FParent.MinimumSize.Height then Y := 0 else if ContainSpotCorner(ActiveSpot.SpotCorner, scTop) then Y := BeforeSize.Height - FParent.MinimumSize.Height; end; FOnTracking(SpotCorner, X, Y, SwapHorz, SwapVert); end; end; procedure TThItemSelection.DrawSelection; var State: TCanvasSaveState; begin with TControl(FParent) do begin State := Canvas.SaveState; try Canvas.Stroke.Color := ItemSelectionColor; Canvas.Stroke.Thickness := ItemSelectionSize/AbsoluteScale.X; Canvas.DrawRect(ClipRect, 0, 0, AllCorners, 1); finally Canvas.RestoreState(State); end; end; end; procedure TThItemSelection.ResizeItemBySpot(ASpot: IItemResizeSpot); var MinSize: TPointF; ItemR: TRectF; ActiveSpot: TThItemCircleResizeSpot; begin ActiveSpot := TThItemCircleResizeSpot(ASpot); ItemR := GetActiveSpotsItemRect(ASpot); MinSize := FParent.MinimumSize; if ItemR.Width < MinSize.X then begin if (ItemR.Width = 0) and ContainSpotCorner(ActiveSpot.SpotCorner, scRight) then // 우측에서 좌로 올라올때 아래로 최소크기 적요되는 버그 개선 ItemR.Left := ItemR.Right - MinSize.X else if ItemR.Right = ActiveSpot.Position.X then {(ItemR.Width = 0) and ContainSpotCorner(ActiveSpot.SpotCorner, scLeft) 포함} ItemR.Right := ItemR.Left + MinSize.X else ItemR.Left := ItemR.Right - MinSize.X; end; if ItemR.Height < MinSize.Y then begin if (ItemR.Height = 0) and ContainSpotCorner(ActiveSpot.SpotCorner, scBottom) then // 아래에서 위로 올라올때 아래로 최소크기 적요되는 버그 개선 ItemR.Top := ItemR.Bottom - MinSize.Y else if ItemR.Bottom = ActiveSpot.Position.Y then {(ItemR.Height = 0) and ContainSpotCorner(ActiveSpot.SpotCorner, scBottom) 포함} ItemR.Bottom := ItemR.Top + MinSize.Y else ItemR.Top := ItemR.Bottom - MinSize.Y; end; if ItemR.Width < 1 then ItemR.Width := 1; if ItemR.Height < 1 then ItemR.Height := 1; ItemR.Offset(FParentControl.Position.Point); FParentControl.BoundsRect := ItemR; end; procedure TThItemSelection.NormalizeSpotCorner(ASpot: IItemResizeSpot); var I: Integer; ActivateSpotRect: TRectF; SpotPos: TPointF; AnotherSpot, ActiveSpot: TItemResizeSpot; ActiveSpotCorner, HSpotCorner, VSpotCorner: TSpotCorner; begin ActivateSpotRect := GetActiveSpotsItemRect(ASpot); ActiveSpot := TItemResizeSpot(ASpot); SpotPos := ActiveSpot.Position.Point; HSpotCorner := scUnknown; if ActivateSpotRect.Width = 0 then // Rect - ActiveSpot의 HorizonSpotCorner를 전환 HSpotCorner := HorizonSpotCornerExchange(AndSpotCorner(ActiveSpot.SpotCorner, HORIZON_CORNERS)) else if ActivateSpotRect.Left = SpotPos.X then HSpotCorner := scLeft else if ActivateSpotRect.Right = SpotPos.X then HSpotCorner := scRight; VSpotCorner := scUnknown; if ActivateSpotRect.Height = 0 then // Rect - ActiveSpot의 VerticalSpotCorner를 전환 VSpotCorner := VerticalSpotCornerExchange(AndSpotCorner(ActiveSpot.SpotCorner, VERTICAL_CORNERS)) else if ActivateSpotRect.Top = SpotPos.Y then VSpotCorner := scTop else if ActivateSpotRect.Bottom = SpotPos.Y then VSpotCorner := scBottom; ActiveSpotCorner := scUnknown; ActiveSpotCorner := SetHorizonSpotCorner(ActiveSpotCorner, HSpotCorner); ActiveSpotCorner := SetVerticalSpotCorner(ActiveSpotCorner, VSpotCorner); for I := 0 to Count - 1 do begin AnotherSpot := TItemResizeSpot(Spots[I]); if AnotherSpot = ActiveSpot then Continue; // Switch horizon spot if ChangeHorizonSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := HorizonSpotCornerExchange(AnotherSpot.SpotCorner); // Switch vertical spot if ChangeVerticalSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := VerticalSpotCornerExchange(AnotherSpot.SpotCorner); end; ActiveSpot.SpotCorner := ActiveSpotCorner; end; procedure TThItemSelection.RealignSpot; var I: Integer; SpotP: TPointF; ItemR: TRectF; Spot: TItemResizeSpot; begin ItemR := FParent.GetItemRect; for I := 0 to Count - 1 do begin Spot := TItemResizeSpot(Spots[I]); case Spot.SpotCorner of scTopLeft: SpotP := PointF(ItemR.Left, ItemR.Top); scTop: SpotP := PointF(RectWidth(ItemR)/2, ItemR.Top); scTopRight: SpotP := PointF(ItemR.Right, ItemR.Top); scLeft: SpotP := PointF(ItemR.Left, RectHeight(ItemR)/2); scRight: SpotP := PointF(ItemR.Right, RectHeight(ItemR)/2); scBottomLeft: SpotP := PointF(ItemR.Left, ItemR.Bottom); scBottom: SpotP := PointF(RectWidth(ItemR)/2, ItemR.Bottom); scBottomRight: SpotP := PointF(ItemR.Right, ItemR.Bottom); end; Spot.Position.Point := SpotP; end; FParentControl.Repaint; end; function TThItemSelection.GetActiveSpotsItemRect(ASpot: IItemResizeSpot): TRectF; var ActiveSpot, OppositeSpot: TItemResizeSpot; begin if not Assigned(ASpot) then ASpot := Spots[0]; ActiveSpot := TItemResizeSpot(ASpot); OppositeSpot := GetSpot(SpotCornerExchange(ActiveSpot.SpotCorner)); if not Assigned(OppositeSpot) then Exit; Result.TopLeft := ActiveSpot.Position.Point; Result.BottomRight := OppositeSpot.Position.Point; Result.NormalizeRect; end; { TThItemCircleResizeSpot } constructor TThItemCircleResizeSpot.Create(AOwner: TComponent; ADirection: TSpotCorner); begin inherited; Width := ItemResizeSpotRadius * 2; Height := ItemResizeSpotRadius * 2; end; function TThItemCircleResizeSpot.DoGetUpdateRect: TRectF; begin Result := inherited DoGetUpdateRect; if Assigned(Canvas) then begin InflateRect(Result, ItemResizeSpotRadius + Canvas.Stroke.Thickness, ItemResizeSpotRadius + Canvas.Stroke.Thickness); end; end; procedure TThItemCircleResizeSpot.Paint; var R: TRectF; begin inherited; Canvas.Stroke.Thickness := 1; Canvas.Stroke.Color := $FF222222; if FDisabled then Canvas.Fill.Color := ItemResizeSpotDisableColor else if IsMouseOver then begin // if SpotCorner = scBottomLeft then // Canvas.Fill.Color := claGreen // else if SpotCorner = scBottomRight then // Canvas.Fill.Color := claBlue // else Canvas.Fill.Color := ItemResizeSpotOverColor end else Canvas.Fill.Color := ItemResizeSpotOutColor; R := R.Empty; InflateRect(R, ItemResizeSpotRadius, ItemResizeSpotRadius); Canvas.FillEllipse(R, 1); Canvas.DrawEllipse(R, 1); end; { TThLineSelection } procedure TThLineSelection.DrawSelection; begin end; procedure TThLineSelection.NormalizeSpotCorner(ASpot: IItemResizeSpot); var I: Integer; ActivateSpotRect: TRectF; SpotPos: TPointF; AnotherSpot, ActiveSpot: TItemResizeSpot; ActiveSpotCorner, HSpotCorner, VSpotCorner: TSpotCorner; begin ActivateSpotRect := GetActiveSpotsItemRect(ASpot); ActiveSpot := TItemResizeSpot(ASpot); SpotPos := ActiveSpot.Position.Point; if ActivateSpotRect.Width = 0 then // Line ActiveSpotCorner := IfThenSpotCorner(ActivateSpotRect.Top = SpotPos.Y, scTop, scBottom) else if ActivateSpotRect.Height = 0 then // Line ActiveSpotCorner := IfThenSpotCorner(ActivateSpotRect.Left = SpotPos.X, scLeft, scRight) else begin HSpotCorner := scUnknown; if ActivateSpotRect.Left = SpotPos.X then HSpotCorner := scLeft else if ActivateSpotRect.Right = SpotPos.X then HSpotCorner := scRight; VSpotCorner := scUnknown; if ActivateSpotRect.Top = SpotPos.Y then VSpotCorner := scTop else if ActivateSpotRect.Bottom = SpotPos.Y then VSpotCorner := scBottom; ActiveSpotCorner := scUnknown; ActiveSpotCorner := SetHorizonSpotCorner(ActiveSpotCorner, HSpotCorner); ActiveSpotCorner := SetVerticalSpotCorner(ActiveSpotCorner, VSpotCorner); end; for I := 0 to Count - 1 do begin AnotherSpot := TItemResizeSpot(Spots[I]); if AnotherSpot = ActiveSpot then Continue; // [Line] Top(Bottom)으로 변경한경우 TopLeft, BottomRight에서는 Bottom(Top)으로 처리 if not SupportedHorizonSpotCorner(ActiveSpotCorner) and SupportedHorizonSpotCorner(AnotherSpot.SpotCorner) then begin AnotherSpot.SpotCorner := VerticalSpotCornerExchange(ActiveSpotCorner); Continue; end; if not SupportedVerticalSpotCorner(ActiveSpotCorner) and SupportedVerticalSpotCorner(AnotherSpot.SpotCorner) then begin AnotherSpot.SpotCorner := HorizonSpotCornerExchange(ActiveSpotCorner); Continue; end; if SupportedHorizonSpotCorner(ActiveSpotCorner) and not SupportedHorizonSpotCorner(AnotherSpot.SpotCorner) or SupportedVerticalSpotCorner(ActiveSpotCorner) and not SupportedVerticalSpotCorner(AnotherSpot.SpotCorner) then begin AnotherSpot.SpotCorner := SpotCornerExchange(ActiveSpotCorner); Continue; end; // Switch horizon spot if ChangeHorizonSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := HorizonSpotCornerExchange(AnotherSpot.SpotCorner); // Switch vertical spot if ChangeVerticalSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := VerticalSpotCornerExchange(AnotherSpot.SpotCorner); end; ActiveSpot.SpotCorner := ActiveSpotCorner; end; procedure TThLineSelection.RealignSpot; var I: Integer; SpotP: TPointF; ItemR: TRectF; Spot: TItemResizeSpot; begin ItemR := FParent.GetItemRect; for I := 0 to Count - 1 do begin Spot := TItemResizeSpot(Spots[I]); case Spot.SpotCorner of scTopLeft: SpotP := PointF(ItemR.Left, ItemR.Top); scTop: SpotP := PointF(0, ItemR.Top); scTopRight: SpotP := PointF(ItemR.Right, ItemR.Top); scLeft: SpotP := PointF(ItemR.Left, 0); scRight: SpotP := PointF(ItemR.Right, 0); scBottomLeft: SpotP := PointF(ItemR.Left, ItemR.Bottom); scBottom: SpotP := PointF(0, ItemR.Bottom); scBottomRight: SpotP := PointF(ItemR.Right, ItemR.Bottom); end; Spot.Position.Point := SpotP; end; FParentControl.Repaint; end; { TThCircleSelection } procedure TThCircleSelection.NormalizeSpotCorner(ASpot: IItemResizeSpot); var I: Integer; ActivateSpotRect: TRectF; SpotPos: TPointF; AnotherSpot, ActiveSpot: TItemResizeSpot; ActiveSpotCorner: TSpotCorner; begin ActivateSpotRect := GetActiveSpotsItemRect(ASpot); ActiveSpot := TItemResizeSpot(ASpot); SpotPos := ActiveSpot.Position.Point; ActiveSpotCorner := scUnknown; // 가로축, 세로축으로만 변경 if SupportedHorizonSpotCorner(ActiveSpot.SpotCorner) then begin if ActivateSpotRect.Width = 0 then // Rect - ActiveSpot의 HorizonSpotCorner를 전환 ActiveSpotCorner := HorizonSpotCornerExchange(AndSpotCorner(ActiveSpot.SpotCorner, HORIZON_CORNERS)) else if ActivateSpotRect.Left = SpotPos.X then ActiveSpotCorner := scLeft else if ActivateSpotRect.Right = SpotPos.X then ActiveSpotCorner := scRight; end else if SupportedVerticalSpotCorner(ActiveSpot.SpotCorner) then begin if ActivateSpotRect.Height = 0 then // Rect - ActiveSpot의 VerticalSpotCorner를 전환 ActiveSpotCorner := VerticalSpotCornerExchange(AndSpotCorner(ActiveSpot.SpotCorner, VERTICAL_CORNERS)) else if ActivateSpotRect.Top = SpotPos.Y then ActiveSpotCorner := scTop else if ActivateSpotRect.Bottom = SpotPos.Y then ActiveSpotCorner := scBottom; end; for I := 0 to Count - 1 do begin AnotherSpot := TItemResizeSpot(Spots[I]); if AnotherSpot = ActiveSpot then Continue; // Switch horizon spot if ChangeHorizonSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := HorizonSpotCornerExchange(AnotherSpot.SpotCorner); // Switch vertical spot if ChangeVerticalSpotCorner(ActiveSpot.SpotCorner, ActiveSpotCorner) then AnotherSpot.SpotCorner := VerticalSpotCornerExchange(AnotherSpot.SpotCorner); end; ActiveSpot.SpotCorner := ActiveSpotCorner; end; function TThCircleSelection.GetActiveSpotsItemRect(ASpot: IItemResizeSpot): TRectF; var ActiveSpot, OppositeSpot: TItemResizeSpot; begin if not Assigned(ASpot) then ASpot := Spots[0]; ActiveSpot := TItemResizeSpot(ASpot); OppositeSpot := GetSpot(SpotCornerExchange(ActiveSpot.SpotCorner)); if not Assigned(OppositeSpot) then Exit; Result := FParent.GetItemRect; case ActiveSpot.SpotCorner of scTop, scBottom: begin Result.Top := ActiveSpot.Position.Y; Result.Bottom := OppositeSpot.Position.Y; end; scLeft, scRight: begin Result.Left := ActiveSpot.Position.X; Result.Right := OppositeSpot.Position.X; end; end; Result.NormalizeRect; end; end.
unit integerhash; //============================================================================= interface //============================================================================= uses hashtable, comparable, sysutils; type TIntHashIterator = class(THashTableIterator) public function getKey: integer; reintroduce; property key: integer read getKey; // property value: TObject read getValue; //protected // constructor create(table: THashTable); end; TIntegerHash = class(TObject) private fHashTable: THashTable; protected procedure fSetValue(key: integer; value: TObject); virtual; public function getIterator: TIntHashIterator; virtual; function containsKey(key: integer): Boolean; virtual; function containsValue(value: TObject): Boolean; virtual; function getValue(key: integer): TObject; virtual; function setValue(key: integer; value: TObject): Boolean; virtual; function remove(key: integer): TObject; virtual; function getCount: integer; virtual; property values[key: integer]: TObject read getValue write fsetValue; property count: integer read getCount; {$IFNDEF FPC} constructor create(initialcapacity: integer = 10); {$ELSE FPC} constructor create; constructor create(initialcapacity: integer); {$ENDIF FPC} destructor destroy; override; procedure clear; virtual; procedure deleteAll; virtual; end; //============================================================================= implementation //============================================================================= // tSHIterator - iterator for integer hash table // basically an adapter shell for tMapIterator procedure throwTypeException(const className: string); begin raise exception.create('Wrong type. Expecting tInteger, got ' + className); end; function TIntHashIterator.getKey: integer; var s: TObject; begin s := inherited getKey; if not (s is tInteger) then throwTypeException(s.ClassName); result := tInteger(s).value; end; (* constructor TIntHashIterator.create(table: THashTable); begin inherited create(table); end; *) //--------------------------------------------------------------------------- // TIntegerHash //--------------------------------------------------------------------------- procedure TIntegerHash.fSetValue(key: integer; value: TObject); begin setValue(key, value); end; function TIntegerHash.getIterator: TIntHashIterator; begin result := TIntHashIterator.create(fHashTable); end; function TIntegerHash.containsKey(key: integer): Boolean; var s: tInteger; begin s := tInteger.create(key); try result := fHashTable.containsKey(s); finally s.free; end; end; function TIntegerHash.containsValue(value: TObject): Boolean; begin result := fHashTable.containsValue(tComparable(value)) end; function TIntegerHash.getValue(key: integer): TObject; var s: tInteger; begin s := tInteger.create(key); try result := fHashTable.getValue(s); finally s.free; end; end; function TIntegerHash.setValue(key: integer; value: TObject): Boolean; begin result := fHashTable.setValue(tInteger.create(key), value); end; function TIntegerHash.remove(key: integer): TObject; var s: tInteger; begin s := tInteger.create(key); try result := fHashTable.remove(s); finally //s.free; end; end; function TIntegerHash.getCount: integer; begin result := fHashTable.getCount; end; {$IFNDEF FPC} constructor TIntegerHash.create(initialcapacity: integer = 10); begin inherited create; fHashTable := THashTable.create(initialcapacity); end; {$ELSE FPC} constructor TIntegerHash.create; begin inherited create; fHashTable := THashTable.create; end; constructor TIntegerHash.create(initialcapacity: integer); begin inherited create; fHashTable := THashTable.create(initialcapacity, 0.75, nil, true); end; {$ENDIF FPC} destructor TIntegerHash.destroy; begin fHashTable.destroy; inherited destroy; end; procedure TIntegerHash.clear; begin fHashTable.clear; end; procedure TIntegerHash.deleteAll; begin fHashTable.deleteAll; end; end.
unit Svg_Proc; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,USVG,USVGGraphics32, GR32, GR32_Image,ExtCtrls; type TForm1 = class(TForm) Open: TButton; ImgView: TImgView32; Panel1: TPanel; CUseAlpha: TCheckBox; BPNGSave: TButton; procedure OpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BPNGSaveClick(Sender: TObject); private { Déclarations privées } public end; var Form1: TForm1; implementation uses GdiPng; {$R *.dfm} procedure TForm1.OpenClick(Sender: TObject); var Doc:TSVGLoader; S:string; begin if not PromptForfilename(s,'*.svg|*.svg','.svg') then Exit; Doc:=TSVGLoader.Create(ImgView.Bitmap ); ImgView.Bitmap.BeginUpdate; try Doc.LoadFromFile(S); finally ImgView.Bitmap.EndUpdate; end; Doc.Free; ImgView.Refresh; end; procedure TForm1.BPNGSaveClick(Sender: TObject); var S:string; FS:TFilestream; begin if not PromptForFilename(S,'png|*.png','.png','','',True) then Exit; FS:=TFilestream.Create(S,fmCreate); try Bitmap32ToPNGStream(ImgView.Bitmap,FS,CuseAlpha.Checked); finally FS.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); begin ImgView.SetupBitmap(True,Color32(ImgView.Color)); end; end.
unit URepositorioMovimentacao; interface uses UTipoMovimentacao , URepositorioTipoMovimentacao , UProduto , URepositorioProduto , UStatus , URepositorioStatus , UDeposito , URepositorioDeposito , URequisicaoEstoque , URepositorioRequisicaoEstoque , UMovimentacao , UEntidade , URepositorioDB , URepositorioPais , SqlExpr ; type TRepositorioMovimentacao = class(TRepositorioDB<TMOVIMETNACAO>) private FRepositorioProduto : TRepositorioProduto; FRepositorioStatus : TRepositorioStatus; FRepositorioDeposito : TRepositorioDeposito; FRepositorioRequisicaoEstoque : TRepositorioRequisicaoEstoque; FRepositorioTipoMovimentacao : TRepositorioTipoMovimentacao; public constructor Create; destructor Destroy; override; procedure AtribuiDBParaEntidade(const coMOVIMENTACAO: TMOVIMETNACAO); override; procedure AtribuiEntidadeParaDB(const coMOVIMENTACAO: TMOVIMETNACAO; const coSQLQuery: TSQLQuery); override; end; implementation { TRepositorioMovimentacao } uses UDM , SysUtils ; procedure TRepositorioMovimentacao.AtribuiDBParaEntidade( const coMOVIMENTACAO: TMOVIMETNACAO); begin inherited; with FSQLSelect do begin coMOVIMENTACAO.TIPOMOVIMENTACAO := TTIPOMOVIMENTACAO( FRepositorioTipoMovimentacao.Retorna(FieldByName(FLD_MOVIMENTACAO_TIPO).AsInteger)); coMOVIMENTACAO.PRODUTO := TPRODUTO( FRepositorioProduto.Retorna(FieldByName(FLD_MOVIMENTACAO_PRODUTO).AsInteger)); coMOVIMENTACAO.STATUS := TSTATUS( FRepositorioStatus.Retorna(FieldByName(FLD_MOVIMENTACAO_STATUS).AsInteger)); coMOVIMENTACAO.DEPOSITO := TDEPOSITO( FRepositorioDeposito.Retorna(FieldByName(FLD_MOVIMENTACAO_DEPOSITO).AsInteger)); coMOVIMENTACAO.REQUISICAO := TREQUISICAOESTOQUE( FRepositorioRequisicaoEstoque.Retorna(FieldByName(FLD_MOVIMENTACAO_REQUISICAO).AsInteger)); coMOVIMENTACAO.QUANTIDADE := FieldByName(FLD_MOVIMENTACAO_QUANTIDADE).AsFloat; coMOVIMENTACAO.SITUACAO := TSituacao(FieldByName(FLD_MOVIMENTACAO_SITUACAO).AsInteger); coMOVIMENTACAO.DATA := FieldByName(FLD_MOVIMENTACAO_DATA).AsDateTime; end; end; procedure TRepositorioMovimentacao.AtribuiEntidadeParaDB( const coMOVIMENTACAO: TMOVIMETNACAO; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_MOVIMENTACAO_TIPO).AsInteger := coMOVIMENTACAO.TIPOMOVIMENTACAO.ID; ParamByName(FLD_MOVIMENTACAO_PRODUTO).AsInteger := coMOVIMENTACAO.PRODUTO.ID; ParamByName(FLD_MOVIMENTACAO_STATUS).AsInteger := coMOVIMENTACAO.STATUS.ID; ParamByName(FLD_MOVIMENTACAO_DEPOSITO).AsInteger := coMOVIMENTACAO.DEPOSITO.ID; ParamByName(FLD_MOVIMENTACAO_REQUISICAO).AsInteger := coMOVIMENTACAO.REQUISICAO.ID; ParamByName(FLD_MOVIMENTACAO_DATA).AsDateTime := coMOVIMENTACAO.DATA; ParamByName(FLD_MOVIMENTACAO_QUANTIDADE).AsFloat := coMOVIMENTACAO.QUANTIDADE; ParamByName(FLD_MOVIMENTACAO_SITUACAO).AsInteger := Integer(coMOVIMENTACAO.SITUACAO); end; end; constructor TRepositorioMovimentacao.Create; begin inherited Create(TMOVIMETNACAO, TBL_MOVIMENTACAO, FLD_ENTIDADE_ID, STR_MOVIMENTACAO); FRepositorioProduto := TRepositorioProduto.Create; FRepositorioStatus := TRepositorioStatus.Create; FRepositorioDeposito := TRepositorioDeposito.create; //FRepositorioRequisicaoEstoque := TRepositorioRequisicaoEstoque.; FRepositorioTipoMovimentacao := TRepositorioTipoMovimentacao.Create; end; destructor TRepositorioMovimentacao.Destroy; begin FreeAndNil(FRepositorioProduto); FreeAndNil(FRepositorioStatus); FreeAndNil(FRepositorioDeposito); FreeAndNil(FRepositorioRequisicaoEstoque); FreeAndNil(FRepositorioTipoMovimentacao); inherited; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.IDE.ProjectMenu; interface uses System.Classes, VCL.Menus, ToolsAPI, DPM.IDE.EditorViewManager; type TDPMProjectMenuNotifier = class(TInterfacedObject, IOTAProjectMenuItemCreatorNotifier, IOTANotifier) private FEditorViewManager : IDPMEditorViewManager; protected procedure AddMenu(const Project : IOTAProject; const IdentList : TStrings; const ProjectManagerMenuList : IInterfaceList; IsMultiSelect : Boolean); procedure AfterSave; procedure BeforeSave; procedure Destroyed; procedure Modified; //procedure OnManagePackages(Sender : TObject); public constructor Create(const editorViewManager : IDPMEditorViewManager); end; TDPMProjectMenu = class(TInterfacedObject, IOTANotifier, IOTALocalMenu, IOTAProjectManagerMenu) private FProject : IOTAProject; FProjectGroup : IOTAProjectGroup; FEditorViewManager : IDPMEditorViewManager; protected //IOTANotifier procedure AfterSave; procedure BeforeSave; procedure Destroyed; procedure Modified; //IOTALocalMenu function GetCaption : string; function GetChecked : Boolean; function GetEnabled : Boolean; function GetHelpContext : Integer; function GetName : string; function GetParent : string; function GetPosition : Integer; function GetVerb : string; procedure SetCaption(const Value : string); procedure SetChecked(Value : Boolean); procedure SetEnabled(Value : Boolean); procedure SetHelpContext(Value : Integer); procedure SetName(const Value : string); procedure SetParent(const Value : string); procedure SetPosition(Value : Integer); procedure SetVerb(const Value : string); procedure Execute(const MenuContextList : IInterfaceList); function GetIsMultiSelectable : Boolean; function PostExecute(const MenuContextList : IInterfaceList) : Boolean; function PreExecute(const MenuContextList : IInterfaceList) : Boolean; procedure SetIsMultiSelectable(Value : Boolean); public constructor Create(const projectGroup : IOTAProjectGroup; const project : IOTAProject; const editorViewManager : IDPMEditorViewManager); end; implementation uses System.SysUtils, Vcl.Dialogs, DPM.IDE.Constants; { TDPMProjectMenu } procedure TDPMProjectMenuNotifier.AddMenu(const Project : IOTAProject; const IdentList : TStrings; const ProjectManagerMenuList : IInterfaceList; IsMultiSelect : Boolean); var menu : IOTAProjectManagerMenu; projectGroup : IOTAProjectGroup; proj : IOTAProject; begin //TODO : Uncomment section below when project groups are supported. if Assigned(Project) and ((IdentList.IndexOf(cDPMContainer) <> -1) or (IdentList.IndexOf(sProjectContainer) <> -1) or (IdentList.IndexOf(sProjectGroupContainer) <> -1) ) then begin proj := Project; if (proj <> nil) and Supports(proj, IOTAProjectGroup, projectGroup) then proj := nil else projectGroup := (BorlandIDEServices as IOTAModuleServices).MainProjectGroup; Assert(projectGroup <> nil); menu := TDPMProjectMenu.Create(projectGroup, proj, FEditorViewManager); ProjectManagerMenuList.Add(menu); end; end; procedure TDPMProjectMenuNotifier.AfterSave; begin end; procedure TDPMProjectMenuNotifier.BeforeSave; begin end; constructor TDPMProjectMenuNotifier.Create(const editorViewManager : IDPMEditorViewManager); begin FEditorViewManager := editorViewManager; end; procedure TDPMProjectMenuNotifier.Destroyed; begin FEditorViewManager.Destroyed; FEditorViewManager := nil; end; procedure TDPMProjectMenuNotifier.Modified; begin end; { TDPMProjectMenu } procedure TDPMProjectMenu.AfterSave; begin end; procedure TDPMProjectMenu.BeforeSave; begin end; constructor TDPMProjectMenu.Create(const projectGroup : IOTAProjectGroup; const project : IOTAProject; const editorViewManager : IDPMEditorViewManager); begin FProjectGroup := projectGroup; FProject := project; FEditorViewManager := editorViewManager; Assert(FProjectGroup <> nil); end; procedure TDPMProjectMenu.Destroyed; begin FEditorViewManager.Destroyed; FEditorViewManager := nil; FProject := nil; end; procedure TDPMProjectMenu.Execute(const MenuContextList : IInterfaceList); begin FEditorViewManager.ShowViewForProject(FProjectGroup, FProject); end; function TDPMProjectMenu.GetCaption : string; begin if FProject <> nil then result := Format('Manage DPM Packages : %s', [ExtractFileName(FProject.FileName)]) else result := 'Manage DPM Packages for Project Group'; end; function TDPMProjectMenu.GetChecked : Boolean; begin result := false; end; function TDPMProjectMenu.GetEnabled : Boolean; begin //since we may need to work directly with the file, it must have been saved before we can manage packages. result := true;// FileExists(FProject.FileName); end; function TDPMProjectMenu.GetHelpContext : Integer; begin result := -1; end; function TDPMProjectMenu.GetIsMultiSelectable : Boolean; begin result := true; end; function TDPMProjectMenu.GetName : string; begin result := 'ManageDPM'; end; function TDPMProjectMenu.GetParent : string; begin result := ''; end; function TDPMProjectMenu.GetPosition : Integer; begin result := pmmpCompile; end; function TDPMProjectMenu.GetVerb : string; begin result := 'ManageDPM'; end; procedure TDPMProjectMenu.Modified; begin end; function TDPMProjectMenu.PostExecute(const MenuContextList : IInterfaceList) : Boolean; begin Result := True; end; function TDPMProjectMenu.PreExecute(const MenuContextList : IInterfaceList) : Boolean; begin Result := True; end; procedure TDPMProjectMenu.SetCaption(const Value : string); begin end; procedure TDPMProjectMenu.SetChecked(Value : Boolean); begin end; procedure TDPMProjectMenu.SetEnabled(Value : Boolean); begin end; procedure TDPMProjectMenu.SetHelpContext(Value : Integer); begin end; procedure TDPMProjectMenu.SetIsMultiSelectable(Value : Boolean); begin end; procedure TDPMProjectMenu.SetName(const Value : string); begin end; procedure TDPMProjectMenu.SetParent(const Value : string); begin end; procedure TDPMProjectMenu.SetPosition(Value : Integer); begin end; procedure TDPMProjectMenu.SetVerb(const Value : string); begin end; end.
unit St_sp_Category_Class_Form_Add; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxLabel, cxControls, cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons; type TClassCategoryFormAdd = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameLabel: TcxLabel; NameEdit: TcxTextEdit; PeopleLabel: TcxLabel; PeopleEdit: TcxTextEdit; PlaceLabel: TcxLabel; PlaceEdit: TcxTextEdit; procedure FormShow(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OKButtonClick(Sender: TObject); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure PeopleEditKeyPress(Sender: TObject; var Key: Char); procedure PlaceEditKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var ClassCategoryFormAdd: TClassCategoryFormAdd; implementation uses Unit_of_Utilits; {$R *.dfm} procedure TClassCategoryFormAdd.FormShow(Sender: TObject); begin NameEdit.SetFocus; end; procedure TClassCategoryFormAdd.CancelButtonClick(Sender: TObject); begin Close; end; procedure TClassCategoryFormAdd.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TClassCategoryFormAdd.OKButtonClick(Sender: TObject); begin if NameEdit.Text = '' then begin ShowMessage('Необходимо ввести наименование.'); NameEdit.SetFocus; exit; end; if not IntegerCheck(PeopleEdit.Text) then begin ShowMessage('Количество людей введено неверно.'); PeopleEdit.SetFocus; exit; end; if not FloatCheck(PlaceEdit.Text) then begin ShowMessage('Количество мест введено неверно.'); PlaceEdit.Setfocus; exit; end; ModalResult := mrOK; end; procedure TClassCategoryFormAdd.NameEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PeopleEdit.SetFocus; end; procedure TClassCategoryFormAdd.PeopleEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PlaceEdit.SetFocus; end; procedure TClassCategoryFormAdd.PlaceEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then OkButton.SetFocus; end; end.
unit mclform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Types; type TMCLFormHandlerType = ( fhClick, fhCloseQuery, fhCreate, fhDblClick, fhHide, fhKeyDown, fhKeyPress, fhKeyUp, fhMouseDown, fhMouseEnter, fhMouseLeave, fhMouseUp, fhMouseMove, fhMouseWheel, fhMouseWheelDown, fhMouseWheelHorz, fhMouseWheelLeft, fhMouseWheelRight, fhMouseWheelUp, fhResize, fhShow, fhWindowStateChange ); TMCLFormHandlerInfo = class public Addr: Cardinal; Arg : Pointer; constructor Create(_Addr: Cardinal; _Arg: Pointer); end; TMCLFormEvent = class HandlerType: TMCLFormHandlerType; Args: TList; constructor Create(hType: TMCLFormHandlerType); destructor Destroy; override; end; { TMCLFormClass } TMCLFormClass = class(TForm) procedure FormClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormCreate(Sender: TObject); procedure FormDblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: char); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseEnter(Sender: TObject); procedure FormMouseLeave(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelHorz(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelLeft(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelRight(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormWindowStateChange(Sender: TObject); public EventHandlers: array[fhClick..fhWindowStateChange] of TMCLFormHandlerInfo; EventStack: TThreadList; procedure RegHandler(Addr: cardinal; Arg: Pointer; HandlerType: TMCLFormHandlerType); function PopEvent: TMCLFormEvent; end; var MCLFormClass: TMCLFormClass; implementation {$R *.lfm} { TMCLFormClass } {** Architecture **} constructor TMCLFormHandlerInfo.Create(_Addr: Cardinal; _Arg: Pointer); begin Addr := _Addr; Arg := _Arg; end; constructor TMCLFormEvent.Create(hType: TMCLFormHandlerType); begin HandlerType := hType; Args := TList.Create; end; destructor TMCLFormEvent.Destroy; begin FreeAndNil(Args); inherited; end; procedure TMCLFormClass.FormCreate(Sender: TObject); var b: byte; begin for b := 0 to Length(EventHandlers) - 1 do EventHandlers[TMCLFormHandlerType(b)] := nil; EventStack := TThreadList.Create; end; procedure TMCLFormClass.FormDestroy(Sender: TObject); var b: byte; begin for b := 0 to Length(EventHandlers) - 1 do if EventHandlers[TMCLFormHandlerType(b)] <> nil then FreeAndNil(EventHandlers); with EventStack.LockList do try while Count > 0 do begin TMCLFormEvent(Items[0]).Free; Delete(0) end; finally FreeAndNil(EventStack); end; end; procedure TMCLFormClass.RegHandler(Addr: cardinal; Arg: Pointer; HandlerType: TMCLFormHandlerType); var OldHandler: TMCLFormHandlerInfo; begin OldHandler := nil; if EventHandlers[HandlerType] <> nil then OldHandler := EventHandlers[HandlerType]; EventHandlers[HandlerType] := TMCLFormHandlerInfo.Create(Addr, Arg); if OldHandler <> nil then FreeAndNil(OldHandler); end; function TMCLFormClass.PopEvent: TMCLFormEvent; begin Result := nil; with EventStack.LockList do try if Count > 0 then begin Result := TMCLFormEvent(Items[0]); Delete(0); end; finally EventStack.UnlockList; end; end; {** Handlers **} procedure TMCLFormClass.FormClick(Sender: TObject); begin if EventHandlers[fhClick] <> nil then EventStack.Add(TMCLFormEvent.Create(fhClick)); end; procedure TMCLFormClass.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin if EventHandlers[fhCloseQuery] <> nil then begin EventStack.Add(TMCLFormEvent.Create(fhCloseQuery)); CanClose := false; end; end; procedure TMCLFormClass.FormDblClick(Sender: TObject); begin if EventHandlers[fhDblClick] <> nil then EventStack.Add(TMCLFormEvent.Create(fhDblClick)); end; procedure TMCLFormClass.FormHide(Sender: TObject); begin if EventHandlers[fhHide] <> nil then EventStack.Add(TMCLFormEvent.Create(fhHide)); end; procedure TMCLFormClass.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Ev: TMCLFormEvent; begin if EventHandlers[fhKeyDown] <> nil then begin Ev := TMCLFormEvent.Create(fhKeyDown); Ev.Args.Add(Pointer( LongWord(Key) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormKeyPress(Sender: TObject; var Key: char); var Ev: TMCLFormEvent; begin if EventHandlers[fhKeyPress] <> nil then begin Ev := TMCLFormEvent.Create(fhKeyPress); Ev.Args.Add(Pointer( Ord(Key) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Ev: TMCLFormEvent; begin if EventHandlers[fhKeyUp] <> nil then begin Ev := TMCLFormEvent.Create(fhKeyUp); Ev.Args.Add(Pointer( LongWord(Key) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Ev: TMCLFormEvent; begin if EventHandlers[fhMouseDown] <> nil then begin Ev := TMCLFormEvent.Create(fhMouseDown); Ev.Args.Add(Pointer( LongWord(X) )); Ev.Args.Add(Pointer( LongWord(Y) )); Ev.Args.Add(Pointer( LongWord(Byte(Button)) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormMouseEnter(Sender: TObject); begin if EventHandlers[fhMouseEnter] <> nil then EventStack.Add(TMCLFormEvent.Create(fhMouseEnter)); end; procedure TMCLFormClass.FormMouseLeave(Sender: TObject); begin if EventHandlers[fhMouseLeave] <> nil then EventStack.Add(TMCLFormEvent.Create(fhMouseLeave)); end; procedure TMCLFormClass.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var Ev: TMCLFormEvent; begin if EventHandlers[fhMouseMove] <> nil then begin Ev := TMCLFormEvent.Create(fhMouseMove); Ev.Args.Add(Pointer( LongWord(X) )); Ev.Args.Add(Pointer( LongWord(Y) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Ev: TMCLFormEvent; begin if EventHandlers[fhMouseUp] <> nil then begin Ev := TMCLFormEvent.Create(fhMouseUp); Ev.Args.Add(Pointer( LongWord(X) )); Ev.Args.Add(Pointer( LongWord(Y) )); Ev.Args.Add(Pointer( LongWord(Byte(Button)) )); EventStack.Add(Ev); end; end; procedure TMCLFormClass.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormMouseWheelHorz(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormMouseWheelLeft(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormMouseWheelRight(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin end; procedure TMCLFormClass.FormResize(Sender: TObject); begin end; procedure TMCLFormClass.FormShow(Sender: TObject); begin end; procedure TMCLFormClass.FormWindowStateChange(Sender: TObject); begin end; end.
unit fre_monitoring; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH Licence conditions (§LIC_END) } {$codepage UTF8} {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FRE_DB_INTERFACE, FRE_DB_COMMON,fos_tool_interfaces,fre_system,fre_diff_transport; type TFRE_DB_MOS_STATUS_TYPE = (fdbstat_ok, fdbstat_warning, fdbstat_error, fdbstat_unknown); const CFRE_DB_MOS_STATUS : array [TFRE_DB_MOS_STATUS_TYPE] of string = ('stat_ok','stat_warning','stat_error','stat_unknown'); CFRE_DB_MOS_COLLECTION = 'monitoring'; type { TFRE_DB_VIRTUALMOSOBJECT } TFRE_DB_VIRTUALMOSOBJECT = class(TFRE_DB_ObjectEx) private procedure SetCaption (const AValue: TFRE_DB_String); function GetCaption : TFRE_DB_String; public class procedure RegisterSystemScheme (const scheme: IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; property caption : TFRE_DB_String read GetCaption write SetCaption; procedure SetMOSStatus (const status: TFRE_DB_MOS_STATUS_TYPE; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION); function GetMOSStatus : TFRE_DB_MOS_STATUS_TYPE; procedure SetMOSKey (const avalue: TFRE_DB_String); function GetMOSKey : TFRE_DB_String; published function WEB_MOSChildStatusChanged (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_MOSStatus (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object; function WEB_MOSContent (const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):IFRE_DB_Object;virtual;abstract; end; procedure Register_DB_Extensions; procedure GFRE_MOS_SetMOSStatusandUpdate (const mosobject:IFRE_DB_Object;const status: TFRE_DB_MOS_STATUS_TYPE; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION); function GFRE_MOS_MOSChildStatusChanged (const mos_UID: TFRE_DB_GUID;const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION):TFRE_DB_MOS_STATUS_TYPE; function String2DBMOSStatus (const fts: string): TFRE_DB_MOS_STATUS_TYPE; procedure CreateMonitoringCollections (const conn: IFRE_DB_COnnection); implementation procedure GFRE_MOS_SetMOSStatusandUpdate(const mosobject: IFRE_DB_Object; const status: TFRE_DB_MOS_STATUS_TYPE; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION); var i : Integer; mosParent : IFRE_DB_Object; mosParents: TFRE_DB_ObjLinkArray; begin if String2DBMOSStatus(mosobject.Field('status_mos').AsString)<>status then begin mosobject.Field('status_mos').AsString:=CFRE_DB_MOS_STATUS[status]; mosParents:=mosobject.Field('mosparentIds').AsObjectLinkArray; CheckDbResult(conn.Update(mosobject)); for i := 0 to Length(mosParents) - 1 do begin CheckDbResult(conn.Fetch(mosParents[i],mosParent)); if mosParent.MethodExists('MOSChildStatusChanged') then begin mosParent.Invoke('MOSChildStatusChanged',input,ses,app,conn); end; end; end; end; function GFRE_MOS_MOSChildStatusChanged(const mos_UID: TFRE_DB_GUID; const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): TFRE_DB_MOS_STATUS_TYPE; var refs : TFRE_DB_GUIDArray; i : Integer; refObj : IFRE_DB_Object; newStatus : TFRE_DB_MOS_STATUS_TYPE; child_stat: IFRE_DB_Object; begin refs:=conn.GetReferences(mos_UID,false,'','MOSPARENTIDS'); //FIXXME - new implementation? newStatus:=fdbstat_ok; for i := 0 to Length(refs) - 1 do begin CheckDbResult(conn.Fetch(refs[i],refObj)); writeln('SWL: GET MOSSTATUS',refobj.SchemeClass); if refObj.MethodExists('MOSStatus') then begin child_stat:=refObj.Invoke('MOSStatus',input,ses,app,conn); case String2DBMOSStatus(child_stat.Field('status_mos').AsString) of fdbstat_ok : ; //do nothing fdbstat_warning: if newStatus=fdbstat_ok then newStatus:=fdbstat_warning; fdbstat_error : newStatus:=fdbstat_error; fdbstat_unknown: begin exit(fdbstat_unknown); end; end; end else begin exit(fdbstat_unknown); end; end; result := newStatus; end; function String2DBMOSStatus(const fts: string): TFRE_DB_MOS_STATUS_TYPE; begin for Result in TFRE_DB_MOS_STATUS_TYPE do begin if CFRE_DB_MOS_STATUS[Result]=fts then exit; end; end; procedure CreateMonitoringCollections(const conn: IFRE_DB_COnnection); var collection: IFRE_DB_COLLECTION; begin if not conn.CollectionExists(CFRE_DB_MOS_COLLECTION) then begin collection := conn.CreateCollection(CFRE_DB_MOS_COLLECTION); collection.DefineIndexOnField('key_mos',fdbft_String,true,true,'def',true); end; end; procedure Register_DB_Extensions; begin GFRE_DBI.RegisterObjectClassEx(TFRE_DB_VIRTUALMOSOBJECT); //GFRE_DBI.Initialize_Extension_Objects; end; { TFRE_DB_VIRTUALMOSOBJECT } function TFRE_DB_VIRTUALMOSOBJECT.GetCaption: TFRE_DB_String; begin Result:=Field('caption_mos').AsString; end; function TFRE_DB_VIRTUALMOSOBJECT.GetMOSStatus: TFRE_DB_MOS_STATUS_TYPE; begin Result:=String2DBMOSStatus(Field('status_mos').AsString); end; procedure TFRE_DB_VIRTUALMOSOBJECT.SetMOSKey(const avalue: TFRE_DB_String); begin Field('key_mos').AsString:=AValue; end; function TFRE_DB_VIRTUALMOSOBJECT.GetMOSKey: TFRE_DB_String; begin result :=Field('key_mos').AsString; end; procedure TFRE_DB_VIRTUALMOSOBJECT.SetCaption(const AValue: TFRE_DB_String); begin Field('caption_mos').AsString:=AValue; end; procedure TFRE_DB_VIRTUALMOSOBJECT.SetMOSStatus(const status: TFRE_DB_MOS_STATUS_TYPE; const input:IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION); begin GFRE_MOS_SetMOSStatusandUpdate(self,status,input,ses,app,conn); end; class procedure TFRE_DB_VIRTUALMOSOBJECT.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_OBJECTEX'); scheme.AddSchemeField('caption_mos',fdbft_String); scheme.AddSchemeField('status_mos',fdbft_String); scheme.AddSchemeField('key_mos',fdbft_String); end; class procedure TFRE_DB_VIRTUALMOSOBJECT.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if currentVersionId='' then begin currentVersionId := '1.0'; end; end; function TFRE_DB_VIRTUALMOSOBJECT.WEB_MOSChildStatusChanged(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin SetMOSStatus(GFRE_MOS_MOSChildStatusChanged(UID,input,ses,app,conn),input,ses,app,conn); Result:=GFRE_DB_NIL_DESC; end; function TFRE_DB_VIRTUALMOSOBJECT.WEB_MOSStatus(const input: IFRE_DB_Object; const ses: IFRE_DB_Usersession; const app: IFRE_DB_APPLICATION; const conn: IFRE_DB_CONNECTION): IFRE_DB_Object; begin Result:=GFRE_DBI.NewObject; Result.Field('status_mos').AsString:=Field('status_mos').AsString; end; end.
{: This sample illustrates basic user-driven camera movements.<p> I'm using the GLScene built-in camera movement methods. The camera object is a child of its target dummy cube (this means that the camera is translated when its target is translate, which is good for flyover/scrolling movements).<p> Movements in this sample are done by moving the mouse with a button pressed, left button will translate the dummy cube (and the camera), right button will rotate the camera around the target, shift+right will rotate the object in camera's axis.<br> Mouse Wheel allows zooming in/out.<br> '7', '9' rotate around the X vector (in red, absolute).<br> '4', '6' rotate around the Y vector (in green, absolute).<br> '1', '3' rotate around the Z vector (in blue, absolute).<br> } unit Unit1; {$MODE Delphi} interface uses Forms, GLScene, GLObjects, Classes, Controls, GLTeapot, GLLCLViewer, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; Teapot1: TGLTeapot; GLLightSource1: TGLLightSource; DummyCube1: TGLDummyCube; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: integer; MousePos: TPoint; var Handled: boolean); procedure FormKeyPress(Sender: TObject; var Key: char); private { Déclarations privées } mdx, mdy: integer; public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.lfm} uses GLVectorGeometry, Math; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin // store mouse coordinates when a button went down mdx := x; mdy := y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); var dx, dy: integer; v: TVector; begin // calculate delta since last move or last mousedown dx := mdx - x; dy := mdy - y; mdx := x; mdy := y; if ssLeft in Shift then begin if ssShift in Shift then begin // right button with shift rotates the teapot // (rotation happens around camera's axis) GLCamera1.RotateObject(Teapot1, dy, dx); end else begin // right button without shift changes camera angle // (we're moving around the parent and target dummycube) GLCamera1.MoveAroundTarget(dy, dx); end; end else if Shift = [ssRight] then begin // left button moves our target and parent dummycube v := GLCamera1.ScreenDeltaToVectorXY(dx, -dy, 0.12 * GLCamera1.DistanceToTarget / GLCamera1.FocalLength); DummyCube1.Position.Translate(v); // notify camera that its position/target has been changed GLCamera1.TransformationChanged; end; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: integer; MousePos: TPoint; var Handled: boolean); begin // Note that 1 wheel-step induces a WheelDelta of 120, // this code adjusts the distance to target with a 10% per wheel-step ratio GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120)); end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: char); begin with Teapot1 do case Key of '7': RotateAbsolute(-15, 0, 0); '9': RotateAbsolute(+15, 0, 0); '4': RotateAbsolute(0, -15, 0); '6': RotateAbsolute(0, +15, 0); '1': RotateAbsolute(0, 0, -15); '3': RotateAbsolute(0, 0, +15); end; end; end.
unit AStar64.FileStructs; //------------------------------------------------------------------------------ // все файловые структуры собраны тут // // !!! ВАЖНО !!! // размер абсолютно всех файловых структур должен быть кратен 8 байт // добавляйте пустое поле в конце при необходимости //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, DateUtils, Math, System.Generics.Collections, AStar64.Typ, Geo.Pos, Geo.Calcs, Geo.Hash, Geo.Hash.Search; const CAstarFileStructsVersionMajor = 1; CAstarFileStructsVersionMinor = 1; CAstarFileStructsVersionRevision = 0; CFeature1Bit = 1; CFeature1Mask = 1 shl (CFeature1Bit - 1); //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! структура гео-хэш вектор //! по сути - вектор из From в To, только выраженный через гео-хэши //------------------------------------------------------------------------------ PHashVector = ^THashVector; THashVector = packed record //! откуда HashFrom: Int64; // 8 //! куда HashTo: Int64; // 16 function Reverse: THashVector; class operator Equal(a, b: THashVector): Boolean; class operator NotEqual(a, b: THashVector): Boolean; function PointFrom: TGeoPos; function PointTo: TGeoPos; function Azimuth: Double; function AzimuthFits(const aAzimuth, aTolerance: Double): Boolean; function AzimuthDiff(const aAzimuth: Double): Double; // function Distance(const AV: THashVector): Double; function FitBBox(const AV: THashVector): Boolean; function HashStr: string; function TruncateToByte: Byte; constructor Create(const ASP: TGeoPos; const ATP: TGeoPos); function ToComplexString: string; end; THashVectorArray = TArray<THashVector>; // ThashVectorDictionary = class(TDictionary<Int64, THashVectorArray>) // procedure Add(AValue: THashVector); overload; // destructor Destroy; override; // end; //------------------------------------------------------------------------------ //! запись в файле графов "дороги" //------------------------------------------------------------------------------ PEdge = ^TEdge; TEdge = packed record //! гео-хэш вектора начало/конец HashVector: THashVector; // 16 //! гео-координаты начала CoordsFrom: TGeoPos; // 32 //! гео-координаты конца CoordsTo: TGeoPos; // 48 //! длина дороги, км Distance: Double; // 56 //! максимальная скорость на дороге, км/ч MaxSpeed: Integer; // 60 //! тип дороги RoadType: Integer; // 64 //! индекс в файле списка дорог ".list_*" LinkIndex: Integer; // 68 //! количество дорог в файле списка дорог ".list_*" LinkCount: Integer; // 72 //! индекс в файле промежуточных точек ".way" (-1 если их нет) WayIndex: Integer; // 76 //! количество промежуточных точек ".way" (может быть 0) WayCount: Integer; // 80 //! ID ID: Int64; // 88 function EqualRouteID(ARouteID: TIDLines): Boolean; end; TEdgeArray = TArray<TEdge>; TEdgeDictionary = TDictionary<THashVector, Integer>; TEdgeDictionaryList = class(TDictionary<Int64, TList<Integer>>) protected procedure ValueNotify(const Item: TList<Integer>; Action: TCollectionNotification); override; public procedure Add(const AFrom: Int64; const AIdx: Integer); end; //------------------------------------------------------------------------------ //! TBD //------------------------------------------------------------------------------ PZoneControl = ^TZoneControl; TZoneControl = UInt64; TZoneControlArray = TArray<TZoneControl>; //------------------------------------------------------------------------------ //! TBD //------------------------------------------------------------------------------ PSignControl = ^TSignControl; TSignControl = UInt64; TSignControlArray = TArray<TSignControl>; //------------------------------------------------------------------------------ //! TBD //------------------------------------------------------------------------------ PWayPoint = ^TWayPoint; TWayPoint = TGeoPos; TWayPointArray = TArray<TWayPoint>; //------------------------------------------------------------------------------ //! TBD //------------------------------------------------------------------------------ PSpeedControl = ^TSpeedControl; //7 дней недели, 4 части суток. //Пишем округленную скорость если есть, если нет, то из edge TTimePeriods = (tpNight, tpMorning, tpDay, tpEvening); TSpeedTimePeriod = array [TTimePeriods] of Byte; TSpeedControl = packed record SpeedWeekDays: array [DayMonday..DaySunday] of TSpeedTimePeriod; end; TSpeedControlArray = TArray<TSpeedControl>; //------------------------------------------------------------------------------ //! расширения файлов графов //------------------------------------------------------------------------------ type TFileType = ( ftEdgeF, ftEdgeB, ftListF, ftListB, ftWay, ftZCF, ftZCB, ftSCF, ftSCB, ftSpeed ); TFileTypeSet = set of TFileType; const CFileType: array[TFileType] of string = ( '.edge_f', '.edge_b', '.list_f', '.list_b', '.way', '.zc_f', '.zc_b', '.signs_f', '.signs_b', '.speed' ); //------------------------------------------------------------------------------ implementation { THashVector } class operator THashVector.Equal(a, b: THashVector): Boolean; begin Result := (a.HashFrom = b.HashFrom) and (a.HashTo = b.HashTo); end; class operator THashVector.NotEqual(a, b: THashVector): Boolean; begin Result := not (a = b); end; function THashVector.Reverse: THashVector; begin Result.HashFrom := HashTo; Result.HashTo := HashFrom; end; function THashVector.ToComplexString: string; var PF, PT: TGeoPos; begin PF := PointFrom; PT := PointTo; Result := Format('[%.16x - %.16x] = [%s - %s] = [%.10f, %.10f - %.10f, %.10f]', [ HashFrom, HashTo, TGeoHash.ConvertBinToString(HashFrom, 12), TGeoHash.ConvertBinToString(HashTo, 12), PF.Latitude, PF.Longitude, PT.Latitude, PT.Longitude ]); end; function THashVector.TruncateToByte: Byte; begin Result := (HashFrom and $0F) shl 4; Result := Result + (HashTo and $0F); end; function THashVector.PointFrom: TGeoPos; begin Result := TGeoHash.DecodePointBin(HashFrom); end; function THashVector.PointTo: TGeoPos; begin Result := TGeoHash.DecodePointBin(HashTo); end; function THashVector.AzimuthFits(const aAzimuth, aTolerance: Double): Boolean; var d: Double; daz: Double; begin d := Abs(Azimuth - aAzimuth); daz := IfThen(d > 180, 360 - d, d); Result := daz <= aTolerance; end; function THashVector.AzimuthDiff(const aAzimuth: Double): Double; var d, z: Double; begin d := aAzimuth - Azimuth; z := IfThen(d < -180, d + 360, d); Result := IfThen(z > 180, d - 360, z); end; constructor THashVector.Create(const ASP, ATP: TGeoPos); begin HashFrom := ASP.ToHash; HashTo := ATP.ToHash; end; function THashVector.Azimuth: Double; begin Result := TGeoCalcs.GetAzimuthDeg( TGeoHash.DecodePointBin(HashFrom), TGeoHash.DecodePointBin(HashTo)); end; function THashVector.FitBBox(const AV: THashVector): Boolean; //var // f,t: TGeoPos; begin Result := True; { f.Latitude := Min(PointFrom.Latitude, PointTo.Latitude); f.Longitude := Min(PointFrom.Longitude, PointTo.Longitude); t.Latitude := Max(PointFrom.Latitude, PointTo.Latitude); t.Longitude := Max(PointFrom.Longitude, PointTo.Longitude); Result := (f.Latitude <= AV.PointFrom.Latitude) and (AV.PointFrom.Latitude <= t.Latitude) and (f.Longitude <= AV.PointFrom.Longitude) and (AV.PointFrom.Longitude <= t.Longitude) and (f.Latitude <= AV.PointTo.Latitude) and (AV.PointTo.Latitude <= t.Latitude) and (f.Longitude <= AV.PointTo.Longitude) and (AV.PointTo.Longitude <= t.Longitude); } end; function THashVector.HashStr: string; begin Result := TGeoHash.EncodePointString(PointFrom, 12) + '-' + TGeoHash.EncodePointString(PointTo, 12); end; { TEdgeDictionaryList } procedure TEdgeDictionaryList.Add(const AFrom: Int64; const AIdx: Integer); begin if not Self.ContainsKey(AFrom) then inherited Add(AFrom, TList<Integer>.Create); Items[AFrom].Add(AIdx); end; procedure TEdgeDictionaryList.ValueNotify(const Item: TList<Integer>; Action: TCollectionNotification); begin if (Action <> cnAdded) then Item.Free(); end; { TEdge } function TEdge.EqualRouteID(ARouteID: TIDLines): Boolean; begin Result := (ID = ARouteID.OSM_ID) and (HashVector.HashFrom = ARouteID.HashStart) and (HashVector.HashTo = ARouteID.HashEnd); end; end.
unit FirstStart; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ipControls, ipButtons, StdCtrls, ipEdit; type TfmFirstStart = class(TForm) Label1: TLabel; GroupBox1: TGroupBox; Label2: TLabel; eTo: TipEditTS; Label8: TLabel; eFrom: TipEditTS; GroupBox2: TGroupBox; Label3: TLabel; eID: TipEditTS; Label4: TLabel; ePwd: TipEditTS; Label5: TLabel; Label6: TLabel; bInfo: TipButton; bOK: TipButton; bCancel: TipButton; procedure bInfoClick(Sender: TObject); private { Private declarations } public class function ShowInfo: boolean; end; var fmFirstStart: TfmFirstStart; implementation {$R *.dfm} uses Main, Info; procedure TfmFirstStart.bInfoClick(Sender: TObject); begin TfmInfo.ShowInfo; end; class function TfmFirstStart.ShowInfo: boolean; begin with TfmFirstStart.Create(Application) do try with fmMain.Settings do begin eID.Text:=Ident; ePwd.Text:=Password; end; with fmMain.SMTP do begin eFrom.Text:=HdrFrom; eTo.Text:=HdrTo; end; Result:=ShowModal=mrOK; if Result then begin with fmMain.Settings do begin Ident:=eID.Text; Password:=ePwd.Text; end; with fmMain.SMTP do begin HdrFrom:=eFrom.Text; HdrTo:=eTo.Text; end; end; finally Free; end; end; end.
{ -internal} {-$Id: SpTimeUtils.pas,v 1.2 2006/10/13 09:20:40 oleg Exp $} {****************************************************************************} { Пакет SpLib } { облегчение работы с Interbase под Delphi 7 } { (c) Qizz 2002-2004 } { ( Олег Волков при участии Даниила Збуривского, Родиона Миронова ) } { распространяется по личной договоренности } {****************************************************************************} { Общие функции работы со временем } unit SpTimeUtils; interface uses SysUtils, Controls, ComCtrls, Math, DateUtils; procedure DecodeTimeString(s: String;var h,m, sec: Integer); function EncodeTimeString(t: TTime; dec: Boolean): String; function EncodeTimeString2(Hours: Double; dec: Boolean): String; procedure SetPickerTime(picker: TDateTimePicker; time: TTime); function StringToTime(s: String): TTime; function TimeDiff(Time_Beg, Time_End: TTime): TTime; function TimeInside(cTime, Time_Beg, Time_End: TTime): Boolean; function PeriodInside(Period_Beg, Period_End, Time_Beg, Time_End: TTime): Boolean; function CalcNightHours(Time_Beg, Time_End, Night_Beg, Night_End: TTime): Double; procedure SplitHours(Time_Beg, Time_End: TTime; Yesterday: Boolean; var W_Beg, W_End: TTime); implementation procedure SplitHours(Time_Beg, Time_End: TTime; Yesterday: Boolean; var W_Beg, W_End: TTime); begin if Yesterday then begin W_Beg := 0; if Time_Beg > Time_End then W_End := Time_End else W_End := 0; end else begin W_Beg := Time_Beg; if Time_Beg > Time_End then W_End := 1 else W_End := Time_End; end; end; function CalcNightHours(Time_Beg, Time_End, Night_Beg, Night_End: TTime): Double; begin Result := Max(Min(Night_End, Time_End) - Time_Beg, 0) + Max(Time_End - Max(Night_Beg, Time_Beg), 0); end; function PeriodInside(Period_Beg, Period_End, Time_Beg, Time_End: TTime): Boolean; begin if not TimeInside(Period_Beg, Time_Beg, Time_End) then Result := False else if not TimeInside(Period_End, Time_Beg, Time_End) then Result := False else if (Period_Beg > Period_End) and (Time_Beg < Time_End) then Result := False else Result := True; end; function TimeInside(cTime, Time_Beg, Time_End: TTime): Boolean; begin if Time_Beg < Time_End then Result := (Time_Beg < cTime) and (cTime < Time_End) else Result := (cTime > Time_Beg) or (cTime < Time_End); end; function TimeDiff(Time_Beg, Time_End: TTime): TTime; begin Result := Time_End - Time_Beg; if Time_Beg > Time_End then Result := Result + 1; end; procedure DecodeTimeString(s: String;var h,m, sec: Integer); var p: Integer; hours: Double; begin p := Pos(':', s); if p = 0 then try s := StringReplace(s, '.', DecimalSeparator, []); s := StringReplace(s, ',', DecimalSeparator, []); hours := StrToFloat(s)/24; h := HourOf(hours); if hours >= 1 then h := 24; m := MinuteOf(hours); sec := SecondOf(hours); except h := 0; m := 0; sec := 0; end else begin try h := StrToInt(Copy(s, 1, p-1)); except h := 0; end; s := Copy(s, p+1, Length(s)); p := Pos(':', s); if p <> 0 then begin try m := StrToInt(Copy(s, 1, p-1)); except m := 0; end; try sec := StrToInt(Copy(s, p+1, Length(s))); except sec := 0; end; end else begin try m := StrToInt(s); except m := 0; end; sec := 0; end; end; end; function StringToTime(s: String): TTime; var h,m,sec: Integer; begin DecodeTimeString(s, h, m, sec); Result := (h+m/60+sec/3600)/24; if Result > 1 then Result := 1; end; function EncodeTimeString2(Hours: Double; dec: Boolean): String; var h, m, s, msec: Word; mstr: String; begin if dec then try Result := FormatFloat('#0.###', Hours); except end else begin DecodeTime(Hours/24, h, m, s, msec); if Hours >= 24 then h := h + 24; Result := IntToStr(h); if m > 0 then begin mstr := IntToStr(m); if Length(mstr) < 2 then mstr := '0' + mstr; Result := Result + ':' + mstr; end; if s > 0 then begin mstr := IntToStr(s); if Length(mstr) < 2 then mstr := '0' + mstr; Result := Result + ':' + mstr; end; end; end; function EncodeTimeString(t: TTime; dec: Boolean): String; var h, m, s, msec: Word; mstr: String; begin if dec then try Result := FormatFloat('0.###', 24*t); except end else begin DecodeTime(t, h, m, s, msec); mstr := IntToStr(m); if Length(mstr) < 2 then mstr := '0' + mstr; Result := IntToStr (h) + ':' + mstr; if s <> 0 then begin mstr := IntToStr(s); if Length(mstr) < 2 then mstr := '0' + mstr; Result := Result + ':' + mstr; end; end; end; procedure SetPickerTime(picker: TDateTimePicker; time: TTime); begin picker.Time := time; picker.Date := 0; picker.ShowCheckbox := False; end; end.
unit IntegerSquareRootTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestIntegerSquareRoot } TTestIntegerSquareRoot = class(TTestCase) published procedure SquareRootOfZero(); procedure SquareRootOfOne(); procedure SquareRootof4(); procedure SquareRootof25(); procedure SquareRootof27(); procedure SquareRootofVeryBigValue(); procedure CallSquareRootofNull(); procedure CallSquareRootofNegativeNumber(); private procedure SquareRootofNull(); procedure SquareRootofNegativeNumber(); end; implementation procedure TTestIntegerSquareRoot.SquareRootOfZero(); var int1: TIntX; begin int1 := TIntX.Create(0); AssertTrue(TIntX.IntegerSquareRoot(int1) = 0); end; procedure TTestIntegerSquareRoot.SquareRootOfOne(); var int1: TIntX; begin int1 := TIntX.Create(1); AssertTrue(TIntX.IntegerSquareRoot(int1) = 1); end; procedure TTestIntegerSquareRoot.SquareRootof4(); var int1: TIntX; begin int1 := TIntX.Create(4); AssertTrue(TIntX.IntegerSquareRoot(int1) = 2); end; procedure TTestIntegerSquareRoot.SquareRootof25(); var int1, res: TIntX; begin int1 := TIntX.Create(25); res := TIntX.IntegerSquareRoot(int1); AssertTrue(res = 5); end; procedure TTestIntegerSquareRoot.SquareRootof27(); var int1, res: TIntX; begin int1 := TIntX.Create(27); res := TIntX.IntegerSquareRoot(int1); AssertTrue(res = 5); end; procedure TTestIntegerSquareRoot.SquareRootofVeryBigValue(); var int1: TIntX; begin int1 := TIntX.Create('783648276815623658365871365876257862874628734627835648726'); AssertEquals('27993718524262253829858552106', TIntX.IntegerSquareRoot(int1).ToString); end; procedure TTestIntegerSquareRoot.SquareRootofNull(); begin TIntX.Create(Default(TIntX)); end; procedure TTestIntegerSquareRoot.CallSquareRootofNull(); var TempMethod: TRunMethod; begin TempMethod := @SquareRootofNull; AssertException(EArgumentNilException, TempMethod); end; procedure TTestIntegerSquareRoot.SquareRootofNegativeNumber(); var int1: TIntX; begin int1 := TIntX.Create(-25); TIntX.IntegerSquareRoot(int1); end; procedure TTestIntegerSquareRoot.CallSquareRootofNegativeNumber(); var TempMethod: TRunMethod; begin TempMethod := @SquareRootofNegativeNumber; AssertException(EArgumentException, TempMethod); end; initialization RegisterTest(TTestIntegerSquareRoot); end.
unit uSendFaxList; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, siComp, siLangRT, PaiDeForms; type TFrmSendFaxList = class(TFrmParentForms) OD: TOpenDialog; Label3: TLabel; flPhoneNumber: TEdit; flFileName: TEdit; sbOpenFile: TSpeedButton; Panel1: TPanel; EspacamentoInferior: TPanel; Panel3: TPanel; flAction: TButton; flCancel: TButton; procedure flActionClick(Sender: TObject); procedure flCancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure sbOpenFileClick(Sender: TObject); private { Private declarations } function GetFaxName : String; procedure SetFaxName(const NewName : String); function GetCoverName : String; procedure SetCoverName(const NewName : String); function GetPhoneNumber : String; procedure SetPhoneNumber(const NewNumber : String); public property FaxName : String read GetFaxName write SetFaxName; property CoverName : String read GetCoverName write SetCoverName; property PhoneNumber : String read GetPhoneNumber write SetPhoneNumber; { Public declarations } end; var FrmSendFaxList: TFrmSendFaxList; implementation uses uDMGlobal, uMsgBox, uMsgConstant; {$R *.DFM} procedure TFrmSendFaxList.flActionClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TFrmSendFaxList.flCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; function TFrmSendFaxList.GetFaxName : String; begin Result := flFileName.Text; end; procedure TFrmSendFaxList.SetFaxName(const NewName : String); begin flFileName.Text := NewName; end; function TFrmSendFaxList.GetCoverName : String; begin Result := ''; end; procedure TFrmSendFaxList.SetCoverName(const NewName : String); begin //flCover.Text := NewName; end; function TFrmSendFaxList.GetPhoneNumber : String; begin Result := flPhoneNumber.Text; end; procedure TFrmSendFaxList.SetPhoneNumber(const NewNumber : String); begin flPhoneNumber.Text := NewNumber; end; procedure TFrmSendFaxList.FormActivate(Sender: TObject); begin flPhoneNumber.SetFocus; end; procedure TFrmSendFaxList.sbOpenFileClick(Sender: TObject); begin if OD.Execute = True then If OD.FileName <> '' then flFileName.Text := OD.FileName; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083044 //////////////////////////////////////////////////////////////////////////////// unit android.media.AudioFocusRequest_Builder; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.media.AudioFocusRequest, android.media.AudioManager_OnAudioFocusChangeListener, Androidapi.JNI.os, android.media.AudioAttributes; type JAudioFocusRequest_Builder = interface; JAudioFocusRequest_BuilderClass = interface(JObjectClass) ['{6D6FEA9B-6E1D-4922-B851-D6BF8FBFCD12}'] function build : JAudioFocusRequest; cdecl; // ()Landroid/media/AudioFocusRequest; A: $1 function init(focusGain : Integer) : JAudioFocusRequest_Builder; cdecl; overload;// (I)V A: $1 function init(requestToCopy : JAudioFocusRequest) : JAudioFocusRequest_Builder; cdecl; overload;// (Landroid/media/AudioFocusRequest;)V A: $1 function setAcceptsDelayedFocusGain(acceptsDelayedFocusGain : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 function setAudioAttributes(attributes : JAudioAttributes) : JAudioFocusRequest_Builder; cdecl;// (Landroid/media/AudioAttributes;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setFocusGain(focusGain : Integer) : JAudioFocusRequest_Builder; cdecl;// (I)Landroid/media/AudioFocusRequest$Builder; A: $1 function setForceDucking(forceDucking : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 function setOnAudioFocusChangeListener(listener : JAudioManager_OnAudioFocusChangeListener) : JAudioFocusRequest_Builder; cdecl; overload;// (Landroid/media/AudioManager$OnAudioFocusChangeListener;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setOnAudioFocusChangeListener(listener : JAudioManager_OnAudioFocusChangeListener; handler : JHandler) : JAudioFocusRequest_Builder; cdecl; overload;// (Landroid/media/AudioManager$OnAudioFocusChangeListener;Landroid/os/Handler;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setWillPauseWhenDucked(pauseOnDuck : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 end; [JavaSignature('android/media/AudioFocusRequest_Builder')] JAudioFocusRequest_Builder = interface(JObject) ['{E1804986-D885-41E7-B310-FC074294EE39}'] function build : JAudioFocusRequest; cdecl; // ()Landroid/media/AudioFocusRequest; A: $1 function setAcceptsDelayedFocusGain(acceptsDelayedFocusGain : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 function setAudioAttributes(attributes : JAudioAttributes) : JAudioFocusRequest_Builder; cdecl;// (Landroid/media/AudioAttributes;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setFocusGain(focusGain : Integer) : JAudioFocusRequest_Builder; cdecl;// (I)Landroid/media/AudioFocusRequest$Builder; A: $1 function setForceDucking(forceDucking : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 function setOnAudioFocusChangeListener(listener : JAudioManager_OnAudioFocusChangeListener) : JAudioFocusRequest_Builder; cdecl; overload;// (Landroid/media/AudioManager$OnAudioFocusChangeListener;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setOnAudioFocusChangeListener(listener : JAudioManager_OnAudioFocusChangeListener; handler : JHandler) : JAudioFocusRequest_Builder; cdecl; overload;// (Landroid/media/AudioManager$OnAudioFocusChangeListener;Landroid/os/Handler;)Landroid/media/AudioFocusRequest$Builder; A: $1 function setWillPauseWhenDucked(pauseOnDuck : boolean) : JAudioFocusRequest_Builder; cdecl;// (Z)Landroid/media/AudioFocusRequest$Builder; A: $1 end; TJAudioFocusRequest_Builder = class(TJavaGenericImport<JAudioFocusRequest_BuilderClass, JAudioFocusRequest_Builder>) end; implementation end.
(* Category: SWAG Title: SORTING ROUTINES Original name: 0019.PAS Description: QUICK5.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:57 *) { >I'm in need of a FAST way of finding the largest and the smallest >30 numbers out of about 1000 different numbers. ...Assuming that the 1000 numbers are in random-order, I imagine that the simplest (perhaps fastest too) method would be to: 1- Read the numbers in an Array. 2- QuickSort the Array. 3- First 30 and last 30 of Array are the numbers you want. ...Here's a QuickSort demo Program that should help you With the sort: } Program QuickSort_Demo; Uses Crt; Const co_MaxItem = 30000; Type Item = Word; ar_Item = Array[1..co_MaxItem] of Item; (***** QuickSort routine. *) (* *) Procedure QuickSort({update} Var ar_Data : ar_Item; {input } wo_Left, wo_Right : Word); Var Pivot, TempItem : Item; wo_Index1, wo_Index2 : Word; begin wo_Index1 := wo_Left; wo_Index2 := wo_Right; Pivot := ar_Data[(wo_Left + wo_Right) div 2]; Repeat While (ar_Data[wo_Index1] < Pivot) do inc(wo_Index1); While (Pivot < ar_Data[wo_Index2]) do dec(wo_Index2); if (wo_Index1 <= wo_Index2) then begin TempItem := ar_Data[wo_Index1]; ar_Data[wo_Index1] := ar_Data[wo_Index2]; ar_Data[wo_Index2] := TempItem; inc(wo_Index1); dec(wo_Index2) end Until (wo_Index1 > wo_Index2); if (wo_Left < wo_Index2) then QuickSort(ar_Data, wo_Left, wo_Index2); if (wo_Index1 < wo_Right) then QuickSort(ar_Data, wo_Index1, wo_Right) end; (* QuickSort. *) Var wo_Index : Word; ar_Buffer : ar_Item; begin Write('Creating ', co_MaxItem, ' random numbers... '); For wo_Index := 1 to co_MaxItem do ar_Buffer[wo_Index] := random(65535); Writeln('Finished!'); Write('Sorting ', co_MaxItem, ' random numbers... '); QuickSort(ar_Buffer, 1, co_MaxItem); Writeln('Finished!'); Writeln; Writeln('Press the <ENTER> key to display all ', co_MaxItem, ' sorted numbers...'); readln; For wo_Index := 1 to co_MaxItem do Write(ar_Buffer[wo_Index]:8) end.
{## DATEBOX v1.2 DateEdit-Dialog with enhanced capabilities (Data-aware) written 1996 by Markus Plesser (e9300600@stud1.tuwien.ac.at) modified by Eduardo Wendel Fevereiro 1998 (c)1996 by MANAGERsoft (not an official company YET - so please donīt blame me ;-) You can now download the latest version (& other stuff) from "http://stud1.tuwien.ac.at/~e9300600" I used the existing component DateEdit (Sorry, but I donīt know who wrote it :-( but I guess it was FreeWare and this one contains nearly nothing from the original ... Added properties: Language ... The Dialog can be displayed in either English, German, French, Spanish or Italian ( If you want messages in other languages - feel free to mail me: - The name of the language - The strings for "Invalid Date:", "Need a valid Date!", "Month", "Year", "Accept", "Cancel" & "Today" ) NeedDate ... Pops up a Message if no Date is entered EditMask ... Define your own look & feel FirstDayOfWeek ... Define the day that is leftmost diplayed in the calendar StartSize ... Pop up in either "small" or "normal" size v1.11 changes: Italian & French Language-support Bugfix with enabled-property "Today"-Button v1.12 changes: Portuguese Language-support v1.2 changes: Small/Normal-size of Form, Option to set the first day of the week, Spanish support The DateBox components now use the date-format supplied by Delphi and you can simply change it by modifying "ShortDateFormat" and "DateSeparator". e.g.: If you want to display a date like "07/28/1996" use the following code: ShortDateFormat := 'mm/dd/yyyy'; DateSeparator := '/'; To use the Data-aware version simply use TDBEditBox ;-) If you like the source-code of this component, you'll have to pay me ...... NOTHING !!! But - as in real life - nothing is for free ;-) so if you you want me to mail you the password for the source-code you'll have to send me a component you've made on your own or a component you think that is worth looking at (pls. no components you can find everywhere and/or worthless comps. ). Please remember - I only accept components INCLUDING _FULL_ SOURCE-CODE !!! If you donīt have any good components, OR want to use this component in a COMMERCIAL Application I charge a fee of US$ 20,- (ATS 260,- / DM 38,-). Please send money/crossed cheque/money-orders to the following account: CREDITANSTALT Kto.: 12412420700 BLZ.: 11000 Please inform me via e-mail, if I should check my account ... Youīll get the password via e-mail. If you want me to send you the password by mail, add another 5 US$ for s&h. Iīm very interested in components like editors (>64k, Fontsupport), "Time-line" components (like occupation of rooms in a hotel), Database-Comps (stuff like InfoPower or cbPlus, but freeware or reg. to me), network & winsock stuff, etc. If you have any suggestions, comments or bugs please mail me in english or german to the above adress. Why I wrote this stuff: There is no good DateEdit-Component available that works fine with Databases, TDateBox & TDBDateBox look the same for the user and can handle changing the year & month in the Dialog. By the way: For my previous compīs I didnīt receive the amount of compīs I expected - probably because you didnīt need the source (Versions for D1 & D2 working perfectly well) - To give you a little "kick" for sending me compīs these fine DateBoxes run only while Delphi is RUNNING >;-]]] *** dark evil grin *** Revision history: ================= ** 30.06.1996 - Created, Initial Release 1.0 ** 07.07.1996 - Minor Bugfixes (for D2 & Button-drawing while designing) v1.01 ** 10.08.1996 - Major Bugfixes, Redesigned TDBDatebox, inherited TDateBox from MaskEdit and TDBDateBox -> v1.1 ** 14.08.1996 - Italian & French support, "Today-Button", "Enabled"-Bugfix -> v1.11 ** 20.08.1996 - Portuguese support -> v1.12 ** 03.09.1996 - Small/Normal-size of Form, Option to set the first day of the week, Spanish support -> v1.2 P.S.: Iīm from Austria, so please accept my apologies for my bad English >8=) P.P.S.: I know that the French-support isnīt finished yet - will be completed in next Ver. If you want to send me a postcard etc. you can reach me at: Markus Plesser Waehringer Guertel 69/4 A-1180 Wien Austria/Europe There are no Kangaroos in Austria !!! } unit DateBox; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Menus, Forms, StdCtrls, Buttons, Dialogs, DB, DBTables, DBCtrls, Mask, Grids, Calendar, ExtCtrls, SuperCalendar, dxCntner, dxEditor, dxExEdtr, dxEdLib; procedure Register; type TLanguage = (English, German, Italian, French, Spanish, Portuguese); {## 6 right now ... } TStartDay = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday); {## What day does the calendar begin with ? } TFormSize = (Normal, Small); {## Size of the popup-Form } TFMGetDate = class(TForm) Shape1: TShape; MainCalender: TSuperCalendar; cmbMes: TComboBox; EditAno: TdxSpinEdit; procedure MainCalenderChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDeactivate(Sender: TObject); procedure MainCalenderClick(Sender: TObject); procedure MainCalenderMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure cmbMesChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditAnoChange(Sender: TObject); private ctlParent: TComponent; procedure SetDate(SetDate: TDateTime); procedure SetClickDate; function GetDate: TDateTime; public property Date: TDateTime read GetDate write SetDate; constructor Create( AOwner: TComponent ); override; end; TDateButton = class( TBitBtn ) protected procedure Click; override; end; TDateBox = class( TMaskEdit ) private FInputTime : Boolean; FButton: TDateButton; {## Something to push at } bmMemory: TBitmap; {## For the dots } FDate: TDateTime; {## Now, what could this be ??? } FNeedIt: Boolean; {## Do we need a Date to exit ? } FLang: TLanguage; {## Language we are using } FEnab: Boolean; {## My Enabled-Property } FFirstDayOfWeek: TStartDay; {## The first day of the week } FFormSize: TFormSize; {## Size of the popup-Form } procedure MyTestDate(IsNeed : Boolean); protected procedure Change; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure WMSize( var Message: TWMSize ); message WM_SIZE; function GetDate: TDateTime; virtual; procedure SetDate( dtArg: TDateTime ); virtual; procedure SetEnabled(Value: Boolean); procedure DoExit; override; public DataAware: Boolean; constructor Create( AOwner: TComponent ); override; destructor Destroy; override; procedure CreateParams( var Params: TCreateParams ); override; procedure Validate; property Date: TDateTime read GetDate write SetDate; published property InputTime : Boolean read FInputTime write FInputTime default True; property NeedDate: Boolean read FNeedIt write FNeedIt default False; property Language: TLanguage read FLang write FLang default English; property Enabled: Boolean read FEnab write SetEnabled default True; property FirstDayOfWeek: TStartDay read FFirstDayOfWeek write FFirstDayOfWeek default Sunday; property StartSize: TFormSize read FFormSize write FFormSize default Normal; // Herdados { property AutoSelect; property AutoSize; property BorderStyle; property CharCase; property Color; property Ctl3D; property DragCursor; property DragMode; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PasswordChar; property Picture; property PopupMenu; property ShowVertScrollBar; property ShowHint; property TabOrder; property TabStop; property UsePictureMask; property Visible; property WantReturns; property WordWrap; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnCheckValue; } end; TDBDateBox = class( TDateBox ) private FDataLink: TFieldDataLink; procedure DataChange(Sender: TObject); procedure EditingChange(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; function GetReadOnly: Boolean; procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure SetFocused(Value: Boolean); procedure SetReadOnly(Value: Boolean); procedure UpdateData(Sender: TObject); procedure WMCut(var Message: TMessage); message WM_CUT; procedure WMPaste(var Message: TMessage); message WM_PASTE; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; protected procedure Change; override; function EditCanModify: Boolean; override; procedure Reset; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetDate: TDateTime; override; procedure SetDate( dtArg: TDateTime ); override; public constructor Create( AOwner: TComponent ); override; property Field: TField read GetField; destructor Destroy; override; property Date: TDateTime read GetDate write SetDate; function iGetDataField: String; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property ReadOnly: Boolean read GetReadOnly write SetReadOnly; end; var frmCalendar: TFMGetDate; implementation {$R *.DFM} uses xBase, uDateTimeFunctions, uDataBaseFunctions; {$DEFINE DBOXREG} {$IFNDEF DBOXREG} function DelphiRunning:Boolean; forward; {$ENDIF} constructor TFMGetDate.Create(AOwner: TComponent); var i : integer; editOwner: TDateBox; rectPlace: TRect; ptUpper, ptLower: TPoint; begin inherited Create(AOwner); {$IFNDEF DBOXREG} if not DelphiRunning then begin MessageDlg('UNREGISTERED DateBox !!! - Good Bye ;-)', mtError,[mbOK],0); Application.Terminate; end; {$ENDIF} { Tests to see if was called from a datebox } if (AOwner is TDateBox) then begin { Dynamically set the size and position } editOwner := TDateBox( AOwner ); ctlParent := editOwner; rectPlace := editOwner.ClientRect; ptUpper.X := rectPlace.Left; ptUpper.Y := rectPlace.Top; ptUpper := editOwner.ClientToScreen( ptUpper ); ptLower.X := rectPlace.Right; ptLower.Y := rectPlace.Bottom; ptLower := editOwner.ClientToScreen( ptLower ); { If too far down, pop the calendar above the control} if ptUpper.X + 1 + Width > Screen.Width then Left := Screen.Width - Width - 1 else Left := ptUpper.X - 1; if ptLower.Y + 1 + Height > Screen.Height then Top := ptUpper.Y - Height else Top := ptLower.Y + 1; { define initial date } case TDateBox( ctlParent ).FirstDayOfWeek of Sunday : MainCalender.StartOfWeek := 0; Monday : MainCalender.StartOfWeek := 1; Tuesday : MainCalender.StartOfWeek := 2; Wednesday : MainCalender.StartOfWeek := 3; Thursday : MainCalender.StartOfWeek := 4; Friday : MainCalender.StartOfWeek := 5; Saturday : MainCalender.StartOfWeek := 6; end; // Carrega o list box dos meses cmbMes.Items.Clear; for i := 1 to 12 do cmbMes.Items.Add(LongMonthNames[i]); if not TDateBox( ctlParent ).DataAware then begin if TDateBox( ctlParent ).Text <> '' then SetDate(MyStrToDate( TDateBox( ctlParent ).Text )) else SetDate(Date); end else begin if TDBDateBox( ctlParent ).Text <> '' then SetDate(MyStrToDate( TDBDateBox( ctlParent ).Text )) else SetDate(Date); end; end else // It does not descend from a edit box begin MainCalender.StartOfWeek := 0; end; end; procedure TFMGetDate.SetDate(SetDate: TDateTime); begin Try MainCalender.CalendarDate := SetDate; except MainCalender.CalendarDate := Date; end; MainCalenderChange(nil); end; function TFMGetDate.GetDate: TDateTime; begin Result := MainCalender.CalendarDate; end; procedure TFMGetDate.MainCalenderChange(Sender: TObject); var s : String; begin cmbMes.ItemIndex := nMonth(MainCalender.CalendarDate)-1; EditAno.Value := nYear(MainCalender.CalendarDate); end; procedure TFMGetDate.SetClickDate; begin if (ctlParent is TDateBox) then begin if TDateBox( ctlParent ).DataAware then TDBDateBox( ctlParent ).Date := GetDate else TDateBox( ctlParent ).Date := GetDate; end; end; {--- TDateButton ---} procedure TDateButton.Click; var editParent: TDateBox; begin editParent := TDateBox( Parent ); frmCalendar := TFMGetDate.Create( editParent ); frmCalendar.Show; inherited Click; end; {--- TDateBox ---} constructor TDateBox.Create( AOwner: TComponent ); begin inherited Create( AOwner ); DataAware := False; bmMemory := TBitmap.Create; FButton := TDateButton.Create( self ); FButton.TabStop := False; FButton.Width := 17; FButton.Height := 17; FButton.Visible := TRUE; FButton.Parent := self; FEnab := True; FInputTime := True; ControlStyle := ControlStyle - [csSetCaption]; //** FLang := Portuguese; FLang := English; end; procedure TDateBox.CreateParams( var Params: TCreateParams ); begin inherited CreateParams( Params ); Params.Style := Params.Style or WS_CLIPCHILDREN; end; destructor TDateBox.Destroy; begin bmMemory.Free; FButton := nil; inherited Destroy; end; procedure TDateBox.WMSize( var Message: TWMSize ); var rectDraw: TRect; nHalfX, nHalfY: integer; begin {$IFNDEF win32} FButton.Top := 2; FButton.Height := Height - 4; FButton.Width := Height - 2; FButton.Left := Width - Height; {$ELSE} FButton.Top := 1; FButton.Height := Height - 6; FButton.Width := Height - 4; FButton.Left := Width - Height; {$ENDIF} rectDraw := FButton.ClientRect; bmMemory.Width := rectDraw.Right - rectDraw.Left - 4; bmMemory.Height := rectDraw.Bottom - rectDraw.Top - 4; nHalfX := bmMemory.Width div 2; nHalfY := bmMemory.Height div 2; rectDraw.Left := 0; rectDraw.Top := 0; rectDraw.Right := bmMemory.Width; rectDraw.Bottom := bmMemory.Height; with bmMemory.Canvas do begin Brush.Color := clSilver; Brush.Style := bsSolid; FillRect( rectDraw ); Pen.Width := 2; Pen.Style := psDot; Pen.Color := clBlack; MoveTo( nHalfX-4, nHalfY ); LineTo( nHalfX-4, nHalfY ); MoveTo( nHalfX, nHalfY ); LineTo( nHalfX, nHalfY ); MoveTo( nHalfX+4, nHalfY ); LineTo( nHalfX+4, nHalfY ); end; FButton.Glyph := bmMemory; FButton.Refresh; end; function TDateBox.GetDate: TDateTime; begin if TestDate(Text) then FDate := StrToDate(Text); if FInputTime then FDate := Int(FDate) + Time; Result := FDate; end; procedure TDateBox.Change; begin inherited; { if TestDate(Text) then FDate := StrToDate(Text); } end; procedure TDateBox.SetDate( dtArg: TDateTime ); var tmpDateFormat: String; Year, Dummy: Word; function upString(const S: String): String; var i: Integer; r: String; begin r := S; for i := 1 to length(s) do r[i] := upcase(r[i]); result := r; end; begin FDate := dtArg; Modified := TRUE; if FDate = 0 then Text := '' else begin {## if the year is > 2000 then display the year ALWAYS in 4 digits ! } DecodeDate(FDate, Year, Dummy, Dummy); Text := FormatDateTime( ShortDateFormat, FDate ); { if Year >= 2000 then begin tmpDateFormat := upString(ShortDateFormat); if(pos('YYYY', tmpDateFormat) = 0) and (pos('YY', tmpDateFormat) <> 0) then begin insert('YY', tmpDateFormat, pos('YY', tmpDateFormat)); Text := FormatDateTime( tmpDateFormat, FDate ); end else Text := FormatDateTime( ShortDateFormat, FDate ); end else Text := FormatDateTime( ShortDateFormat, FDate ); } end; end; procedure TDateBox.SetEnabled(Value: Boolean); begin FEnab := Value; inherited Enabled := FEnab; FButton.Enabled := FEnab; end; procedure TDateBox.Validate; begin MyTestDate(True); end; procedure TDateBox.DoExit; begin inherited DoExit; //** MyTestDate(FNeedIt); MyTestDate(True); end; procedure TDateBox.MyTestDate(IsNeed : Boolean); var Msg: String; begin try if Text <> '' then Date := StrToDate( Text ); except if IsNeed then begin case FLang of English: Msg := 'Invalid Date: '; German: Msg := 'Ungültiges Datum: '; Italian: Msg := 'Data in formato scorretto: '; French: Msg := 'Date non valable: '; Spanish: Msg := 'Fecha incorrecta: '; Portuguese: Msg := 'Data Inválida: '; end; SetFocus; raise Exception.Create(Msg + Text); end; end; end; procedure TDateBox.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if (Key = VK_F2) then FButton.Click; end; {--- TDBDateBox ---} constructor TDBDateBox.Create( AOwner: TComponent ); begin inherited Create( AOwner ); FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnEditingChange := EditingChange; FDataLink.OnUpdateData := UpdateData; DataAware := True; end; {$ifndef DBOXREG} function DelphiRunning : boolean; var H1, H2, H3, H4 : Hwnd; const A1 : array[0..12] of char = 'TApplication'#0; A2 : array[0..15] of char = 'TAlignPalette'#0; A3 : array[0..18] of char = 'TPropertyInspector'#0; A4 : array[0..11] of char = 'TAppBuilder'#0; {$ifndef win32} T1 : array[0..6] of char = 'Delphi'#0; {$endif} begin {$ifndef win32} H1 := FindWindow(A1, T1); {$endif} H2 := FindWindow(A2, nil); H3 := FindWindow(A3, nil); H4 := FindWindow(A4, nil); {$ifdef win32} Result := (H2 <> 0) and (H3 <> 0) and (H4 <> 0); {$else} Result := (H1 <> 0) and (H2 <> 0) and (H3 <> 0) and (H4 <> 0); {$endif} end; {$endif} destructor TDBDateBox.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; function TDBDateBox.GetDate: TDateTime; begin inherited GetDate; end; procedure TDBDateBox.SetDate( dtArg: TDateTime ); begin inherited SetDate(dtArg); if FDate <> 0 then begin with FDataLink do begin Edit; if FInputTime then FDate := Int(FDate) + Time; Field.AsDateTime := FDate; end; end; end; function TDBDateBox.iGetDataField: String; begin if FDate <> 0 then result := FormatDateTime(ShortDateFormat, FDate) else result := ''; end; procedure TDBDateBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TDBDateBox.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) then FDataLink.Edit else if (Key = VK_F5) and (not FNeedIt) then begin EditMask := ''; CheckEditState(FDataLink.DataSource.DataSet); Text := ''; Modified := True; end; end; procedure TDBDateBox.KeyPress(var Key: Char); begin inherited KeyPress(Key); if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin MessageBeep(0); Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; #27: begin { FDataLink.Reset; SelectAll; Key := #0; } end; end; end; function TDBDateBox.EditCanModify: Boolean; begin Result := FDataLink.Edit; end; procedure TDBDateBox.Reset; begin FDataLink.Reset; SelectAll; end; procedure TDBDateBox.SetFocused(Value: Boolean); begin FDataLink.Reset; end; procedure TDBDateBox.Change; begin FDataLink.Modified; inherited Change; end; function TDBDateBox.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TDBDateBox.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; end; function TDBDateBox.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TDBDateBox.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; function TDBDateBox.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; procedure TDBDateBox.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; Enabled := not Value; FButton.Enabled := not Value; end; function TDBDateBox.GetField: TField; begin Result := FDataLink.Field; end; procedure TDBDateBox.DataChange(Sender: TObject); begin if FDataLink.Field <> nil then begin if FDataLink.Field.AsString = '' then Text := '' else Text := FormatDateTime(ShortDateFormat, FDataLink.Field.AsDateTime); end else begin MaxLength := 0; if csDesigning in ComponentState then Text := Name else Text := ''; end; end; procedure TDBDateBox.EditingChange(Sender: TObject); begin inherited ReadOnly := not FDataLink.Editing; end; procedure TDBDateBox.UpdateData(Sender: TObject); begin ValidateEdit; FDataLink.Field.Text := Text; end; procedure TDBDateBox.WMPaste(var Message: TMessage); begin FDataLink.Edit; inherited; end; procedure TDBDateBox.WMCut(var Message: TMessage); begin FDataLink.Edit; inherited; end; procedure TDBDateBox.CMEnter(var Message: TCMEnter); begin { if Pos('/', Text) = 0 then } EditMask := FDataLink.Field.EditMask; SetFocused(True); // FDataLink.Edit; Retirado !!! inherited; end; procedure TDBDateBox.CMExit(var Message: TCMExit); begin try if FNeedIt or Modified then FDataLink.UpdateRecord; except SelectAll; SetFocus; raise; end; SetFocused(False); SetCursor(0); if FNeedIt or Modified then DoExit; end; procedure Register; begin RegisterComponents('NewPower', [TDateBox]); RegisterComponents('NewPower', [TDBDateBox]); end; procedure TFMGetDate.FormShow(Sender: TObject); begin MainCalender.SetFocus; end; procedure TFMGetDate.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFMGetDate.FormDeactivate(Sender: TObject); begin Close; end; procedure TFMGetDate.MainCalenderClick(Sender: TObject); begin SetClickDate; end; procedure TFMGetDate.MainCalenderMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Close; end; procedure TFMGetDate.cmbMesChange(Sender: TObject); const DiasPorMes : array [1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); var DiaAnt, MesAnt : Word; begin DiaAnt := MainCalender.Day; if (DiaAnt > DiasPorMes[cmbMes.ItemIndex + 1]) then begin MesAnt := cmbMes.ItemIndex + 1; MainCalender.Day := DiasPorMes[cmbMes.ItemIndex + 1]; MainCalender.Month := MesAnt; end else MainCalender.Month := cmbMes.ItemIndex + 1 end; procedure TFMGetDate.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN, VK_ESCAPE : Close; 34 : MainCalender.NextMonth; // Page Down 33 : MainCalender.PrevMonth; // Page Up end; end; procedure TFMGetDate.EditAnoChange(Sender: TObject); begin MainCalender.Year := Round(EditAno.Value); end; end.
unit FMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.MultiView, FMX.Layouts, FMX.ListBox, FMX.ScrollBox, FMX.Memo, Demo; type TFormMain = class(TForm) MultiView: TMultiView; PanelDetails: TPanel; ToolBarMultiView: TToolBar; LabelMultiView: TLabel; ToolBarOutput: TToolBar; LabelOutput: TLabel; ButtonMaster: TSpeedButton; MemoOutput: TMemo; ListBoxDemos: TListBox; procedure FormCreate(Sender: TObject); procedure ListBoxDemosChange(Sender: TObject); private { Private declarations } FDemos: TArray<TDemoInfo>; public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} procedure TFormMain.FormCreate(Sender: TObject); var Demo: TDemoInfo; Item: TListBoxItem; begin ReportMemoryLeaksOnShutdown := True; {$IF Defined(MSWINDOWS)} MultiView.Mode := TMultiViewMode.Panel; {$ENDIF} FDemos := TDemo.GetDemos; for Demo in FDemos do begin Item := TListBoxItem.Create(Self); Item.Text := Demo.Name; ListBoxDemos.AddObject(Item); end; end; procedure TFormMain.ListBoxDemosChange(Sender: TObject); var Index: Integer; Demo: TDemo; begin MemoOutput.Lines.Clear; Index := ListBoxDemos.ItemIndex; if (Index < 0) or (Index >= Length(FDemos)) then Exit; MultiView.HideMaster; Demo := FDemos[Index].Clazz.Create(MemoOutput.Lines); try Demo.Run; finally Demo.Free; end; end; end.
{..............................................................................} { Summary Queries the current PCB document for PCB Layer pairs. } { A layer stack can have multiple layer pairs. } { } { Copyright (c) 2007 by Altium Limited } {..............................................................................} Procedure QueryLayerPairs; Var PCBBoard : IPCB_Board; i : Integer; LayerPairs : TStringList; PCBLayerPair : IPCB_DrillLayerPair; LowLayerObj : IPCB_LayerObject; HighLayerObj : IPCB_LayerObject; LowPos : Integer; HighPos : Integer; LS : String; Begin PCBBoard := PCBServer.GetCurrentPCBBoard; If PCBBoard = Nil Then Exit; // Show the current layer for the PCB document ShowInfo('Current Layer: ' + Layer2String(PCBBoard.CurrentLayer)); // Create a TStringList object to store Low and High Layer Names // for Drill layer Pairs. LayerPairs := TStringList.Create; For i := 0 To PCBBoard.DrillLayerPairsCount - 1 Do Begin PCBLayerPair := PCBBoard.LayerPair[i]; LowLayerObj := PCBBoard.LayerStack.LayerObject[PCBLayerPair.LowLayer]; HighLayerObj := PCBBoard.LayerStack.LayerObject[PCBLayerPair.HighLayer]; LowPos := PCBBoard.LayerPositionInSet(SetUnion(SignalLayers,InternalPlanes), LowLayerObj); HighPos := PCBBoard.LayerPositionInSet(SetUnion(SignalLayers,InternalPlanes), HighLayerObj); If LowPos <= HighPos Then LayerPairs.Add(LowLayerObj .Name + ' - ' + HighLayerObj.Name) Else LayerPairs.Add(HighLayerObj.Name + ' - ' + LowLayerObj .Name); End; // Format the layer pairs data string and display it. LS := ''; For i := 0 to LayerPairs.Count - 1 Do LS := LS + LayerPairs[i] + #13#10; ShowInfo('Layer Pairs:'#13#10 + LS); LayerPairs.Free; End; {..............................................................................} {..............................................................................}
{ publish with BSD Licence. Copyright (c) Terry Lao } unit packing; {$MODE Delphi} interface uses iLBC_define, constants, helpfun,C2Delphi_header; {----------------------------------------------------------------* * splitting an integer into first most significant bits and * remaining least significant bits *---------------------------------------------------------------} procedure packsplit( index:pinteger; { (i) the value to split } firstpart:pinteger; { (o) the value specified by most significant bits } rest:pinteger; { (o) the value specified by least significant bits } bitno_firstpart:integer; { (i) number of bits in most significant part } bitno_total:integer { (i) number of bits in full range of value } ); procedure packcombine( index:pinteger; { (i/o) the msb value in the combined value out } rest:integer; { (i) the lsb value } bitno_rest:integer { (i) the number of bits in the lsb part } ); procedure dopack( bitstream :ppchar; { (i/o) on entrance pointer to place in bitstream to pack new data, on exit pointer to place in bitstream to pack future data } index:integer; { (i) the value to pack } bitno:integer; { (i) the number of bits that the value will fit within } pos:pinteger { (i/o) write position in the current byte } ); procedure unpack( bitstream :ppchar; { (i/o) on entrance pointer to place in bitstream to unpack new data from, on exit pointer to place in bitstream to unpack future data from } index:pinteger; { (o) resulting value } bitno:integer; { (i) number of bits used to represent the value } pos:pinteger { (i/o) read position in the current byte } ); implementation procedure packsplit( index:pinteger; { (i) the value to split } firstpart:pinteger; { (o) the value specified by most significant bits } rest:pinteger; { (o) the value specified by least significant bits } bitno_firstpart:integer; { (i) number of bits in most significant part } bitno_total:integer { (i) number of bits in full range of value } ); var bitno_rest:integer; begin bitno_rest := bitno_total-bitno_firstpart; firstpart^ := index^ shr (bitno_rest); rest^ := index^-(firstpart^ shl (bitno_rest)); end; {----------------------------------------------------------------* * combining a value corresponding to msb's with a value * corresponding to lsb's *---------------------------------------------------------------} procedure packcombine( index:pinteger; { (i/o) the msb value in the combined value out } rest:integer; { (i) the lsb value } bitno_rest:integer { (i) the number of bits in the lsb part } ); begin index^ := index^ shl bitno_rest; index^ :=index^ + rest; end; {----------------------------------------------------------------* * packing of bits into bitstream, i.e., vector of bytes *---------------------------------------------------------------} procedure dopack( bitstream :ppchar; { (i/o) on entrance pointer to place in bitstream to pack new data, on exit pointer to place in bitstream to pack future data } index:integer; { (i) the value to pack } bitno:integer; { (i) the number of bits that the value will fit within } pos:pinteger { (i/o) write position in the current byte } ); var posLeft:integer; begin { Clear the bits before starting in a new byte } if (pos^=0) then begin bitstream^^:=#0; end; while (bitno>0) do begin { Jump to the next byte if end of this byte is reached} if (pos^=8) then begin pos^:=0; inc(bitstream^);//(*bitstream)++; bitstream^^:=#0; end; posLeft:=8-(pos^); { Insert index into the bitstream } if (bitno <= posLeft) then begin bitstream^^ := char(byte(bitstream^^) or (index shl (posLeft-bitno))); pos^:=pos^+bitno; bitno:=0; end else begin bitstream^^:=char(byte(bitstream^^) or (index shr (bitno-posLeft))); pos^:=8; index:=index-((index shr (bitno-posLeft)) shl (bitno-posLeft)); bitno:=bitno-posLeft; end; end; end; {----------------------------------------------------------------* * unpacking of bits from bitstream, i.e., vector of bytes *---------------------------------------------------------------} procedure unpack( bitstream :ppchar; { (i/o) on entrance pointer to place in bitstream to unpack new data from, on exit pointer to place in bitstream to unpack future data from } index:pinteger; { (o) resulting value } bitno:integer; { (i) number of bits used to represent the value } pos:pinteger { (i/o) read position in the current byte } ); var BitsLeft:integer; begin index^:=0; while (bitno>0) do begin { move forward in bitstream when the end of the byte is reached } if (pos^=8) then begin pos^:=0; inc(bitstream^);//(*bitstream)++; end; BitsLeft:=8-(pos^); { Extract bits to index } if (BitsLeft>=bitno) then begin index^:=index^+ (((byte(bitstream^^) shl (pos^)) and $FF) shr (8-bitno)); pos^:=pos^+bitno; bitno:=0; end else begin if ((8-bitno)>0) then begin index^:=index^+(((byte(bitstream^^) shl (pos^)) and $FF) shr (8-bitno)); pos^:=8; end else begin index^:=index^+((((byte(bitstream^^) shl (pos^)) and $FF)) shl (bitno-8)); pos^:=8; end; bitno:=bitno-BitsLeft; end; end; end; end.
unit MediaFilesController; interface uses Generics.Collections, MediaFile, Aurelius.Engine.ObjectManager; type TMediaFilesController = class private FManager: TObjectManager; public constructor Create; destructor Destroy; override; function GetAllMediaFiles: TList<TMediaFile>; procedure DeleteMediaFile(MediaFile: TMediaFile); end; implementation uses DBConnection; { TMediaFilesController } constructor TMediaFilesController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TMediaFilesController.DeleteMediaFile(MediaFile: TMediaFile); begin if not FManager.IsAttached(MediaFile) then MediaFile := FManager.Find<TMediaFile>(MediaFile.Id); FManager.Remove(MediaFile); end; destructor TMediaFilesController.Destroy; begin FManager.Free; inherited; end; function TMediaFilesController.GetAllMediaFiles: TList<TMediaFile>; begin FManager.Clear; Result := FManager.FindAll<TMediaFile>; end; end.
unit uObject; interface uses classes, ADODB; type TTableMap = class protected FKeyList: TStringList; FValueList: TList; FMasterFieldList: TStringList; FDetailFieldList: TStringList; public constructor Create; destructor Destroy; override; procedure AddProperty(Key: String; Value: TADOTable; MasterField, DetailField: String); function GetValue(Key: String; var Value: TADOTable; var MasterField, DetailField: String): boolean; end; implementation { TPropertyMap } procedure TTableMap.AddProperty(Key: String; Value: TADOTable; MasterField, DetailField: String); var Pos: integer; begin Pos:=FKeyList.IndexOf(Key); if Pos<>-1 then begin FKeyList.Delete(Pos); FValueList.Delete(Pos); FMasterFieldList.Delete(Pos); FDetailFieldList.Delete(Pos); end; FKeyList.Add(Key); FValueList.Add(Value); FMasterFieldList.Add(MasterField); FDetailFieldList.Add(DetailField); end; constructor TTableMap.Create; begin inherited create; FKeyList := TStringList.Create; FValueList := TList.Create; FMasterFieldList := TStringList.Create; FDetailFieldList := TStringList.Create; end; destructor TTableMap.Destroy; begin FKeyList.Free; FValueList.Free; FMasterFieldList.Free; FDetailFieldList.Free; inherited destroy; end; function TTableMap.GetValue(Key: String; var Value: TADOTable; var MasterField, DetailField: String): boolean; var Pos: integer; begin result:=false; Pos:=FKeyList.IndexOf(Key); if Pos=-1 then begin Value := nil; MasterField := ''; DetailField := ''; exit; end; Value:=FValueList[Pos]; MasterField:=FMasterFieldList[Pos]; DetailField:=FDetailFieldList[Pos]; result:=true; end; end.
unit uAutorModel; interface type TAutorModel = class private FCodigo: Integer; FNome: String; procedure SetCodigo(const Value: Integer); procedure SetNome(const Value: String); public property Codigo: Integer read FCodigo write SetCodigo; property Nome: String read FNome write SetNome; constructor Create(ACodigo: Integer = 0; ANome: String = ''); end; implementation uses SysUtils; { TAutorModel } constructor TAutorModel.Create(ACodigo: Integer; ANome: String); begin FCodigo := ACodigo; FNome := ANome; end; procedure TAutorModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TAutorModel.SetNome(const Value: String); begin FNome := Value; end; end.
unit MainUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Platform, FMX.Layouts, FMX.ListBox; type TMainForm = class(TForm) ProgressBarLoading: TProgressBar; ImageLoading: TImage; Label1: TLabel; EventListBox: TListBox; procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure FormFocusChanged(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation var clientScreenService : IFMXScreenService; clientScreenScale : Single; {$R *.fmx} procedure TMainForm.FormActivate(Sender: TObject); begin EventListBox.Items.Add('FormActivate'); end; procedure TMainForm.FormCreate(Sender: TObject); begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(clientScreenService)) then begin clientScreenScale := clientScreenService.GetScreenScale; end; EventListBox.ItemHeight := 24; end; procedure TMainForm.FormDeactivate(Sender: TObject); begin EventListBox.Items.Add('FormDeactivate'); end; procedure TMainForm.FormFocusChanged(Sender: TObject); begin EventListBox.Items.Add('FormFocusChanged'); end; procedure TMainForm.FormHide(Sender: TObject); begin EventListBox.Items.Add('FormHide'); end; procedure TMainForm.FormResize(Sender: TObject); var I : Integer; begin EventListBox.Items.Add('FormResize, clientSize : '+IntToStr(Trunc(ClientWidth))+'x'+IntToStr(Trunc(ClientHeight))); If (clientWidth = clientScreenService.GetScreenSize.X) and (clientHeight = clientScreenService.GetScreenSize.Y) then Begin // Create progress indicator on a black background image ImageLoading.SetBounds(0,0,clientWidth,clientHeight); ImageLoading.Bitmap.SetSize(Trunc(clientWidth),Trunc(clientHeight)); ImageLoading.Bitmap.Clear($FF000000); // Position everything ProgressBarLoading.Width := Trunc(clientWidth*0.75); ProgressBarLoading.Position.X := Trunc((ClientWidth-ProgressBarLoading.Width) / 2); ProgressBarLoading.Position.Y := Trunc(ClientHeight*0.75); // Make sure progress indicator are covering the other elements ImageLoading.BringToFront; ProgressBarLoading.BringToFront; For I := 1 to 100 do Begin ProgressBarLoading.Value := I; Application.ProcessMessages; Sleep(25); End; // Hide progress indicator ProgressBarLoading.Visible := False; ImageLoading.Visible := False; EventListBox.Items.Add('Finished pre-processing'); End; end; procedure TMainForm.FormShow(Sender: TObject); begin EventListBox.Items.Add('FormShow'); end; end.
program exam1_6; procedure TaskOne; {Вариант 6, Задача 1 Дано натуральное n > 0. Найти произведение первых n простых чисел. Подсказка: используйте булевскую функцию для проверки, является число простым числом или нет.} var n, i, j:Integer; result :LongInt; b :Boolean; begin {Получаем натральное число, защищаем от ввода некорректного значения} repeat write('Введите n > 0: '); ReadLn(n); until n > 0; {Используем цикл для вычисления n-количества простых чисел, путем прохода через чикл n-раз} for i := 1 to n do begin j := 2; b := true; {Во вложенном цикле используется флаг-b для выхода из него} while ( j < i div 2) and (b) do begin if i mod j = 0 then b := false; Inc(j); end; {В случае получения необходимого значения мы опираясь на флаг-b произодим математическую операцию} if b then result := result * i; end; WriteLn('Произведение первых ', n, ' простых чисел является: ', result); end; procedure TaskTwo(); {Вариант 6, Задача 2 Из данной строки удалить все цифры и малые латинские буквы.} var s:string; i:Integer; begin {Получаем натральное число, защищаем от ввода некорректного значения} repeat write('Введите строку: '); ReadLn(s); until Length(s) > 0; {В цикле проходим по всем элементам строки сверяя их с условием} for i:=length(s) downto 1 do if s[i] in ['a'..'z','0'..'9'] then delete(s,i,1); WriteLn('Результат очистки строки: ', s); end; {/**Main**/} begin WriteLn('Задача 1'); TaskOne(); WriteLn('Задача 2'); TaskTwo(); end.
unit PBKDF2_HMACTests; interface uses SysUtils, {$IFDEF FPC} fpcunit, testregistry, {$ELSE} TestFramework, {$ENDIF FPC} HlpIHash, HlpIHashInfo, HlpHashFactory, HlpConverters, HashLibTestBase; type TPBKDF2_HMACTestCase = class abstract(THashLibAlgorithmTestCase) end; type TTestPBKDF2_HMACSHA1 = class(TPBKDF2_HMACTestCase) published procedure TestOne; end; type TTestPBKDF2_HMACSHA2_256 = class(TPBKDF2_HMACTestCase) published procedure TestOne; end; implementation { TTestPBKDF2_HMACSHA1 } procedure TTestPBKDF2_HMACSHA1.TestOne; var Password, Salt, Key: TBytes; Hash: IHash; PBKDF2: IPBKDF2_HMAC; begin FExpectedString := 'BFDE6BE94DF7E11DD409BCE20A0255EC327CB936FFE93643'; Password := TBytes.Create($70, $61, $73, $73, $77, $6F, $72, $64); Salt := TBytes.Create($78, $57, $8E, $5A, $5D, $63, $CB, $06); Hash := THashFactory.TCrypto.CreateSHA1(); PBKDF2 := TKDF.TPBKDF2_HMAC.CreatePBKDF2_HMAC(Hash, Password, Salt, 2048); Key := PBKDF2.GetBytes(24); PBKDF2.Clear(); FActualString := TConverters.ConvertBytesToHexString(Key, False); CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.', [FExpectedString, FActualString])); end; { TTestPBKDF2_HMACSHA2_256 } procedure TTestPBKDF2_HMACSHA2_256.TestOne; var Password, Salt, Key: TBytes; Hash: IHash; PBKDF2: IPBKDF2_HMAC; begin FExpectedString := '0394A2EDE332C9A13EB82E9B24631604C31DF978B4E2F0FBD2C549944F9D79A5'; Password := TConverters.ConvertStringToBytes('password', TEncoding.UTF8); Salt := TConverters.ConvertStringToBytes('salt', TEncoding.UTF8); Hash := THashFactory.TCrypto.CreateSHA2_256(); PBKDF2 := TKDF.TPBKDF2_HMAC.CreatePBKDF2_HMAC(Hash, Password, Salt, 100000); Key := PBKDF2.GetBytes(32); PBKDF2.Clear(); FActualString := TConverters.ConvertBytesToHexString(Key, False); CheckEquals(FExpectedString, FActualString, Format('Expected %s but got %s.', [FExpectedString, FActualString])); end; initialization // Register any test cases with the test runner {$IFDEF FPC} RegisterTest(TTestPBKDF2_HMACSHA1); RegisterTest(TTestPBKDF2_HMACSHA2_256); {$ELSE} RegisterTest(TTestPBKDF2_HMACSHA1.Suite); RegisterTest(TTestPBKDF2_HMACSHA2_256.Suite); {$ENDIF FPC} end.
unit uDlgFind; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, cxGraphics, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxMRUEdit, cxRadioGroup, cxCheckBox, cxGroupBox, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type TdlgFind = class(TForm) btnClose: TcxButton; edtText: TcxMRUEdit; Label1: TLabel; btnFindNext: TcxButton; cxGroupBox1: TcxGroupBox; cbWholeCell: TcxCheckBox; cbCaseSensitive: TcxCheckBox; rbFindUp: TcxRadioButton; rbFindDown: TcxRadioButton; Label2: TLabel; lblField: TLabel; Bevel1: TBevel; procedure FormCreate(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnFindNextClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure edtTextPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); private FGrid: TcxGrid; FAutoCaption: boolean; procedure SetFieldName(const Value: string); { Private declarations } protected function FindParent(var p: TObject; ParentClass: TClass): boolean; virtual; procedure SetDialogCaption; virtual; public property Grid: TcxGrid read FGrid write FGrid; property AutoCaption: boolean read FAutoCaption write FAutoCaption; property FieldName: string write SetFieldName; destructor Destroy; override; constructor Create(AOwner: TComponent); override; end; var dlgFindGlobalLookup: TStringList; implementation uses Registry, cxGridDBBandedTableView, cxPC; {$R *.dfm} var Registry: TRegistry; destructor TdlgFind.Destroy; var Registry: TRegistry; begin Registry:=TRegistry.Create; try Registry.RootKey:=HKEY_CURRENT_USER; Registry.OpenKey('Software\SIS\Реестр имущества', True); Registry.WriteString('FindDialogLookupItems', edtText.Properties.LookupItems.Text); finally Registry.Free; end; inherited; end; procedure TdlgFind.FormCreate(Sender: TObject); var Registry: TRegistry; begin { Registry:=TRegistry.Create; try Registry.RootKey:=HKEY_CURRENT_USER; Registry.OpenKey('Software\SIS\Реестр имущества', True); edtText.Properties.LookupItems.Text:=Registry.ReadString('FindDialogLookupItems'); finally Registry.Free; end;} end; procedure TdlgFind.btnCloseClick(Sender: TObject); begin Close; end; procedure TdlgFind.btnFindNextClick(Sender: TObject); var sFilterString: string; i: integer; v: TcxGridTableView; f: TObject; begin { sFilterString:='%'+edtText.Text+'%'; v:=Grid.ActiveView as TcxGridDBBandedTableView; with v.DataController.Filter.Root do begin Clear; BoolOperatorKind:=fboOr; for i:=0 to v.ItemCount-1 do AddItem(v.Items[i], foLike, sFilterString, sFilterString); end; v.DataController.Filter.Active:=true;} f:=nil; if FindParent(f, TCustomForm) then (f as TCustomForm).Show; v:=Grid.ActiveView as TcxGridTableView; try v.DataController.Search.SearchFromBegin:=false; v.DataController.Search.SearchWholeCell:=cbWholeCell.Checked; v.DataController.Search.SearchCaseSensitive:=cbCaseSensitive.Checked; v.Controller.IncSearchingText:=edtText.Text; v.DataController.Search.LocateNext(rbFindDown.Checked); finally v.DataController.Search.SearchFromBegin:=true; v.DataController.Search.SearchWholeCell:=false; v.DataController.Search.SearchCaseSensitive:=false; end; end; function TdlgFind.FindParent(var p: TObject; ParentClass: TClass): boolean; var par: TWinControl; begin par:=Grid.Parent; while Assigned(par) and (not (par is ParentClass)) do par:=par.Parent; result:=Assigned(par); if result then p:=par; end; procedure TdlgFind.FormShow(Sender: TObject); begin if AutoCaption then SetDialogCaption; end; procedure TdlgFind.SetDialogCaption; var par: TWinControl; cap: string; begin par:=Grid.Parent; cap:=''; while true do begin if par is TCustomForm then begin cap:=(par as TCustomForm).Caption; break; end; if (par is TcxTabSheet) and ((par as TcxTabSheet).Caption<>'') then begin cap:=(par as TcxTabSheet).Caption; break; end; par:=par.Parent; if not Assigned(par) then break; end; Caption:='Поиск: '+cap end; constructor TdlgFind.Create(AOwner: TComponent); begin inherited; FAutoCaption:=true; end; procedure TdlgFind.SetFieldName(const Value: string); begin if Value='ForADOInsertCol' then lblField.Caption:='' else lblField.Caption:=Value; end; procedure TdlgFind.FormActivate(Sender: TObject); begin edtText.Properties.LookupItems.Assign(dlgFindGlobalLookup); end; procedure TdlgFind.edtTextPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); function ItemInList(item: string): boolean; var i: integer; begin result:=false; item:=AnsiUpperCase(item); for i:=0 to dlgFindGlobalLookup.Count-1 do if AnsiUpperCase(dlgFindGlobalLookup[i])=item then begin result:=true; break; end; end; begin if not ItemInList(DisplayValue) then dlgFindGlobalLookup.Insert(0, DisplayValue); end; initialization begin dlgFindGlobalLookup:=TStringList.Create; Registry:=TRegistry.Create; try Registry.RootKey:=HKEY_CURRENT_USER; Registry.OpenKey('Software\SIS\Реестр имущества', True); dlgFindGlobalLookup.Text:=Registry.ReadString('FindDialogLookupItems'); finally Registry.Free; end; end; finalization begin Registry:=TRegistry.Create; try Registry.RootKey:=HKEY_CURRENT_USER; Registry.OpenKey('Software\SIS\Реестр имущества', True); Registry.WriteString('FindDialogLookupItems', dlgFindGlobalLookup.Text); dlgFindGlobalLookup.Free; finally Registry.Free; end; end; end.
unit VirtualWideStrings; // Version 1.3.0 // // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the // specific language governing rights and limitations under the License. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- // This unit contains Unicode functions and classes. They will work // in Win9x-ME and WinNT. The fundamental function is Unicode but if it is not // running in an Unicode enviroment it will convert to ASCI call the ASCI function // then convert back to Unicode. (The opposite of what happens in NT with a // Delphi program, convert from ASCI to Unicode then back to ASCI) // It borrows a lot of functions from Mike Lischke's Unicode collection: // http://www.lischke-online.de/Unicode.html // It also borrows a few ideas from Troy Wolbrink's TNT Unicode VCL controls // http://home.ccci.org/wolbrink/tnt/delphi_unicode_controls.htm // // // Issues: // 7.13.02 // -ShortenStringEx needs to implmement RTL languages once I understand // it better. interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses SysUtils, Windows, Classes, {$ifdef COMPILER_6_UP} RTLConsts {$else} Consts {$endif}, ActiveX, ShellAPI, ShlObj, Graphics, VirtualResources, VirtualUtilities, VirtualUnicodeDefines; const // definitions of frequently used characters: // Note: Use them only for tests of a certain character not to determine character // classes (like white spaces) as in Unicode are often many code points defined // being in a certain class. WideNull = WideChar(#0); WideTabulator = WideChar(#9); WideSpace = WideChar(#32); // logical line breaks WideLF = WideChar(#10); WideLineFeed = WideChar(#10); WideVerticalTab = WideChar(#11); WideFormFeed = WideChar(#12); WideCR = WideChar(#13); WideCarriageReturn = WideChar(#13); WideCRLF: WideString = #13#10; WideLineSeparator = WideChar($2028); WideParagraphSeparator = WideChar($2029); //From Mike's Unicode library // byte order marks for strings // Unicode text files should contain $FFFE as first character to identify such a file clearly. Depending on the system // where the file was created on this appears either in big endian or little endian style. BOM_LSB_FIRST = WideChar($FEFF); // this is how the BOM appears on x86 systems when written by a x86 system BOM_MSB_FIRST = WideChar($FFFE); type TWideFileStream = class(THandleStream) public constructor Create(const FileName: WideString; Mode: Word); destructor Destroy; override; end; procedure SaveWideString(S: TStream; Str: WideString); procedure LoadWideString(S: TStream; var Str: WideString); type TShortenStringEllipsis = ( sseEnd, // Ellipsis on end of string sseFront, // Ellipsis on begining of string sseMiddle, // Ellipsis in middle of string sseFilePathMiddle // Ellipsis is in middle of string but tries to show the entire filename ); type TWideStringList = class; // forward PWideStringItem = ^TWideStringItem; TWideStringItem = record FWideString: WideString; FObject: TObject; end; PWideStringItemList = ^TWideStringItemList; TWideStringItemList = array[0..MaxListSize] of TWideStringItem; TWideStringListSortCompare = function(List: TWideStringList; Index1, Index2: Integer): Integer; {*******************************************************************************} { TWideStringList } { A simple reincarnation of TStringList that can deal with Unicode or ANSI.} { It will work on NT or 9x-ME. } {*******************************************************************************} TWideStringList = class(TPersistent) private FList: PWideStringItemList; FCount: Integer; FCapacity: Integer; FSorted: Boolean; FDuplicates: TDuplicates; FOnChange: TNotifyEvent; FOnChanging: TNotifyEvent; FOwnsObjects: Boolean; procedure ExchangeItems(Index1, Index2: Integer); procedure Grow; procedure QuickSort(L, R: Integer; SCompare: TWideStringListSortCompare); procedure InsertItem(Index: Integer; const S: WideString; AObject: TObject); procedure SetSorted(Value: Boolean); function GetName(Index: Integer): WideString; function GetTextStr: WideString; function GetValue(const Name: WideString): WideString; function GetValueFromIndex(Index: Integer): WideString; procedure SetTextStr(const Value: WideString); procedure SetValue(const Name, Value: WideString); procedure SetValueFromIndex(Index: Integer; const Value: WideString); function GetCommaText: WideString; procedure SetCommaText(const Value: WideString); protected procedure AssignTo(Dest: TPersistent); override; procedure Changed; virtual; procedure Changing; virtual; procedure Error(const Msg: String; Data: Integer); function Get(Index: Integer): WideString; virtual; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; function GetObject(Index: Integer): TObject; virtual; procedure Put(Index: Integer; const S: WideString); virtual; procedure PutObject(Index: Integer; AObject: TObject); virtual; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetUpdateState(Updating: Boolean); virtual; public destructor Destroy; override; function Add(const S: WideString): Integer; virtual; function AddObject(const S: WideString; AObject: TObject): Integer; virtual; procedure AddStrings(Strings: TWideStringList); overload; virtual; procedure AddStrings(Strings: TStrings); overload; virtual; procedure Assign(Source: TPersistent); override; procedure Clear; virtual; procedure CustomSort(Compare: TWideStringListSortCompare); virtual; procedure Delete(Index: Integer); virtual; procedure Exchange(Index1, Index2: Integer); virtual; function Find(const S: WideString; var Index: Integer): Boolean; virtual; function IndexOf(const S: WideString): Integer; virtual; function IndexOfName(const Name: WideString): Integer; function IndexOfObject(AObject: TObject): Integer; procedure Insert(Index: Integer; const S: WideString); virtual; procedure Sort; virtual; procedure LoadFromFile(const FileName: WideString); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure SaveToFile(const FileName: WideString); virtual; procedure SaveToStream(Stream: TStream); virtual; property CommaText: WideString read GetCommaText write SetCommaText; property Count: Integer read GetCount; property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Names[Index: Integer]: WideString read GetName; property Sorted: Boolean read FSorted write SetSorted; property Strings[Index: Integer]: WideString read Get write Put; default; property Objects[Index: Integer]: TObject read GetObject write PutObject; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; property Text: WideString read GetTextStr write SetTextStr; property Values[const Name: WideString]: WideString read GetValue write SetValue; property ValueFromIndex[Index: Integer]: WideString read GetValueFromIndex write SetValueFromIndex; end; // functions involving null-terminated strings // NOTE: PWideChars as well as WideStrings are NOT managed by reference counting under Win32. // In Kylix this is different. WideStrings are reference counted there, just like ANSI strings. function StrLenW(Str: PWideChar): Cardinal; function StrEndW(Str: PWideChar): PWideChar; function StrMoveW(Dest, Source: PWideChar; Count: Cardinal): PWideChar; function StrCopyW(Dest, Source: PWideChar): PWideChar; function StrECopyW(Dest, Source: PWideChar): PWideChar; function StrLCopyW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar; function StrPCopyW(Dest: PWideChar; const Source: string): PWideChar; function StrPLCopyW(Dest: PWideChar; const Source: string; MaxLen: Cardinal): PWideChar; function StrCatW(Dest, Source: PWideChar): PWideChar; function StrLCatW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar; function StrCompW(Str1, Str2: PWideChar): Integer; function StrICompW(Str1, Str2: PWideChar): Integer; function StrLCompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; function StrLICompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; function StrLowerW(Str: PWideChar): PWideChar; function StrNScanW(S1, S2: PWideChar): Integer; function StrRNScanW(S1, S2: PWideChar): Integer; function StrScanW(Str: PWideChar; Chr: WideChar): PWideChar; overload; function StrScanW(Str: PWideChar; Chr: WideChar; StrLen: Cardinal): PWideChar; overload; function StrRScanW(Str: PWideChar; Chr: WideChar): PWideChar; function StrPosW(Str, SubStr: PWideChar): PWideChar; function StrAllocW(Size: Cardinal): PWideChar; function StrBufSizeW(Str: PWideChar): Cardinal; function StrNewW(Str: PWideChar): PWideChar; procedure StrDisposeW(Str: PWideChar); procedure StrSwapByteOrder(Str: PWideChar); function StrUpperW(Str: PWideChar): PWideChar; // functions involving Delphi wide strings function WideAdjustLineBreaks(const S: WideString): WideString; function WideCharPos(const S: WideString; const Ch: WideChar; const Index: Integer): Integer; //az function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): WideString; function WideLowerCase(const S: WideString): WideString; function WideQuotedStr(const S: WideString; Quote: WideChar): WideString; function WideStringOfChar(C: WideChar; Count: Cardinal): WideString; function WideUpperCase(const S: WideString): WideString; // Utilities function AddCommas(NumberString: WideString): WideString; function CalcuateFolderSize(FolderPath: WideString; Recurse: Boolean): Int64; function CreateDirW(const DirName: WideString): Boolean; function DirExistsW(const FileName: WideString): Boolean; overload; function DirExistsW(const FileName: PWideChar): Boolean; overload; function DiskInDrive(C: Char): Boolean; {$IFDEF DELPHI_5} function ExcludeTrailingPathDelimiter(const S: string): string; {$ENDIF} function ExtractFileDirW(const FileName: WideString): WideString; function ExtractFileDriveW(const FileName: WideString): WideString; function ExtractFileExtW(const FileName: WideString): WideString; function ExtractFileNameW(const FileName: WideString): WideString; function ExtractRemoteComputerW(const UNCPath: WideString): WideString; function ExpandFileNameW(const FileName: WideString): WideString; function FileCreateW(const FileName: WideString): Integer; function FileExistsW(const FileName: WideString): Boolean; {$IFDEF DELPHI_5} function IncludeTrailingPathDelimiter(const S: string): string; {$ENDIF} function IncludeTrailingBackslashW(const S: WideString): WideString; procedure InsertW(Source: WideString; var S: WideString; Index: Integer); function IntToStrW(Value: integer): WideString; function IsDriveW(Drive: WideString): Boolean; function IsFloppyW(FileFolder: WideString): boolean; function IsFTPPath(Path: WideString): Boolean; function IsPathDelimiterW(const S: WideString; Index: Integer): Boolean; function IsTextTrueType(DC: HDC): Boolean; overload; function IsTextTrueType(Canvas: TCanvas): Boolean; overload; function IsUNCPath(const Path: WideString): Boolean; function MessageBoxWide(Window: HWND; ACaption, AMessage: WideString; uType: integer): integer; function NewFolderNameW(ParentFolder: WideString; SuggestedFolderName: WideString = ''): WideString; function ShortenStringEx(DC: HDC; const S: WideString; Width: Integer; RTL: Boolean; EllipsisPlacement: TShortenStringEllipsis): WideString; procedure ShowWideMessage(Window: HWND; ACaption, AMessage: WideString); function StripExtW(AFile: WideString): WideString; function StripRemoteComputerW(const UNCPath: WideString): WideString; function StripTrailingBackslashW(const S: WideString; Force: Boolean = False): WideString; function StrRetToStr(StrRet: TStrRet; APIDL: PItemIDList): WideString; function SystemDirectory: WideString; function TextExtentW(Text: WideString; Font: TFont): TSize; overload; function TextExtentW(Text: WideString; Canvas: TCanvas): TSize; overload; function TextExtentW(Text: PWideChar; Canvas: TCanvas): TSize; overload; function TextExtentW(Text: PWideChar; DC: hDC): TSize; overload; function TextTrueExtentsW(Text: WideString; DC: HDC): TSize; function UniqueFileName(const AFilePath: WideString): WideString; function UniqueDirName(const ADirPath: WideString): WideString; function WindowsDirectory: WideString; //From Troy's TntClasses: function WideFileCreate(const FileName: WideString): Integer; function WideFileOpen(const FileName: WideString; Mode: LongWord): Integer; implementation uses VirtualShellUtilities; // Internal Helper Functions type TABCArray = array of TABC; function TextTrueExtentsW(Text: WideString; DC: HDC): TSize; var ABC: TABC; TextMetrics: TTextMetric; S: string; i: integer; begin // Get the Height at least GetTextExtentPoint32W(DC, PWideChar(Text), Length(Text), Result); GetTextMetrics(DC, TextMetrics); if TextMetrics.tmPitchAndFamily and TMPF_TRUETYPE <> 0 then begin Result.cx := 0; // Is TrueType if Win32Platform = VER_PLATFORM_WIN32_NT then begin for i := 1 to Length(Text) do begin GetCharABCWidthsW_VST(DC, Ord(Text[i]), Ord(Text[i]), ABC); Result.cx := Result.cx + ABC.abcA + integer(ABC.abcB) + ABC.abcC; end end else begin S := Text; for i := 1 to Length(S) do begin GetCharABCWidthsA(DC, Ord(S[i]), Ord(S[i]), ABC); Result.cx := Result.cx + ABC.abcA + integer(ABC.abcB) + ABC.abcC; end end; end end; function InternalTextExtentW(Text: PWideChar; DC: HDC): TSize; var S: string; begin if IsUnicode then GetTextExtentPoint32W(DC, PWideChar(Text), Length(Text), Result) else begin S := WideString( Text); GetTextExtentPoint32(DC, PChar(S), Length(S), Result) end; end; procedure SumFolder(FolderPath: WideString; Recurse: Boolean; var Size: Int64); { Returns the size of all files within the passed folder, including all } { sub-folders. This is recurcive don't initialize Size to 0 in the function! } var Info: TWin32FindData; InfoW: TWin32FindDataW; FHandle: THandle; FolderPathA: string; begin if IsUnicode then begin FHandle := FindFirstFileW_VST(PWideChar( FolderPath + '\*.*'), InfoW); if FHandle <> INVALID_HANDLE_VALUE then try if Recurse and (InfoW.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin if (lstrcmpiW_VST(InfoW.cFileName, '.') <> 0) and (lstrcmpiW_VST(InfoW.cFileName, '..') <> 0) then SumFolder(FolderPath + '\' + InfoW.cFileName, Recurse, Size) end else Size := Size + InfoW.nFileSizeHigh * MAXDWORD + InfoW.nFileSizeLow; while FindNextFileW(FHandle, InfoW) do begin if Recurse and (InfoW.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin if (lstrcmpiW_VST(InfoW.cFileName, '.') <> 0) and (lstrcmpiW_VST(InfoW.cFileName, '..') <> 0) then SumFolder(FolderPath + '\' + InfoW.cFileName, Recurse, Size) end else Size := Size + InfoW.nFileSizeHigh * MAXDWORD + InfoW.nFileSizeLow; end; finally Windows.FindClose(FHandle) end end else begin FolderPathA := FolderPath; FHandle := FindFirstFile(PChar( FolderPathA + '\*.*'), Info); if FHandle <> INVALID_HANDLE_VALUE then try if Recurse and (Info.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin if (lstrcmpi(Info.cFileName, '.') <> 0) and (lstrcmpi(Info.cFileName, '..') <> 0) then SumFolder(FolderPathA + '\' + Info.cFileName, Recurse, Size) end else Size := Size + Info.nFileSizeHigh * MAXDWORD + Info.nFileSizeLow; while FindNextFile(FHandle, Info) do begin if Recurse and (Info.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) then begin if (lstrcmpi(Info.cFileName, '.') <> 0) and (lstrcmpi(Info.cFileName, '..') <> 0) then SumFolder(FolderPathA + '\' + Info.cFileName, Recurse, Size) end else Size := Size + Info.nFileSizeHigh * MAXDWORD + Info.nFileSizeLow; end; finally Windows.FindClose(FHandle) end end end; // Exported Functions function FindRootToken(const Path: WideString): PWideChar; const RootToken = WideString(':\'); begin Result := StrPosW(PWideChar(Path), RootToken); end; //----------------- functions for null terminated strings -------------------------------------------------------------- function StrLenW(Str: PWideChar): Cardinal; // returns number of characters in a string excluding the null terminator asm MOV EDX, EDI MOV EDI, EAX MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW MOV EAX, 0FFFFFFFEH SUB EAX, ECX MOV EDI, EDX end; //---------------------------------------------------------------------------------------------------------------------- function StrEndW(Str: PWideChar): PWideChar; // returns a pointer to the end of a null terminated string asm MOV EDX, EDI MOV EDI, EAX MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW LEA EAX, [EDI - 2] MOV EDI, EDX end; //---------------------------------------------------------------------------------------------------------------------- function StrMoveW(Dest, Source: PWideChar; Count: Cardinal): PWideChar; // Copies the specified number of characters to the destination string and returns Dest // also as result. Dest must have enough room to store at least Count characters. asm PUSH ESI PUSH EDI MOV ESI, EDX MOV EDI, EAX MOV EDX, ECX CMP EDI, ESI JG @@1 JE @@2 SHR ECX, 1 REP MOVSD MOV ECX, EDX AND ECX, 1 REP MOVSW JMP @@2 @@1: LEA ESI, [ESI + 2 * ECX - 2] LEA EDI, [EDI + 2 * ECX - 2] STD AND ECX, 1 REP MOVSW SUB EDI, 2 SUB ESI, 2 MOV ECX, EDX SHR ECX, 1 REP MOVSD CLD @@2: POP EDI POP ESI end; //---------------------------------------------------------------------------------------------------------------------- function StrCopyW(Dest, Source: PWideChar): PWideChar; // copies Source to Dest and returns Dest asm PUSH EDI PUSH ESI MOV ESI, EAX MOV EDI, EDX MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW NOT ECX MOV EDI, ESI MOV ESI, EDX MOV EDX, ECX MOV EAX, EDI SHR ECX, 1 REP MOVSD MOV ECX, EDX AND ECX, 1 REP MOVSW POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrECopyW(Dest, Source: PWideChar): PWideChar; // copies Source to Dest and returns a pointer to the null character ending the string asm PUSH EDI PUSH ESI MOV ESI, EAX MOV EDI, EDX MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW NOT ECX MOV EDI, ESI MOV ESI, EDX MOV EDX, ECX SHR ECX, 1 REP MOVSD MOV ECX, EDX AND ECX, 1 REP MOVSW LEA EAX, [EDI - 2] POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrLCopyW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar; // copies a specified maximum number of characters from Source to Dest asm PUSH EDI PUSH ESI PUSH EBX MOV ESI, EAX MOV EDI, EDX MOV EBX, ECX XOR AX, AX TEST ECX, ECX JZ @@1 REPNE SCASW JNE @@1 INC ECX @@1: SUB EBX, ECX MOV EDI, ESI MOV ESI, EDX MOV EDX, EDI MOV ECX, EBX SHR ECX, 1 REP MOVSD MOV ECX, EBX AND ECX, 1 REP MOVSW STOSW MOV EAX, EDX POP EBX POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrPCopyW(Dest: PWideChar; const Source: string): PWideChar; // copies a Pascal-style string to a null-terminated wide string begin Result := StrPLCopyW(Dest, Source, Length(Source)); Result[Length(Source)] := WideNull; end; //---------------------------------------------------------------------------------------------------------------------- function StrPLCopyW(Dest: PWideChar; const Source: string; MaxLen: Cardinal): PWideChar; // copies characters from a Pascal-style string into a null-terminated wide string asm PUSH EDI PUSH ESI MOV EDI, EAX MOV ESI, EDX MOV EDX, EAX XOR AX, AX @@1: LODSB STOSW DEC ECX JNZ @@1 MOV EAX, EDX POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrCatW(Dest, Source: PWideChar): PWideChar; // appends a copy of Source to the end of Dest and returns the concatenated string begin StrCopyW(StrEndW(Dest), Source); Result := Dest; end; //---------------------------------------------------------------------------------------------------------------------- function StrLCatW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar; // appends a specified maximum number of WideCharacters to string asm PUSH EDI PUSH ESI PUSH EBX MOV EDI, Dest MOV ESI, Source MOV EBX, MaxLen SHL EBX, 1 CALL StrEndW MOV ECX, EDI ADD ECX, EBX SUB ECX, EAX JBE @@1 MOV EDX, ESI SHR ECX, 1 CALL StrLCopyW @@1: MOV EAX, EDI POP EBX POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- const // data used to bring UTF-16 coded strings into correct UTF-32 order for correct comparation UTF16Fixup: array[0..31] of Word = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $2000, $F800, $F800, $F800, $F800 ); function StrCompW(Str1, Str2: PWideChar): Integer; // Binary comparation of Str1 and Str2 with surrogate fix-up. // Returns < 0 if Str1 is smaller in binary order than Str2, = 0 if both strings are // equal and > 0 if Str1 is larger than Str2. // // This code is based on an idea of Markus W. Scherer (IBM). // Note: The surrogate fix-up is necessary because some single value code points have // larger values than surrogates which are in UTF-32 actually larger. var C1, C2: Word; Run1, Run2: PWideChar; begin // Assert(True = False, 'StrCompW: I have seen this function fail while sorting a directory. I would not use it'); Run1 := Str1; Run2 := Str2; repeat C1 := Word(Run1^); C1 := Word(C1 + UTF16Fixup[C1 shr 11]); C2 := Word(Run2^); C2 := Word(C2 + UTF16Fixup[C2 shr 11]); // now C1 and C2 are in UTF-32-compatible order Result := Integer(C1) - Integer(C2); if(Result <> 0) or (C1 = 0) or (C2 = 0) then Break; Inc(Run1); Inc(Run2); until False; // If the strings have different lengths but the comparation returned equity so far // then adjust the result so that the longer string is marked as the larger one. if Result = 0 then Result := (Run1 - Str1) - (Run2 - Str2); end; //---------------------------------------------------------------------------------------------------------------------- function StrICompW(Str1, Str2: PWideChar): Integer; // Insensitive case comparison var S1, S2: string; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := lstrcmpiW_VST(Str1, Str2) else begin S1 := Str1; S2 := Str2; Result := lstrcmpi(PChar(S1), PChar(S2)) end end; //---------------------------------------------------------------------------------------------------------------------- function StrLCompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; // compares strings up to MaxLen code points // see also StrCompW var C1, C2: Word; begin if MaxLen > 0 then begin repeat C1 := Word(Str1^); C1 := Word(C1 + UTF16Fixup[C1 shr 11]); C2 := Word(Str2^); C2 := Word(C2 + UTF16Fixup[C2 shr 11]); // now C1 and C2 are in UTF-32-compatible order // TODO: surrogates take up 2 words and are counted twice here, count them only once Result := Integer(C1) - Integer(C2); Dec(MaxLen); if(Result <> 0) or (C1 = 0) or (C2 = 0) or (MaxLen = 0) then Break; Inc(Str1); Inc(Str2); until False; end else Result := 0; end; function StrLICompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer; // Insensitive case comparison var S1, S2: string; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := lstrcmpiW_VST(Str1, Str2) else begin S1 := Str1; S2 := Str2; Result := lstrcmpi(PChar(S1), PChar(S2)) end end; //---------------------------------------------------------------------------------------------------------------------- function StrLowerW(Str: PWideChar): PWideChar; // Returns the string in Str converted to lower case var S: string; WS: WideString; begin Result := Str; if IsUnicode then CharLowerBuffW_VST(Str, StrLenW(Str)) else begin S := Str; CharLowerBuff(PChar(S), Length(S)); WS := S; { WS is a string index from 1, Result is PWideChar index from 0 } Move(WS[1], Result[0], Length(WS)); end; end; //---------------------------------------------------------------------------------------------------------------------- function StrNScanW(S1, S2: PWideChar): Integer; // Determines where (in S1) the first time one of the characters of S2 appear. // The result is the length of a string part of S1 where none of the characters of // S2 do appear (not counting the trailing #0 and starting with position 0 in S1). var Run: PWideChar; begin Result := -1; if (S1 <> nil) and (S2 <> nil) then begin Run := S1; while (Run^ <> #0) do begin if StrScanW(S2, Run^) <> nil then Break; Inc(Run); end; Result := Run - S1; end; end; //---------------------------------------------------------------------------------------------------------------------- function StrRNScanW(S1, S2: PWideChar): Integer; // This function does the same as StrRNScanW but uses S1 in reverse order. This // means S1 points to the last character of a string, is traversed reversely // and terminates with a starting #0. This is useful for parsing strings stored // in reversed macro buffers etc. var Run: PWideChar; begin Result := -1; if (S1 <> nil) and (S2 <> nil) then begin Run := S1; while (Run^ <> #0) do begin if StrScanW(S2, Run^) <> nil then Break; Dec(Run); end; Result := S1 - Run; end; end; //---------------------------------------------------------------------------------------------------------------------- function StrScanW(Str: PWideChar; Chr: WideChar): PWideChar; // returns a pointer to first occurrence of a specified character in a string asm PUSH EDI PUSH EAX MOV EDI, Str MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW NOT ECX POP EDI MOV AX, Chr REPNE SCASW MOV EAX, 0 JNE @@1 MOV EAX, EDI SUB EAX, 2 @@1: POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrScanW(Str: PWideChar; Chr: WideChar; StrLen: Cardinal): PWideChar; // Returns a pointer to first occurrence of a specified character in a string // or nil if not found. // Note: this is just a binary search for the specified character and there's no // check for a terminating null. Instead at most StrLen characters are // searched. This makes this function extremly fast. // // on enter EAX contains Str, EDX contains Chr and ECX StrLen // on exit EAX contains result pointer or nil asm TEST EAX, EAX JZ @@Exit // get out if the string is nil or StrLen is 0 JCXZ @@Exit @@Loop: CMP [EAX], DX // this unrolled loop is actually faster on modern processors JE @@Exit // than REP SCASW ADD EAX, 2 DEC ECX JNZ @@Loop XOR EAX, EAX @@Exit: end; //---------------------------------------------------------------------------------------------------------------------- function StrRScanW(Str: PWideChar; Chr: WideChar): PWideChar; // returns a pointer to the last occurance of Chr in Str asm PUSH EDI MOV EDI, Str MOV ECX, 0FFFFFFFFH XOR AX, AX REPNE SCASW NOT ECX STD SUB EDI, 2 MOV AX, Chr REPNE SCASW MOV EAX, 0 JNE @@1 MOV EAX, EDI ADD EAX, 2 @@1: CLD POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrPosW(Str, SubStr: PWideChar): PWideChar; // returns a pointer to the first occurance of SubStr in Str asm PUSH EDI PUSH ESI PUSH EBX OR EAX, EAX JZ @@2 OR EDX, EDX JZ @@2 MOV EBX, EAX MOV EDI, EDX XOR AX, AX MOV ECX, 0FFFFFFFFH REPNE SCASW NOT ECX DEC ECX JZ @@2 MOV ESI, ECX MOV EDI, EBX MOV ECX, 0FFFFFFFFH REPNE SCASW NOT ECX SUB ECX, ESI JBE @@2 MOV EDI, EBX LEA EBX, [ESI - 1] @@1: MOV ESI, EDX LODSW REPNE SCASW JNE @@2 MOV EAX, ECX PUSH EDI MOV ECX, EBX REPE CMPSW POP EDI MOV ECX, EAX JNE @@1 LEA EAX, [EDI - 2] JMP @@3 @@2: XOR EAX, EAX @@3: POP EBX POP ESI POP EDI end; //---------------------------------------------------------------------------------------------------------------------- function StrAllocW(Size: Cardinal): PWideChar; // Allocates a buffer for a null-terminated wide string and returns a pointer // to the first character of the string. begin Size := SizeOf(WideChar) * Size + SizeOf(Cardinal); GetMem(Result, Size); FillChar(Result^, Size, 0); Cardinal(Pointer(Result)^) := Size; Inc(Result, SizeOf(Cardinal) div SizeOf(WideChar)); end; //---------------------------------------------------------------------------------------------------------------------- function StrBufSizeW(Str: PWideChar): Cardinal; // Returns max number of wide characters that can be stored in a buffer // allocated by StrAllocW. begin Dec(Str, SizeOf(Cardinal) div SizeOf(WideChar)); Result := (Cardinal(Pointer(Str)^) - SizeOf(Cardinal)) div 2; end; //---------------------------------------------------------------------------------------------------------------------- function StrNewW(Str: PWideChar): PWideChar; // Duplicates the given string (if not nil) and returns the address of the new string. var Size: Cardinal; begin if Str = nil then Result := nil else begin Size := StrLenW(Str) + 1; Result := StrMoveW(StrAllocW(Size), Str, Size); end; end; //---------------------------------------------------------------------------------------------------------------------- procedure StrDisposeW(Str: PWideChar); // releases a string allocated with StrNew begin if Str <> nil then begin Dec(Str, SizeOf(Cardinal) div SizeOf(WideChar)); FreeMem(Str, Cardinal(Pointer(Str)^)); end; end; //---------------------------------------------------------------------------------------------------------------------- procedure StrSwapByteOrder(Str: PWideChar); // exchanges in each character of the given string the low order and high order // byte to go from LSB to MSB and vice versa. // EAX contains address of string asm PUSH ESI PUSH EDI MOV ESI, EAX MOV EDI, ESI XOR EAX, EAX // clear high order byte to be able to use 32bit operand below @@1: LODSW OR EAX, EAX JZ @@2 XCHG AL, AH STOSW JMP @@1 @@2: POP EDI POP ESI end; //---------------------------------------------------------------------------------------------------------------------- function StrUpperW(Str: PWideChar): PWideChar; // Returns the string in Str converted to Upper case var S: string; WS: WideString; begin Result := Str; if IsUnicode then CharUpperBuffW(Str, StrLenW(Str)) else begin S := Str; CharUpperBuff(PChar(S), Length(S)); WS := S; { WS is a string index from 1, Result is PWideChar index from 0 } Move(WS[1], Result[0], Length(WS)); end; end; //---------------------------------------------------------------------------------------------------------------------- function WideAdjustLineBreaks(const S: WideString): WideString; var Source, SourceEnd, Dest: PWideChar; Extra: Integer; begin Source := Pointer(S); SourceEnd := Source + Length(S); Extra := 0; while Source < SourceEnd do begin case Source^ of WideLF: Inc(Extra); WideCR: if Source[1] = WideLineFeed then Inc(Source) else Inc(Extra); end; Inc(Source); end; Source := Pointer(S); SetString(Result, nil, SourceEnd - Source + Extra); Dest := Pointer(Result); while Source < SourceEnd do begin case Source^ of WideLineFeed: begin Dest^ := WideLineSeparator; Inc(Dest); Inc(Source); end; WideCarriageReturn: begin Dest^ := WideLineSeparator; Inc(Dest); Inc(Source); if Source^ = WideLineFeed then Inc(Source); end; else Dest^ := Source^; Inc(Dest); Inc(Source); end; end; end; //---------------------------------------------------------------------------------------------------------------------- function WideQuotedStr(const S: WideString; Quote: WideChar): WideString; // works like QuotedStr from SysUtils.pas but can insert any quotation character var P, Src, Dest: PWideChar; AddCount: Integer; begin AddCount := 0; P := StrScanW(PWideChar(S), Quote); while (P <> nil) do begin Inc(P); Inc(AddCount); P := StrScanW(P, Quote); end; if AddCount = 0 then Result := Quote + S + Quote else begin SetLength(Result, Length(S) + AddCount + 2); Dest := PWideChar(Result); Dest^ := Quote; Inc(Dest); Src := PWideChar(S); P := StrScanW(Src, Quote); repeat Inc(P); Move(Src^, Dest^, 2 * (P - Src)); Inc(Dest, P - Src); Dest^ := Quote; Inc(Dest); Src := P; P := StrScanW(Src, Quote); until P = nil; P := StrEndW(Src); Move(Src^, Dest^, 2 * (P - Src)); Inc(Dest, P - Src); Dest^ := Quote; end; end; //---------------------------------------------------------------------------------------------------------------------- function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): WideString; // extracts a string enclosed in quote characters given by Quote var P, Dest: PWideChar; DropCount: Integer; begin Result := ''; if (Src = nil) or (Src^ <> Quote) then Exit; Inc(Src); DropCount := 1; P := Src; Src := StrScanW(Src, Quote); while Src <> nil do // count adjacent pairs of quote chars begin Inc(Src); if Src^ <> Quote then Break; Inc(Src); Inc(DropCount); Src := StrScanW(Src, Quote); end; if Src = nil then Src := StrEndW(P); if (Src - P) <= 1 then Exit; if DropCount = 1 then SetString(Result, P, Src - P - 1) else begin SetLength(Result, Src - P - DropCount); Dest := PWideChar(Result); Src := StrScanW(P, Quote); while Src <> nil do begin Inc(Src); if Src^ <> Quote then Break; Move(P^, Dest^, 2 * (Src - P)); Inc(Dest, Src - P); Inc(Src); P := Src; Src := StrScanW(Src, Quote); end; if Src = nil then Src := StrEndW(P); Move(P^, Dest^, 2 * (Src - P - 1)); end; end; //---------------------------------------------------------------------------------------------------------------------- function WideLowerCase(const S: WideString): WideString; var Str: string; begin if IsUnicode then begin Result := S; CharLowerBuffW_VST(PWideChar(Result), Length(Result)) end else begin Str := S; CharLowerBuff(PChar(Str), Length(Str)); Result := Str end end; //---------------------------------------------------------------------------------------------------------------------- function WideStringOfChar(C: WideChar; Count: Cardinal): WideString; // returns a string of Count characters filled with C var I: Integer; begin SetLength(Result, Count); for I := 1 to Count do Result[I] := C; end; //---------------------------------------------------------------------------------------------------------------------- function WideUpperCase(const S: WideString): WideString; var Str: string; begin if IsUnicode then begin Result := S; CharUpperBuffW(PWideChar(Result), Length(Result)) end else begin Str := S; CharUpperBuff(PChar(Str), Length(Str)); Result := Str end end; //---------------------------------------------------------------------------------------------------------------------- function WideCharPos(const S: WideString; const Ch: WideChar; const Index: Integer): Integer; // returns the index of character Ch in S, starts searching at index Index // Note: This is a quick memory search. No attempt is made to interpret either // the given charcter nor the string (ligatures, modifiers, surrogates etc.) // Code from Azret Botash. asm TEST EAX,EAX // make sure we are not null JZ @@StrIsNil DEC ECX // make index zero based JL @@IdxIsSmall PUSH EBX PUSH EDI MOV EDI, EAX // EDI := S XOR EAX, EAX MOV AX, DX // AX := Ch MOV EDX, [EDI - 4] // EDX := Length(S) * 2 SHR EDX, 1 // EDX := EDX div 2 MOV EBX, EDX // save the length to calc. result SUB EDX, ECX // EDX = EDX - Index = # of chars to scan JLE @@IdxIsBig SHL ECX, 1 // two bytes per char ADD EDI, ECX // point to index'th char MOV ECX, EDX // loop counter REPNE SCASW JNE @@NoMatch MOV EAX, EBX // result := saved length - SUB EAX, ECX // loop counter value POP EDI POP EBX RET @@IdxIsBig: @@NoMatch: XOR EAX,EAX POP EDI POP EBX RET @@IdxIsSmall: XOR EAX, EAX @@StrIsNil: end; //---------------------------------------------------------------------------------------------------------------------- function AddCommas(NumberString: WideString): WideString; var i: integer; begin { Trimming white space in Unicode is tough don't pass any } i := Length(NumberString) mod 3; if i = 0 then i := 3; while i < Length(NumberString) do begin InsertW(ThousandSeparator, NumberString, i); Inc(i, 4); end; Result := NumberString end; //---------------------------------------------------------------------------------------------------------------------- function CalcuateFolderSize(FolderPath: WideString; Recurse: Boolean): Int64; // Recursivly gets the size of the folder and subfolders var S: string; FreeSpaceAvailable, TotalSpace: Int64; SectorsPerCluster, BytesPerSector, FreeClusters, TotalClusters: DWORD; begin Result := 0; if Recurse and IsDriveW(FolderPath) then begin if IsUnicode and Assigned(GetDiskFreeSpaceExW_VST) then begin if GetDiskFreeSpaceExW_VST(PWideChar(FolderPath), FreeSpaceAvailable, TotalSpace, nil) then Result := TotalSpace - FreeSpaceAvailable end else if not IsWin95_SR1 and Assigned(GetDiskFreeSpaceExA_VST) then begin S := FolderPath; if GetDiskFreeSpaceExA_VST(PChar(S), FreeSpaceAvailable, TotalSpace, nil) then Result := TotalSpace - FreeSpaceAvailable; end else begin GetDiskFreeSpaceA(PChar( S), SectorsPerCluster, BytesPerSector, FreeClusters, TotalClusters); Result := SectorsPerCluster * BytesPerSector * TotalClusters end; end else SumFolder(FolderPath, Recurse, Result); end; //---------------------------------------------------------------------------------------------------------------------- function CreateDirW(const DirName: WideString): Boolean; var S: string; PIDL: PItemIDList; begin if IsUnicode then Result := CreateDirectoryW_VST(PWideChar( DirName), nil) else begin S := DirName; Result := CreateDirectory(PChar( S), nil); end; if Result then begin PIDL := PathToPIDL(DirName); SHChangeNotify(SHCNE_MKDIR, SHCNF_IDLIST, PIDL, PIDL); PIDLMgr.FreePIDL(PIDL) end; end; //---------------------------------------------------------------------------------------------------------------------- function DirExistsW(const FileName: WideString): Boolean; begin Result := DirExistsW(PWideChar(FileName)); end; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- function DirExistsW(const FileName: PWideChar): Boolean; var ErrorCode: LongWord; S: string; begin if FileName <> '' then begin if (Win32Platform = VER_PLATFORM_WIN32_NT) then ErrorCode := GetFileAttributesW_VST(FileName) else begin S := FileName; ErrorCode := GetFileAttributes(PChar(S)) end; Result := (Integer(ErrorCode) <> -1) and (FILE_ATTRIBUTE_DIRECTORY and ErrorCode <> 0); end else Result := False end; //---------------------------------------------------------------------------------------------------------------------- function DiskInDrive(C: Char): Boolean; var OldErrorMode: Integer; begin C := UpCase(C); if C in ['A'..'Z'] then begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); Result := DiskFree(Ord(C) - Ord('A') + 1) > -1; SetErrorMode(OldErrorMode); end else Result := False end; {$IFDEF DELPHI_5} function ExcludeTrailingPathDelimiter(const S: string): string; begin Result := ExcludeTrailingBackSlash(S) end; {$ENDIF} //---------------------------------------------------------------------------------------------------------------------- function ExtractFileDirW(const FileName: WideString): WideString; var WP: PWideChar; begin Result := ''; if (Length(FileName) < 3) and (Length(FileName) > 0) then begin if (((FileName[1] >= 'A') and (FileName[1] >= 'Z')) or ((FileName[1] >= 'a') and (FileName[1] >= 'z'))) then begin Result := WideString(FileName[1]) + ':\'; end end else begin WP := FindRootToken(FileName); if Assigned(WP) then begin { Find the last '\' } WP := StrRScanW(PWideChar( FileName), WideChar( '\')); if Assigned(WP) then begin { The stripped file name leaves just the root directory } if (Length(FileName) > 1) and ( (WP - 1)^ = ':') then WP := WP + 1; // Tack on the '\' SetLength(Result, WP - @FileName[1]); StrMoveW(PWideChar(Result), PWideChar(FileName), WP - @FileName[1]); end end end end; //---------------------------------------------------------------------------------------------------------------------- function ExtractFileDriveW(const FileName: WideString): WideString; var WP: PWideChar; begin Result := ''; WP := FindRootToken(FileName); if Assigned(WP) then begin Inc(WP, 1); SetLength(Result, WP - @FileName[1]); StrMoveW(PWideChar(Result), PWideChar(FileName), WP - @FileName[1]); end; end; //---------------------------------------------------------------------------------------------------------------------- function ExtractFileExtW(const FileName: WideString): WideString; // Returns the extension of the file var WP: PWideChar; begin WP := StrRScanW(PWideChar( FileName), WideChar( '.')); if Assigned(WP) then Result := WP; end; //---------------------------------------------------------------------------------------------------------------------- function ExtractRemoteComputerW(const UNCPath: WideString): WideString; var Head: PWideChar; begin Result := ''; if IsUNCPath(UNCPath) then begin Result := UNCPath; Head := @Result[1]; Head := Head + 2; // Skip past the '\\' Head := StrScanW(Head, WideChar('\')); if Assigned(Head) then Head^ := WideChar(#0); SetLength(Result, StrLenW(PWideChar(Result))); end; end; //---------------------------------------------------------------------------------------------------------------------- function ExtractFileNameW(const FileName: WideString): WideString; // Returns the file name of the path // WARNING MAKES NO ASSUMPTIONS ABOUT IF IT HAS JUST STRIPPED OFF A FILE OR // A FOLDER!!!!!! var WP: PWideChar; begin Result := ''; if Length(FileName) > 3 then begin WP := StrRScanW(PWideChar(FileName), WideChar('\')); if Assigned(WP) then Result := WP + 1; end; end; //---------------------------------------------------------------------------------------------------------------------- function ExpandFileNameW(const FileName: WideString): WideString; var Name: PWideChar; Buffer: array[0..MAX_PATH - 1] of WideChar; begin if IsUnicode then begin if GetFullPathNameW_VST(PWideChar(FileName), Length(Buffer), @Buffer[0], Name) > 0 then begin SetLength(Result, StrLenW(Buffer)); Move(Buffer, Result[1], StrLenW(Buffer)*2); end; end else Result := ExpandFileName(FileName); // Use the ANSI version in the VCL end; //---------------------------------------------------------------------------------------------------------------------- function FileCreateW(const FileName: WideString): Integer; var s: string; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := Integer(CreateFileW_VST(PWideChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)) else begin s := FileName; Result := Integer(CreateFile(PChar(s), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)) end end; //---------------------------------------------------------------------------------------------------------------------- function FileExistsW(const FileName: WideString): Boolean; var Handle: THandle; FindData: TWin32FindData; FindDataW: TWin32FindDataW; FileNameA: string; begin Result := True; if Win32Platform = VER_PLATFORM_WIN32_NT then Handle := FindFirstFileW_VST(PWideChar(FileName), FindDataW) else begin FileNameA := FileName; Handle := FindFirstFile(PChar(FileNameA), FindData) end; if Handle <> INVALID_HANDLE_VALUE then Windows.FindClose(Handle) else Result := False; end; {$IFDEF DELPHI_5} function IncludeTrailingPathDelimiter(const S: string): string; begin Result := IncludeTrailingBackslash(S) end; {$ENDIF} //---------------------------------------------------------------------------------------------------------------------- function IncludeTrailingBackslashW(const S: WideString): WideString; begin Result := S; if not IsPathDelimiterW(Result, Length(Result)) then Result := Result + '\'; end; //---------------------------------------------------------------------------------------------------------------------- procedure InsertW(Source: WideString; var S: WideString; Index: Integer); { It appears there is a WideString Insert in the VCL already but since mine } { looks better and is simpler and I spent my time I will use mine <g> } { _WStrInsert in System through compiler magic. } var OriginalLen: integer; begin if (Index < Length(S) + 1) and (Index > - 1) then begin OriginalLen := Length(S); SetLength(S, Length(Source) + Length(S)); { We are correct up to Index } { Slide to end of new string leaving space for insert } Move(S[Index + 1], S[Index + 1 + Length(Source)], (OriginalLen - Index) * 2); Move(Source[1], S[Index + 1], Length(Source) * 2); end end; //---------------------------------------------------------------------------------------------------------------------- function IntToStrW(Value: integer): WideString; { Need to find a way to do this in Unicode. } begin Result := IntToStr(Value); end; //---------------------------------------------------------------------------------------------------------------------- function IsDriveW(Drive: WideString): Boolean; begin if Length(Drive) = 3 then Result := (LowerCase(Drive[1]) >= 'a') and (LowerCase(Drive[1]) <= 'z') and (Drive[2] = ':') and (Drive[3] = '\') else if Length(Drive) = 2 then Result := (LowerCase(Drive[1]) >= 'a') and (LowerCase(Drive[1]) <= 'z') and (Drive[2] = ':') else Result := False end; //---------------------------------------------------------------------------------------------------------------------- function IsFloppyW(FileFolder: WideString): boolean; begin if Length(FileFolder) > 0 then Result := IsDriveW(FileFolder) and (Char(FileFolder[1]) in ['A', 'a', 'B', 'b']) else Result := False end; function IsFTPPath(Path: WideString): Boolean; begin if Length(Path) > 3 then begin Path := UpperCase(Path); Result := (Path[1] = 'F') and (Path[2] = 'T') and (Path[3] = 'P') end else Result := False end; //---------------------------------------------------------------------------------------------------------------------- function IsPathDelimiterW(const S: WideString; Index: Integer): Boolean; begin Result := (Index > 0) and (Index <= Length(S)) and (S[Index] = '\'); end; //---------------------------------------------------------------------------------------------------------------------- function IsTextTrueType(DC: HDC): Boolean; var TextMetrics: TTextMetric; begin GetTextMetrics(DC, TextMetrics); Result := TextMetrics.tmPitchAndFamily and TMPF_TRUETYPE <> 0 end; //---------------------------------------------------------------------------------------------------------------------- function IsTextTrueType(Canvas: TCanvas): Boolean; begin Result := IsTextTrueType(Canvas.Handle); end; //---------------------------------------------------------------------------------------------------------------------- function IsUNCPath(const Path: WideString): Boolean; begin Result := ((Path[1] = '\') and (Path[2] = '\')) and (DirExistsW(Path) or FileExistsW(Path)) end; //---------------------------------------------------------------------------------------------------------------------- function MessageBoxWide(Window: HWND; ACaption, AMessage: WideString; uType: integer): integer; var TextA, CaptionA: string; begin if IsUnicode then Result := MessageBoxW(Window, PWideChar( AMessage), PWideChar( ACaption), uType) else begin TextA := AMessage; CaptionA := ACaption; Result := MessageBoxA(Window, PChar( TextA), PChar( CaptionA), uType) end end; //---------------------------------------------------------------------------------------------------------------------- function NewFolderNameW(ParentFolder: WideString; SuggestedFolderName: WideString = ''): WideString; var i: integer; TempFoldername: String; begin ParentFolder := StripTrailingBackslashW(ParentFolder, True); // Strip even if a root folder i := 1; if SuggestedFolderName = '' then Begin Result := ParentFolder + '\' + STR_NEWFOLDER; TempFoldername := STR_NEWFOLDER; end else Begin Result := ParentFolder + '\' + SuggestedFolderName; Tempfoldername := SuggestedFolderName; End; while DirExistsW(Result) and (i <= 20) do begin Result := ParentFolder + '\' + Tempfoldername + ' (' + IntToStr(i) + ')'; Inc(i); end; if i > 20 then Result := ''; end; function ShortenStringEx(DC: HDC; const S: WideString; Width: Integer; RTL: Boolean; EllipsisPlacement: TShortenStringEllipsis): WideString; // Shortens the passed string and inserts ellipsis "..." in the requested place. // This is not a fast function but it is clear how it works. Also the RTL implmentation // is still being understood. var Len: Integer; EllipsisWidth: Integer; TargetString: WideString; Tail, Head, Middle: PWideChar; L, ResultW: integer; begin Len := Length(S); if (Len = 0) or (Width <= 0) then Result := '' else begin // Determine width of triple point using the current DC settings TargetString := '...'; EllipsisWidth := TextExtentW(PWideChar(TargetString), DC).cx; if Width <= EllipsisWidth then Result := '' else begin TargetString := S; Head := PWideChar(TargetString); Tail := Head; Inc(Tail, StrLenW(PWideChar(TargetString))); case EllipsisPlacement of sseEnd: begin L := EllipsisWidth + TextExtentW(PWideChar(TargetString), DC).cx; while (L > Width) do begin Dec(Tail); Tail^ := WideNull; L := EllipsisWidth + TextExtentW(PWideChar(TargetString), DC).cx; end; Result := PWideChar(TargetString) + '...'; end; sseFront: begin L := EllipsisWidth + TextExtentW(PWideChar(TargetString), DC).cx; while (L > Width) do begin Inc(Head); L := EllipsisWidth + TextExtentW(PWideChar(Head), DC).cx; end; Result := '...' + PWideChar(Head); end; sseMiddle: begin L := EllipsisWidth + TextExtentW(PWideChar(TargetString), DC).cx; while (L > Width div 2 - EllipsisWidth div 2) do begin Dec(Tail); Tail^ := WideNull; L := TextExtentW(PWideChar(TargetString), DC).cx; end; Result := PWideChar(TargetString) + '...'; ResultW := TextExtentW(PWideChar(Result), DC).cx; TargetString := S; Head := PWideChar(TargetString); Middle := Head; Inc(Middle, StrLenW(PWideChar(Result)) - 3); // - 3 for ellipsis letters Tail := Head; Inc(Tail, StrLenW(PWideChar(TargetString))); Head := Tail - 1; L := ResultW + TextExtentW(Head, DC).cx; while (L < Width) and (Head >= Middle) do begin Dec(Head); L := ResultW + TextExtentW(PWideChar(Head), DC).cx; end; Inc(Head); Result := Result + Head; end; sseFilePathMiddle: begin Head := Tail - 1; L := EllipsisWidth + TextExtentW(Head, DC).cx; while (Head^ <> '\') and (Head <> @TargetString[1]) and (L < Width) do begin Dec(Head); L := EllipsisWidth + TextExtentW(Head, DC).cx; end; if Head^ <> '\' then Inc(Head); Result := '...' + Head; ResultW := TextExtentW(PWideChar(Result), DC).cx; Head^ := WideNull; SetLength(TargetString, StrLenW(PWideChar(TargetString))); Head := PWideChar(TargetString); Tail := Head; Inc(Tail, StrLenW(Head)); L := ResultW + TextExtentW(PWideChar(TargetString), DC).cx; while (L > Width) and (Tail > @TargetString[1]) do begin Dec(Tail); Tail^ := WideNull; L := ResultW + TextExtentW(PWideChar(TargetString), DC).cx; end; Result := Head + Result; end; end; // Windows 2000 automatically switches the order in the string. For every other system we have to take care. { if IsWin2000 or not RTL then Result := Copy(S, 1, N - 1) + '...' else Result := '...' + Copy(S, 1, N - 1); } end; end; end; procedure ShowWideMessage(Window: HWND; ACaption, AMessage: WideString); var TextA, CaptionA: string; begin if IsUnicode then MessageBoxW(Window, PWideChar( AMessage), PWideChar( ACaption), MB_ICONEXCLAMATION or MB_OK) else begin TextA := AMessage; CaptionA := ACaption; MessageBoxA(Window, PChar( TextA), PChar( CaptionA), MB_ICONEXCLAMATION or MB_OK) end end; //---------------------------------------------------------------------------------------------------------------------- function StripExtW(AFile: WideString): WideString; { Strips the extenstion off a file name } var i: integer; Done: Boolean; begin i := Length(AFile); Done := False; Result := AFile; while (i > 0) and not Done do begin if AFile[i] = '.' then begin Done := True; SetLength(Result, i - 1); end; Dec(i); end; end; //---------------------------------------------------------------------------------------------------------------------- function StripRemoteComputerW(const UNCPath: WideString): WideString; // Strips the \\RemoteComputer\ part of an UNC path var Head: PWideChar; begin Result := ''; if IsUNCPath(UNCPath) then begin Result := ''; if IsUNCPath(UNCPath) then begin Result := UNCPath; Head := @Result[1]; Head := Head + 2; // Skip past the '\\' Head := StrScanW(Head, WideChar('\')); if Assigned(Head) then begin Head := Head + 1; Move(Head[0], Result[1], (StrLenW(Head) + 1) * 2); end; SetLength(Result, StrLenW(PWideChar(Result))); end; end; end; //---------------------------------------------------------------------------------------------------------------------- function StripTrailingBackslashW(const S: WideString; Force: Boolean = False): WideString; begin Result := S; if Result <> '' then begin // Works with FilePaths and FTP Paths if Result[ Length(Result)] in [WideChar('/'), WideChar('\')] then if not IsDriveW(Result) or Force then // Don't strip off if is a root drive SetLength(Result, Length(Result) - 1); end; end; //---------------------------------------------------------------------------------------------------------------------- function StrRetToStr(StrRet: TStrRet; APIDL: PItemIDList): WideString; { Extracts the string from the StrRet structure. } var P: PChar; // S: string; begin case StrRet.uType of STRRET_CSTR: begin SetString(Result, StrRet.cStr, lStrLen(StrRet.cStr)); // Result := S end; STRRET_OFFSET: begin if Assigned(APIDL) then begin {$R-} P := PChar(@(APIDL).mkid.abID[StrRet.uOffset - SizeOf(APIDL.mkid.cb)]); {$R+} SetString(Result, P, StrLen(P)); // Result := S; end else Result := ''; end; STRRET_WSTR: begin Result := StrRet.pOleStr; if Assigned(StrRet.pOleStr) then PIDLMgr.FreeOLEStr(StrRet.pOLEStr); end; end; end; //---------------------------------------------------------------------------------------------------------------------- function SystemDirectory: WideString; var Len: integer; S: string; begin Result := ''; if Win32Platform = VER_PLATFORM_WIN32_NT then Len := GetSystemDirectoryW_VST(PWideChar(Result), 0) else Len := GetSystemDirectoryA(PChar(S), 0); if Len > 0 then begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin SetLength(Result, Len - 1); GetSystemDirectoryW_VST(PWideChar(Result), Len); end else begin SetLength(S, Len - 1); GetSystemDirectoryA(PChar(S), Len); Result := S end end end; //---------------------------------------------------------------------------------------------------------------------- function TextExtentW(Text: WideString; Font: TFont): TSize; var Canvas: TCanvas; begin FillChar(Result, SizeOf(Result), #0); if Text <> '' then begin Canvas := TCanvas.Create; try Canvas.Handle := GetDC(0); Canvas.Lock; Canvas.Font.Assign(Font); Result := InternalTextExtentW(PWideChar(Text), Canvas.Handle); finally if Assigned(Canvas) and (Canvas.Handle <> 0) then ReleaseDC(0, Canvas.Handle); Canvas.Unlock; Canvas.Free end end end; //---------------------------------------------------------------------------------------------------------------------- function TextExtentW(Text: WideString; Canvas: TCanvas): TSize; begin FillChar(Result, SizeOf(Result), #0); if Assigned(Canvas) and (Text <> '') then begin Canvas.Lock; Result := InternalTextExtentW(PWideChar(Text), Canvas.Handle); Canvas.Unlock; end; end; function TextExtentW(Text: PWideChar; Canvas: TCanvas): TSize; begin FillChar(Result, SizeOf(Result), #0); if Assigned(Canvas) and (Assigned(Text)) then begin Canvas.Lock; Result := InternalTextExtentW(Text, Canvas.Handle); Canvas.Unlock; end; end; function TextExtentW(Text: PWideChar; DC: hDC): TSize; begin FillChar(Result, SizeOf(Result), #0); if (DC <> 0) and (Assigned(Text)) then Result := InternalTextExtentW(Text, DC); end; //---------------------------------------------------------------------------------------------------------------------- function UniqueFileName(const AFilePath: WideString): WideString; { Creates a unique file name in based on other files in the passed path } var i: integer; WP: PWideChar; begin Result := AFilePath; i := 2; while FileExistsW(Result) and (i < 20) do begin Result := AFilePath; WP := StrRScanW(PWideChar( Result), '.'); if Assigned(WP) then InsertW( ' (' + IntToStrW(i) + ')', Result, PWideChar(WP) - PWideChar(Result)) else begin Result := ''; Break; end; Inc(i) end; end; //---------------------------------------------------------------------------------------------------------------------- function UniqueDirName(const ADirPath: WideString): WideString; var i: integer; begin Result := ADirPath; i := 2; while DirExistsW(Result) and (i < 20) do begin Result := ADirPath; InsertW( ' (' + IntToStrW(i) + ')', Result, Length(Result)); Inc(i) end; end; //---------------------------------------------------------------------------------------------------------------------- function WindowsDirectory: WideString; var Len: integer; S: string; begin Result := ''; if Win32Platform = VER_PLATFORM_WIN32_NT then Len := GetWindowsDirectoryW_VST(PWideChar(Result), 0) else Len := GetWindowsDirectoryA(PChar(S), 0); if Len > 0 then begin if IsUnicode then begin SetLength(Result, Len - 1); GetWindowsDirectoryW_VST(PWideChar(Result), Len); end else begin SetLength(S, Len - 1); GetWindowsDirectoryA(PChar(S), Len); Result := S end end end; //---------------------------------------------------------------------------------------------------------------------- { TWideStringList } function TWideStringList.Add(const S: WideString): Integer; begin Result := AddObject(S, nil); end; function TWideStringList.AddObject(const S: WideString; AObject: TObject): Integer; begin if not Sorted then Result := FCount else if Find(S, Result) then case Duplicates of dupIgnore: Exit; dupError: Error(SDuplicateString, 0); end; InsertItem(Result, S, AObject); end; procedure TWideStringList.AddStrings(Strings: TWideStringList); var I: Integer; begin for I := 0 to Strings.Count - 1 do AddObject(Strings[I], Strings.Objects[I]); end; procedure TWideStringList.AddStrings(Strings: TStrings); var I: Integer; begin for I := 0 to Strings.Count - 1 do AddObject(Strings[I], Strings.Objects[I]); end; procedure TWideStringList.Assign(Source: TPersistent); begin if Source is TWideStringList then begin Clear; AddStrings(TWideStringList(Source)); end else if Source is TStrings then begin Clear; AddStrings(TStrings(Source)); end else inherited; end; procedure TWideStringList.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TWideStringList then Dest.Assign(Self) else if Dest is TStrings then begin TStrings(Dest).Clear; for I := 0 to Count - 1 do TStrings(Dest).AddObject(Strings[I], Objects[I]); end else inherited; end; procedure TWideStringList.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TWideStringList.Changing; begin if Assigned(FOnChanging) then FOnChanging(Self); end; procedure TWideStringList.Clear; begin if FCount <> 0 then begin Changing; while FCount > 0 do Delete(0); SetCapacity(0); Changed; end; end; procedure TWideStringList.CustomSort(Compare: TWideStringListSortCompare); begin if not Sorted and (FCount > 1) then begin Changing; QuickSort(0, FCount - 1, Compare); Changed; end; end; procedure TWideStringList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; if OwnsObjects then if Assigned(Objects[Index]) then begin Objects[Index].Free; Objects[Index] := nil; end; Finalize(FList^[Index]); Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TWideStringItem)); Changed; end; destructor TWideStringList.Destroy; begin FOnChange := nil; FOnChanging := nil; Clear; inherited Destroy; SetCapacity(0); end; procedure TWideStringList.Error(const Msg: String; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX, [EBP + 4] end; begin raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; procedure TWideStringList.Exchange(Index1, Index2: Integer); begin if (Index1 < 0) or (Index1 >= FCount) then Error(SListIndexError, Index1); if (Index2 < 0) or (Index2 >= FCount) then Error(SListIndexError, Index2); Changing; ExchangeItems(Index1, Index2); Changed; end; procedure TWideStringList.ExchangeItems(Index1, Index2: Integer); var Temp: Integer; Item1, Item2: PWideStringItem; begin Item1 := @FList^[Index1]; Item2 := @FList^[Index2]; Temp := Integer(Item1^.FWideString); Integer(Item1^.FWideString) := Integer(Item2^.FWideString); Integer(Item2^.FWideString) := Temp; Temp := Integer(Item1^.FObject); Integer(Item1^.FObject) := Integer(Item2^.FObject); Integer(Item2^.FObject) := Temp; end; function TWideStringList.Find(const S: WideString; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; if Win32Platform = VER_PLATFORM_WIN32_NT then C := lstrcmpiW_VST(PWideChar( FList^[I].FWideString), PWideChar( S)) else C := AnsiCompareText(FList^[I].FWideString, S); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> dupAccept then L := I; end; end; end; Index := L; end; function TWideStringList.Get(Index: Integer): WideString; begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Result := FList^[Index].FWideString; end; function TWideStringList.GetCapacity: Integer; begin Result := FCapacity; end; function TWideStringList.GetCommaText: WideString; var S: WideString; P: PWideChar; I, Count: Integer; begin Count := GetCount; if (Count = 1) and (Get(0) = '') then Result := '""' else begin Result := ''; for I := 0 to Count - 1 do begin S := Get(I); P := PWideChar(S); while not (P^ in [WideNull..WideSpace, WideChar('"'), WideChar(',')]) do Inc(P); if (P^ <> WideNull) then S := WideQuotedStr(S, '"'); Result := Result + S + ','; end; System.Delete(Result, Length(Result), 1); end; end; function TWideStringList.GetCount: Integer; begin Result := FCount; end; function TWideStringList.GetName(Index: Integer): WideString; var P: Integer; begin Result := Get(Index); P := Pos('=', Result); if P > 0 then SetLength(Result, P - 1) else Result := ''; end; function TWideStringList.GetObject(Index: Integer): TObject; begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Result := FList^[Index].FObject; end; function TWideStringList.GetTextStr: WideString; var I, L, Size, Count: Integer; P: PWideChar; S: WideString; begin Count := GetCount; Size := 0; for I := 0 to Count - 1 do Inc(Size, Length(Get(I)) + 2); SetLength(Result, Size); P := Pointer(Result); for I := 0 to Count - 1 do begin S := Get(I); L := Length(S); if L <> 0 then begin System.Move(Pointer(S)^, P^, 2 * L); Inc(P, L); end; P^ := WideCarriageReturn; Inc(P); P^ := WideLineFeed; Inc(P); end; end; function TWideStringList.GetValue(const Name: WideString): WideString; var I: Integer; begin I := IndexOfName(Name); if I >= 0 then Result := Copy(Get(I), Length(Name) + 2, MaxInt) else Result := ''; end; function TWideStringList.GetValueFromIndex(Index: Integer): WideString; var S: WideString; begin Result := ''; if Index >= 0 then begin S := Names[Index]; if S <> '' then Result := Copy(Get(Index), Length(S) + 2, MaxInt); end; end; procedure TWideStringList.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; function TWideStringList.IndexOf(const S: WideString): Integer; begin if not Sorted then begin for Result := 0 to GetCount - 1 do begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin if lstrcmpiW_VST(PWideChar( Get(Result)), PWideChar(S)) = 0 then Exit end else begin if AnsiCompareText(Get(Result), S) = 0 then Exit; end end; Result := -1; end else if not Find(S, Result) then Result := -1; end; function TWideStringList.IndexOfName(const Name: WideString): Integer; var P: Integer; S: WideString; SA, NameA: string; begin for Result := 0 to GetCount - 1 do begin S := Get(Result); P := Pos('=', S); if P > 0 then if Win32Platform = VER_PLATFORM_WIN32_NT then begin if lstrcmpiW_VST(PWideChar(Copy(S, 1, P - 1)), PWideChar(Name)) = 0 then Exit; end else begin SA := S; NameA := Name; if lstrcmpi(PChar(Copy(SA, 1, P - 1)), PChar(NameA)) = 0 then Exit; end end; Result := -1; end; function TWideStringList.IndexOfObject(AObject: TObject): Integer; begin for Result := 0 to GetCount - 1 do if GetObject(Result) = AObject then Exit; Result := -1; end; procedure TWideStringList.Insert(Index: Integer; const S: WideString); begin if Sorted then Error(SSortedListError, 0); if (Index < 0) or (Index > FCount) then Error(SListIndexError, Index); InsertItem(Index, S, nil); end; procedure TWideStringList.InsertItem(Index: Integer; const S: WideString; AObject: TObject); begin Changing; if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TWideStringItem)); with FList^[Index] do begin Pointer(FWideString) := nil; FObject := AObject; FWideString := S; end; Inc(FCount); Changed; end; procedure TWideStringList.LoadFromFile(const FileName: WideString); var Stream: TStream; begin try Stream := TWideFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); try LoadFromStream(Stream); finally Stream.Free; end; except {$IFNDEF COMPILER_6_UP} RaiseLastWin32Error; {$ELSE} RaiseLastOSError; {$ENDIF} end; end; procedure TWideStringList.LoadFromStream(Stream: TStream); var Size, BytesRead: Integer; Order: WideChar; SW: WideString; SA: String; begin Size := Stream.Size - Stream.Position; BytesRead := Stream.Read(Order, 2); if (Order = BOM_LSB_FIRST) or (Order = BOM_MSB_FIRST) then begin SetLength(SW, (Size - 2) div 2); Stream.Read(PWideChar(SW)^, Size - 2); if Order = BOM_MSB_FIRST then StrSwapByteOrder(PWideChar(SW)); SetTextStr(SW); end else begin // without byte order mark it is assumed that we are loading ANSI text Stream.Seek(-BytesRead, soFromCurrent); SetLength(SA, Size); Stream.Read(PChar(SA)^, Size); SetTextStr(SA); end; end; procedure TWideStringList.Put(Index: Integer; const S: WideString); begin if Sorted then Error(SSortedListError, 0); if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; FList^[Index].FWideString := S; Changed; end; procedure TWideStringList.PutObject(Index: Integer; AObject: TObject); begin if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index); Changing; FList^[Index].FObject := AObject; Changed; end; procedure TWideStringList.QuickSort(L, R: Integer; SCompare: TWideStringListSortCompare); var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while SCompare(Self, I, P) < 0 do Inc(I); while SCompare(Self, J, P) > 0 do Dec(J); if I <= J then begin ExchangeItems(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J, SCompare); L := I; until I >= R; end; procedure TWideStringList.SaveToFile(const FileName: WideString); var Stream: TStream; L: TStringList; begin // the strings were saved as Unicode, even on W9x if Win32Platform = VER_PLATFORM_WIN32_NT then begin Stream := TWideFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end else begin L := TStringList.Create; try AssignTo(L); L.SaveToFile(Filename); finally L.free; end; end; end; procedure TWideStringList.SaveToStream(Stream: TStream); //The strings will allways be saved as Unicode. var SW, BOM: WideString; begin SW := GetTextStr; BOM := BOM_LSB_FIRST; Stream.WriteBuffer(PWideChar(BOM)^, 2); Stream.WriteBuffer(PWideChar(SW)^, 2 * Length(SW)); end; procedure TWideStringList.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then Error(SListCapacityError, NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(TWideStringItem)); FCapacity := NewCapacity; end; end; procedure TWideStringList.SetCommaText(const Value: WideString); var P, P1: PWideChar; S: WideString; begin Clear; P := PWideChar(Value); while P^ in [WideChar(#1)..WideSpace] do Inc(P); while P^ <> WideNull do begin if P^ = '"' then S := WideExtractQuotedStr(P, '"') else begin P1 := P; while (P^ > WideSpace) and (P^ <> ',') do Inc(P); SetString(S, P1, P - P1); end; Add(S); while P^ in [WideChar(#1)..WideSpace] do Inc(P); if P^ = ',' then repeat Inc(P); until not (P^ in [WideChar(#1)..WideSpace]); end; end; procedure TWideStringList.SetSorted(Value: Boolean); begin if FSorted <> Value then begin if Value then Sort; FSorted := Value; end; end; procedure TWideStringList.SetTextStr(const Value: WideString); var Head, Tail: PWideChar; S: WideString; begin Clear; Head := PWideChar(Value); while Head^ <> WideNull do begin Tail := Head; while not (Tail^ in [WideNull, WideLineFeed, WideCarriageReturn, WideVerticalTab, WideFormFeed]) and (Tail^ <> WideLineSeparator) and (Tail^ <> WideParagraphSeparator) do Inc(Tail); SetString(S, Head, Tail - Head); Add(S); Head := Tail; if Head^ <> WideNull then begin Inc(Head); if (Tail^ = WideCarriageReturn) and (Head^ = WideLineFeed) then Inc(Head); end; end; end; procedure TWideStringList.SetUpdateState(Updating: Boolean); begin if Updating then Changing else Changed; end; procedure TWideStringList.SetValue(const Name, Value: WideString); var I : Integer; begin I := IndexOfName(Name); if Value <> '' then begin if I < 0 then I := Add(''); Put(I, Name + '=' + Value); end else if I >= 0 then Delete(I); end; procedure TWideStringList.SetValueFromIndex(Index: Integer; const Value: WideString); begin if Value <> '' then begin if Index < 0 then Index := Add(''); Put(Index, Names[Index] + '=' + Value); end else if Index >= 0 then Delete(Index); end; function WideStringListCompare(List: TWideStringList; Index1, Index2: Integer): Integer; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := lstrcmpiW_VST(PWideChar( List.FList^[Index1].FWideString), PWideChar( List.FList^[Index2].FWideString)) else Result := AnsiCompareText(List.FList^[Index1].FWideString, List.FList^[Index2].FWideString); end; procedure TWideStringList.Sort; begin CustomSort(WideStringListCompare); end; { TWideFileStream } constructor TWideFileStream.Create(const FileName: WideString; Mode: Word); var CreateHandle: Integer; begin if Mode = fmCreate then begin CreateHandle := WideFileCreate(FileName); if CreateHandle < 0 then {$IFNDEF COMPILER_5_UP} raise EFCreateError.Create('Can not create file: ' + FileName); {$ELSE} raise EFCreateError.CreateResFmt(PResStringRec(@SFCreateError), [FileName]); {$ENDIF COMPILER_5_UP} end else begin CreateHandle := WideFileOpen(FileName, Mode); if CreateHandle < 0 then {$IFNDEF COMPILER_5_UP} raise EFCreateError.Create('Can not create file: ' + FileName); {$ELSE} raise EFCreateError.CreateResFmt(PResStringRec(@SFCreateError), [FileName]); {$ENDIF COMPILER_5_UP} end; inherited Create(CreateHandle); end; destructor TWideFileStream.Destroy; begin if Handle >= 0 then FileClose(Handle); inherited Destroy; end; function WideFileCreate(const FileName: WideString): Integer; begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := Integer(CreateFileW(PWideChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)) else Result := Integer(CreateFileA(PAnsiChar(AnsiString(PWideChar(FileName))), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); end; function WideFileOpen(const FileName: WideString; Mode: LongWord): Integer; const AccessMode: array[0..2] of LongWord = ( GENERIC_READ, GENERIC_WRITE, GENERIC_READ or GENERIC_WRITE); ShareMode: array[0..4] of LongWord = ( 0, 0, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE); begin if Win32Platform = VER_PLATFORM_WIN32_NT then Result := Integer(CreateFileW(PWideChar(FileName), AccessMode[Mode and 3], ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)) else Result := Integer(CreateFileA(PAnsiChar(AnsiString(FileName)), AccessMode[Mode and 3], ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)); end; procedure LoadWideString(S: TStream; var Str: WideString); var Count: Integer; begin S.Read(Count, SizeOf(Integer)); SetLength(Str, Count); S.Read(PWideChar(Str)^, Count * 2) end; procedure SaveWideString(S: TStream; Str: WideString); var Count: Integer; begin Count := Length(Str); S.Write(Count, SizeOf(Integer)); S.Write(PWideChar(Str)^, Count * 2) end; end.
unit FDescription; (*==================================================================== Edit window for the descriptions ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus, UTypes; type TFormDescription = class(TForm) Panel1: TPanel; ButtonOK: TButton; ButtonCancel: TButton; MemoDesc: TMemo; LabelFile: TLabel; MainMenu1: TMainMenu; MenuEdit: TMenuItem; MenuCut: TMenuItem; MenuFile: TMenuItem; MenuExitAndSave: TMenuItem; MenuExit: TMenuItem; MenuCopy: TMenuItem; MenuPaste: TMenuItem; N1: TMenuItem; MenuSelectAll: TMenuItem; MenuSearch: TMenuItem; MenuFind: TMenuItem; MenuNext: TMenuItem; FindDialog: TFindDialog; ButtonLast: TButton; procedure MenuExitAndSaveClick(Sender: TObject); procedure MenuExitClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure MenuCutClick(Sender: TObject); procedure MenuCopyClick(Sender: TObject); procedure MenuPasteClick(Sender: TObject); procedure MemoDescKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure MenuEditClick(Sender: TObject); procedure MenuSelectAllClick(Sender: TObject); procedure MenuFindClick(Sender: TObject); procedure FindDialogFind(Sender: TObject); procedure MenuNextClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MemoDescChange(Sender: TObject); procedure ButtonLastClick(Sender: TObject); private pLastText: PChar; LastTextSize: integer; public procedure DefaultHandler(var Message); override; procedure SetFormSize; { Public declarations } end; var FormDescription: TFormDescription; implementation uses Clipbrd, IniFiles, ULang, FSettings; {$R *.dfm} //-------------------------------------------------------------------- // Form creation procedure TFormDescription.FormCreate(Sender: TObject); begin LastTextSize := 0; pLastText := nil; end; //-------------------------------------------------------------------- // Actions done before showing the window procedure TFormDescription.FormShow(Sender: TObject); begin ActiveControl := MemoDesc; ButtonLast.Visible := LastTextSize > 0; ButtonLast.Enabled := MemoDesc.GetTextLen = 0; end; //-------------------------------------------------------------------- // Handles the Save and Exit event - saves the text to the pLastText, so that // it can be pasted next time procedure TFormDescription.MenuExitAndSaveClick(Sender: TObject); begin if (LastTextSize > 0) then begin FreeMem(pLastText, LastTextSize); pLastText := nil; LastTextSize := 0; end; with MemoDesc do if (GetTextLen > 0) then begin LastTextSize := GetTextLen + 1; GetMem(pLastText, LastTextSize); GetTextBuf(pLastText, LastTextSize); end; ModalResult := mrOK; end; //-------------------------------------------------------------------- // Handles the Exit event - warns about not saving modified text procedure TFormDescription.MenuExitClick(Sender: TObject); var Query: Integer; begin if MemoDesc.Modified then begin Query := Application.MessageBox(lsDescrTextModified, lsDescription, mb_YesNoCancel); if Query = IDYes then ModalResult := mrOK; if Query = IDNo then ModalResult := mrCancel; end else ModalResult := mrCancel; end; //-------------------------------------------------------------------- procedure TFormDescription.FormDestroy(Sender: TObject); begin if (LastTextSize > 0) then begin FreeMem(pLastText, LastTextSize); pLastText := nil; LastTextSize := 0; end; end; //-------------------------------------------------------------------- // Cuts the text to Clipboard procedure TFormDescription.MenuCutClick(Sender: TObject); begin MemoDesc.CutToClipboard; end; //-------------------------------------------------------------------- // Copies the text to clipboard procedure TFormDescription.MenuCopyClick(Sender: TObject); begin MemoDesc.CopyToClipboard; end; //-------------------------------------------------------------------- // Pastes the text from clipboard procedure TFormDescription.MenuPasteClick(Sender: TObject); begin MemoDesc.PasteFromClipboard; end; //-------------------------------------------------------------------- // Key handler - assures closing the from on Escape or Ctrl-Enter procedure TFormDescription.MemoDescKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Escape then MenuExitClick(Sender); if (Key = VK_RETURN) and (ssCtrl in Shift) then MenuExitAndSaveClick(Sender); end; //-------------------------------------------------------------------- // Enables/disables items in the menu. procedure TFormDescription.MenuEditClick(Sender: TObject); begin MenuCopy.Enabled := MemoDesc.SelLength > 0; MenuCut.Enabled := MemoDesc.SelLength > 0; MenuPaste.Enabled := Clipboard.HasFormat(CF_TEXT); end; //-------------------------------------------------------------------- // Selects all text procedure TFormDescription.MenuSelectAllClick(Sender: TObject); begin MemoDesc.SelectAll; end; //-------------------------------------------------------------------- // Displays the find dialog procedure TFormDescription.MenuFindClick(Sender: TObject); begin if FindDialog.Execute then begin end; end; //-------------------------------------------------------------------- // Handles the find action from the find dialog box procedure TFormDescription.FindDialogFind(Sender: TObject); var Buffer : PChar; Size : longint; Start : longint; FoundCh, StartCh : PChar; StringToFind: array[0..256] of char; begin ActiveControl := MemoDesc; with MemoDesc do begin Size := GetTextLen; Inc(Size); GetMem(Buffer, Size); GetTextBuf(Buffer, Size); Start := SelStart + SelLength; StartCh := @Buffer[Start]; StrPCopy(StringToFind, FindDialog.FindText); if not (frMatchCase in FindDialog.Options) then begin AnsiUpperCase(StringToFind); AnsiUpperCase(StartCh); end; FoundCh := StrPos(StartCh, StringToFind); if FoundCh <> nil then begin ///Start := Start + FoundCh - StartCh; SelStart := Start; SelLength := length(FindDialog.FindText); end; FreeMem(Buffer, Size); end; end; //-------------------------------------------------------------------- // Repeats the find action procedure TFormDescription.MenuNextClick(Sender: TObject); begin FindDialogFind(Sender); end; //-------------------------------------------------------------------- // Called on change in the text procedure TFormDescription.MemoDescChange(Sender: TObject); begin ButtonLast.Enabled := MemoDesc.GetTextLen = 0; end; //-------------------------------------------------------------------- // Pastes the text from previous description to the text procedure TFormDescription.ButtonLastClick(Sender: TObject); begin MemoDesc.SetTextBuf(pLastText); ActiveControl := MemoDesc; end; //----------------------------------------------------------------------------- // Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay // to the top window, so we must have this handler in all forms. procedure TFormDescription.DefaultHandler(var Message); begin with TMessage(Message) do if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and g_CommonOptions.bDisableCdAutorun then Result := 1 else inherited DefaultHandler(Message) end; //----------------------------------------------------------------------------- procedure TFormDescription.SetFormSize; var IniFile: TIniFile; SLeft, STop, SWidth, SHeight: integer; begin IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); SLeft := IniFile.ReadInteger ('DescriptionWindow', 'Left', (Screen.Width - Width) div 2); STop := IniFile.ReadInteger ('DescriptionWindow', 'Top', (Screen.Height - Height) div 2); SWidth := IniFile.ReadInteger ('DescriptionWindow', 'Width', Width); SHeight := IniFile.ReadInteger ('DescriptionWindow', 'Height', Height); IniFile.Free; SetBounds(SLeft, STop, SWidth, SHeight); end; //-------------------------------------------------------------------- end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.StdCtrls, FMX.Dialogs, FMX.Controls.Presentation; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses NtResource; procedure TForm1.FormCreate(Sender: TObject); const NAME_C = 'Bill'; PLACE_C = 'Helsinki'; begin Label1.Text := _T('Hello World'); //loc This is a comment Label2.Text := _T('Characters'); //loc MaxChars=20 This is characters comment Label3.Text := _T('Pixels'); //loc MaxPixels=100 This is pixels comment // Same pattern string three times. // First without a comment, then with comment but without placeholder description. // Finally with proper descriptions. Label4.Text := Format(_T('Hello %s, welcome to %s'), [NAME_C, PLACE_C]); Label5.Text := Format(_T('Hello %s, welcome to %s'), [NAME_C, PLACE_C]); //loc This is comment but no placeholder descriptions Label6.Text := Format(_T('Hello %s, welcome to %s'), [NAME_C, PLACE_C]); //loc 0: Name of the person, 1: Name of the place end; end.
program leskovar_projekt_final; // Program pouziva hashovaci tabulku, kolize resi spojovym seznamem // Deklarace spojoveho seznamu type PNode = ^TNode; TNode = record Value: ShortString; Next: PNode; end; var MainArray: array[0..99] of PNode; Node1, Node2: PNode; Load: ShortString; i, n, index: byte; sum: integer; token, avail, fail: boolean; TextFile: text; function Hash(Word: string): byte; begin // Hashovani -> soucet ascii kodu vsech znaku stringu mod velikost pole sum:= 0; for i:= 1 to length(Word) do begin if ord(Word[i]) = 0 then break; sum:= sum + ord(Word[i]); end; Hash:= sum mod 100; end; procedure InsertIntoTable(Word: string; Position: byte); begin // Hashovaci tabulka je pole s nody -> postup jako u spojovych seznamu new(Node1); // Pokud je seznam prazdny, spojime pointer z pole s novym nodem if MainArray[Position] = nil then begin MainArray[Position] := Node1; Node1^.Value:= Word; Node1^.Next:= nil; end else // Pokud uz seznam existuje, dojdeme nakonec a spojime ho s novym nodem begin Node2:= MainArray[Position]; while Node2^.Next <> nil do Node2:= Node2^.Next; Node2^.Next:= Node1; Node1^.Value:= Word; Node1^.Next:= nil; end; end; procedure WriteList; // Pro testovani begin writeln('Vypis seznamu'); for i:=0 to 99 do begin Node1:= MainArray[i]; while Node1 <> nil do begin writeln('Index ', i, ' ',Node1^.Value); Node1:= Node1^.Next; end; end; end; begin writeln('Press "1" to use the Console.'); writeln('Press "2" to link a Text File.'); writeln; write('Choose the input method: '); readln(Load); // Telo cyklu zajistujiciho navrat while true do begin writeln; // Vetev pro textovy vstup if Load = '2' then begin writeln('Please, ensure that the Text File is in the same folder as the executable of this program.'); writeln; writeln('In this case, each line is considered a word. Please, make sure that the file is formatted accordingly.'); writeln; write('File name (excluding the ".txt" extension): '); readln(Load); Load:= concat(Load,'.txt'); // Inicializace textoveho souboru assignfile(TextFile, Load); try Reset(TextFile); while not eof(TextFile) do begin readln(TextFile, Load); // Hashovani index:= Hash(Load); // Vlozeni slova do node InsertIntoTable(Load, index); end; close(TextFile); except writeln; writeln('File Error! File not found. The program will now terminate.'); readln; exit; end; end // Konec vetve pro textovy vstup // Vetev pro konzolovy vstup else if Load = '1' then begin // Zacatek vytvareni slovniku writeln('Please type the Dictionary entries one on each line, separate using "Enter".'); writeln; writeln('Once you are complete with the Dictionary, type "-1" as a separate entry to exit.'); writeln; while true do begin readln(Load); if Load = '-1' then break; // Hashovani index:= Hash(Load); // Vlozeni slova do node InsertIntoTable(Load, index); end; end // Konec vetve pro textovy vstup // Vetev pro nespravy vyber else begin writeln('Wrong Key! The program will now terminate.'); readln; exit; end; // Konec vetve pro nespravny vyber // Konec vytvareni slovniku // Zde je dobre misto pro WriteList; // Zadani hledaneho slova while true do begin writeln; write('Riddle me this: '); readln(Load); // Hashovani index:= Hash(Load); Node1:= MainArray[index]; writeln; writeln('Results:'); fail:= true; while Node1 <> nil do begin // Srovnavaci algoritmus if length(Load) = length(Node1^.Value) then begin // avail := flag pro cele slovo - pokud nekdy chybi token -> konec avail:= false; for i:=1 to length(Load) do begin // token := flag pro pismeno - pokud nektere chybi -> konec token:= false; for n:=1 to length(Node1^.Value) do if Load[i] = Node1^.Value[n] then token:= true; if token = true then avail:= true else avail:= false; end; end; if avail = true then begin writeln(Node1^.Value); fail:= false; end; Node1:= Node1^.Next; end; // fail := flag pro uspesnost hledani if fail = true then writeln('No Words Found.'); // Telo cyklu pro volbu uzivatele while true do begin writeln; writeln('What now?'); writeln('Press "1" to add more words to the dictionary.'); writeln('Press "2" to search for another word.'); writeln('Press "0" to exit.'); write('Choose your next action: '); readln(Load); if (Load <> '1') and (Load <> '2') and (Load <> '0') then begin writeln; writeln('Wrong Key! Try again.') end else break; end; if Load = '0' then exit; if Load <> '2' then break; end; // Pokud jsme tady, jdeme zpatky na zacatek end; end.
unit MensagensFactory.View; interface uses MensagensFactory.View.Interf, Base.View.Interf, Tipos.Controller.Interf; type TMensagemFactoryView = class(TInterfacedObject, IMensagemFactoryView) private public constructor Create; destructor Destroy; override; class function New: IMensagemFactoryView; function exibirMensagem(AValue: TTIpoMensagem): IBaseMensagemView; end; implementation { TMensagemFactoryView } uses M0001ALE.View, M0001CON.View, M0001ERR.View, M0001INF.View; constructor TMensagemFactoryView.Create; begin end; destructor TMensagemFactoryView.Destroy; begin inherited; end; function TMensagemFactoryView.exibirMensagem(AValue: TTIpoMensagem) : IBaseMensagemView; begin case AValue of tmInformacao: Result := TFM0001INFView.New; tmAlerta: Result := TFM0001ALEView.New; tmErro: Result := TFM0001ERRView.New; tmConfirmacao: Result := TFM0001CONView.New; end; end; class function TMensagemFactoryView.New: IMensagemFactoryView; begin Result := Self.Create; end; end.
unit Dbackdim; {-------------------------------------------------------------------} { Unit: Dbackdim.pas } { Project: EPA SWMM } { Version: 5.0 } { Date: 3/29/05 (5.0.005) } { Author: L. Rossman } { } { Dialog form unit that allows the user to set the dimensions of } { the backdrop picture for the study area map. } {-------------------------------------------------------------------} interface uses Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, NumEdit, Uproject, Uglobals, Uutils; type TBackdropDimensionsForm = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; LLYEdit: TNumEdit; LLXEdit: TNumEdit; Label3: TLabel; Label4: TLabel; MapLLX: TPanel; MapLLY: TPanel; GroupBox2: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; URYEdit: TNumEdit; URXEdit: TNumEdit; MapURX: TPanel; MapURY: TPanel; OKBtn: TButton; CancelBtn: TButton; HelpBtn: TButton; ScaleBackdropBtn: TRadioButton; ScaleMapBtn: TRadioButton; ResizeOnlyBtn: TRadioButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OKBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure ResizeOnlyBtnClick(Sender: TObject); procedure ScaleBackdropBtnClick(Sender: TObject); procedure ScaleMapBtnClick(Sender: TObject); procedure LLXEditChange(Sender: TObject); procedure HelpBtnClick(Sender: TObject); private { Private declarations } BackLL: TExtendedPoint; BackUR: TExtendedPoint; MapLL : TExtendedPoint; MapUR : TExtendedPoint; procedure EnableEditFields(Enable: Boolean); procedure ScaleMapToBackdrop; procedure DisplayBackdropDimensions(LL, UR: TExtendedPoint; D: Integer); procedure DisplayMapDimensions(LL, UR: TExtendedPoint; D: Integer); public { Public declarations } procedure SetData; end; var BackdropDimensionsForm: TBackdropDimensionsForm; implementation {$R *.dfm} uses Fmap, Fovmap, Ucoords; const MSG_BLANK_FIELD = 'Blank data field not allowed.'; MSG_ILLEGAL_DIMENSIONS = 'Illegal dimensions.'; procedure TBackdropDimensionsForm.FormCreate(Sender: TObject); //----------------------------------------------------------------------------- // Form's OnCreate handler. //----------------------------------------------------------------------------- begin Uglobals.SetFont(self); end; procedure TBackdropDimensionsForm.FormShow(Sender: TObject); //----------------------------------------------------------------------------- // Form's OnShow handler. //----------------------------------------------------------------------------- begin SetData; end; procedure TBackdropDimensionsForm.OKBtnClick(Sender: TObject); //----------------------------------------------------------------------------- // OnClick handler for the OKBtn. //----------------------------------------------------------------------------- var x1,x2,y1,y2: Extended; BadNumEdit: TNumEdit; begin // Find which NumEdit control has an invalid numerical entry. BadNumEdit := nil; if not Uutils.GetExtended(LLXEdit.Text, x1) then BadNumEdit := LLXEdit; if not Uutils.GetExtended(LLYEdit.Text, y1) then BadNumEdit := LLYEdit; if not Uutils.GetExtended(URXEdit.Text, x2) then BadNumEdit := URXEdit; if not Uutils.GetExtended(URYEdit.Text, y2) then BadNumEdit := URYEdit; // Display an error message for the control and reset the focus to it. if BadNumEdit <> nil then begin MessageDlg(MSG_BLANK_FIELD, mtError, [mbOK], 0); BadNumEdit.SetFocus; Exit; end; // Check that the X and Y ranges are not 0. if (x1 = x2) or (y1 = y2) then begin MessageDlg(MSG_ILLEGAL_DIMENSIONS, mtError, [mbOK], 0); LLXEdit.SetFocus; Exit; end; // Set the dimensions of the Map's Backdrop image with MapForm.Map.Backdrop do begin LowerLeft.X := x1; LowerLeft.Y := y1; UpperRight.X := x2; UpperRight.Y := y2; OVmapForm.OVmap.Backdrop.LowerLeft := LowerLeft; OVmapForm.OVmap.Backdrop.UpperRight := UpperRight; end; // Scale the Map to the Backdrop if called for if ScaleMapBtn.Checked then ScaleMapToBackdrop; // Redraw the Map on the MapForm at full extent Hide; MapForm.DrawFullExtent; Uglobals.HasChanged := True; Close; end; procedure TBackdropDimensionsForm.CancelBtnClick(Sender: TObject); //----------------------------------------------------------------------------- // OnClick handler for the CancelBtn. //----------------------------------------------------------------------------- begin Close; end; procedure TBackdropDimensionsForm.ResizeOnlyBtnClick(Sender: TObject); //----------------------------------------------------------------------------- // OnClick handler for the Resize Backdrop Only radio button. Displays // the map's dimensions in both the Map panels and the Backdrop edit // boxes. Allows the user to edit dimensions for the Backdrop. //----------------------------------------------------------------------------- var D: Integer; begin D := MapForm.Map.Dimensions.Digits; DisplayMapDimensions(MapLL, MapUR, D); DisplayBackdropDimensions(MapLL, MapUR, D); EnableEditFields(True); end; procedure TBackdropDimensionsForm.ScaleBackdropBtnClick(Sender: TObject); //----------------------------------------------------------------------------- // OnClick handler for the Scale Backdrop to Map radio button. Displays // the map's dimensions in both the Map panels and the Backdrop edit // boxes. Does not allow the user to edit the Backdrop's dimensions. //----------------------------------------------------------------------------- var D: Integer; begin D := MapForm.Map.Dimensions.Digits; DisplayMapDimensions(MapLL, MapUR, D); DisplayBackdropDimensions(MapLL, MapUR, D); EnableEditFields(False); end; procedure TBackdropDimensionsForm.ScaleMapBtnClick(Sender: TObject); //----------------------------------------------------------------------------- // OnClick handler for the Scale Map to Backdrop radio button. Displays // the Backdrop's dimensions in the Map panels. Allows the user to edit // the Backdrop's dimensions. //----------------------------------------------------------------------------- begin MapLLX.Caption := LLXEdit.Text; MapLLY.Caption := LLYEdit.Text; MapURX.Caption := URXEdit.Text; MapURY.Caption := URYEdit.Text; EnableEditFields(True); end; procedure TBackdropDimensionsForm.LLXEditChange(Sender: TObject); //----------------------------------------------------------------------------- // OnChange handler for all of the Backdrop edit boxes. Sets the map // dimension displayed in the Map panel to that shown in the Backdrop // edit box when the Scale Map to Backdrop button is selected. //----------------------------------------------------------------------------- begin if ScaleMapBtn.Checked then begin if Sender = LLXEdit then MapLLX.Caption := LLXEdit.Text else if Sender = LLYEdit then MapLLY.Caption := LLYEdit.Text else if Sender = URXEdit then MapURX.Caption := URXEdit.Text else if Sender = URYEdit then MapURY.Caption := URYEdit.Text; end; end; procedure TBackdropDimensionsForm.EnableEditFields(Enable: Boolean); //----------------------------------------------------------------------------- // Enables/disables the Backdrop dimension edit boxes. //----------------------------------------------------------------------------- begin LLXEdit.Enabled := Enable; LLYEdit.Enabled := Enable; URXEdit.Enabled := Enable; URYEdit.Enabled := Enable; end; procedure TBackdropDimensionsForm.SetData; //----------------------------------------------------------------------------- // Saves original Map and Backdrop dimensions and displays them on the form. //----------------------------------------------------------------------------- var D: Integer; begin // Save original map & backdrop dimensions with MapForm.Map.Dimensions do begin MapLL := LowerLeft; MapUR := UpperRight; end; with MapForm.Map.Backdrop do begin BackLL := LowerLeft; BackUR := UpperRight; end; // Display original map dimensions D := MapForm.Map.Dimensions.Digits; DisplayMapDimensions(MapLL, MapUR, D); DisplayBackdropDimensions(BackLL, BackUR, D); end; procedure TBackdropDimensionsForm.DisplayMapDimensions( LL, UR: TExtendedPoint; D: Integer); //----------------------------------------------------------------------------- // Displays Map dimensions on the form's Map dimension panels. //----------------------------------------------------------------------------- begin MapLLX.Caption := FloatToStrF(LL.X, ffFixed, 18, D); MapLLY.Caption := FloatToStrF(LL.Y, ffFixed, 18, D); MapURX.Caption := FloatToStrF(UR.X, ffFixed, 18, D); MapURY.Caption := FloatToStrF(UR.Y, ffFixed, 18, D); end; procedure TBackdropDimensionsForm.DisplayBackdropDimensions( LL, UR: TExtendedPoint; D: Integer); //----------------------------------------------------------------------------- // Displays dimensions in the form's Backdrop dimensions edit boxes. //----------------------------------------------------------------------------- begin LLXEdit.Text := FloatToStrF(LL.X, ffFixed, 18, D); LLYEdit.Text := FloatToStrF(LL.Y, ffFixed, 18, D); URXEdit.Text := FloatToStrF(UR.X, ffFixed, 18, D); URYEdit.Text := FloatToStrF(UR.Y, ffFixed, 18, D); end; procedure TBackdropDimensionsForm.ScaleMapToBackdrop; //----------------------------------------------------------------------------- // Transforms the coordinates of all map objects so that they scale // proportionately to the dimensions of the Backdrop image. //----------------------------------------------------------------------------- begin with MapForm.Map do begin Ucoords.TransformCoords(Dimensions.LowerLeft, Dimensions.UpperRight, Backdrop.LowerLeft, Backdrop.UpperRight); Dimensions.LowerLeft := Backdrop.LowerLeft; Dimensions.UpperRight := Backdrop.UpperRight; end; end; procedure TBackdropDimensionsForm.HelpBtnClick(Sender: TObject); begin Application.HelpCommand(HELP_CONTEXT, 212960); end; procedure TBackdropDimensionsForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F1 then HelpBtnClick(Sender); end; end.
{ Rotary Encoder Tester 1.0 - 2019.04.27 - Nicola Perotto <nicola@nicolaperotto.it> } {$I+,R+,Q+} {$MODE DELPHI} Program RotaryTest; Uses CThreads, CMem, Classes, SysUtils, Rotary, InputUtils, Crt; Var MyRotaryName : string; MyRotary : TRotary; bStopNow : Boolean; cc : char; begin writeln('Rotary Encoder Test'); MyRotaryName := EventFileSearch('rotary'); //or rotary@11 (11 = pin for A input in hex -> BCM 17) if (MyRotaryName = '') then begin writeln('not found.'); Halt(1); end; MyRotary := TRotary.Create(True, MyRotaryName); writeln('Press ESC to terminate'); writeln('Press "a" to change step size'); MyRotary.Position := 0; MyRotary.Min := -1000; MyRotary.Max := 1000; MyRotary.Step := 1; MyRotary.Circular := False; MyRotary.Start; bStopNow := False; while (not bStopNow) do begin if MyRotary.Changed then begin writeln(Format('%6d (%3d)', [MyRotary.Position, MyRotary.Step])); MyRotary.Changed := False; end; if KeyPressed then begin cc := ReadKey; if cc = #27 then bStopNow := True; //to terminate the test if cc = 'a' then begin if MyRotary.Step = 1 then MyRotary.Step := 10 else MyRotary.Step := 1; end; end; if bStopNow then Break; //from Signal Handler or keypress Sleep(5); end; //while MyRotary.Terminate; MyRotary.WaitFor; FreeAndNil(MyRotary); end.
unit LayoutTest; interface uses Types, Graphics, Layout, Render3, Nodes; function BuildNodeList: TNodeList; function BuildBoxList(inCanvas: TCanvas; inNodes: TNodeList): TBoxList; procedure RenderBoxList(inBoxes: TBoxList; inCanvas: TCanvas; inRect: TRect); procedure TestLayoutRenderer(inCanvas: TCanvas; inRect: TRect); implementation function BuildNodeList: TNodeList; var node, nd: TNode; begin Result := TNodeList.Create; // node := TDivNode.Create; node.Text := 'Hello Top Div! Hello Top Div! Hello Top Div! Hello Top Div!'; node.Style.BackgroundColor := clYellow; node.Style.Width := 300; Result.Add(node); // node.Nodes := TNodeList.Create; with node.Nodes do begin nd := TInlineNode.Create; nd.Text := 'Inline 1'; nd.Style.BackgroundColor := clLime; Add(nd); // nd := TInlineNode.Create; nd.Text := 'Inline 2'; nd.Style.BackgroundColor := clAqua; Add(nd); // nd := TInlineNode.Create; nd.Text := 'Inline 3'; nd.Style.BackgroundColor := clAqua; Add(nd); end; // node := TDivNode.Create; node.Text := 'Hello world. '; node.Style.BackgroundColor := clFuchsia; node.Style.Width := 100; node.Style.Height := 100; Result.Add(node); end; function BuildBoxList(inCanvas: TCanvas; inNodes: TNodeList): TBoxList; begin with TLayout.Create(inCanvas) do try Result := BuildBoxes(inNodes); finally Free; end; end; procedure RenderBoxList(inBoxes: TBoxList; inCanvas: TCanvas; inRect: TRect); begin with TRenderer.Create do try Render(inBoxes, inCanvas, inRect); finally Free; end; end; procedure TestLayoutRenderer(inCanvas: TCanvas; inRect: TRect); var n: TNodeList; b: TBoxList; begin n := BuildNodeList; b := BuildBoxList(inCanvas, n); RenderBoxList(b, inCanvas, inRect); b.Free; n.Free; end; end.
unit BookmarksView; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, AmlView, ComCtrls; type TBookmarksViewer = class(TForm) BookmarksTree: TTreeView; procedure BookmarksTreeDblClick(Sender: TObject); procedure BookmarksTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected FBookmarks : TBookmarks; FAddrMgr : IAddressManager; FStatus : IStatusDisplay; FOwnTheData : Boolean; procedure SetBookmarks(const ABookmarks : TBookmarks); virtual; public destructor Destroy; override; procedure UpdateContents; virtual; property AddressMgr : IAddressManager read FAddrMgr write FAddrMgr; property Bookmarks : TBookmarks read FBookmarks write SetBookmarks; property OwnTheData : Boolean read FOwnTheData write FOwnTheData; property Status : IStatusDisplay read FStatus write FStatus; end; implementation uses Main; {$R *.DFM} destructor TBookmarksViewer.Destroy; begin if FOwnTheData and (FBookmarks <> Nil) then FBookmarks.Free; inherited Destroy; end; procedure TBookmarksViewer.SetBookmarks(const ABookmarks : TBookmarks); begin FBookmarks := ABookmarks; UpdateContents; end; procedure TBookmarksViewer.UpdateContents; procedure AddNodes(const AParent : TTreeNode; const ANodes : TBookmarks); forward; procedure AddNode(const AParent : TTreeNode; const ANode : TBookmarkNode); var NewNode : TTreeNode; begin Assert(ANode <> Nil); NewNode := BookmarksTree.Items.AddChild(AParent, ANode.Caption); NewNode.Data := ANode; if ANode.SmallIcon <> Nil then NewNode.ImageIndex := MainForm.ImagesSmall.AddMasked(ANode.SmallIcon, clWhite) else if ANode.SmallIconIdx >= 0 then NewNode.ImageIndex := ANode.SmallIconIdx else begin if ANode.Children.Count > 0 then NewNode.ImageIndex := DefaultBmkCatgIdxSmall else NewNode.ImageIndex := DefaultBmkItemIdxSmall; end; NewNode.SelectedIndex := NewNode.ImageIndex; AddNodes(NewNode, ANode.Children); end; procedure AddNodes(const AParent : TTreeNode; const ANodes : TBookmarks); var C, I : Cardinal; begin C := ANodes.Count; if C > 0 then begin Dec(C); for I := 0 to C do AddNode(AParent, ANodes.Bookmarks[I]); end; end; begin BookmarksTree.Items.BeginUpdate; BookmarksTree.Items.Clear; if FBookmarks <> Nil then AddNodes(Nil, FBookmarks); BookmarksTree.Items.EndUpdate; end; procedure TBookmarksViewer.BookmarksTreeDblClick(Sender: TObject); var Node : TBookmarkNode; begin if BookmarksTree.Selected <> Nil then begin Node := TBookmarkNode(BookmarksTree.Selected.Data); if (Node <> Nil) and (Node.Address <> '') then FAddrMgr.SetAddress(Node.Address); end; end; procedure TBookmarksViewer.BookmarksTreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) and (BookmarksTree.Selected <> Nil) then begin if BookmarksTree.Selected.Count > 0 then BookmarksTree.Selected.Expanded := not BookmarksTree.Selected.Expanded else BookmarksTreeDblClick(Sender); end; end; end.
unit CmpUnit; interface uses uDBBaseTypes, SysUtils, Classes, uMemory; procedure SpilitWords(S: string; var Words: TStrings); procedure AddWords(var S, D: Tstrings); procedure DeleteWords(S: TStrings; var D: TStrings); overload; function AddWordsA(S: string; var D: string): Boolean; procedure DelSpaces(S: TStrings); procedure DelSpacesA(var S: string); procedure DelSpacesW(var S: string); function WordExists(Words: TStrings; S: string): Boolean; procedure GetCommonWords(A, B: Tstrings; var D: TStrings); function WordsToString(Words: TStrings): string; function GetCommonWordsA(Words: TStringList): string; procedure DeleteWords(var Words: string; WordsToDelete: string); overload; procedure ReplaceWords(A, B: string; var D: string); function VariousKeyWords(S1, S2: string): Boolean; function MaxStatBool(Bools: TArBoolean): Boolean; function MaxStatDate(Dates: TArDateTime): TDateTime; function MaxStatTime(Times: TArTime): TDateTime; implementation function WordExists(Words: TStrings; S: string): Boolean; var I: Integer; begin Result := False; for I := 0 to Words.Count - 1 do if Words[I] = S then begin Result := True; Break; end; end; function ValidChar(const C: Char): Boolean; begin Result := (C <> ' ') and (C <> ',') and (C <> '.'); end; procedure SpilitWords(S: string; var Words: TStrings); var I, J: Integer; Pi_: PInteger; begin if Words = nil then Words := TStringList.Create; Words.Clear; S := ' ' + S + ' '; Pi_ := @I; for I := 1 to Length(S) - 1 do begin if I + 1 > Length(S) - 1 then Break; if (not ValidChar(S[I])) and ValidChar(S[I + 1]) then for J := I + 1 to Length(S) do if not ValidChar(S[J]) or (J = Length(S)) then begin Words.Add(Copy(S, I + 1, J - I - 1)); Pi_^ := J - 1; Break; end; end; DelSpaces(Words); end; procedure AddWords(var S, D: TStrings); var I: Integer; begin for I := 0 to S.Count - 1 do if not WordExists(D, S[I]) then D.Text := D.Text + ' ' + S[I]; end; procedure DeleteWords(S: TStrings; var D: TStrings); var I: Integer; Temp: TStrings; begin Temp := TStringList.Create; try for I := 0 to D.Count - 1 do if not WordExists(S, D[I]) then Temp.Add(D[I]); D.Assign(Temp); finally F(Temp); end; end; procedure DelSpaces(S: TStrings); var I: Integer; St: string; begin for I := 0 to S.Count - 1 do begin St := S[I]; DelSpacesA(St); S[I] := St; end; end; procedure DelSpacesA(var S: string); var I: Integer; begin for I := Length(S) downto 1 do if S[I] = ' ' then Delete(S, I, 1); end; procedure DelSpacesW(var S: string); var I: Integer; begin for I := Length(S) downto 2 do if (S[I] = ' ') and (S[I - 1] = ' ') then Delete(S, I, 1); end; function AddWordsA(S: string; var D: string): Boolean; var I: Integer; S_, D_: Tstrings; begin Result := False; S_ := TStringList.Create; D_ := TStringList.Create; try SpilitWords(S, S_); SpilitWords(D, D_); if Length(D) > 1 then if D[Length(D)] = ' ' then Delete(D, Length(D), 1); for I := 0 to S_.Count - 1 do if not WordExists(D_, S_[I]) then begin Result := True; D := D + ' ' + S_[I]; end; finally F(S_); F(D_); end; end; procedure ReplaceWords(A, B: string; var D: string); var A_, B_, D_: TStrings; begin A_ := TStringList.Create; B_ := TStringList.Create; D_ := TStringList.Create; try SpilitWords(A, A_); SpilitWords(B, B_); SpilitWords(D, D_); DeleteWords(A_, D_); AddWords(B_, D_); D := WordsToString(D_); finally F(A_); F(B_); F(D_); end; end; procedure GetCommonWords(A, B: TStrings; var D: TStrings); var I: Integer; begin if D = nil then D := TStringList.Create; D.Clear; for I := 0 to A.Count - 1 do if WordExists(B, A[I]) then D.Add(A[I]) end; function WordsToString(Words: TStrings): string; var I: Integer; begin Result := ''; for I := 0 to Words.Count - 1 do if Result = '' then Result := Words[0] else Result := Result + ' ' + Words[I]; DelSpacesW(Result); end; function GetCommonWordsA(Words: TStringList): string; var Common, Temp, Str: TStrings; I: Integer; begin if Words.Count = 0 then Exit; Common := TStringList.Create; Temp := TStringList.Create; Str := TStringList.Create; try SpilitWords(Words[0], Common); for I := 1 to Words.Count - 1 do begin SpilitWords(Words[I], Temp); GetCommonWords(Common, Temp, Str); Common.Assign(Str); if Common.Count = 0 then Break; end; Result := WordsToString(Common); finally F(Common); F(Temp); F(Str); end; end; function VariousKeyWords(S1, S2: string): Boolean; var I: Integer; A1, A2: TStrings; begin Result := False; A1 := Tstringlist.Create; A2 := Tstringlist.Create; try SpilitWords(S1, A1); SpilitWords(S2, A2); for I := 1 to A1.Count do if not WordExists(A2, A1[I - 1]) then begin Result := True; Exit; end; for I := 1 to A2.Count do if not WordExists(A1, A2[I - 1]) then begin Result := True; Exit; end; finally F(A1); F(A2); end; end; function MaxStatDate(Dates: TArDateTime): TDateTime; type TDateStat = record Date: TDateTime; Count: Integer; end; TArDateStat = array of TDateStat; var I: Integer; Stat: TArDateStat; MaxC, MaxN: Integer; procedure AddStat(var DatesStat: TArDateStat; Date: TDateTime); var J: Integer; begin for J := 0 to Length(DatesStat) - 1 do if DatesStat[J].Date = Date then begin DatesStat[J].Count := DatesStat[J].Count + 1; Exit; end; SetLength(DatesStat, Length(DatesStat) + 1); DatesStat[Length(DatesStat) - 1].Date := Date; DatesStat[Length(DatesStat) - 1].Count := 0; end; begin Result := 0; if Length(Dates) = 0 then Exit; SetLength(Stat, 0); for I := 0 to Length(Dates) - 1 do AddStat(Stat, Dates[I]); MaxC := Stat[0].Count; MaxN := 0; for I := 0 to Length(Stat) - 1 do if MaxC < Stat[I].Count then begin MaxC := Stat[I].Count; MaxN := I; end; Result := Stat[MaxN].Date; end; function MaxStatTime(Times: TArTime): TDateTime; type TDateStat = record Time: TDateTime; Count: Integer; end; TArDateStat = array of TDateStat; var I: Integer; Stat: TArDateStat; MaxC, MaxN: Integer; procedure AddStat(var DatesStat: TArDateStat; Time: TDateTime); var J: Integer; begin for J := 0 to Length(DatesStat) - 1 do if DatesStat[J].Time = Time then begin DatesStat[J].Count := DatesStat[J].Count + 1; Exit; end; SetLength(DatesStat, Length(DatesStat) + 1); DatesStat[Length(DatesStat) - 1].Time := Time; DatesStat[Length(DatesStat) - 1].Count := 0; end; begin Result := 0; if Length(Times) = 0 then Exit; SetLength(Stat, 0); for I := 0 to Length(Times) - 1 do AddStat(Stat, Times[I]); MaxC := Stat[0].Count; MaxN := 0; for I := 0 to Length(Stat) - 1 do if MaxC < Stat[I].Count then begin MaxC := Stat[I].Count; MaxN := I; end; Result := Stat[MaxN].Time; end; function MaxStatBool(Bools: TArBoolean): Boolean; type TBoolStat = record Bool: Boolean; Count: Integer; end; TArBoolStat = array of TBoolStat; var I: Integer; Stat: TArBoolStat; MaxC, MaxN: Integer; procedure AddStat(var BoolStat: TArBoolStat; Bool: Boolean); var J: Integer; begin for J := 0 to Length(BoolStat) - 1 do if BoolStat[J].Bool = Bool then begin BoolStat[J].Count := BoolStat[J].Count + 1; Exit; end; SetLength(Boolstat, Length(BoolStat) + 1); BoolStat[Length(BoolStat) - 1].Bool := Bool; BoolStat[Length(BoolStat) - 1].Count := 0; end; begin Result := False; if Length(Bools) = 0 then Exit; SetLength(Stat, 0); for I := 0 to Length(Bools) - 1 do AddStat(Stat, Bools[I]); MaxC := Stat[0].Count; MaxN := 0; for I := 0 to Length(Stat) - 1 do if MaxC < Stat[I].Count then begin MaxC := Stat[I].Count; MaxN := I; end; Result := Stat[MaxN].Bool; end; procedure DeleteWords(var Words: string; WordsToDelete: string); var S, D: TStrings; begin S := TStringList.Create; D := TStringList.Create; try SpilitWords(Words, D); SpilitWords(WordsToDelete, S); DeleteWords(S, D); Words := WordsToString(D); finally F(S); F(D); end; end; end.
unit Compress; { $Log: D:\Util\GP-Version\Archives\VCLZip Zip Utility\UNZIP\Compress.UFV { { Rev 1.2 Sun 10 May 1998 16:54:57 Supervisor Version: 2.12 { Version 2.12 } { { Rev 1.1 Tue 24 Mar 1998 19:03:56 Supervisor { Modifications to allow storing filenames and paths in DOS { 8.3 format } interface uses {$IFDEF WIN32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Dialogs, FileCtrl, Spin; type TCompressDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; ZipFileGroup: TGroupBox; ZipFilename: TEdit; ZipFileBtn: TBitBtn; GroupBox1: TGroupBox; SelectFilesBtn: TBitBtn; SelectedFiles: TComboBox; GroupBox2: TGroupBox; RootDirBtn: TBitBtn; RootDir: TEdit; RecurseChk: TCheckBox; Label6: TLabel; Password: TEdit; Label1: TLabel; ZipAction: TComboBox; Label2: TLabel; SaveDirInfoChk: TCheckBox; ClearBtn: TBitBtn; DeleteBtn: TBitBtn; GetZipFileDlg: TSaveDialog; Wildcards: TEdit; AddWildCardBtn: TBitBtn; SpinButton1: TSpinButton; CompLevel: TLabel; DisposeChk: TCheckBox; MultiMode: TComboBox; MultiModeLabel: TLabel; SaveVolumesChk: TCheckBox; FirstBlockSize: TEdit; BlockSize: TEdit; WriteDiskLabelsChk: TCheckBox; FirstDiskLabel: TLabel; Label4: TLabel; RelativeDir: TCheckBox; FileSelectDlg: TOpenDialog; Store83Format: TCheckBox; Label5: TLabel; SaveZipInfoChk: TCheckBox; procedure ZipFileBtnClick(Sender: TObject); procedure SelectFilesBtnClick(Sender: TObject); procedure RootDirBtnClick(Sender: TObject); procedure ClearBtnClick(Sender: TObject); procedure AddWildCardBtnClick(Sender: TObject); procedure WildcardsChange(Sender: TObject); procedure SpinButton1DownClick(Sender: TObject); procedure SpinButton1UpClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DeleteBtnClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure SaveDirInfoChkClick(Sender: TObject); procedure MultiModeChange(Sender: TObject); procedure RootDirChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var CompressDlg: TCompressDlg; saveFirstBlockSize: String; implementation {$R *.DFM} procedure TCompressDlg.ZipFileBtnClick(Sender: TObject); var tmpZipName: String; begin If (GetZipFileDlg.Execute) then begin tmpZipName := GetZipFileDlg.Filename; If UpperCase(ExtractFileExt(tmpZipName)) <> '.ZIP' then ChangeFileExt( tmpZipName, '.zip' ); ZipFilename.Text := tmpZipName; end; end; procedure TCompressDlg.SelectFilesBtnClick(Sender: TObject); var i: Integer; begin FileSelectDlg.Files.Clear; FileSelectDlg.Filename := ''; {$IFNDEF WIN32} FileSelectDlg.Options := FileSelectDlg.Options - [ofNoValidate]; FileSelectDlg.Title := 'Select File(s) to be compressed'; {$ENDIF} If (FileSelectDlg.Execute) then For i := 0 to FileSelectDlg.Files.Count-1 do If SelectedFiles.Items.IndexOf(FileSelectDlg.Files[i]) = -1 then SelectedFiles.Items.Add( FileSelectDlg.Files[i] ); end; procedure TCompressDlg.RootDirBtnClick(Sender: TObject); var theDir: String; begin theDir := 'C:\'; If SelectDirectory(theDir, [sdAllowCreate, sdPerformCreate, sdPrompt], 0) then RootDir.Text := theDir; end; procedure TCompressDlg.ClearBtnClick(Sender: TObject); begin SelectedFiles.Clear; end; procedure TCompressDlg.AddWildCardBtnClick(Sender: TObject); begin SelectedFiles.Items.Add(WildCards.Text); WildCards.Text := ''; AddWildCardBtn.Enabled := False; end; procedure TCompressDlg.WildcardsChange(Sender: TObject); begin AddWildCardBtn.Enabled := Length( Wildcards.Text ) > 0; end; procedure TCompressDlg.SpinButton1DownClick(Sender: TObject); var Value: Integer; begin Value := StrToInt(CompLevel.Caption) - 1; If (Value >= 0) and (Value < 10) then CompLevel.Caption := IntToStr(Value); end; procedure TCompressDlg.SpinButton1UpClick(Sender: TObject); var Value: Integer; begin Value := StrToInt(CompLevel.Caption) + 1; If (Value > 0) and (Value < 10) then CompLevel.Caption := IntToStr(Value); end; procedure TCompressDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin If (ModalResult = mrOK) and (SelectedFiles.Items.Count = 0) then begin ShowMessage('No files have been specified to be compressed'); Action := caNone; end; end; procedure TCompressDlg.DeleteBtnClick(Sender: TObject); begin SelectedFiles.Items.Delete( SelectedFiles.ItemIndex ); end; procedure TCompressDlg.FormActivate(Sender: TObject); begin AddWildCardBtn.Enabled := False; MultiMode.ItemIndex := 0; MultiModeChange( Self ); saveFirstBlockSize := FirstBlockSize.Text; end; procedure TCompressDlg.SaveDirInfoChkClick(Sender: TObject); begin If SaveDirInfoChk.Checked then SaveVolumesChk.Enabled := True Else begin SaveVolumesChk.Checked := False; SaveVolumesChk.Enabled := False; end; RelativeDir.Enabled := (RootDir.Text <> '') and (SaveDirInfoChk.Checked); end; procedure TCompressDlg.MultiModeChange(Sender: TObject); begin Case MultiMode.ItemIndex of 0: begin { mmNone } BlockSize.Enabled := False; FirstBlockSize.Enabled := False; WriteDiskLabelsChk.Enabled := False; end; 1: begin { mmSpan } BlockSize.Enabled := False; FirstBlockSize.Enabled := True; FirstBlockSize.Text := '0'; FirstDiskLabel.Caption := 'Save Space on First Disk'; WriteDiskLabelsChk.Enabled := True; end; 2: begin { mmBlocks } BlockSize.Enabled := True; FirstBlockSize.Enabled := True; FirstBlockSize.Text := saveFirstBlockSize; FirstDiskLabel.Caption := 'First Block Size'; WriteDiskLabelsChk.Enabled := False; end; end; end; procedure TCompressDlg.RootDirChange(Sender: TObject); begin RelativeDir.Enabled := (RootDir.Text <> '') and (SaveDirInfoChk.Checked); end; end.
namespace proholz.xsdparser; interface type XsdAbstractElementVisitor = public class protected owner : XsdAbstractElement; public constructor( aowner : XsdAbstractElement); begin self.owner := aowner; end; method visit(element: XsdAll); virtual; begin visit(XsdMultipleElements( element)); end; method visit(element: XsdAttribute); virtual; begin visit(XsdNamedElements( element)); end; method visit(element: XsdAttributeGroup); virtual; begin visit(XsdNamedElements (element)); end; method visit(element: XsdChoice); virtual; begin visit(XsdMultipleElements( element)); end; method visit(element: XsdComplexType); virtual; empty; method visit(element: XsdElement); virtual; begin visit(XsdNamedElements( element)); end; method visit(element: XsdGroup); virtual; begin visit(XsdNamedElements( element)); end; method visit(element: XsdSequence); virtual; begin visit(XsdMultipleElements( element)); end; method visit(element: XsdMultipleElements); virtual; empty; method visit(element: XsdNamedElements); virtual; begin var refBase := ReferenceBase.createFromXsd(element); if (refBase is UnsolvedReference) then begin element.getParser().addUnsolvedReference(UnsolvedReference( refBase)); end; end; method visit(element: XsdSimpleType); virtual; empty; method visit(element: XsdRestriction); virtual; empty; method visit(element: XsdList); virtual; empty; method visit(element: XsdUnion); virtual; empty; method visit(element: XsdEnumeration); virtual; empty; method visit(element: XsdFractionDigits); virtual; empty; method visit(element: XsdLength); virtual; empty; method visit(element: XsdMaxExclusive); virtual; empty; method visit(element: XsdMaxInclusive); virtual; empty; method visit(element: XsdMaxLength); virtual; empty; method visit(element: XsdMinExclusive); virtual; empty; method visit(element: XsdMinInclusive); virtual; empty; method visit(element: XsdMinLength); virtual; empty; method visit(element: XsdPattern); virtual; empty; method visit(element: XsdTotalDigits); virtual; empty; method visit(element: XsdWhiteSpace); virtual; empty; method visit(element: XsdExtension); virtual; empty; method visit(element: XsdComplexContent); virtual; empty; method visit(element: XsdSimpleContent); virtual; empty; method visit(element: XsdDocumentation); virtual; empty; method visit(element: XsdAppInfo); virtual; empty; method visit(xsdAnnotation: XsdAnnotation); virtual; empty; method visit(xsdImport: XsdImport); virtual; empty; method visit(xsdInclude: XsdInclude); virtual; empty; method getOwner: XsdAbstractElement; final; begin exit owner; end; end; implementation end.
{----------------------------------------------------------------------------- Least-Resistance Designer Library The Initial Developer of the Original Code is Scott J. Miles <sjmiles (at) turbophp (dot) com>. Portions created by Scott J. Miles are Copyright (C) 2005 Least-Resistance Software. All Rights Reserved. -------------------------------------------------------------------------------} unit DesignHandles; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls; type TDesignHandleId = ( dhNone, dhLeftTop, dhMiddleTop, dhRightTop, dhLeftMiddle, dhRightMiddle, dhLeftBottom, dhMiddleBottom, dhRightBottom ); // TDesignHandle = class(TCustomControl) private FResizeable: Boolean; protected procedure PaintHandle(const inRect: TRect); protected function HandleRect(inIndex: Integer): TRect; function HitRect(X, Y: Integer): Integer; procedure Paint; override; property Resizeable: Boolean read FResizeable write FResizeable; end; // TDesignHandles = class(TComponent) private FContainer: TWinControl; FSelected: TControl; Handles: array[0..3] of TDesignHandle; FResizeable: Boolean; protected function GetHandleWidth: Integer; function GetSelectionRect: TRect; function SelectedToScreenRect(const inRect: TRect): TRect; procedure CreateHandles; procedure SetContainer(const Value: TWinControl); procedure SetHandleRects(const inRect: TRect); procedure SetResizeable(const Value: Boolean); procedure SetSelected(const Value: TControl); procedure ShowHideHandles(inShow: Boolean); public constructor Create(inOwner: TComponent); override; function HitRect(X, Y: Integer): TDesignHandleId; function SelectedToContainer(const inPt: TPoint): TPoint; procedure RepaintHandles; procedure UpdateHandles; property Container: TWinControl read FContainer write SetContainer; property HandleWidth: Integer read GetHandleWidth; property Resizeable: Boolean read FResizeable write SetResizeable; property Selected: TControl read FSelected write SetSelected; end; implementation uses DesignController; var ShadedBits: TBitmap; function NeedShadedBits: TBitmap; begin if ShadedBits = nil then begin //ShadedBits := AllocPatternBitmap(clSilver, clGray); ShadedBits := TBitmap.Create; ShadedBits.Width := 4; ShadedBits.Height := 2; ShadedBits.Canvas.Pixels[0, 0] := clGray; ShadedBits.Canvas.Pixels[1, 0] := clBtnFace; ShadedBits.Canvas.Pixels[2, 0] := clBtnFace; ShadedBits.Canvas.Pixels[3, 0] := clBtnFace; ShadedBits.Canvas.Pixels[0, 1] := clBtnFace; ShadedBits.Canvas.Pixels[1, 1] := clBtnFace; ShadedBits.Canvas.Pixels[2, 1] := clGray; ShadedBits.Canvas.Pixels[3, 1] := clBtnFace; end; Result := ShadedBits; end; { TDesignHandle } function TDesignHandle.HandleRect(inIndex: Integer): TRect; var w: Integer; begin w := TDesignHandles(Owner).HandleWidth; case inIndex of 0: Result := Rect(0, 0, w, w); 1: Result := Rect((Width - w) div 2, 0, (Width + w) div 2, w); 2: Result := Rect(Width - w, 0, Width, w); 3: Result := Rect(0, (Height - w) div 2, w, (Height + w) div 2); end; end; procedure TDesignHandle.PaintHandle(const inRect: TRect); begin Canvas.Rectangle(inRect); end; procedure TDesignHandle.Paint; begin inherited; with Canvas do begin Brush.Bitmap := NeedShadedBits; FillRect(ClientRect); Brush.Bitmap := nil; Brush.Color := clWhite; Pen.Color := clBlack; if Resizeable then if (Width > Height) then begin PaintHandle(HandleRect(0)); PaintHandle(HandleRect(1)); PaintHandle(HandleRect(2)); end else PaintHandle(HandleRect(3)); end; end; function TDesignHandle.HitRect(X, Y: Integer): Integer; var i: Integer; r: TRect; begin Result := -1; for i := 0 to 3 do begin r := HandleRect(i); if PtInRect(r, Point(X, Y)) then begin Result := i; break; end; end; end; { TDesignHandles } constructor TDesignHandles.Create(inOwner: TComponent); begin inherited; CreateHandles; Resizeable := true; end; procedure TDesignHandles.CreateHandles; var i: Integer; begin for i := 0 to 3 do Handles[i] := TDesignHandle.Create(Self); end; function TDesignHandles.GetHandleWidth: Integer; begin Result := TDesignController(Owner).HandleWidth; end; procedure TDesignHandles.SetContainer(const Value: TWinControl); var i: Integer; begin FContainer := Value; for i := 0 to 3 do begin Handles[i].Visible := false; Handles[i].Parent := FContainer; end; end; procedure TDesignHandles.SetSelected(const Value: TControl); begin if (Selected <> Value) then begin if (Value is TDesignHandle) then FSelected := nil else FSelected := Value; UpdateHandles; end; end; procedure TDesignHandles.SetResizeable(const Value: Boolean); var i: Integer; begin FResizeable := Value; for i := 0 to 3 do Handles[i].Resizeable := Value; end; procedure TDesignHandles.ShowHideHandles(inShow: Boolean); var i: Integer; begin for i := 0 to 3 do with Handles[i] do begin Visible := inShow; if inShow then BringToFront; Update; end; end; procedure TDesignHandles.UpdateHandles; begin if (Selected <> nil) and (Container <> nil) and (Selected <> Container) then begin SetHandleRects(GetSelectionRect); ShowHideHandles(true); end else ShowHideHandles(false) end; procedure TDesignHandles.RepaintHandles; var i: INteger; begin for i := 0 to 3 do Handles[i].Repaint; end; function TDesignHandles.HitRect(X, Y: Integer): TDesignHandleId; const cRectIds: array[0..3, 0..3] of TDesignHandleId = ( ( dhLeftTop, dhMiddleTop, dhRightTop, dhNone ), ( dhNone, dhNone, dhNone, dhLeftMiddle ), ( dhNone, dhNone, dhNone, dhRightMiddle ), ( dhLeftBottom, dhMiddleBottom, dhRightBottom, dhNone ) ); var i, r: Integer; begin for i := 0 to 3 do begin with Handles[i] do r := HitRect(X - Left, Y - Top); if (r >= 0) then begin Result := cRectIds[i][r]; exit; end; end; Result := dhNone; end; function TDesignHandles.SelectedToContainer(const inPt: TPoint): TPoint; var c: TControl; begin Result := inPt; c := Selected.Parent; while (c <> Container) and (c <> nil) do begin Inc(Result.X, c.Left); Inc(Result.Y, c.Top); c := c.Parent; end; end; function TDesignHandles.SelectedToScreenRect(const inRect: TRect): TRect; var p: TWinControl; begin if Selected = Container then p := Container else p := Selected.Parent; Result.topLeft := p.ClientToScreen(inRect.topLeft); Result.bottomRight := p.ClientToScreen(inRect.bottomRight); end; function TDesignHandles.GetSelectionRect: TRect; var p: TPoint; begin if (Selected = Container) then p := Point(0, 0) else p := SelectedToContainer(Selected.BoundsRect.topLeft); Result := Rect(p.X, p.Y, p.X + Selected.Width, p.y + Selected.Height); InflateRect(Result, -HandleWidth div 2, -HandleWidth div 2); end; procedure TDesignHandles.SetHandleRects(const inRect: TRect); var w: Integer; begin w := HandleWidth; with inRect do begin Handles[0].BoundsRect := Rect(Left - w, Top - w, Right + w, Top); Handles[1].BoundsRect := Rect(Left - w, Top, Left, Bottom); Handles[2].BoundsRect := Rect(Right, Top, Right + w, Bottom); Handles[3].BoundsRect := Rect(Left - w, Bottom, Right + w, Bottom + w); end; end; end.
unit uMaquina; interface uses UIMaquina, Classes, UTroco; type TMaquina = class( TInterfacedObject, IMaquina ) public function MontarTroco( Troco: Double ): TList; end; implementation uses Math; function TMaquina.MontarTroco( Troco: Double ): TList; var I, Ct: Integer; ITroco: TTroco; V, Vlr: Double; begin Result := TList.Create; Vlr := Trunc( Troco ); I := 0; while ( Vlr <> 0 ) do begin V := ITroco.GetvalorCedula( TCedula( I ) ); Ct := Trunc( Vlr / V ); if ( Ct <> 0 ) then begin Result.Add( TTroco.Create( TCedula( I ), Ct ) ); Vlr := Math.FMod( Vlr, V ); end; I := I + 1; end; Vlr := SimpleRoundTo( ( Troco - Trunc( Troco ) ), -2 ); I := 7; while ( Vlr <> 0 ) do begin V := ITroco.GetvalorCedula( TCedula( I ) ); Ct := Trunc( Vlr / V ); if ( Ct <> 0 ) then begin Result.Add( TTroco.Create( TCedula( I ), Ct ) ); Vlr := SimpleRoundTo( Math.FMod( Vlr, V ), -2 ); end; I := I + 1; end; end; end.
unit API_Strings; interface type TStrTool = class class function CheckCyrChar(const aStr: string): Boolean; class function CutArrayByKey(const aStr, aFirstKey, aLastKey: string): TArray<string>; class function CutByKey(const aStr, aFirstKey, aLastKey: string; aFirstKeyNum: integer = 1): string; class function CutByKeyRearward(const aStr, aFirstKey, aLastKey: string; aFirstKeyNum: Integer = 1): string; class function CutFromKey(const aStr, aKey: string; aKeyNum: Integer = 1): string; class function CutToKey(const aStr, aKey: string; aKeyNum: Integer = 1): string; class function ExtractKey(const aKeyValue: string): string; class function ExtractValue(const aKeyValue: string): string; class function GetRegExFirstMatch(const aStr: string; aRegEx: string): string; class function GetRegExMatch(const aStr: string; aRegEx: string): TArray<string>; class function GetRegExReplaced(const aStr, aRegEx, aReplacement: string): string; class function HTMLDecodeChars(const aHTMLCode: string): string; class function HTMLToInnerText(const aHTMLCode: string): string; class function HTMLRemoveTags(const aHTMLCode: string): string; class function Reverse(const aStr: string): string; end; THTMLChar = TArray<string>; THTMLChars = TArray<THTMLChar>; implementation uses System.Character, System.NetEncoding, System.RegularExpressions, System.SysUtils; class function TStrTool.CheckCyrChar(const aStr: string): Boolean; var Ch: Char; i: Integer; begin Result := False; for i := 1 to Length(aStr) do begin Ch := aStr[i].ToLower; if Ch.IsInArray(['à','á','â','ã','ä','å','¸','æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ']) then Exit(True); end; end; class function TStrTool.GetRegExReplaced(const aStr, aRegEx, aReplacement: string): string; begin Result := TRegEx.Replace(aStr, aRegEx, aReplacement); end; class function TStrTool.HTMLToInnerText(const aHTMLCode: string): string; begin Result := HTMLRemoveTags(aHTMLCode); Result := HTMLDecodeChars(Result); end; class function TStrTool.GetRegExMatch(const aStr: string; aRegEx: string): TArray<string>; var Match: TMatch; begin Match := TRegEx.Match(aStr, aRegEx); while Match.Success do begin Result := Result + [Match.value]; Match := Match.NextMatch; end; end; class function TStrTool.GetRegExFirstMatch(const aStr: string; aRegEx: string): string; var Matches: TArray<string>; begin Result := ''; Matches := GetRegExMatch(aStr, aRegEx); if Length(Matches) > 0 then Result := Matches[0]; end; class function TStrTool.ExtractValue(const aKeyValue: string): string; begin Result := aKeyValue.Substring(aKeyValue.IndexOf('=') + 1, aKeyValue.Length); end; class function TStrTool.ExtractKey(const aKeyValue: string): string; begin Result := aKeyValue.Substring(0, aKeyValue.IndexOf('=')); end; class function TStrTool.CutFromKey(const aStr, aKey: string; aKeyNum: Integer = 1): string; var i: Integer; begin Result := aStr; for i := 1 to aKeyNum do Result := Result.Remove(Result.LastIndexOf(aKey), Result.Length); end; class function TStrTool.CutToKey(const aStr, aKey: string; aKeyNum: Integer = 1): string; var i: Integer; begin Result := aStr; for i := 1 to aKeyNum - 1 do Result := Result.Remove(0, Result.IndexOf(aKey) + aKey.Length); end; class function TStrTool.CutByKeyRearward(const aStr, aFirstKey, aLastKey: string; aFirstKeyNum: Integer = 1): string; var i: integer; begin Result := aStr; Result := CutFromKey(Result, aFirstKey, aFirstKeyNum); Result := Result.Substring(Result.LastIndexOf(aLastKey) + 1, Result.Length); end; class function TStrTool.CutArrayByKey(const aStr, aFirstKey, aLastKey: string): TArray<string>; var Page: string; Row: string; begin Page := aStr; Result := []; while Page.Contains(aFirstKey) do begin Row := CutByKey(Page, aFirstKey, aLastKey); Result := Result + [Row]; Page := Page.Remove(0, Page.IndexOf(aFirstKey) + aFirstKey.Length); Page := Page.Remove(0, Page.IndexOf(aLastKey) + aLastKey.Length); end; end; class function TStrTool.Reverse(const aStr: string): string; var i: Integer; begin Result := ''; for i := aStr.Length downto 1 do Result := Result + aStr[i]; end; class function TStrTool.HTMLRemoveTags(const aHTMLCode: string): string; var i: Integer; IsOpenTag: Boolean; TagText: string; begin IsOpenTag := False; TagText := ''; Result := aHTMLCode; for i := 1 to Length(aHTMLCode) do begin if not Result.Contains('>') or not Result.Contains('<') then Exit(Result); if aHTMLCode[i] = '<' then IsOpenTag := True; if IsOpenTag then TagText := TagText + aHTMLCode[i]; if aHTMLCode[i] = '>' then begin Result := StringReplace(Result, TagText, '', [rfReplaceAll, rfIgnoreCase]); IsOpenTag := False; TagText := ''; end; end; end; class function TStrTool.CutByKey(const aStr, aFirstKey, aLastKey: string; aFirstKeyNum: integer = 1): string; begin Result := aStr; Result := CutToKey(Result, aFirstKey, aFirstKeyNum); if Result.Contains(aFirstKey) or aFirstKey.IsEmpty then begin Result := Result.Substring(Result.IndexOf(aFirstKey) + aFirstKey.Length, Result.Length); Result := Result.Remove(Result.IndexOf(aLastKey), Result.Length); end else Result := ''; end; class function TStrTool.HTMLDecodeChars(const aHTMLCode: string): string; var HTMLChar: THTMLChar; HTMLChars: THTMLChars; PossibleHTMLChar: string; PossibleHTMLChars: TArray<string>; begin HTMLChars := [ ['aacute', #$00E1], ['Aacute', #$00C1], ['acirc', #$00E2], ['Acirc', #$00C2], ['agrave', #$00E0], ['Agrave', #$00C0], ['aring', #$00E5], ['Aring', #$00C5], ['atilde', #$00E3], ['Atilde', #$00C3], ['auml', #$00E4], ['Auml', #$00C4], ['aelig', #$00E6], ['AElig', #$00C6], ['ccedil', #$00E7], ['Ccedil', #$00C7], ['eth', #$00F0], ['ETH', #$00D0], ['eacute', #$00E9], ['Eacute', #$00C9], ['ecirc', #$00EA], ['Ecirc', #$00CA], ['egrave', #$00E8], ['Egrave', #$00C8], ['euml', #$00EB], ['Euml', #$00CB], ['iacute', #$00ED], ['Iacute', #$00CD], ['icirc', #$00EE], ['Icirc', #$00CE], ['igrave', #$00EC], ['Igrave', #$00CC], ['iuml', #$00EF], ['Iuml', #$00CF], ['ntilde', #$00F1], ['Ntilde', #$00D1], ['oacute', #$00F3], ['Oacute', #$00D3], ['ocirc', #$00F4], ['Ocirc', #$00D4], ['ograve', #$00F2], ['Ograve', #$00D2], ['oslash', #$00F8], ['Oslash', #$00D8], ['otilde', #$00F5], ['Otilde', #$00D5], ['ouml', #$00F6], ['Ouml', #$00D6], ['szlig', #$00DF], ['thorn', #$00FE], ['THORN', #$00DE], ['uacute', #$00FA], ['Uacute', #$00DA], ['ucirc', #$00FB], ['Ucirc', #$00DB], ['ugrave', #$00F9], ['Ugrave', #$00D9], ['uuml', #$00FC], ['Uuml', #$00DC], ['yacute', #$00FD], ['Yacute', #$00DD], ['yuml', #$00FF], ['abreve', #$0103], ['Abreve', #$0102], ['amacr', #$0101], ['Amacr', #$0100], ['aogon', #$0105], ['Aogon', #$0104], ['cacute', #$0107], ['Cacute', #$0106], ['ccaron', #$010D], ['Ccaron', #$010C], ['ccirc', #$0109], ['Ccirc', #$0108], ['cdot', #$010B], ['Cdot', #$010A], ['dcaron', #$010F], ['Dcaron', #$010E], ['dstrok', #$0111], ['Dstrok', #$0110], ['ecaron', #$011B], ['Ecaron', #$011A], ['edot', #$0117], ['Edot', #$0116], ['emacr', #$0113], ['Emacr', #$0112], ['eogon', #$0119], ['Eogon', #$0118], ['gacute', #$01F5], ['gbreve', #$011F], ['Gbreve', #$011E], ['Gcedil', #$0122], ['gcirc', #$011D], ['Gcirc', #$011C], ['gdot', #$0121], ['Gdot', #$0120], ['hcirc', #$0125], ['Hcirc', #$0124], ['hstrok', #$0127], ['Hstrok', #$0126], ['Idot', #$0130], ['Imacr', #$012A], ['imacr', #$012B], ['ijlig', #$0133], ['IJlig', #$0132], ['inodot.1', #$0131], ['iogon', #$012F], ['Iogon', #$012E], ['itilde', #$0129], ['Itilde', #$0128], ['jcirc', #$0135], ['Jcirc', #$0134], ['kcedil', #$0137], ['Kcedil', #$0136], ['kgreen', #$0138], ['lacute', #$013A], ['Lacute', #$0139], ['lcaron', #$013E], ['Lcaron', #$013D], ['lcedil', #$013C], ['Lcedil', #$013B], ['lmidot', #$0140], ['Lmidot', #$013F], ['lstrok', #$0142], ['Lstrok', #$0141], ['nacute', #$0144], ['Nacute', #$0143], ['eng', #$014B], ['ENG', #$014A], ['napos', #$0149], ['ncaron', #$0148], ['Ncaron', #$0147], ['ncedil', #$0146], ['Ncedil', #$0145], ['odblac', #$0151], ['Odblac', #$0150], ['Omacr', #$014C], ['omacr', #$014D], ['oelig', #$0153], ['OElig', #$0152], ['racute', #$0155], ['Racute', #$0154], ['rcaron', #$0159], ['Rcaron', #$0158], ['rcedil', #$0157], ['Rcedil', #$0156], ['sacute', #$015B], ['Sacute', #$015A], ['scaron', #$0161], ['Scaron', #$0160], ['scedil', #$015F], ['Scedil', #$015E], ['scirc', #$015D], ['Scirc', #$015C], ['tcaron', #$0165], ['Tcaron', #$0164], ['tcedil', #$0163], ['Tcedil', #$0162], ['tstrok', #$0167], ['Tstrok', #$0166], ['ubreve', #$016D], ['Ubreve', #$016C], ['udblac', #$0171], ['Udblac', #$0170], ['umacr', #$016B], ['Umacr', #$016A], ['uogon', #$0173], ['Uogon', #$0172], ['uring', #$016F], ['Uring', #$016E], ['utilde', #$0169], ['Utilde', #$0168], ['wcirc', #$0175], ['Wcirc', #$0174], ['ycirc', #$0177], ['Ycirc', #$0176], ['Yuml', #$0178], ['zacute', #$017A], ['Zacute', #$0179], ['zcaron', #$017E], ['Zcaron', #$017D], ['zdot', #$017C], ['Zdot', #$017B], ['agr', #$03B1], ['Agr', #$0391], ['bgr', #$03B2], ['Bgr', #$0392], ['ggr', #$03B3], ['Ggr', #$0393], ['dgr', #$03B4], ['Dgr', #$0394], ['egr', #$03B5], ['Egr', #$0395], ['zgr', #$03B6], ['Zgr', #$0396], ['eegr', #$03B7], ['EEgr', #$0397], ['thgr', #$03B8], ['THgr', #$0398], ['igr', #$03B9], ['Igr', #$0399], ['kgr', #$03BA], ['Kgr', #$039A], ['lgr', #$03BB], ['Lgr', #$039B], ['mgr', #$03BC], ['Mgr', #$039C], ['ngr', #$03BD], ['Ngr', #$039D], ['xgr', #$03BE], ['Xgr', #$039E], ['ogr', #$03BF], ['Ogr', #$039F], ['pgr', #$03C0], ['Pgr', #$03A0], ['rgr', #$03C1], ['Rgr', #$03A1], ['sgr', #$03C3], ['Sgr', #$03A3], ['sfgr', #$03C2], ['tgr', #$03C4], ['Tgr', #$03A4], ['ugr', #$03C5], ['Ugr', #$03A5], ['phgr', #$03C6], ['PHgr', #$03A6], ['khgr', #$03C7], ['KHgr', #$03A7], ['psgr', #$03C8], ['PSgr', #$03A8], ['ohgr', #$03C9], ['OHgr', #$03A9], ['aacgr', #$03AC], ['Aacgr', #$0386], ['eacgr', #$03AD], ['Eacgr', #$0388], ['eeacgr', #$03AE], ['EEacgr', #$0389], ['idigr', #$03CA], ['Idigr', #$03AA], ['iacgr', #$03AF], ['Iacgr', #$038A], ['idiagr', #$0390], ['oacgr', #$03CC], ['Oacgr', #$038C], ['udigr', #$03CB], ['Udigr', #$03AB], ['uacgr', #$03CD], ['Uacgr', #$038E], ['udiagr', #$03B0], ['ohacgr', #$03CE], ['OHacgr', #$038F], ['acy', #$0430], ['Acy', #$0410], ['bcy', #$0431], ['Bcy', #$0411], ['vcy', #$0432], ['Vcy', #$0412], ['gcy', #$0433], ['Gcy', #$0413], ['dcy', #$0434], ['Dcy', #$0414], ['iecy', #$0435], ['IEcy', #$0415], ['iocy', #$0451], ['IOcy', #$0401], ['zhcy', #$0436], ['ZHcy', #$0416], ['zcy', #$0437], ['Zcy', #$0417], ['icy', #$0438], ['Icy', #$0418], ['jcy', #$0439], ['Jcy', #$0419], ['kcy', #$043A], ['Kcy', #$041A], ['lcy', #$043B], ['Lcy', #$041B], ['mcy', #$043C], ['Mcy', #$041C], ['ncy', #$043D], ['Ncy', #$041D], ['ocy', #$043E], ['Ocy', #$041E], ['pcy', #$043F], ['Pcy', #$041F], ['rcy', #$0440], ['Rcy', #$0420], ['scy', #$0441], ['Scy', #$0421], ['tcy', #$0442], ['Tcy', #$0422], ['ucy', #$0443], ['Ucy', #$0423], ['fcy', #$0444], ['Fcy', #$0424], ['khcy', #$0445], ['KHcy', #$0425], ['tscy', #$0446], ['TScy', #$0426], ['chcy', #$0447], ['CHcy', #$0427], ['shcy', #$0448], ['SHcy', #$0428], ['shchcy', #$0449], ['SHCHcy', #$0429], ['hardcy', #$044A], ['HARDcy', #$042A], ['ycy', #$044B], ['Ycy', #$042B], ['softcy', #$044C], ['SOFTcy', #$042C], ['ecy', #$044D], ['Ecy', #$042D], ['yucy', #$044E], ['YUcy', #$042E], ['yacy', #$044F], ['YAcy', #$042F], ['numero', #$2116], ['djcy', #$0452], ['DJcy', #$0402], ['gjcy', #$0453], ['GJcy', #$0403], ['jukcy', #$0454], ['Jukcy', #$0404], ['dscy', #$0455], ['DScy', #$0405], ['iukcy', #$0456], ['Iukcy', #$0406], ['yicy', #$0457], ['YIcy', #$0407], ['jsercy', #$0458], ['Jsercy', #$0408], ['ljcy', #$0459], ['LJcy', #$0409], ['njcy', #$045A], ['NJcy', #$040A], ['tshcy', #$045B], ['TSHcy', #$040B], ['kjcy', #$045C], ['KJcy', #$040C], ['ubrcy', #$045E], ['Ubrcy', #$040E], ['dzcy', #$045F], ['DZcy', #$040F], ['half', #$00BD], ['frac12', #$00BD], ['frac14', #$00BC], ['frac34', #$00BE], ['frac18', #$215B], ['frac38', #$215C], ['frac58', #$215D], ['frac78', #$215E], ['sup1', #$00B9], ['sup2', #$00B2], ['sup3', #$00B3], ['plus', #$002B], ['plusmn', #$00B1], ['lt', #$003C], ['equals', #$003D], ['gt', #$003E], ['divide', #$00F7], ['times', #$00D7], ['curren', #$00A4], ['pound', #$00A3], ['dollar', #$0024], ['cent', #$00A2], ['yen', #$00A5], ['num', #$0023], ['percnt', #$0025], ['amp', #$0026], ['ast', #$002A], ['commat', #$0040], ['lsqb', #$005B], ['bsol', #$005C], ['rsqb', #$005D], ['lcub', #$007B], ['horbar', #$2015], ['verbar', #$007C], ['rcub', #$007D], ['micro', #$00B5], ['ohm', #$2126], ['deg', #$00B0], ['ordm', #$00BA], ['ordf', #$00AA], ['sect', #$00A7], ['para', #$00B6], ['middot', #$00B7], ['larr', #$2190], ['rarr', #$2192], ['uarr', #$2191], ['darr', #$2193], ['copy', #$00A9], ['reg', #$00AE], ['trade', #$2122], ['brvbar', #$00A6], ['not', #$00AC], ['sung', #$00A0], ['excl', #$0021], ['iexcl', #$00A1], ['quot', #$0022], ['apos', #$0027], ['lpar', #$0028], ['rpar', #$0029], ['comma', #$002C], ['lowbar', #$005F], ['hyphen', #$002D], ['period', #$002E], ['sol', #$002F], ['colon', #$003A], ['semi', #$003B], ['quest', #$003F], ['iquest', #$00BF], ['laquo', #$00AB], ['raquo', #$00BB], ['lsquo', #$2018], ['rsquo', #$2019], ['ldquo', #$201C], ['rdquo', #$201D], ['nbsp', #$00A0], ['shy', #$00AD], ['acute', #$00B4], ['breve', #$02D8], ['caron', #$02C7], ['cedil', #$00B8], ['circ', #$005E], ['dblac', #$02DD], ['die', #$00A8], ['dot', #$02D9], ['grave', #$0060], ['macr', #$00AF], ['ogon', #$02DB], ['ring', #$02DA], ['tilde', #$02DC], ['uml', #$00A8], ['emsp', #$2003], ['ensp', #$2002], ['emsp13', #$2004], ['emsp14', #$2005], ['numsp', #$2007], ['puncsp', #$2008], ['thinsp', #$2009], ['hairsp', #$200A], ['mdash', #$2014], ['ndash', #$2013], ['dash', #$2010], ['blank', #$2423], ['hellip', #$2026], ['nldr', #$2025], ['frac13', #$2153], ['frac23', #$2154], ['frac15', #$2155], ['frac25', #$2156], ['frac35', #$2157], ['frac45', #$2158], ['frac16', #$2159], ['frac56', #$215A], ['incare', #$2105], ['block', #$2588], ['uhblk', #$2580], ['lhblk', #$2584], ['blk14', #$2591], ['blk12', #$2592], ['blk34', #$2593], ['marker', #$25AE], ['cir', #$25CB], ['squ', #$25A1], ['rect', #$25AD], ['utri', #$25B5], ['dtri', #$25BF], ['star', #$22C6], ['bull', #$2022], ['squf', #$25AA], ['utrif', #$25B4], ['dtrif', #$25BE], ['ltrif', #$25C2], ['rtrif', #$25B8], ['clubs', #$2663], ['diams', #$2666], ['hearts', #$2661], ['spades', #$2660], ['malt', #$2720], ['dagger', #$2020], ['Dagger', #$2021], ['check', #$2713], ['cross', #$2717], ['sharp', #$266F], ['flat', #$266D], ['male', #$2642], ['female', #$2640], ['phone', #$260E], ['telrec', #$2315], ['copysr', #$2117], ['caret', #$2041], ['lsquor', #$201A], ['ldquor', #$201E], ['fflig', #$FB00], ['filig', #$FB01], ['fjlig', #$FFFD], ['ffilig', #$FB03], ['ffllig', #$FB04], ['fllig', #$FB02], ['mldr', #$2026], ['rdquor', #$201D], ['rsquor', #$2019], ['vellip', #$22EE], ['hybull', #$2043], ['loz', #$25CA], ['lozf', #$2726], ['ltri', #$25C3], ['rtri', #$25B9], ['starf', #$2605], ['natur', #$266E], ['rx', #$211E], ['sext', #$2736], ['target', #$2316], ['dlcrop', #$230D], ['drcrop', #$230C], ['ulcrop', #$230F], ['urcrop', #$230E], ['boxh', #$2500], ['boxv', #$2502], ['boxur', #$2514], ['boxul', #$2518], ['boxdl', #$2510], ['boxdr', #$250C], ['boxvr', #$251C], ['boxhu', #$2534], ['boxvl', #$2524], ['boxhd', #$252C], ['boxvh', #$253C], ['boxvR', #$255E], ['boxhU', #$2568], ['boxvL', #$2561], ['boxhD', #$2565], ['boxvH', #$256A], ['boxH', #$2550], ['boxV', #$2551], ['boxUR', #$255A], ['boxUL', #$255D], ['boxDL', #$2557], ['boxDR', #$2554], ['boxVR', #$2560], ['boxHU', #$2569], ['boxVL', #$2563], ['boxHD', #$2566], ['boxVH', #$256C], ['boxVr', #$255F], ['boxHu', #$2567], ['boxVl', #$2562], ['boxHd', #$2564], ['boxVh', #$256B], ['boxuR', #$2558], ['boxUl', #$255C], ['boxdL', #$2555], ['boxDr', #$2553], ['boxUr', #$2559], ['boxuL', #$255B], ['boxDl', #$2556], ['boxdR', #$2552], ['aleph', #$2135], ['and', #$2227], ['ang90', #$221F], ['angsph', #$2222], ['ap', #$2248], ['becaus', #$2235], ['bottom', #$22A5], ['cap', #$2229], ['cong', #$2245], ['conint', #$222E], ['cup', #$222A], ['equiv', #$2261], ['exist', #$2203], ['forall', #$2200], ['fnof', #$0192], ['ge', #$2265], ['iff', #$21D4], ['infin', #$221E], ['int', #$222B], ['isin', #$2208], ['lang', #$3008], ['lArr', #$21D0], ['le', #$2264], ['minus', #$2212], ['mnplus', #$2213], ['nabla', #$2207], ['ne', #$2260], ['ni', #$220B], ['or', #$2228], ['par', #$2225], ['part', #$2202], ['permil', #$2030], ['perp', #$22A5], ['prime', #$2032], ['Prime', #$2033], ['prop', #$221D], ['radic', #$221A], ['rang', #$3009], ['rArr', #$21D2], ['sim', #$223C], ['sime', #$2243], ['square', #$25A1], ['sub', #$2282], ['sube', #$2286], ['sup', #$2283], ['supe', #$2287], ['there4', #$2234], ['Verbar', #$2016], ['angst', #$212B], ['bernou', #$212C], ['compfn', #$2218], ['Dot', #$00A8], ['DotDot', #$20DC], ['hamilt', #$210B], ['lagran', #$2112], ['lowast', #$2217], ['notin', #$2209], ['order', #$2134], ['phmmat', #$2133], ['tdot', #$20DB], ['tprime', #$2034], ['wedgeq', #$2259], ['alpha', #$03B1], ['beta', #$03B2], ['gamma', #$03B3], ['Gamma', #$0393], ['gammad', #$03DC], ['delta', #$03B4], ['Delta', #$0394], ['epsi', #$03B5], ['epsiv', #$025B], ['epsis', #$03B5], ['zeta', #$03B6], ['eta', #$03B7], ['thetas', #$03B8], ['Theta', #$0398], ['thetav', #$03D1], ['iota', #$03B9], ['kappa', #$03BA], ['kappav', #$03F0], ['lambda', #$03BB], ['Lambda', #$039B], ['mu', #$03BC], ['nu', #$03BD], ['xi', #$03BE], ['Xi', #$039E], ['pi', #$03C0], ['piv', #$03D6], ['Pi', #$03A0], ['rho', #$03C1], ['rhov', #$03F1], ['sigma', #$03C3], ['Sigma', #$03A3], ['sigmav', #$03C2], ['tau', #$03C4], ['upsi', #$03C5], ['Upsi', #$03D2], ['phis', #$03C6], ['Phi', #$03A6], ['phiv', #$03D5], ['chi', #$03C7], ['psi', #$03C8], ['Psi', #$03A8], ['omega', #$03C9], ['Omega', #$03A9], ['b.alpha', #$03B1], ['b.beta', #$03B2], ['b.gamma', #$03B3], ['b.Gamma', #$0393], ['b.gammad', #$03DC], ['b.delta', #$03B4], ['b.Delta', #$0394], ['b.epsi', #$03B5], ['b.epsiv', #$025B], ['b.epsis', #$03B5], ['b.zeta', #$03B6], ['b.eta', #$03B7], ['b.thetas', #$03B8], ['b.Theta', #$0398], ['b.thetav', #$03D1], ['b.iota', #$03B9], ['b.kappa', #$03BA], ['b.kappav', #$03F0], ['b.lambda', #$03BB], ['b.Lambda', #$039B], ['b.mu', #$03BC], ['b.nu', #$03BD], ['b.xi', #$03BE], ['b.Xi', #$039E], ['b.pi', #$03C0], ['b.Pi', #$03A0], ['b.piv', #$03D6], ['b.rho', #$03C1], ['b.rhov', #$03F1], ['b.sigma', #$03C3], ['b.Sigma', #$03A3], ['b.sigmav', #$03C2], ['b.tau', #$03C4], ['b.upsi', #$03C5], ['b.Upsi', #$03D2], ['b.phis', #$03C6], ['b.Phi', #$03A6], ['b.phiv', #$03D5], ['b.chi', #$03C7], ['b.psi', #$03C8], ['b.Psi', #$03A8], ['b.omega', #$03C9], ['b.Omega', #$03A9], ['ang', #$2220], ['angmsd', #$2221], ['beth', #$2136], ['bprime', #$2035], ['comp', #$2201], ['daleth', #$2138], ['ell', #$2113], ['empty', #$2205], ['gimel', #$2137], ['image', #$2111], ['inodot.2', #$0131], ['jnodot', #$FFFD], ['nexist', #$2204], ['oS', #$24C8], ['planck', #$0127], ['real', #$211C], ['sbsol', #$FE68], ['vprime', #$2032], ['weierp', #$2118], ['amalg', #$2201], ['Barwed', #$22BC], ['barwed', #$22BC], ['Cap', #$22D2], ['Cup', #$22D3], ['cuvee', #$22CE], ['cuwed', #$22CF], ['diam', #$22C4], ['divonx', #$22C7], ['intcal', #$22BA], ['lthree', #$22CB], ['ltimes', #$22C9], ['minusb', #$229F], ['oast', #$229B], ['ocir', #$229A], ['odash', #$229D], ['odot', #$2299], ['ominus', #$2296], ['oplus', #$2295], ['osol', #$2298], ['otimes', #$2297], ['plusb', #$229E], ['plusdo', #$2214], ['rthree', #$22CC], ['rtimes', #$22CA], ['sdot', #$22C5], ['sdotb', #$22A1], ['setmn', #$2216], ['sqcap', #$2293], ['sqcup', #$2294], ['ssetmn', #$2216], ['sstarf', #$22C6], ['timesb', #$22A0], ['top', #$22A4], ['uplus', #$228E], ['wreath', #$2240], ['xcirc', #$25EF], ['xdtri', #$25BD], ['xutri', #$25B3], ['coprod', #$2210], ['prod', #$220F], ['sum', #$2211], ['ape', #$224A], ['asymp', #$224D], ['bcong', #$224C], ['bepsi', #$220D], ['bowtie', #$22C8], ['bsim', #$223D], ['bsime', #$22CD], ['bump', #$224E], ['bumpe', #$224F], ['cire', #$2257], ['colone', #$2254], ['cuepr', #$22DE], ['cuesc', #$22DF], ['cupre', #$227C], ['dashv', #$22A3], ['ecir', #$2256], ['ecolon', #$2255], ['eDot', #$2251], ['esdot', #$2250], ['efDot', #$2252], ['egs', #$22DD], ['els', #$22DC], ['erDot', #$2253], ['fork', #$22D4], ['frown', #$2322], ['gap', #$2273], ['gsdot', #$22D7], ['gE', #$2267], ['gel', #$22DB], ['gEl', #$22DB], ['ges', #$2265], ['Gg', #$22D9], ['gl', #$2277], ['gsim', #$2273], ['Gt', #$226B], ['lap', #$2272], ['ldot', #$22D6], ['lE', #$2266], ['lEg', #$22DA], ['leg', #$22DA], ['les', #$2264], ['lg', #$2276], ['Ll', #$22D8], ['lsim', #$2272], ['Lt', #$226A], ['ltrie', #$22B4], ['mid', #$2223], ['models', #$22A7], ['pr', #$227A], ['prap', #$227E], ['pre', #$227C], ['prsim', #$227E], ['rtrie', #$22B5], ['samalg', #$2210], ['sc', #$227B], ['scap', #$227F], ['sccue', #$227D], ['sce', #$227D], ['scsim', #$227F], ['sfrown', #$2322], ['smid', #$FFFD], ['smile', #$2323], ['spar', #$2225], ['sqsub', #$228F], ['sqsube', #$2291], ['sqsup', #$2290], ['sqsupe', #$2292], ['ssmile', #$2323], ['Sub', #$22D0], ['subE', #$2286], ['Sup', #$22D1], ['supE', #$2287], ['thkap', #$2248], ['thksim', #$223C], ['trie', #$225C], ['twixt', #$226C], ['vdash', #$22A2], ['Vdash', #$22A9], ['vDash', #$22A8], ['veebar', #$22BB], ['vltri', #$22B2], ['vprop', #$221D], ['vrtri', #$22B3], ['Vvdash', #$22AA], ['gnap', #$FFFD], ['gne', #$2269], ['gnE', #$2269], ['gnsim', #$22E7], ['gvnE', #$2269], ['lnap', #$FFFD], ['lnE', #$2268], ['lne', #$2268], ['lnsim', #$22E6], ['lvnE', #$2268], ['nap', #$2249], ['ncong', #$2247], ['nequiv', #$2262], ['ngE', #$2271], ['nge', #$2271], ['nges', #$2271], ['ngt', #$226F], ['nle', #$2270], ['nlE', #$2270], ['nles', #$2270], ['nlt', #$226E], ['nltri', #$22EA], ['nltrie', #$22EC], ['nmid', #$2224], ['npar', #$2226], ['npr', #$2280], ['npre', #$22E0], ['nrtri', #$22EB], ['nrtrie', #$22ED], ['nsc', #$2281], ['nsce', #$22E1], ['nsim', #$2241], ['nsime', #$2244], ['nsmid', #$FFFD], ['nspar', #$2226], ['nsub', #$2284], ['nsube', #$2288], ['nsubE', #$2288], ['nsup', #$2285], ['nsupE', #$2289], ['nsupe', #$2289], ['nvdash', #$22AC], ['nvDash', #$22AD], ['nVDash', #$22AF], ['nVdash', #$22AE], ['prnap', #$22E8], ['prnE', #$FFFD], ['prnsim', #$22E8], ['scnap', #$22E9], ['scnE', #$FFFD], ['scnsim', #$22E9], ['subne', #$228A], ['subnE', #$228A], ['supne', #$228B], ['supnE', #$228B], ['vsubnE', #$FFFD], ['vsubne', #$228A], ['vsupne', #$228B], ['vsupnE', #$228B], ['cularr', #$21B6], ['curarr', #$21B7], ['dArr', #$21D3], ['darr2', #$21CA], ['dharl', #$21C3], ['dharr', #$21C2], ['lAarr', #$21DA], ['Larr', #$219E], ['larr2', #$21C7], ['larrhk', #$21A9], ['larrlp', #$21AB], ['larrtl', #$21A2], ['lhard', #$21BD], ['lharu', #$21BC], ['hArr', #$21D4], ['harr', #$2194], ['lrarr2', #$21C6], ['rlarr2', #$21C4], ['harrw', #$21AD], ['rlhar2', #$21CC], ['lrhar2', #$21CB], ['lsh', #$21B0], ['map', #$21A6], ['mumap', #$22B8], ['nearr', #$2197], ['nlArr', #$21CD], ['nlarr', #$219A], ['nhArr', #$21CE], ['nharr', #$21AE], ['nrarr', #$219B], ['nrArr', #$21CF], ['nwarr', #$2196], ['olarr', #$21BA], ['orarr', #$21BB], ['rAarr', #$21DB], ['Rarr', #$21A0], ['rarr2', #$21C9], ['rarrhk', #$21AA], ['rarrlp', #$21AC], ['rarrtl', #$21A3], ['rarrw', #$21DD], ['rhard', #$21C1], ['rharu', #$21C0], ['rsh', #$21B1], ['drarr', #$2198], ['dlarr', #$2199], ['uArr', #$21D1], ['uarr2', #$21C8], ['vArr', #$21D5], ['varr', #$2195], ['uharl', #$21BF], ['uharr', #$21BE], ['xlArr', #$21D0], ['xhArr', #$2194], ['xharr', #$2194], ['xrArr', #$21D2], ['rceil', #$2309], ['rfloor', #$230B], ['rpargt', #$FFFD], ['urcorn', #$231D], ['drcorn', #$231F], ['lceil', #$2308], ['lfloor', #$230A], ['lpargt', #$FFFD], ['ulcorn', #$231C], ['dlcorn', #$231E] ]; Result := aHTMLCode; PossibleHTMLChars := CutArrayByKey(aHTMLCode, '&', ';'); for PossibleHTMLChar in PossibleHTMLChars do for HTMLChar in HTMLChars do begin if HTMLChar[0] = PossibleHTMLChar then begin Result := Result.Replace('&' + PossibleHTMLChar + ';', HTMLChar[1]); Break; end; end; //Result := TNetEncoding.HTML.Decode(Result); end; end.
unit frmSearchU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.UITypes, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, LibraryHelperU, Vcl.Menus; type TfrmSearch = class(TForm) Panel1: TPanel; Panel2: TPanel; btnOk: TBitBtn; btnCancel: TBitBtn; ActionList: TActionList; ActionFind: TAction; ActionClose: TAction; Panel3: TPanel; Panel4: TPanel; Label2: TLabel; cbIgnoreCase: TCheckBox; editFind: TComboBox; GroupBoxDestination: TGroupBox; GridPanel1: TGridPanel; cbAndroid32: TCheckBox; cbIOS32: TCheckBox; cbIOS64: TCheckBox; cbIOSSimulator: TCheckBox; cbOSX: TCheckBox; cbWin32: TCheckBox; cbWin64: TCheckBox; cbLinux64: TCheckBox; PopupMenuLibrary: TPopupMenu; CheckAll1: TMenuItem; UncheckAll1: TMenuItem; ListViewSearch: TListView; procedure FormShow(Sender: TObject); procedure ActionCloseExecute(Sender: TObject); procedure CheckAll1Click(Sender: TObject); procedure UncheckAll1Click(Sender: TObject); procedure ActionFindExecute(Sender: TObject); procedure editFindKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FDelphiInstallation: TDelphiInstallation; procedure UpdateComboBoxOptions(ADelphiInstallation: TDelphiInstallation); procedure Find(AFind: string; AIgnoreCase: Boolean); procedure SetDestinationsChecked(AValue: Boolean); public function Execute(ADelphiInstallation: TDelphiInstallation): Boolean; end; implementation {$R *.dfm} uses System.StrUtils, frmProgressU, dmDelphiLibraryHelperU; procedure TfrmSearch.ActionCloseExecute(Sender: TObject); begin Self.ModalResult := mrCancel; end; procedure TfrmSearch.SetDestinationsChecked(AValue: Boolean); begin cbAndroid32.Checked := AValue; cbIOS32.Checked := AValue; cbIOS64.Checked := AValue; cbIOSSimulator.Checked := AValue; cbOSX.Checked := AValue; cbWin32.Checked := AValue; cbWin64.Checked := AValue; cbLinux64.Checked := AValue; end; procedure TfrmSearch.ActionFindExecute(Sender: TObject); begin Find(editFind.Text, cbIgnoreCase.Checked); if ListViewSearch.Items.Count = 0 then begin MessageDlg(Format('"%s" was not found.', [editFind.Text]), mtInformation, [mbOK], 0); end; end; procedure TfrmSearch.CheckAll1Click(Sender: TObject); begin SetDestinationsChecked(True); end; procedure TfrmSearch.editFindKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then ActionFind.Execute; end; function TfrmSearch.Execute(ADelphiInstallation: TDelphiInstallation): Boolean; begin Result := True; if Assigned(ADelphiInstallation) then begin FDelphiInstallation := ADelphiInstallation; UpdateComboBoxOptions(FDelphiInstallation); SetDestinationsChecked(True); Self.ShowModal; end; end; procedure TfrmSearch.Find(AFind: string; AIgnoreCase: Boolean); var LLibrary: TStringList; function SearchText(AText, ASubText: string; AIgnoreCase: Boolean): Boolean; begin if AIgnoreCase then begin Result := ContainsStr(AText, ASubText); end else begin Result := ContainsText(AText, ASubText); end; end; procedure AddFind(AEntry: string; APath: string; ALibrary: string); begin with ListViewSearch.Items.Add do begin Caption := AEntry; SubItems.Add(APath); SubItems.Add(ALibrary); end; end; procedure SearchLibrary(ALibrary: TDelphiLibrary); var LLibrary: TStringList; LIdx: integer; LLibraryPath: string; LLibraryEntry: string; begin LLibrary := TStringList.Create; try FDelphiInstallation.LibraryAsStrings(LLibrary, ALibrary); for LIdx := 0 to Pred(LLibrary.Count) do begin LLibraryEntry := LLibrary[LIdx]; LLibraryPath := FDelphiInstallation.ExpandLibraryPath(LLibraryEntry, ALibrary); if SearchText(LLibraryPath, AFind, AIgnoreCase) then begin AddFind(LLibraryEntry, LLibraryPath, FDelphiInstallation.GetLibraryPlatformName(ALibrary)); end; end; finally FreeAndNil(LLibrary); end; end; begin ShowProgress('Searching...'); LLibrary := TStringList.Create; ListViewSearch.Items.Clear; ListViewSearch.Items.BeginUpdate; try if cbAndroid32.Checked then begin SearchLibrary(dlAndroid32); end; if cbIOS32.Checked then begin SearchLibrary(dlIOS32); end; if cbIOS64.Checked then begin SearchLibrary(dlIOS64); end; if cbIOSSimulator.Checked then begin SearchLibrary(dlIOSimulator); end; if cbOSX.Checked then begin SearchLibrary(dlOSX32); end; if cbWin32.Checked then begin SearchLibrary(dlWin32); end; if cbWin64.Checked then begin SearchLibrary(dlWin64); end; if cbLinux64.Checked then begin SearchLibrary(dlLinux64); end; finally ListViewSearch.Items.EndUpdate; FreeAndNil(LLibrary); HideProgress; end; end; procedure TfrmSearch.FormShow(Sender: TObject); begin editFind.SetFocus; end; procedure TfrmSearch.UncheckAll1Click(Sender: TObject); begin SetDestinationsChecked(False); end; procedure TfrmSearch.UpdateComboBoxOptions(ADelphiInstallation : TDelphiInstallation); var LItems: TStringList; function ValidatePath(APath: string; ADelphiLibrary: TDelphiLibrary): Boolean; var LPath: string; begin Result := False; LPath := APath; if Trim(LPath) <> '' then begin LPath := FDelphiInstallation.ExpandLibraryPath(LPath, ADelphiLibrary); Result := DirectoryExists(LPath); end; end; procedure AddLibraryPaths(ADelphiLibrary: TDelphiLibrary); var LLibrary: TStringList; LIdx: integer; LLibraryValue: string; begin LLibrary := TStringList.Create; try FDelphiInstallation.LibraryAsStrings(LLibrary, ADelphiLibrary); for LIdx := 0 to Pred(LLibrary.Count) do begin LLibraryValue := LLibrary[LIdx]; if ValidatePath(LLibraryValue, ADelphiLibrary) then begin LItems.Add(LLibrary[LIdx]); end; end; finally FreeAndNil(LLibrary); end; end; procedure AddEnvironmentVariables(AEnvironmentVariables : TEnvironmentVariables); var LIdx: integer; LLibraryValue: string; begin for LIdx := 0 to Pred(AEnvironmentVariables.Count) do begin LLibraryValue := AEnvironmentVariables.Variable[LIdx].Value; if ValidatePath(LLibraryValue, dlWin32) then begin LItems.Add(LLibraryValue); end; LLibraryValue := AEnvironmentVariables.Variable[LIdx].Name; if Trim(LLibraryValue) <> '' then begin LLibraryValue := '${' + LLibraryValue + '}'; LItems.Add(LLibraryValue); end; end; end; begin editFind.Items.Clear; ListViewSearch.Items.Clear; LItems := TStringList.Create; try LItems.Duplicates := dupIgnore; LItems.Sorted := True; AddLibraryPaths(dlAndroid32); AddLibraryPaths(dlIOS32); AddLibraryPaths(dlIOS64); AddLibraryPaths(dlOSX32); AddLibraryPaths(dlIOSimulator); AddLibraryPaths(dlIOS32); AddLibraryPaths(dlWin32); AddLibraryPaths(dlWin64); AddLibraryPaths(dlLinux64); AddEnvironmentVariables(FDelphiInstallation.EnvironmentVariables); AddEnvironmentVariables(FDelphiInstallation.SystemEnvironmentVariables); editFind.Items.Text := LItems.Text; finally FreeAndNil(LItems); end; end; end.