text
stringlengths
14
6.51M
unit SceneMainMenu; interface uses DGLE, DGLE_Types, Engine, SceneCustom, SceneManager, Button; type TMenuItem = (miNone, miTavern, miAbout, miQuit); const MenuCaption: array [miTavern..miQuit] of AnsiString = ('Таверна', 'Авторы', 'Выход'); type TSceneMainMenu = class(TSceneCustom) private Buttons: array [miTavern..miQuit] of TButton; procedure SellectButton(S: TMenuItem); procedure UseButton(I: TMenuItem); public constructor Create; destructor Destroy; override; procedure Render(); override; procedure Update(); override; end; implementation uses SysUtils, uBox, SceneEngine; { TMainMenu } procedure TSceneMainMenu.SellectButton(S: TMenuItem); var I: TMenuItem; begin for I := miTavern to miQuit do Buttons[I].Sellected := False; Buttons[S].Sellected := True; end; constructor TSceneMainMenu.Create; var T: Word; I: TMenuItem; begin inherited Create('Menu.jpg'); for I := miTavern to miQuit do begin Buttons[I] := TButton.Create; Buttons[I].Width := BUTTON_WIDTH; Buttons[I].Height := BUTTON_HEIGHT; T := (SCREEN_HEIGHT div 2) - ((System.Length(Buttons) * (BUTTON_HEIGHT + 5)) div 2); Buttons[I].Top := T + ((Ord(I) - 1) * (BUTTON_HEIGHT + 5)); Buttons[I].Left := SCREEN_WIDTH - (BUTTON_WIDTH + 30); Buttons[I].Caption := MenuCaption[I]; Buttons[I].FontColorOver := ColorYellow(); Buttons[I].FontColorDefault := ColorGrey(); Buttons[I].FontColorSellected := ColorOrange(); if (I = miTavern) then Buttons[I].Sellected := True; end; end; destructor TSceneMainMenu.Destroy; var I: TMenuItem; begin for I := miTavern to miQuit do Buttons[I].Free; inherited; end; procedure TSceneMainMenu.Render; var I: TMenuItem; begin inherited; for I := miTavern to miQuit do Buttons[I].Render; TextOut(0, 0, Round(MousePos.X), Color4(0, 0, 0, 255)); TextOut(0, 20, Round(MousePos.Y), Color4(0, 0, 0, 255)); TextOut(100, 100, 'Hi all!!!', Color4(0, 0, 255, 255)); end; procedure TSceneMainMenu.Update; var I: TMenuItem; begin for I := miTavern to miQuit do begin Buttons[I].Update; if Buttons[I].Click then begin SellectButton(I); UseButton(I); end; end; end; procedure TSceneMainMenu.UseButton(I: TMenuItem); begin case I of miTavern: begin SceneMan.Scene := SceneGame; end; miAbout: begin SceneMan.Scene := SceneAbout; end; miQuit: begin pEngineCore.QuitEngine(); end; end; end; end.
unit uhttpdownload; {$mode objfpc}{$H+} { **************************************************************************** uhttpdownload Unit Threaded download with progress details using Synapse Library (c) 2016 by Dio Affriza under BSD License See the file LICENSE.txt, included in this distribution, for details about the copyright. **************************************************************************** } interface uses Classes, SysUtils, FileUtil, httpsend, blcksock, typinfo, Math, Dialogs, ssl_openssl_lib, ssl_openssl; type THTTPDownloader = class; TNoPresizeFileStream = class(TFileStream) procedure SetSize(const NewSize: int64); override; end; TOnReadyEvent = procedure(Sender: TObject; AMsg: string; ABytes, AMaxBytes: longint) of object; THTTPDownloadThread = class(TThread) public constructor Create(Owner: THTTPDownloader; URL, TargetFile, RqRangeVal: string; fOnReady: TOnReadyEvent); protected procedure Execute; override; private ffOwner: THTTPDownloader; ffOnReady: TOnReadyEvent; ffValue, ffRqRange: string; Bytes, MaxBytes: longint; fURL, fTargetFile: string; exitd: boolean; procedure Ready; end; THTTPDownloader = class(TComponent) private DownloadThread: THTTPDownloadThread; fOnReady: TOnReadyEvent; fStarted: boolean; fRqRange: string; fFileName, fURL: string; // Variables just like a drops of a shit. But this is Pascal // Only look at top declaration to see all variables procedure setURL(Value: string); procedure setFileName(Value: string); procedure setRqRange(Value: string); public constructor Create(AOwner: TComponent); override; procedure Start; procedure Stop; published property OnReady: TOnReadyEvent read fOnReady write fOnReady; property URL: string read fURL write setURL; property FileName: string read fFileName write setFileName; property RqRange: string read fRqRange write setRqRange; end; implementation procedure Split(const Delimiter: char; Input: string; const Strings: TStrings); begin Assert(Assigned(Strings)); Strings.Clear; Strings.StrictDelimiter := True; Strings.Delimiter := Delimiter; Strings.DelimitedText := Input; end; procedure TNoPresizeFileStream.SetSize(const NewSize: int64); begin end; // Downloader Component Class constructor THTTPDownloader.Create(AOwner: TComponent); begin inherited Create(AOwner); fRqRange := '0-0'; end; procedure THTTPDownloader.setRqRange(Value: string); begin if Value = '' then fRqRange := '0-0' else fRqRange := Value; end; procedure THTTPDownloader.setURL(Value: string); begin fURL := Value; end; procedure THTTPDownloader.setFileName(Value: string); begin fFileName := Value; end; procedure THTTPDownloader.Start; begin if not fStarted then DownloadThread := THttpDownloadThread.Create(Self, fURL, fFileName, fRqRange, fOnReady); DownloadThread.Start; end; procedure THTTPDownloader.Stop; begin DownloadThread.Terminate; DownloadThread.WaitFor; end; // Thread of Downloads procedure THTTPDownloadThread.Execute; var HTTPGetResult: boolean; RangeInf: TStringList; i: integer; s: string; Result: boolean; HTTPSender: THTTPSend; HEADResult: longint; Buffer: TNoPreSizeFileStream; begin RangeInf := TStringList.Create; split('-', ffRqRange, RangeInf); Result := False; Bytes := 0; MaxBytes := -1; exitd := False; HTTPSender := THTTPSend.Create; HTTPSender.UserAgent:=''; ffValue := 'Sending HEAD'; Synchronize(@Ready); HTTPSender.Sock.CreateWithSSL(TSSLOpenSSL); HTTPSender.Sock.SSLDoConnect; HTTPGetResult := HTTPSender.HTTPMethod('HEAD', fURL); for i := 0 to HTTPSender.Headers.Count - 1 do begin s := UpperCase(HTTPSender.Headers[i]); if pos('CONTENT-LENGTH:', s) > 0 then MaxBytes := StrToIntDef(copy(s, pos(':', s) + 1, length(s)), 0); end; HEADResult := HTTPSender.ResultCode; if (HEADResult >= 300) and (HEADResult <= 399) then begin showmessage('redirection'+#13+ 'Not implemented, but could be.'); exitd := true; end else if (HEADResult >= 500) and (HEADResult <= 599) then begin showmessage('internal server error'+#13+ 'When you use HTTPS, try change to HTTP'); exitd := true; end; HTTPSender.Free; ffValue := 'Sending GET'; Synchronize(@Ready); if exitd = false then repeat HTTPSender := THTTPSend.Create; HTTPSender.UserAgent:=''; HTTPSender.Sock.CreateWithSSL(TSSLOpenSSL); HTTPSender.Sock.SSLDoConnect; if not FileExists(fTargetFile) then begin Buffer := TNoPreSIzeFileStream.Create(fTargetFile, fmCreate); end else begin Buffer := TNoPreSIzeFileStream.Create(fTargetFile, fmOpenReadWrite); if not exitd then Buffer.Seek(Max(0, Buffer.Size - 4096), soFromBeginning); end; try if ffRqRange = '0-0' then HTTPSender.RangeStart := Buffer.Position else HTTPSender.RangeStart := StrToInt(RangeInf[0]); if ffRqRange = '0-0' then begin if not (Buffer.Size + 50000 >= MaxBytes) then HTTPSender.RangeEnd := Buffer.Size + 50000 else HTTPSender.RangeEnd := Buffer.Size + (MaxBytes - Buffer.Size); HTTPGetResult := HTTPSender.HTTPMethod('GET', fURL); end else begin if not (Buffer.Size + 50000 >= StrToInt(RangeInf[1])) then HTTPSender.RangeEnd := Buffer.Size + 50000 else HTTPSender.RangeEnd := Buffer.Size + (StrToInt(RangeInf[1]) - Buffer.Size); HTTPGetResult := HTTPSender.HTTPMethod('GET', fURL); end; if buffer.Size < MaxBytes then exitd := False else exitd := True; if (HTTPSender.ResultCode >= 100) and (HTTPSender.ResultCode <= 299) then begin HTTPSender.Document.SaveToStream(buffer); Result := True; end; finally Bytes := buffer.Position; HTTPSender.Free; buffer.Free; end; ffValue := 'Downloading'; Synchronize(@Ready); until exitd or terminated; RangeInf.Free; if Result = True then ffValue := 'OK' else ffValue := 'Download failed'; Synchronize(@Ready); end; constructor THTTPDownloadThread.Create(Owner: THTTPDownloader; URL, TargetFile, RqRangeVal: string; fOnReady: TOnReadyEvent); begin fURL := URL; fTargetFile := TargetFile; inherited Create(True); ffOwner := Owner; ffRqRange := RqRangeVal; Priority := tpHigher; Suspended := False; ffOnReady := fOnReady; FreeOnTerminate := True; end; procedure THTTPDownloadThread.Ready; begin if Assigned(ffOnReady) then ffOnReady(Self, ffValue, Bytes, MaxBytes); end; end.
{$include lem_directives.inc} unit LemGraphicSet; interface uses Classes, GR32, LemTypes, LemMetaObject, LemMetaTerrain; type TBaseGraphicSetClass = class of TBaseGraphicSet; TBaseGraphicSet = class(TPersistent) private protected fGraphicSetId : Integer; // number identifier fGraphicSetIdExt : Integer; // extended graphics identifier fGraphicSetName : string; // string identifier fDescription : string; // displayname fMetaObjects : TMetaObjects; fMetaTerrains : TMetaTerrains; fTerrainBitmaps : TBitmaps; fObjectBitmaps : TBitmaps; fSpecialBitmap : TBitmap32; procedure SetMetaObjects(Value: TMetaObjects); virtual; procedure SetMetaTerrains(Value: TMetaTerrains); virtual; { dynamic creation } function DoCreateMetaObjects: TMetaObjects; dynamic; function DoCreateMetaTerrains: TMetaTerrains; dynamic; { these must be overridden } procedure DoReadMetaData; dynamic; abstract; procedure DoReadData; dynamic; abstract; procedure DoClearMetaData; dynamic; procedure DoClearData; dynamic; public constructor Create; virtual; destructor Destroy; override; procedure ReadMetaData; procedure ReadData; procedure ClearMetaData; procedure ClearData; property TerrainBitmaps: TBitmaps read fTerrainBitmaps; property ObjectBitmaps: TBitmaps read fObjectBitmaps; property SpecialBitmap: TBitmap32 read fSpecialBitmap; published property Description: string read fDescription write fDescription; property GraphicSetId: Integer read fGraphicSetId write fGraphicSetId; property GraphicSetIdExt: Integer read fGraphicSetIdExt write fGraphicSetIdExt; property GraphicSetName: string read fGraphicSetName write fGraphicSetName; property MetaObjects: TMetaObjects read fMetaObjects write SetMetaObjects; property MetaTerrains: TMetaTerrains read fMetaTerrains write SetMetaTerrains; end; implementation { TBaseGraphicSet } procedure TBaseGraphicSet.ClearData; begin DoClearData; end; procedure TBaseGraphicSet.ClearMetaData; begin DoClearMetaData; end; constructor TBaseGraphicSet.Create; begin inherited Create; fMetaObjects := DoCreateMetaObjects; fMetaTerrains := DoCreateMetaTerrains; fTerrainBitmaps := TBitmaps.Create; fObjectBitmaps := TBitmaps.Create; fSpecialBitmap := TBitmap32.Create; end; destructor TBaseGraphicSet.Destroy; begin fMetaObjects.Free; fMetaTerrains.Free; fTerrainBitmaps.Free; fObjectBitmaps.Free; fSpecialBitmap.Free; inherited Destroy; end; procedure TBaseGraphicSet.DoClearData; begin fGraphicSetId := 0; fGraphicSetIdExt := 0; fGraphicSetName := ''; fDescription := ''; fTerrainBitmaps.Clear; fObjectBitmaps.Clear; fSpecialBitmap.SetSize(0, 0); end; procedure TBaseGraphicSet.DoClearMetaData; begin fMetaObjects.Clear; fMetaTerrains.Clear; end; function TBaseGraphicSet.DoCreateMetaObjects: TMetaObjects; begin Result := TMetaObjects.Create; end; function TBaseGraphicSet.DoCreateMetaTerrains: TMetaTerrains; begin Result := TMetaTerrains.Create; end; procedure TBaseGraphicSet.ReadData; begin DoReadData; end; procedure TBaseGraphicSet.ReadMetaData; begin DoReadMetaData; end; procedure TBaseGraphicSet.SetMetaObjects(Value: TMetaObjects); begin fMetaObjects.Assign(Value); end; procedure TBaseGraphicSet.SetMetaTerrains(Value: TMetaTerrains); begin fMetaTerrains.Assign(Value); end; end.
{$I ok_sklad.inc} unit BankPersonsEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ExtCtrls, StdCtrls, cxButtons, ssFormStorage, ActnList, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, ssMemDS, ssBaseIntfDlg, ssBevel, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, xButton; type TfrmBankPersonsEdit = class(TfrmBaseIntfDlg) FormStorage: TssFormStorage; panMain: TPanel; ssBevel2: TssBevel; lName: TLabel; edName: TcxTextEdit; lJob: TLabel; edJob: TcxTextEdit; lPhone: TLabel; edPhone: TcxTextEdit; lEMail: TLabel; edEMail: TcxTextEdit; memNotes: TcxMemo; lNotes: TLabel; procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure DataModified(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private FOnDate: TDateTime; FModified: boolean; protected FParentName: string; FID: integer; procedure SetID(const Value: integer); procedure SetParentName(const Value: string); procedure SetOnDate(const Value: TDateTime); procedure DoCreate; override; public MainHandle: HWND; mdC: TssMemoryData; UseMemDS: boolean; PID: integer; property ParentNameEx: string read FParentName write SetParentName; property ID: integer read FID write SetID; property OnDate: TDateTime read FOnDate write SetOnDate; procedure SetCaptions; end; var frmBankPersonsEdit: TfrmBankPersonsEdit; implementation uses prConst, prFun, DB, ssBaseConst, ssClientDataSet, DBClient, ClientData, Udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} { TBaseDlg } //============================================================================================== procedure TfrmBankPersonsEdit.SetOnDate(const Value: TDateTime); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.SetOnDate') else _udebug := nil;{$ENDIF} FOnDate := Value; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.SetParentName(const Value: string); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.SetParentName') else _udebug := nil;{$ENDIF} FParentName := Value; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.SetCaptions') else _udebug := nil;{$ENDIF} aOk.Caption := rs(Self.Name,'OK'); aCancel.Caption := rs(Self.Name,'Cancel'); aApply.Caption := rs(Self.Name,'Apply'); lName.Caption := rs(Self.Name,'FIO'); lJob.Caption := rs(Self.Name,'Job'); lPhone.Caption := rs(Self.Name,'Phone'); lEMail.Caption := rs(Self.Name,'EMail'); lNotes.Caption := rs(Self.Name,'Notes'); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.DoCreate; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.DoCreate') else _udebug := nil;{$ENDIF} inherited; FormStorage.IniFileName := PrRegKey; FormStorage.IniSection := Self.Name; FormStorage.Active := True; //SetStyle(Self, IStyle); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.ActionListUpdate') else _udebug := nil;{$ENDIF} aOk.Enabled := (Trim(edName.Text)<>EmptyStr); aApply.Enabled := aOk.Enabled and FModified and (ID=0); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.SetID(const Value: integer); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmBankPersonsEdit.SetID') else _udebug := nil;{$ENDIF} FID := Value; if Value <> 0 then begin panTitleBar.Caption := rs(Self.Name,'PersonProps'); aApply.Enabled := False; end else panTitleBar.Caption := rs(Self.Name,'NewPerson'); if UseMemDS then begin if Value <> 0 then begin edName.Text := mdC.fieldbyname('name').AsString; edPhone.Text := mdC.fieldbyname('phone').AsString; edEMail.Text := mdC.fieldbyname('email').AsString; edJob.Text := mdC.fieldbyname('job').AsString; memNotes.Text := mdC.fieldbyname('notes').AsString; end; end else begin if Value <> 0 then begin with newDataset do try ProviderName := 'pBankPersons_Get'; FetchParams; Params.ParamByName('personid').AsInteger := Value; Open; edName.Text := fieldbyname('name').AsString; edPhone.Text := fieldbyname('phone').AsString; edEMail.Text := fieldbyname('email').AsString; edJob.Text := fieldbyname('job').AsString; memNotes.Text := fieldbyname('notes').AsString; Close; finally Free; end; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmBankPersonsEdit.DataModified(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.DataModified') else _udebug := nil;{$ENDIF} FModified := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmBankPersonsEdit.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var Maxx: integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmBankPersonsEdit.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrYes, mrOK] then begin CanClose := False; if UseMemDS then begin if ID = 0 then mdC.Append else mdC.Edit; mdC.FieldByName('name').AsString := edName.Text; mdC.FieldByName('phone').AsString := edPhone.Text; mdC.FieldByName('job').AsString := edJob.Text; mdC.FieldByName('email').AsString := edEMail.Text; mdC.FieldByName('notes').AsString := memNotes.Text; mdC.Post; end else with newDataset do try if ID = 0 then begin ProviderName := 'pBankPersons_Max'; Open; Maxx := Fields[0].AsInteger+1; Close; end else Maxx := ID; if ID = 0 then ProviderName := 'pBankPersons_Ins' else ProviderName := 'pBankPersons_Upd'; FetchParams; Params.ParamByName('personid').AsInteger := Maxx; Params.ParamByName('bankid').AsInteger := PID; Params.ParamByName('name').AsString := edName.Text; Params.ParamByName('phone').AsString := edPhone.Text; Params.ParamByName('email').AsString := edEMail.Text; Params.ParamByName('job').AsString := edJob.Text; Params.ParamByName('notes').AsString := memNotes.Text; Execute; SendMessage(MainHandle, WM_REFRESH, Maxx, 1); finally Free; end; if ModalResult = mrOk then CanClose := True else begin edName.Clear; edPhone.Clear; edEMail.Clear; edJob.Clear; memNotes.Clear; edName.SetFocus; end; end; //if ModalResult in [mrYes, mrOK] {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('BankPersonsEdit', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
{ Subroutine SST_R_PAS_IFUNC (SYM, TERM) * * Process an intrinsic function call. SYM is the symbol descriptor for the * intrinsic function. TERM is the expression term descriptor to fill in. * The OP2, OP1, STR_H, and VAL_EVAL fields have already been set or initialized. * This routine needs to fill in the TTYPE field, and the fields specific to * the particular chosen term type. The DTYPE_P, VAL_FND, * VAL, and DTYPE_HARD fields will be inferred later from the other information. * * The syntax position is in the ITEM syntax, and the last tag read was for * VARIABLE right before any possible function arguments. The next tag is * for the function arguments, if any. The syntax position should be left * at the end of the ITEM syntax. } module sst_r_pas_IFUNC; define sst_r_pas_ifunc; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_ifunc ( {process intrinsic function call} in sym: sst_symbol_t; {symbol descriptor for intrinsic function} in out term: sst_exp_term_t); {filled in descriptor for term in expression} const max_msg_parms = 1; {max parameters we can pass to a message} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} n_args: sys_int_machine_t; {number of function arguments found} exp_chain_p: sst_exp_chain_p_t; {points to one link in func args chain} exp_chain_pp: sst_exp_chain_pp_t; {points to current end of func args chain} exp_p: sst_exp_p_t; {scratch pointer to expression descriptor} term_p: sst_exp_term_p_t; {scratch pointer to term in an expression} ele_p: sst_ele_exp_p_t; {points to current set element descriptor} ele_pp: ^sst_ele_exp_p_t; {points to set elements expression chain link} dt_p: sst_dtype_p_t; {scratch pointer to data type} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label loop_arg; { ************************************************************* * * Local subroutine CHECK_ARGS_N (N) * * Check that the number of function arguments matches N. } procedure check_args_n ( in n: sys_int_machine_t); {number of arguments required} begin if n_args = n then return; {no problems ?} sys_msg_parm_int (msg_parm[1], n); syo_error (str_h, 'sst', 'func_intrinsic_args_n_bad', msg_parm, 1); end; { ************************************************************* * * Local subroutine INSERT_EXP (EXP, EXP_CHAIN_P) * * Insert the expression EXP into an expressions chain. EXP_CHAIN_P is the * pointer to the expression just before where EXP is to be inserted. } procedure insert_exp ( in exp: sst_exp_t; {expression to add to chain} in out exp_chain_p: sst_exp_chain_p_t); {chain pointer to start of chain} var chain_p: sst_exp_chain_p_t; {points to new chain link record} begin sst_mem_alloc_scope (sizeof(chain_p^), chain_p); {create new chain link descriptor} chain_p^.exp_p := addr(exp); {point chain link to its expression} chain_p^.next_p := exp_chain_p; {point to next link in chain} exp_chain_p := chain_p; {insert new link in chain} end; { ************************************************************* * * Start of main routine. } begin { * Init the term as if the Pascal intrinsic function maps directly to a * translator intrinsic function (since most do). Since no information is * lost in this process, any functions that don't map directly can be handled * later. } term.ttype := sst_term_ifunc_k; {init to term is an intrinsic function} n_args := 0; {init number of function arguments found} syo_get_tag_msg ( {get function arguments tag} tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); case tag of 1: begin {no function arguments exists here} term.ifunc_args_p := nil; end; 2: begin {function arguments exist within ()} syo_level_down; {down into FUNCTION_ARGUMENTS syntax} exp_chain_pp := addr(term.ifunc_args_p); {init pointer to end of args chain} loop_arg: {back here each new function argument} syo_get_tag_msg ( {get tag for argument expression} tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); case tag of 1: begin {TAG is for new function argument expression} sst_mem_alloc_scope ( {get mem for new link in args chain} sizeof(exp_chain_p^), exp_chain_p); exp_chain_pp^ := exp_chain_p; {add new link to end of chain} exp_chain_p^.next_p := nil; {init new link as end of chain} exp_chain_pp := addr(exp_chain_p^.next_p); {update pointer to end of chain} if sym.front_p^.ifunc = ifunc_addr_k then begin {ADDR function ?} addr_of := true; {indicate we are processing arg to ADDR} end; sst_r_pas_exp (str_h, false, exp_chain_p^.exp_p); {get func arg expression} if sym.front_p^.ifunc = ifunc_addr_k then begin {ADDR function ?} addr_of := false; {done processing ADDR argument} end; n_args := n_args + 1; {count one more function argument} goto loop_arg; {back for next function argument} end; syo_tag_end_k: begin syo_level_up; {back up from FUNCTION_ARGUMENTS syntax} end; otherwise {unexpected tag value in FUNCTION_ARGUMENTS} syo_error_tag_unexp (tag, str_h); end; end; {end of function args exist case} otherwise {unexpected tag value in ITEM syntax} syo_error_tag_unexp (tag, str_h); end; { * TERM has been initialized as an intrinsic function with the function arguments * chain in place. The intrinsic function type has not been set. N_ARGS is * the number of function arguments that were found. } str_h := term.str_h; {save locally so that nested proc can see it} case sym.front_p^.ifunc of {which intrinsic function is this ?} { ******************* } ifunc_abs_k: begin term.ifunc_id := sst_ifunc_abs_k; end; { ******************* } ifunc_addr_k: begin term.ifunc_id := sst_ifunc_addr_k; end; { ******************* } ifunc_arctan_k: begin check_args_n (1); sst_exp_const_float (1.0, exp_p); {add 1.0 as second argument} insert_exp (exp_p^, term.ifunc_args_p^.next_p); term.ifunc_id := sst_ifunc_atan_k; end; { ******************* } ifunc_arshft_k: begin term.ifunc_id := sst_ifunc_shiftr_ar_k; end; { ******************* } ifunc_chr_k: begin term.ifunc_id := sst_ifunc_char_k; end; { ******************* } ifunc_cos_k: begin term.ifunc_id := sst_ifunc_cos_k; end; { ******************* } ifunc_exp_k: begin term.ifunc_id := sst_ifunc_exp_k; end; { ******************* } ifunc_firstof_k: begin term.ifunc_id := sst_ifunc_first_k; end; { ******************* } ifunc_lastof_k: begin term.ifunc_id := sst_ifunc_last_k; end; { ******************* } ifunc_ln_k: begin term.ifunc_id := sst_ifunc_ln_k; end; { ******************* } ifunc_lshft_k: begin term.ifunc_id := sst_ifunc_shiftl_lo_k; end; { ******************* } ifunc_max_k: begin term.ifunc_id := sst_ifunc_max_k; end; { ******************* } ifunc_min_k: begin term.ifunc_id := sst_ifunc_min_k; end; { ******************* * * Pascal intrinsic function ODD. This function returns TRUE if the argument * is odd. The argument must be of type integer. * * This function will be emulated with the expression: * * (arg & 1) <> 0 * * EXP_P will be used to point to the top expression descriptor. TERM_P will * will point to each term in the expression in turn. } ifunc_odd_k: begin check_args_n (1); {must have exactly one argument} sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {allocate top expression descriptor} exp_p^.str_h := term.str_h; exp_p^.val_eval := false; with term.ifunc_args_p^.exp_p^: arg do begin {ARG is exp desc for argument} if arg.term1.next_p = nil then begin {argument expression has only one term} exp_p^.term1 := arg.term1; {argument will be first term in new exp} end else begin {argument expression has more than one term} exp_p^.term1.next_p := nil; exp_p^.term1.op2 := sst_op2_none_k; exp_p^.term1.op1 := sst_op1_none_k; exp_p^.term1.ttype := sst_term_exp_k; exp_p^.term1.str_h := exp_p^.str_h; exp_p^.term1.val_eval := false; exp_p^.term1.exp_exp_p := addr(arg); sst_term_eval (exp_p^.term1, false); end ; {done setting first term in expression} end; {done with ARG abbreviation} sst_mem_alloc_scope (sizeof(term_p^), term_p); {alloc memory for second term} exp_p^.term1.next_p := term_p; term_p^.next_p := nil; term_p^.op2 := sst_op2_btand_k; term_p^.op1 := sst_op1_none_k; term_p^.ttype := sst_term_const_k; term_p^.str_h := term.ifunc_args_p^.exp_p^.str_h; term_p^.dtype_p := sst_dtype_int_max_p; term_p^.dtype_hard := false; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val.dtype := sst_dtype_int_k; term_p^.val.int_val := 1; term_p^.rwflag := [sst_rwflag_read_k]; sst_mem_alloc_scope ( {allocate memory for third term} sizeof(term_p^.next_p^), term_p^.next_p); term_p := term_p^.next_p; {make third term the current term} term_p^.next_p := nil; term_p^.op2 := sst_op2_ne_k; term_p^.op1 := sst_op1_none_k; term_p^.ttype := sst_term_const_k; term_p^.str_h := term.ifunc_args_p^.exp_p^.str_h; term_p^.dtype_p := sst_dtype_int_max_p; term_p^.dtype_hard := false; term_p^.val_eval := true; term_p^.val_fnd := true; term_p^.val.dtype := sst_dtype_int_k; term_p^.val.int_val := 0; term_p^.rwflag := [sst_rwflag_read_k]; sst_exp_eval (exp_p^, false); {evaluate compound expression, if possible} term.ttype := sst_term_exp_k; {term for ifunc value is an expression} term.exp_exp_p := exp_p; {point term to its expression descriptor} end; { ******************* } ifunc_ord_k: begin term.ifunc_id := sst_ifunc_ord_val_k; end; { ******************* } ifunc_pred_k: begin term.ifunc_id := sst_ifunc_dec_k; end; { ******************* } ifunc_round_k: begin term.ifunc_id := sst_ifunc_int_near_k; end; { ******************* } ifunc_rshft_k: begin term.ifunc_id := sst_ifunc_shiftr_lo_k; end; { ******************* } ifunc_sin_k: begin term.ifunc_id := sst_ifunc_sin_k; end; { ******************* } ifunc_sizeof_k: begin term.ifunc_id := sst_ifunc_size_align_k; end; { ******************* } ifunc_sqr_k: begin term.ifunc_id := sst_ifunc_sqr_k; end; { ******************* } ifunc_sqrt_k: begin term.ifunc_id := sst_ifunc_sqrt_k; end; { ******************* } ifunc_succ_k: begin term.ifunc_id := sst_ifunc_inc_k; end; { ******************* } ifunc_trunc_k: begin term.ifunc_id := sst_ifunc_int_zero_k; end; { ******************* } ifunc_xor_k: begin term.ifunc_id := sst_ifunc_xor_k; end; { ******************* } ifunc_alignof_k: begin term.ifunc_id := sst_ifunc_align_k; end; { ******************* } ifunc_arctan2_k: begin term.ifunc_id := sst_ifunc_atan_k; end; { ******************* } ifunc_offset_k: begin term.ifunc_id := sst_ifunc_offset_k; end; { ******************* } ifunc_shift_k: begin term.ifunc_id := sst_ifunc_shift_lo_k; end; { ******************* } ifunc_szchar_k: begin term.ifunc_id := sst_ifunc_size_char_k; end; { ******************* } ifunc_szmin_k: begin term.ifunc_id := sst_ifunc_size_min_k; end; { ******************* } ifunc_val_k: begin check_args_n (1); {must have exatly one argument} if not term.ifunc_args_p^.exp_p^.val_fnd then begin {argument not a known const ?} syo_error (term.ifunc_args_p^.exp_p^.str_h, 'sst', 'exp_not_const_val', nil, 0); end; term.val := term.ifunc_args_p^.exp_p^.val; term.ttype := sst_term_const_k; end; { ******************* * * COG Intrinsic function SETOF. The first argument declares the SET data type, * and the remaining arguments are set element expressions. } ifunc_setof_k: begin exp_chain_p := term.ifunc_args_p; {init pointer to first SETOF argument} if exp_chain_p = nil then begin syo_error (term.str_h, 'sst_pas_read', 'setof_arg1_missing', nil, 0); end; term.dtype_p := exp_chain_p^.exp_p^.dtype_p; {init function's data type} while term.dtype_p^.dtype = sst_dtype_copy_k {resolve base data type} do term.dtype_p := term.dtype_p^.copy_dtype_p; if term.dtype_p^.dtype <> sst_dtype_set_k then begin syo_error (term.str_h, 'sst_pas_read', 'setof_dtype_bad', nil, 0); end; if {specified data type is ambiguous ?} (not exp_chain_p^.exp_p^.dtype_hard) or (not term.dtype_p^.set_dtype_final) then begin syo_error (term.str_h, 'sst_pas_read', 'setof_dtype_ambiguous', nil, 0); end; dt_p := term.dtype_p^.set_dtype_p; {resolve base data type of set elements} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; { * Move the remaining arguments onto set elements expressions chain. } term.set_first_p := nil; {init to no element expressions exist} ele_pp := addr(term.set_first_p); {init pointer to end of elements exp chain} exp_chain_p := exp_chain_p^.next_p; {init pointer to first ifunc arg descriptor} while exp_chain_p <> nil do begin {once for each intrinsic function argument} sst_exp_useage_check ( {check that expression is valid ele value} exp_chain_p^.exp_p^, {expression to check} [sst_rwflag_read_k], {expression must be readable} dt_p^); {must be convertable to base elements dtype} sst_mem_alloc_scope (sizeof(ele_p^), ele_p); {alloc mem for set ele chain desc} ele_p^.next_p := nil; {fill in set descriptor for this set element} ele_p^.first_p := exp_chain_p^.exp_p; ele_p^.last_p := nil; ele_pp^ := ele_p; {link this element expression to chain} ele_pp := addr(ele_p^.next_p); exp_chain_p := exp_chain_p^.next_p; {advance to next intrinsic function argument} end; {back and process this new ifunc arg} term.ttype := sst_term_set_k; {indicate term is a set expression} term.dtype_hard := true; term.val_eval := true; term.val_fnd := false; term.val.dtype := sst_dtype_set_k; term.rwflag := [sst_rwflag_read_k]; end; {end of intrinsic function SETOF} { ******************* } otherwise sys_msg_parm_int (msg_parm[1], ord(sym.front_p^.ifunc)); syo_error (term.str_h, 'sst_pas_read', 'ifunc_unexpected', msg_parm, 1); end; end;
unit IConnectionUnit; interface uses Classes, GenericParametersUnit, DataObjectUnit, UtilsUnit, CommonTypesUnit; type IConnection = interface ['{393B451A-B5C8-4A79-8745-AB0AD2310E9A}'] procedure SetProxy(Host: String; Port: integer; Username, Password: String); function Get(Url: String; Data: TGenericParameters; ResultClassType: TClass; out ErrorString: String): TObject; overload; function Get(Url: String; Data: TGenericParameters; PossibleResultClassType: TClassArray; out ErrorString: String): TObject; overload; function Post(Url: String; Data: TGenericParameters; ResultClassType: TClass; out ErrorString: String): TObject; overload; function Post(Url: String; Data: TGenericParameters; Stream: TStream; ResultClassType: TClass; out ErrorString: String): TObject; overload; function Post(Url: String; Data: TGenericParameters; PossibleResultClassType: TClassArray; out ErrorString: String): TObject; overload; function Put(Url: String; Data: TGenericParameters; ResultClassType: TClass; out ErrorString: String): TObject; function Delete(Url: String; Data: TGenericParameters; ResultClassType: TClass; out ErrorString: String): TObject; end; implementation end.
unit clEmpresaContrato; interface uses clConexao, Vcl.Dialogs, System.SysUtils, clTipoContrato; type TEmpresaContrato = class(TObject) protected FContrato: Integer; FInicio: TDateTime; FEmpresa: Integer; FTermino: TDateTime; conexao: TConexao; tipocontrato: TTipoContrato; private procedure SetEmpresa(val: Integer); procedure SetContrato(val: Integer); procedure SetInicio(val: TDateTime); procedure SetTermino(val: TDateTime); public constructor Create; property Empresa: Integer read FEmpresa write SetEmpresa; property Contrato: Integer read FContrato write SetContrato; property Inicio: TDateTime read FInicio write SetInicio; property Termino: TDateTime read FTermino write SetTermino; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getObjects: Boolean; function getField(sCampo: String; sColuna: String): String; destructor Destroy; override; end; const TABLENAME = 'CAD_EMPRESA_CONTRATO'; implementation uses udm; constructor TEmpresaContrato.Create; begin inherited Create; conexao := TConexao.Create; tipocontrato := TTipoContrato.Create; end; procedure TEmpresaContrato.SetEmpresa(val: Integer); begin FEmpresa := val; end; procedure TEmpresaContrato.SetContrato(val: Integer); begin FContrato := val; end; procedure TEmpresaContrato.SetInicio(val: TDateTime); begin FInicio := val; end; procedure TEmpresaContrato.SetTermino(val: TDateTime); begin FTermino := val; end; function TEmpresaContrato.Validar: Boolean; begin Result := False; if Self.Empresa = 0 then begin MessageDlg('Informe o código da empresa!', mtWarning, [mbCancel], 0); Exit; end; if Self.Contrato = 0 then begin MessageDlg('Informe tipo de contrato da empresa!', mtWarning, [mbCancel], 0); Exit; end else begin if (not tipocontrato.getObject(IntToStr(Self.Contrato),'CODIGO') ) then begin MessageDlg('Código de Tipo de Contrato não cadastrado!', mtWarning, [mbCancel], 0); Exit; end else begin dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; end; end; if Self.Inicio = 0 then begin MessageDlg('Informe a data de início do contrato!', mtWarning, [mbCancel], 0); Exit; end; Result := True; end; function TEmpresaContrato.Insert: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_EMPRESA, ' + 'COD_TIPO_CONTRATO, ' + 'DAT_INICIO, ' + 'DAT_TERMINO) ' + 'VALUES(' + ':CODIGO, ' + ':TIPO, ' + ':INICIO, ' + ':TERMINO)'; ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('TIPO').AsInteger := Self.Contrato; ParamByName('INICIO').AsDate := Self.Inicio; ParamByName('TERMINO').AsDate := Self.Termino; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEmpresaContrato.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_INICIO = :INICIO, ' + 'DAT_TERMINO = :TERMINO ' + 'WHERE COD_EMPRESA = :EMPRESA AND COD_TIPO_CONTRATO = :TIPO'; ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('TIPO').AsInteger := Self.Contrato; ParamByName('INICIO').AsDate := Self.Inicio; ParamByName('TERMINO').AsDate := Self.Termino; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEmpresaContrato.Delete(sFiltro: String): Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Empresa; end else if sFiltro = 'SEQUENCIA' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO AND COD_TIPO_CONTRATO = :TIPO'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('TIPO').AsInteger := Self.Contrato; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEmpresaContrato.getObject(sId: String; sFiltro: String): Boolean; begin try Result := False; if sId.IsEmpty then begin Exit; end; if sFiltro.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(sId); end else if sFiltro = 'TIPO' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO AND COD_TIPO_CONTRATO = :TIPO'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('TIPO').AsInteger := StrToInt(sId); end else if sFiltro = 'INICIO' then begin SQL.Add('WHERE DAT_INICIO = :INICIO'); ParamByName('INICIO').AsDate := StrToDate(sId); end else if sFiltro = 'TERMINO' then begin SQL.Add('WHERE DAT_TERMINO = :TERMINO'); ParamByName('TERMINO').AsDate := StrToDate(sId); end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Self.Empresa := FieldByName('COD_EMPRESA').AsInteger; Self.Contrato := FieldByName('COD_TIPO_CONTRATO').AsInteger; Self.Inicio := FieldByName('DAT_INICIO').AsDateTime; Self.Termino := FieldByName('DAT_TERMINO').AsDateTime; Result := True; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEmpresaContrato.getObjects: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Result := True; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TEmpresaContrato.getField(sCampo: String; sColuna: String): String; begin try Result := ''; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if sColuna = 'CODIGO' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Empresa; end else if sColuna = 'TIPO' then begin SQL.Add('WHERE COD_EMPRESA = :CODIGO AND COD_TIPO_CONTRATO = :TIPO'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('TIPO').AsInteger := Self.Contrato; end else if sColuna = 'INICIO' then begin SQL.Add('WHERE DAT_INICIO = :INICIO'); ParamByName('INICIO').AsDate := Self.Inicio; end else if sColuna = 'TERMINO' then begin SQL.Add('WHERE DAT_TERMINO = :TERMINO'); ParamByName('TERMINO').AsDate := Self.Termino; end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Result := FieldByName(sCampo).AsString; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; destructor TEmpresaContrato.Destroy; begin conexao.Free; tipocontrato.Free; inherited Destroy; end; end.
unit l3Const; {* Константы библиотеки L3. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. } { Модуль: l3Const - } { Начат: 13.04.1998 14:05 } { $Id: l3Const.pas,v 1.28 2011/05/18 17:46:00 lulin Exp $ } // $Log: l3Const.pas,v $ // Revision 1.28 2011/05/18 17:46:00 lulin // {RequestLink:266409354}. // // Revision 1.27 2010/06/02 11:13:59 dinishev // [$216074494] // // Revision 1.26 2010/03/18 14:15:46 lulin // {RequestLink:197951943}. // // Revision 1.25 2009/09/23 13:43:21 dinishev // [$163068489]. Более правильные рабочие константы. // // Revision 1.24 2009/09/23 08:09:04 dinishev // Типа стандартизация и таблицы лучше выглядят. // // Revision 1.23 2007/01/22 15:20:13 oman // - new: Локализация библиотек - l3 (cq24078) // // Revision 1.22 2005/05/26 16:01:48 lulin // - избавил базовую канву вывода от знания о константах Эвереста. // // Revision 1.21 2005/05/24 14:50:09 lulin // - готовим модуль evGraph к переезду в L3. // // Revision 1.20 2005/05/24 13:43:34 lulin // - rename unit: evLineAr -> l3LineArray. // // Revision 1.19 2005/05/24 13:21:57 lulin // - new const: l3Inch. // // Revision 1.18 2001/09/26 14:33:48 law // - cleanup: удалена переменная l3NilVar. // // Revision 1.17 2001/09/26 14:06:59 law // - cleanup: l3NilObject заменен на _l3NilOp. // // Revision 1.16 2001/09/03 09:27:07 law // - bug fix. // // Revision 1.15 2001/09/03 09:21:12 law // - bug fix. // // Revision 1.14 2001/08/31 12:19:58 law // - cleanup: первые шаги к кроссплатформенности. // // Revision 1.13 2001/08/29 07:01:10 law // - split unit: l3Intf -> l3BaseStream, l3BaseDraw, l3InterfacedComponent. // // Revision 1.12 2000/12/15 15:19:00 law // - вставлены директивы Log. // {$I l3Define.inc } interface uses Windows; const l3BitInLong = 32; {* Число бит в целом. } l3ParseBufSize = 32{8} * 1024; l3NotFound = -1; {* Признак ненайденной подстроки. } const l3NilLong = High(Longint); {* NULL для целых. } l3Inch = 1440; {* Дюйм. } l3mmInInch = 254; {* - число сантиметров в дюйме. } l3FontIndexDelta = l3Inch div 16; {-} l3Epsilon = l3Inch div 120; {* - предел точности. } l3AlingDelta = l3Epsilon * 7; { Велчина выравнивания (значения отличающиеся на меньшую по модулю велчину считаются равными). } l3ShapeNil = Low(Longint) div 2; {* - NULL для координат рисуемых объектов. } const S_Ok = Windows.S_Ok; {* Успешное завершение. } S_False = Windows.S_False; {* Неуспешное завершение. } E_NoInterface = Windows.E_NoInterface; {* Интерфейс не поддерживается. } E_ClassNotAvailable = Windows.CLASS_E_CLASSNOTAVAILABLE; {* Класс недоступен. } E_Fail = Windows.E_Fail; {-} {$IfNDef Delphi6} E_UNEXPECTED = Windows.E_UNEXPECTED; {-} E_NOTIMPL = Windows.E_NOTIMPL; {-} {$EndIf Delphi6} {Коды клавиш} VK_ALT = VK_MENU; resourcestring l3ErrSeekPastEOF = 'Seek past EOF'; l3ErrSeekError = 'Seek error'; l3ErrPutbackOverflow = 'Putback overflow'; l3ErrInvalidOrigin = 'Invalid origin in seek method'; l3NULLStr = '<NULL>'; implementation end.
{ Invokable interface ISoapFish } unit SoapFishIntf; interface uses InvokeRegistry, Types, XSBuiltIns; type { Invokable interfaces must derive from IInvokable } ISoapFish = interface(IInvokable) ['{4E4C57BF-4AC9-41C2-BB2A-64BCE470D450}'] function GetCds: TSoapAttachment; stdcall; function GetImage(fishName: string): TSoapAttachment; stdcall; end; implementation initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(ISoapFish)); end.
unit nsLanguageMap; {* реализация мапы "строка"-"строка" } // $Log: nsLanguageMap.pas,v $ // Revision 1.8 2013/10/25 07:21:22 morozov // {RequestLink: 495815045} // // Revision 1.7 2013/10/25 07:15:34 morozov // {RequestLink: 495815045} // // Revision 1.6 2013/04/25 13:21:02 morozov // {$RequestLink:363571639} // // Revision 1.5 2009/02/20 12:25:12 lulin // - <K>: 136941122. // // Revision 1.4 2009/02/10 15:43:25 lulin // - <K>: 133891247. Выделяем интерфейсы локализации. // // Revision 1.3 2008/10/02 11:46:43 oman // - fix: Не рисовались на 98 (К-120721126) // // Revision 1.2 2008/10/01 11:54:01 oman // - fix: Меняем раскладку клавиатуры (К-120718336) // // Revision 1.1.2.1 2008/10/01 11:48:33 oman // - fix: Меняем раскладку клавиатуры (К-120718336) // // {$Include nsDefine.inc } interface uses Classes, l3Interfaces, l3BaseWithID, l3ValueMap, l3Types, l3Tree_TLB, l3TreeInterfaces, vcmExternalInterfaces, vcmInterfaces, L10nInterfaces ; type TnsLanguageMap = class(Tl3ValueMap, InsStringValueMap, InsStringsSource) private // Il3IntegerValueMap function DisplayNameToValue(const aDisplayName: Il3CString): Il3CString; function ValueToDisplayName(const aValue: Il3CString): Il3CString; // InsStringsSource procedure FillStrings(const aStrings: IvcmStrings); protected procedure DoGetDisplayNames(const aList: Il3StringsEx); override; function GetMapSize: Integer; override; public class function Make(const aID: TnsValueMapID): InsStringValueMap; end;//TnsLanguageMap implementation uses SysUtils, Windows, l3Base, l3String, l3Nodes, afwFacade, vcmBase, nsValueMapsIDs, nsValueMaps, SystemStr ; { TnsStringValueMap } function TnsLanguageMap.DisplayNameToValue(const aDisplayName: Il3CString): Il3CString; {-} begin Result := l3CStr(li_il_Russian); end; procedure TnsLanguageMap.FillStrings(const aStrings: IvcmStrings); begin aStrings.Clear; aStrings.Add(ValueToDisplayName(nil)); end; procedure TnsLanguageMap.DoGetDisplayNames(const aList: Il3StringsEx); begin aList.Clear; aList.Add(ValueToDisplayName(nil)); end; function TnsLanguageMap.GetMapSize: Integer; begin Result := 1; end; function TnsLanguageMap.ValueToDisplayName(const aValue: Il3CString): Il3CString; function lp_FiltrateStr(const aString: WideString): WideString; const cTerminatingZeroCharW : WideChar = #0; var l_Index: Integer; begin l_Index := 1; for l_Index := 1 to Length(aString) do if (aString[l_Index] <> cTerminatingZeroCharW) then Result := Result + aString[l_Index] else Exit; end;//lp_FiltrateStr const // Константа для Vista+ вместо LOCALE_SLANGUAGE LC_LOCALE_SLOCALIZEDLANGUAGENAME = $0000006f; // Константа для W7+ вместо LOCALE_SNATIVELANGNAME LC_LOCALE_SNATIVELANGUAGENAME = $00000004; var l_Size: Cardinal; l_Locale: LCID; l_UnicodeText: WideString; l_Text: String; l_FlagLangFullLocalized, l_FlagLangNative: LCTYPE; l_WindowsVersion: DWORD; l_AnsiText : String; begin l_Locale := afw.Application.LocaleInfo.ID; if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then begin l_Size := GetLocaleInfoA(l_Locale, LOCALE_SLANGUAGE, nil, 0); SetLength(l_Text, l_Size + 1); GetLocaleInfoA(l_Locale, LOCALE_SNATIVELANGNAME , PAnsiChar(l_Text), l_Size); Result := l3CStr(l_Text); end else begin // В W7 GetLocaleInfoW с флагом LOCALE_SLANGUAGE возвращает неверное // число символов для названия языка (в 2 раза больше) - K363571639 // LOCALE_SLANGUAGE - deprecated в Vista и выше l_WindowsVersion := GetVersion; l_FlagLangNative := LOCALE_SNATIVELANGNAME; if (LOBYTE(LOWORD(l_WindowsVersion)) >= 6) then begin l_FlagLangFullLocalized := LC_LOCALE_SLOCALIZEDLANGUAGENAME; // В W7 и выше LOCALE_SNATIVELANGNAME - deprecated if (HIBYTE(LOWORD(l_WindowsVersion)) >= 1) then l_FlagLangNative := LC_LOCALE_SNATIVELANGUAGENAME; end else l_FlagLangFullLocalized := LOCALE_SLANGUAGE; l_Size := GetLocaleInfoW(l_Locale, l_FlagLangFullLocalized, nil, 0); SetLength(l_UnicodeText, l_Size); GetLocaleInfoW(l_Locale, l_FlagLangNative, PWideChar(l_UnicodeText), l_Size); // MSDN: If the function succeeds and the value of cchData is 0, // the return value is the required size, in characters including a null // character, for the locale data buffer. // - а вот и нет. Возвращает GetLocaleInfo на W7 упорно размер в байтах, на XP - // в символах. // http://mdp.garant.ru/pages/viewpage.action?pageId=495815045 l_AnsiText := lp_FiltrateStr(l_UnicodeText); Result := l3CStr(l_AnsiText); end; end; class function TnsLanguageMap.Make(const aID: TnsValueMapID): InsStringValueMap; var l_Map: TnsLanguageMap; begin l_Map := Create(aID); try Result := l_Map; finally vcmFree(l_Map); end; end; end.
{ *************************************************************************** Copyright (c) 2015-2022 Kike Pérez Unit : Quick.JSON.Serializer Description : Json Serializer Author : Kike Pérez Version : 1.12 Created : 21/05/2018 Modified : 17/05/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** 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 Quick.Json.Serializer; {$i QuickLib.inc} interface uses {$IFDEF DEBUG_SERIALIZER} Quick.Debug.Utils, {$ENDIF} Classes, SysUtils, Rtti, TypInfo, Quick.Serializer.Intf, Quick.Base64, {$IFDEF FPC} rttiutils, fpjson, jsonparser, strUtils, //jsonreader, //fpjsonrtti, Quick.Json.fpc.Compatibility, {$ELSE} {$IFDEF DELPHIXE7_UP} System.Json, {$ELSE} Data.DBXJSON, {$ENDIF} {$IFDEF DELPHIRX10_UP} {$ENDIF} Variants, {$ENDIF} Generics.Collections, Quick.RTTI.Utils, DateUtils, Quick.Commons, Quick.JSON.Utils; type IJsonSerializer = ISerializer; EJsonSerializeError = class(Exception); EJsonDeserializeError = class(Exception); {$IFNDEF FPC} TNotSerializableProperty = class(TCustomAttribute); TCommentProperty = class(TCustomAttribute) private fComment : string; public constructor Create(const aComment: string); property Comment : string read fComment; end; TSerializerOptions = Quick.Serializer.Intf.TSerializerOptions; TCustomNameProperty = class(TCustomAttribute) private fName : string; public constructor Create(const aName: string); property Name : string read fName; end; {$IFNDEF DELPHIXE7_UP} TJSONArrayHelper = class helper for Data.DBXJson.TJSONArray private function GetItem(aValue : Integer) : TJSONValue; public function Count : Integer; property Items[index : Integer] : TJSONValue read GetItem; procedure SetElements(aElements : TList<TJSONValue>); end; TJSONValueHelper = class helper for Data.DBXJson.TJSONValue public function ToJson : string; end; TJSONObjectHelper = class helper for Data.DBXJson.TJSONObject private function GetPair(aValue : Integer) : TJSONPair; public function Count : Integer; function GetValue(const aName : string) : TJSONValue; property Pairs[index : Integer] : TJSONPair read GetPair; end; {$ENDIF} {$ENDIF} TSerializeLevel = (slPublicProperty, slPublishedProperty); TRTTIJson = class type TGenericListType = (gtNone, gtList, gtObjectList); private fSerializeLevel : TSerializeLevel; fUseEnumNames : Boolean; fUseJsonCaseSense : Boolean; fUseBase64Stream : Boolean; fUseNullStringsAsEmpty : Boolean; fUseGUIDWithBrackets : Boolean; fUseGUIDLowercase : Boolean; fOptions : TSerializerOptions; function GetValue(aAddr: Pointer; aType: TRTTIType): TValue; overload; {$IFDEF FPC} function GetValue(aAddr: Pointer; aTypeInfo: PTypeInfo): TValue; overload; {$ENDIF} function IsAllowedProperty(aObject : TObject; const aPropertyName : string) : Boolean; //function GetPropertyValue(Instance : TObject; const PropertyName : string) : TValue; function GetPropertyValueFromObject(Instance : TObject; const PropertyName : string) : TValue; {$IFNDEF FPC} function GetFieldValueFromRecord(const aValue : TValue; const FieldName : string) : TValue; {$ENDIF} {$IFDEF FPC} procedure SetPropertyValue(Instance : TObject; aPropInfo : PPropInfo; aValue : TValue); overload; procedure SetPropertyValue(Instance : TObject; const PropertyName : string; aValue : TValue); overload; function FloatProperty(aObject : TObject; aPropInfo: PPropInfo): string; function GetPropType(aPropInfo: PPropInfo): PTypeInfo; procedure LoadSetProperty(aInstance : TObject; aPropInfo: PPropInfo; const aValue: string); {$ENDIF} {$IFNDEF FPC} function CreateInstance(aClass: TClass): TValue; overload; function CreateInstance(aType: TRttiType): TValue; overload; {$ENDIF} function GUIDToStringFormated(const aGUID : TGUID) : string; public constructor Create(aSerializeLevel : TSerializeLevel; aUseEnumNames : Boolean = True); destructor Destroy; override; property UseEnumNames : Boolean read fUseEnumNames write fUseEnumNames; property UseJsonCaseSense : Boolean read fUseJsonCaseSense write fUseJsonCaseSense; property UseBase64Stream : Boolean read fUseBase64Stream write fUseBase64Stream; property UseNullStringsAsEmpty : Boolean read fUseNullStringsAsEmpty write fUseNullStringsAsEmpty; property UseGUIDWithBrackets : Boolean read fUseGUIDWithBrackets write fUseGUIDWithBrackets; property UseGUIDLowercase : Boolean read fUseGUIDLowercase write fUseGUIDLowercase; property Options : TSerializerOptions read fOptions write fOptions; function GetJsonPairValueByName(aJson : TJSONObject; const aName : string) : TJsonValue; function GetJsonPairByName(aJson : TJSONObject; const aName : string) : TJSONPair; function IsGenericList(aObject : TObject) : Boolean; function IsStream(aObject : TObject) : Boolean; function IsGenericXArray(const aClassName : string) : Boolean; function GetGenericListType(aObject : TObject) : TGenericListType; //serialize methods function SerializeValue(const aValue : TValue) : TJSONValue; function SerializeObject(aObject : TObject) : TJSONObject; overload; function SerializeStream(aObject : TObject) : TJSONValue; {$IFNDEF FPC} function SerializeDynArray(const aValue: TValue; aMaxElements : Integer = -1) : TJsonArray; function SerializeRecord(const aValue : TValue) : TJSONValue; {$ELSE} function SerializeObject(aObject : TObject; aType : TTypeKind; const aPropertyName : string) : TJSONPair; {$ENDIF} //deserialize methods function DeserializeClass(aType : TClass; const aJson : TJSONObject) : TObject; function DeserializeObject(aObject : TObject; const aJson : TJSONObject) : TObject; overload; function DeserializeProperty(aObject : TObject; const aName : string; aProperty : TRttiProperty; const aJson : TJSONObject) : TObject; overload; function DeserializeStream(aObject : TObject; const aJson : TJSONValue) : TObject; {$IFNDEF FPC} function DeserializeType(aObject : TObject; aType : TTypeKind; aTypeInfo : PTypeInfo; const aValue: string) : TValue; function DeserializeDynArray(aTypeInfo : PTypeInfo; aObject : TObject; const aJsonArray: TJSONArray) : TValue; function DeserializeRecord(const aRecord : TValue; aObject : TObject; const aJson : TJSONObject) : TValue; function DeserializeList(aObject: TObject; const aName : string; const aJson: TJSONObject) : TObject; procedure DeserializeXArray(Instance : TObject; aRecord : TValue; aProperty : TRttiProperty; const aPropertyName : string; aJson : TJsonObject); {$ELSE} function DeserializeType(aObject : TObject; aType : TTypeKind; const aPropertyName, aValue: string) : TValue; procedure DeserializeDynArray(aTypeInfo: PTypeInfo; const aPropertyName : string; aObject: TObject; const aJsonArray: TJSONArray); {$ENDIF} end; TJsonSerializer = class(TInterfacedObject,IJsonSerializer) strict private fSerializeLevel : TSerializeLevel; fUseEnumNames : Boolean; fUseJsonCaseSense : Boolean; fUseBase64Stream : Boolean; fUseNullStringsAsEmpty : Boolean; fUseGUIDWithBrackets: Boolean; fUseGUIDLowercase: Boolean; fRTTIJson : TRTTIJson; private procedure SetUseEnumNames(const Value: Boolean); procedure SetUseJsonCaseSense(const Value: Boolean); procedure SetSerializeLevel(const Value: TSerializeLevel); procedure SetUseBase64Stream(const Value: Boolean); //Only Delphi -> Workaround, use this when something passes : {Test : "Null"} but we expect : {Test : ""} procedure SetUseNullStringsAsEmpty(const Value : Boolean); procedure SetUseGUIDLowerCase(const Value: Boolean); procedure SetUseGUIDWithBrackets(const Value: Boolean); public constructor Create(aSerializeLevel: TSerializeLevel; aUseEnumNames : Boolean = True; aUseNullStringsAsEmpty : Boolean = False); destructor Destroy; override; property SerializeLevel : TSerializeLevel read fSerializeLevel write SetSerializeLevel; property UseEnumNames : Boolean read fUseEnumNames write SetUseEnumNames; property UseJsonCaseSense : Boolean read fUseJsonCaseSense write SetUseJsonCaseSense; property UseBase64Stream : Boolean read fUseBase64Stream write SetUseBase64Stream; property UseNullStringsAsEmpty : Boolean read fUseNullStringsAsEmpty write SetUseNullStringsAsEmpty; property UseGUIDWithBrackets : Boolean read fUseGUIDWithBrackets write SetUseGUIDWithBrackets; property UseGUIDLowerCase : Boolean read fUseGUIDLowercase write SetUseGUIDLowerCase; function JsonToObject(aType : TClass; const aJson: string) : TObject; overload; function JsonToObject(aObject : TObject; const aJson: string) : TObject; overload; function JsonStreamToObject(aObject : TObject; aJsonStream : TStream) : TObject; function ObjectToJson(aObject : TObject; aIndent : Boolean = False): string; function ObjectToJsonString(aObject : TObject; aIndent : Boolean = False): string; procedure ObjectToJsonStream(aObject : TObject; aStream : TStream); function ValueToJson(const aValue : TValue; aIndent : Boolean = False) : string; function ValueToJsonString(const aValue : TValue; aIndent : Boolean = False) : string; function ArrayToJson<T>(aArray : TArray<T>; aIndent : Boolean = False) : string; function ArrayToJsonString<T>(aArray : TArray<T>; aIndent : Boolean = False) : string; {$IFNDEF FPC} function JsonToArray<T>(const aJson : string) : TArray<T>; function JsonToValue(const aJson: string): TValue; {$ENDIF} function Options : TSerializerOptions; end; EJsonSerializerError = class(Exception); PPByte = ^PByte; resourcestring cNotSupportedDataType = 'Not supported data type "%s"'; cSerializeObjectError = 'Serialize object "%s" error: %s'; cSerializePropertyError = 'Property "%s" ("%s")'; cNotSerializable = 'Object is not serializable'; cNotValidJson = 'Not a valid Json'; implementation { TRTTIJson } {$IFNDEF FPC} function TRTTIJson.DeserializeDynArray(aTypeInfo: PTypeInfo; aObject: TObject; const aJsonArray: TJSONArray) : TValue; var rType: PTypeInfo; len: NativeInt; pArr: Pointer; rItemValue: TValue; i: Integer; objClass: TClass; ctx : TRttiContext; json : TJSONObject; rDynArray : TRttiDynamicArrayType; propObj : TObject; begin if GetTypeData(aTypeInfo).DynArrElType = nil then Exit; if not assigned(aJsonArray) then Exit; len := aJsonArray.Count; rType := GetTypeData(aTypeInfo).DynArrElType^; pArr := nil; DynArraySetLength(pArr,aTypeInfo, 1, @len); try TValue.Make(@pArr,aTypeInfo, Result); rDynArray := ctx.GetType(Result.TypeInfo) as TRTTIDynamicArrayType; for i := 0 to aJsonArray.Count - 1 do begin rItemValue := nil; case rType.Kind of tkClass : begin if aJsonArray.Items[i] is TJSONObject then begin propObj := GetValue(PPByte(Result.GetReferenceToRawData)^ +rDynArray.ElementType.TypeSize * i, rDynArray.ElementType).AsObject; if propObj = nil then begin objClass := rType.TypeData.ClassType; rItemValue := DeserializeClass(objClass, TJSONObject(aJsonArray.Items[i])); end else begin DeserializeObject(propObj,TJSONObject(aJsonArray.Items[i])); end; end; end; tkRecord : begin json := TJSONObject(aJsonArray.Items[i]); rItemValue := DeserializeRecord(GetValue(PPByte(Result.GetReferenceToRawData)^ +rDynArray.ElementType.TypeSize * i, rDynArray.ElementType),aObject,json); end; tkMethod, tkPointer, tkClassRef ,tkInterface, tkProcedure : begin //skip these properties end else begin rItemValue := DeserializeType(aObject,rType.Kind,rType,aJsonArray.Items[i].Value); end; end; if not rItemValue.IsEmpty then Result.SetArrayElement(i,rItemValue); end; //aProperty.SetValue(aObject,rValue); finally DynArrayClear(pArr,aTypeInfo); end; end; {$ELSE} procedure TRTTIJson.DeserializeDynArray(aTypeInfo: PTypeInfo; const aPropertyName : string; aObject: TObject; const aJsonArray: TJSONArray); var rType: PTypeInfo; len: NativeInt; pArr: Pointer; rItemValue: TValue; i: Integer; objClass: TClass; propObj : TObject; rValue : TValue; begin if GetTypeData(aTypeInfo).ElType2 = nil then Exit; len := aJsonArray.Count; rType := GetTypeData(aTypeInfo).ElType2; pArr := nil; DynArraySetLength(pArr,aTypeInfo, 1, @len); try TValue.Make(@pArr,aTypeInfo, rValue); for i := 0 to aJsonArray.Count - 1 do begin rItemValue := nil; case rType.Kind of tkClass : begin if aJsonArray.Items[i] is TJSONObject then begin propObj := GetValue(PPByte(rValue.GetReferenceToRawData)^ +GetTypeData(aTypeInfo).elSize * i, GetTypeData(aTypeInfo).ElType2).AsObject; if propObj = nil then begin objClass := GetTypeData(aTypeInfo).ClassType; rItemValue := DeserializeClass(objClass, TJSONObject(aJsonArray.Items[i])); end else begin DeserializeObject(propObj,TJSONObject(aJsonArray.Items[i])); end; end; end; tkRecord : begin {json := TJSONObject(aJsonArray.Items[i]); rItemValue := DeserializeRecord(GetValue(PPByte(Result.GetReferenceToRawData)^ +rDynArray.ElementType.TypeSize * i, rDynArray.ElementType),aObject,json); } end; tkMethod, tkPointer, tkClassRef ,tkInterface, tkProcedure : begin //skip these properties end else begin rItemValue := DeserializeType(aObject,GetTypeData(aTypeInfo).ElType2.Kind,aPropertyName,aJsonArray.Items[i].Value); end; end; if not rItemValue.IsEmpty then rValue.SetArrayElement(i,rItemValue); end; //aProperty.SetValue(aObject,rValue); SetDynArrayProp(aObject,GetPropInfo(aObject,aPropertyName),pArr); finally DynArrayClear(pArr,aTypeInfo); end; end; {$ENDIF} {$IFNDEF FPC} function TRTTIJson.DeserializeRecord(const aRecord : TValue; aObject : TObject; const aJson : TJSONObject) : TValue; var ctx : TRttiContext; rRec : TRttiRecordType; rField : TRttiField; rValue : TValue; member : TJsonValue; jArray : TJSONArray; json : TJSONObject; objClass : TClass; propobj : TObject; begin rRec := ctx.GetType(aRecord.TypeInfo).AsRecord; for rField in rRec.GetFields do begin rValue := nil; //member := TJSONPair(aJson.GetValue(rField.Name)); member := GetJsonPairValueByName(aJson,rField.Name); if member <> nil then case rField.FieldType.TypeKind of tkDynArray : begin jArray := TJSONObject.ParseJSONValue(member.ToJSON) as TJSONArray; try rValue := DeserializeDynArray(rField.FieldType.Handle,aObject,jArray); finally jArray.Free; end; end; tkClass : begin //if (member.JsonValue is TJSONObject) then begin propobj := rField.GetValue(@aRecord).AsObject; json := TJSONObject.ParseJSONValue(member.ToJson) as TJSONObject; try if propobj = nil then begin objClass := rField.FieldType.Handle^.TypeData.ClassType;// aProperty.PropertyType.Handle^.TypeData.ClassType; rValue := DeserializeClass(objClass,json); end else begin DeserializeObject(propobj,json); end; finally json.Free; end; end end; tkRecord : begin json := TJSONObject.ParseJSONValue(member.ToJson) as TJSONObject; try rValue := DeserializeRecord(rField.GetValue(aRecord.GetReferenceToRawData),aObject,json); finally json.Free; end; end else begin //rValue := DeserializeType(aObject,rField.FieldType.TypeKind,rField.FieldType.Handle,member.ToJson); //avoid return unicode escaped chars if string if rField.FieldType.TypeKind in [tkString, tkLString, tkWString, tkUString] then {$IFDEF DELPHIRX10_UP} rValue := DeserializeType(aObject,rField.FieldType.TypeKind,rField.FieldType.Handle,TJsonValue(member).value) {$ELSE} rValue := DeserializeType(aObject,rField.FieldType.TypeKind,rField.FieldType.Handle,member.Value) {$ENDIF} else rValue := DeserializeType(aObject,rField.FieldType.TypeKind,rField.FieldType.Handle,member.ToJSON); end; end; if not rValue.IsEmpty then rField.SetValue(aRecord.GetReferenceToRawData,rValue); end; Result := aRecord; end; {$ENDIF} function TRTTIJson.DeserializeStream(aObject: TObject; const aJson: TJSONValue): TObject; var stream : TStringStream; begin if fOptions.UseBase64Stream then stream := TStringStream.Create(Base64Decode(aJson.Value),TEncoding.Ansi) else stream := TStringStream.Create({$IFNDEF FPC}aJson.Value{$ELSE}string(aJson.Value){$ENDIF},TEncoding.Ansi); try TStream(aObject).CopyFrom(stream,stream.Size); finally stream.Free; end; Result := aObject; end; constructor TRTTIJson.Create(aSerializeLevel : TSerializeLevel; aUseEnumNames : Boolean = True); begin fOptions := TSerializerOptions.Create; fSerializeLevel := aSerializeLevel; fUseEnumNames := aUseEnumNames; fUseJsonCaseSense := False; fUseBase64Stream := True; fUseGUIDWithBrackets := False; fUseGUIDLowerCase := True; fOptions.UseEnumNames := aUseEnumNames; fOptions.UseJsonCaseSense := False; fOptions.UseBase64Stream := True; fOptions.UseGUIDLowercase := False; fOptions.UseGUIDLowercase := True; end; destructor TRTTIJson.Destroy; begin fOptions.Free; inherited; end; {$IFNDEF FPC} function TRTTIJson.CreateInstance(aClass: TClass): TValue; var ctx : TRttiContext; rtype : TRttiType; begin Result := nil; rtype := ctx.GetType(aClass); Result := CreateInstance(rtype); end; {$ENDIF} {$IFNDEF FPC} function TRTTIJson.CreateInstance(aType: TRttiType): TValue; var rmethod : TRttiMethod; begin Result := nil; if atype = nil then Exit; for rmethod in TRttiInstanceType(atype).GetMethods do begin if rmethod.IsConstructor then begin //create if don't have parameters if Length(rmethod.GetParameters) = 0 then begin Result := rmethod.Invoke(TRttiInstanceType(atype).MetaclassType,[]); Break; end; end; end; end; {$ENDIF} function TRTTIJson.DeserializeClass(aType: TClass; const aJson: TJSONObject): TObject; begin Result := nil; if (aJson = nil) or ((aJson as TJSONValue) is TJSONNull) or (aJson.Count = 0) then Exit; {$IFNDEF FPC} Result := CreateInstance(aType).AsObject; {$ELSE} Result := aType.Create; {$ENDIF} try Result := DeserializeObject(Result,aJson); except on E : Exception do begin Result.Free; raise EJsonDeserializeError.CreateFmt('Deserialize error class "%s" : %s',[aType.ClassName,e.Message]); end; end; end; function TRTTIJson.DeserializeObject(aObject: TObject; const aJson: TJSONObject): TObject; var ctx: TRttiContext; rType: TRttiType; rProp: TRttiProperty; {$IFNDEF FPC} attr: TCustomAttribute; propvalue : TValue; {$ENDIF} propertyname : string; begin Result := aObject; if (aJson = nil) or ((aJson as TJSONValue) is TJSONNull) or (aJson.Count = 0) or (Result = nil) then Exit; try //if generic list {$IFNDEF FPC} if IsGenericList(aObject) then begin DeserializeList(aObject,'List',aJson); Exit; end else {$ENDIF} if IsStream(aObject) then begin DeserializeStream(aObject,aJson); Exit; end; //if standard object rType := ctx.GetType(aObject.ClassInfo); for rProp in rType.GetProperties do begin {$IFNDEF FPC} if ((fSerializeLevel = slPublicProperty) and (rProp.PropertyType.IsPublicType)) or ((fSerializeLevel = slPublishedProperty) and ((IsPublishedProp(aObject,rProp.Name)) or (rProp.Name = 'List'))) then {$ENDIF} begin if ((rProp.IsWritable) or (rProp.Name = 'List')) and (IsAllowedProperty(aObject,rProp.Name)) then begin propertyname := rProp.Name; {$IFNDEF FPC} for attr in rProp.GetAttributes do if attr is TCustomNameProperty then propertyname := TCustomNameProperty(attr).Name; propvalue := rProp.GetValue(aObject); if rProp.Name = 'List' then begin Result := DeserializeList(Result,propertyname,aJson); end else if propvalue.IsObject then begin if propvalue.AsObject = nil then begin propvalue := CreateInstance(rProp.PropertyType); rProp.SetValue(aObject,propvalue); end; if IsGenericList(propvalue.AsObject) then DeserializeList(propvalue.AsObject,'List',TJSONObject(aJson.GetValue(propertyname))) else Result := DeserializeProperty(Result,propertyname,rProp,aJson); end else if IsGenericXArray(string(propvalue{$IFNDEF NEXTGEN}.TypeInfo.Name{$ELSE}.TypeInfo.NameFld.ToString{$ENDIF})) then begin DeserializeXArray(Result,propvalue,rProp,propertyname,aJson); end else {$ENDIF} Result := DeserializeProperty(Result,propertyname,rProp,aJson); end; end; end; except on E : Exception do begin Result.Free; raise EJsonDeserializeError.CreateFmt('Deserialize error for object "%s" : %s',[aObject.ClassName,e.Message]); end; end; end; {$IFNDEF FPC} function TRTTIJson.DeserializeList(aObject: TObject; const aName : string; const aJson: TJSONObject) : TObject; var ctx : TRttiContext; rType : TRttiType; jarray : TJSONArray; member : TJsonValue; rvalue : TValue; i : Integer; n : Integer; rProp : TRttiProperty; {$IFDEF DELPHIRX10_UP} rMethod: TRttiMethod; {$ELSE} rfield : TRttiField; {$ENDIF} begin Result := aObject; rType := ctx.GetType(aObject.ClassInfo); rProp := rType.GetProperty('List'); if (rProp = nil) or (aJson = nil) or (aJson.ClassType = TJSONNull) then Exit; member := nil; //check if exists List (denotes delphi json serialized) or not (normal json serialized) if aJson.ClassType = TJSONObject then member := GetJsonPairValueByName(aJson,aName); if member = nil then begin if aJson.ClassType <> TJSONArray then raise EJsonDeserializeError.CreateFmt('Not valid value for "%s" List',[aName]); jArray := TJSONObject.ParseJSONValue(aJson.ToJSON) as TJSONArray; end else begin if member.ClassType <> TJSONArray then raise EJsonDeserializeError.CreateFmt('Not valid value for "%s" List',[aName]); jArray := TJSONObject.ParseJSONValue(member.ToJSON) as TJSONArray; end; try rvalue := DeserializeDynArray(rProp.PropertyType.Handle,Result,jArray); //i := jarray.Count; finally jArray.Free; end; if not rValue.IsEmpty then begin {$IFDEF DELPHIRX10_UP} if (aObject <> nil) and (rvalue.IsArray) then begin rMethod := ctx.GetType(aObject.ClassType).GetMethod('Clear'); if rMethod = nil then raise EJsonDeserializeError.Create('Unable to find RTTI method'); rMethod.Invoke(aObject, []); rMethod := ctx.GetType(aObject.ClassType).GetMethod('Add'); if rMethod = nil then raise EJsonDeserializeError.Create('Unable to find RTTI method'); n := rvalue.GetArrayLength - 1; for i := 0 to n do rMethod.Invoke(aObject, [rvalue.GetArrayElement(i)]); end; {$ELSE} n := 0; for rfield in rType.GetFields do begin if rfield.Name = 'FOwnsObjects' then rfield.SetValue(aObject,True); //if rfield.Name = 'FCount' then rfield.SetValue(aObject,i); if rfield.Name = 'FItems' then begin //if TList(aObject) <> nil then TList(aObject).Clear; //rfield.GetValue(aObject).AsObject.Free;// aValue.GetReferenceToRawData) rfield.SetValue(aObject,rValue);// .SetDynArrayProp(aObject,'fItems',Result); Break; end; end; rProp := rType.GetProperty('Count'); rProp.SetValue(aObject,n); {$ENDIF} end; end; {$ENDIF} {$IFNDEF FPC} procedure TRTTIJson.DeserializeXArray(Instance : TObject; aRecord : TValue; aProperty : TRttiProperty; const aPropertyName : string; aJson : TJsonObject); var ctx : TRttiContext; rRec : TRttiRecordType; rfield : TRttiField; rValue : TValue; member : TJsonValue; jArray : TJSONArray; begin rRec := ctx.GetType(aRecord.TypeInfo).AsRecord; rfield := rRec.GetField('fArray'); if rfield <> nil then begin rValue := nil; //member := TJSONPair(aJson.GetValue(rField.Name)); member := GetJsonPairValueByName(aJson,aPropertyName); if (member <> nil) and (rField.FieldType.TypeKind = tkDynArray) then begin jArray := TJSONObject.ParseJSONValue(member.ToJSON) as TJSONArray; try rValue := DeserializeDynArray(rField.FieldType.Handle,nil,jArray); finally jArray.Free; end; end; end; if not rValue.IsEmpty then rField.SetValue(aRecord.GetReferenceToRawData,rValue); aProperty.SetValue(Instance,aRecord); end; {$ENDIF} function StringToGUIDEx(const aGUID : string) : TGUID; begin if not aGUID.StartsWith('{') then Result := System.SysUtils.StringToGUID('{' + aGUID + '}') else Result := System.SysUtils.StringToGUID(aGUID); end; function TRTTIJson.GUIDToStringFormated(const aGUID : TGUID) : string; begin if fOptions.UseGUIDWithBrackets then Result := System.SysUtils.GUIDToString(aGUID) else Result := GetSubString(System.SysUtils.GUIDToString(aGUID),'{','}'); if fOptions.UseGUIDLowercase then Result := Result.ToLower; end; function TRTTIJson.DeserializeProperty(aObject : TObject; const aName : string; aProperty : TRttiProperty; const aJson : TJSONObject) : TObject; var rValue : TValue; {$IFNDEF FPC} member : TJsonValue; {$ELSE} member : TJsonObject; {$ENDIF} objClass: TClass; jArray : TJSONArray; json : TJSONObject; begin Result := aObject; rValue := nil; {$IFNDEF FPC} //member := TJSONPair(aJson.GetValue(aName)); member := GetJsonPairValueByName(aJson,aName); {$ELSE} member := TJsonObject(aJson.Find(aName)); {$ENDIF} if member <> nil then begin case aProperty.PropertyType.TypeKind of tkDynArray : begin {$IFNDEF FPC} if member is TJSONNull then Exit; jArray := TJSONObject.ParseJSONValue(member.ToJSON) as TJSONArray; {$ELSE} if member.ClassType = TJSONNull.ClassType then Exit; jArray := TJSONArray(TJSONObject.ParseJSONValue(member.ToJSON)); {$ENDIF} try {$IFNDEF FPC} aProperty.SetValue(aObject,DeserializeDynArray(aProperty.PropertyType.Handle,Result,jArray)); {$ELSE} DeserializeDynArray(aProperty.PropertyType.Handle,aName,Result,jArray); {$ENDIF} Exit; finally jArray.Free; end; end; tkClass : begin //if (member.JsonValue is TJSONObject) then begin json := TJsonObject(TJSONObject.ParseJSONValue(member.ToJson)); try if aProperty.GetValue(aObject).AsObject = nil then begin {$IFNDEF FPC} objClass := aProperty.PropertyType.Handle^.TypeData.ClassType; rValue := DeserializeClass(objClass,json); {$ELSE} objClass := GetObjectPropClass(aObject,aName); //objClass := GetTypeData(aProperty.PropertyType.Handle)^.ClassType; rValue := DeserializeClass(objClass,json); SetObjectProp(aObject,aName,rValue.AsObject); Exit; {$ENDIF} end else begin rValue := DeserializeObject(aProperty.GetValue(aObject).AsObject,json); Exit; end; finally json.Free; end; end end; {$IFNDEF FPC} tkRecord : begin if aProperty.GetValue(aObject).TypeInfo = System.TypeInfo(TGUID) then begin //get value from TGUID string with and without {} (more compatibility) rValue:=TValue.From<TGUID>(StringToGUIDEx(UnQuotedStr(member.ToJSON,'"'))); end else begin json := TJSONObject.ParseJSONValue(member.ToJson) as TJSONObject; try rValue := DeserializeRecord(aProperty.GetValue(aObject),aObject,json); finally json.Free; end; end; end; {$ENDIF} else begin {$IFNDEF FPC} //avoid return unicode escaped chars if string if aProperty.PropertyType.TypeKind in [tkString, tkLString, tkWString, tkUString] then {$IFDEF DELPHIRX10_UP} rValue := DeserializeType(aObject,aProperty.PropertyType.TypeKind,aProperty.GetValue(aObject).TypeInfo,TJsonValue(member).value) {$ELSE} rValue := DeserializeType(aObject,aProperty.PropertyType.TypeKind,aProperty.GetValue(aObject).TypeInfo,member.Value) {$ENDIF} else rValue := DeserializeType(aObject,aProperty.PropertyType.TypeKind,aProperty.GetValue(aObject).TypeInfo,member.ToJSON); {$ELSE} rValue := DeserializeType(aObject,aProperty.PropertyType.TypeKind,aName,member.ToJSON); if not rValue.IsEmpty then SetPropertyValue(aObject,aName,rValue); {$ENDIF} end; end; {$IFNDEF FPC} if not rValue.IsEmpty then aProperty.SetValue(Result,rValue); {$ENDIF} end; end; {$IFNDEF FPC} function TRTTIJson.DeserializeType(aObject : TObject; aType : TTypeKind; aTypeInfo : PTypeInfo; const aValue: string) : TValue; var i : Integer; value : string; fsettings : TFormatSettings; begin try value := UnQuotedStr(aValue,'"'); case aType of tkString, tkLString, tkWString, tkUString : begin if fOptions.UseNullStringsAsEmpty and (CompareText(value, 'null') = 0) then Result := '' else Result := value; end; tkChar, tkWChar : begin Result := value; end; tkInteger : begin if CompareText(value,'null') <> 0 then Result := StrToIntDef(value,0) else Result := 0; end; tkInt64 : begin if CompareText(value,'null') <> 0 then Result := StrToInt64Def(value,0) else Result := 0; end; tkFloat : begin if aTypeInfo = TypeInfo(TDateTime) then begin if CompareText(value,'null') <> 0 then Result := JsonDateToDateTime(value); end else if aTypeInfo = TypeInfo(TDate) then begin if CompareText(value,'null') <> 0 then Result := StrToDate(value); end else if aTypeInfo = TypeInfo(TTime) then begin Result := StrToTime(value); end else begin fsettings := TFormatSettings.Create; Result := StrToFloat(StringReplace(value,'.',fsettings.DecimalSeparator,[])); end; end; tkEnumeration : begin if aTypeInfo = System.TypeInfo(Boolean) then begin Result := StrToBool(value); end else begin //if fUseEnumNames then TValue.Make(GetEnumValue(aTypeInfo,value),aTypeInfo, Result) // else TValue.Make(StrToInt(value),aTypeInfo, Result); if not TryStrToInt(value,i) then TValue.Make(GetEnumValue(aTypeInfo,value),aTypeInfo, Result) else TValue.Make(StrToInt(value),aTypeInfo, Result); end; end; tkSet : begin i := StringToSet(aTypeInfo,value); TValue.Make(@i,aTypeInfo,Result); end; else begin //raise EclJsonSerializerError.Create('Not supported data type!'); end; end; except on E : Exception do begin raise EJsonDeserializeError.CreateFmt('Deserialize error type "%s.%s" : %s',[aObject.ClassName,GetTypeName(aTypeInfo),e.Message]); end; end; end; {$ELSE} function TRTTIJson.DeserializeType(aObject : TObject; aType : TTypeKind; const aPropertyName, aValue: string) : TValue; var value : string; propinfo : PPropInfo; fsettings : TFormatSettings; begin try value := UnQuotedStr(aValue,'"'); if value = '' then begin Result := nil; Exit; end; propinfo := GetPropInfo(aObject,aPropertyName); //case propinfo.PropType.Kind of case aType of tkString, tkLString, tkWString, tkUString, tkAString : begin Result := value; //SetStrProp(aObject,propinfo,value); end; tkChar, tkWChar : begin Result := value; end; tkInteger : begin if CompareText(value,'null') <> 0 then Result := StrToInt(value) else Result := 0; end; tkInt64 : begin if CompareText(value,'null') <> 0 then Result := StrToInt64(value) else Result := 0; end; tkFloat : begin if propinfo.PropType = TypeInfo(TDateTime) then begin if CompareText(value,'null') <> 0 then Result := JsonDateToDateTime(value); end else if propinfo.PropType = TypeInfo(TDate) then begin if CompareText(value,'null') <> 0 then Result := StrToDate(value); end else if propinfo.PropType = TypeInfo(TTime) then begin Result := StrToTime(value); end else begin fsettings := DefaultFormatSettings; Result := StrToFloat(StringReplace(value,'.',fsettings.DecimalSeparator,[])); end; end; tkEnumeration: begin Result := value; end; tkBool : begin Result := StrToBool(value); end; tkSet : begin Result := value; end; else begin //raise EclJsonSerializerError.Create('Not supported data type!'); end; end; //if not Result.IsEmpty then SetPropertyValue(aObject,propinfo,Result); except on E : Exception do begin raise EJsonDeserializeError.CreateFmt('Deserialize error type "%s" : %s',[aObject.ClassName,e.Message]); end; end; end; {$ENDIF} function TRTTIJson.IsAllowedProperty(aObject : TObject; const aPropertyName : string) : Boolean; var propname : string; begin Result := True; propname := aPropertyName.ToLower; if IsGenericList(aObject) then begin if (propname = 'capacity') or (propname = 'count') or (propname = 'ownsobjects') then Result := False; end else if (propname = 'refcount') then Result := False; end; function TRTTIJson.IsGenericList(aObject : TObject) : Boolean; var cname : string; begin if aObject = nil then Exit(False); cname := aObject.ClassName; Result := (cname.StartsWith('TObjectList')) or (cname.StartsWith('TList')); end; function TRTTIJson.IsStream(aObject : TObject) : Boolean; begin if aObject = nil then Exit(False); Result := aObject.InheritsFrom(TStream); end; function TRTTIJson.GetGenericListType(aObject : TObject) : TGenericListType; var cname : string; begin if aObject = nil then Exit(TGenericListType.gtNone); cname := aObject.ClassName; if cname.StartsWith('TObjectList') then Result := TGenericListType.gtObjectList else if cname.StartsWith('TList') then Result := TGenericListType.gtList else Result := TGenericListType.gtNone; end; function TRTTIJson.IsGenericXArray(const aClassName : string) : Boolean; begin Result := aClassName.StartsWith('TXArray'); end; function TRTTIJson.GetJsonPairValueByName(aJson: TJSONObject; const aName: string): TJsonValue; var candidate : TJSONPair; i : Integer; begin if fOptions.UseJsonCaseSense then begin Result := aJson.GetValue(aName); Exit; end else begin for i := 0 to aJson.Count - 1 do begin candidate := aJson.Pairs[I]; if candidate.JsonValue = nil then continue; if CompareText(candidate.JsonString{$IFNDEF FPC}.Value{$ENDIF},aName) = 0 then Exit(candidate.JsonValue); end; end; Result := nil; end; function TRTTIJson.GetJsonPairByName(aJson: TJSONObject; const aName: string): TJSONPair; var i : Integer; begin if fOptions.UseJsonCaseSense then begin Result := TJSONPair(aJson.GetValue(aName)); Exit; end else begin if aJson <> nil then begin for i := 0 to aJson.Count - 1 do begin Result := aJson.Pairs[I]; if Result.JsonValue = nil then continue; if CompareText(Result.JsonString{$IFNDEF FPC}.Value{$ENDIF},aName) = 0 then Exit; end; end; end; Result := nil; end; //function TRTTIJson.GetPropertyValue(Instance : TObject; const PropertyName : string) : TValue; //var // pinfo : PPropInfo; //begin // Result := nil; // pinfo := GetPropInfo(Instance,PropertyName); // if pinfo = nil then raise EJsonSerializeError.CreateFmt('Property "%s" not found!',[PropertyName]); // case pinfo.PropType^.Kind of // tkInteger : Result := GetOrdProp(Instance,pinfo); // tkInt64 : Result := GetInt64Prop(Instance,PropertyName); // tkFloat : Result := GetFloatProp(Instance,PropertyName); // tkChar : Result := Char(GetOrdProp(Instance,PropertyName)); // {$IFDEF FPC} // tkWString : Result := GetWideStrProp(Instance,PropertyName); // tkSString, // tkAString, // {$ELSE} // tkWString, // {$ENDIF} // tkLString : Result := GetStrProp(Instance,pinfo); // {$IFDEF FPC} // tkEnumeration : // begin // if fUseEnumNames then Result := GetEnumName(pinfo.PropType,GetOrdProp(Instance,PropertyName)) // else Result := GetOrdProp(Instance,PropertyName); // end; // {$ELSE} // tkEnumeration : // begin // if fUseEnumNames then Result := GetEnumName(@pinfo.PropType,GetOrdProp(Instance,PropertyName)) // else Result := GetOrdProp(Instance,PropertyName); // end; // {$ENDIF} // tkSet : Result := GetSetProp(Instance,pinfo,True); // {$IFNDEF FPC} // tkClass : // {$ELSE} // tkBool : Result := Boolean(GetOrdProp(Instance,pinfo)); // tkObject : // {$ENDIF} Result := GetObjectProp(Instance,pinfo); // tkDynArray : Result := GetDynArrayProp(Instance,pinfo); // end; //end; function TRTTIJson.GetPropertyValueFromObject(Instance : TObject; const PropertyName : string) : TValue; var ctx : TRttiContext; rprop : TRttiProperty; begin rprop := ctx.GetType(Instance.ClassInfo).GetProperty(PropertyName); Result := rprop.GetValue(Instance); end; {$IFNDEF FPC} function TRTTIJson.GetFieldValueFromRecord(const aValue : TValue; const FieldName : string) : TValue; var ctx : TRttiContext; rec : TRttiRecordType; rfield : TRttiField; begin rec := ctx.GetType(aValue.TypeInfo).AsRecord; rfield := rec.GetField(FieldName); if rfield <> nil then Result := rField.GetValue(aValue.GetReferenceToRawData) else Result := nil; end; {$ENDIF} {$IFDEF FPC} procedure TRTTIJson.SetPropertyValue(Instance : TObject; const PropertyName : string; aValue : TValue); var pinfo : PPropInfo; begin pinfo := GetPropInfo(Instance,PropertyName); SetPropertyValue(Instance,pinfo,aValue); end; procedure TRTTIJson.SetPropertyValue(Instance : TObject; aPropInfo : PPropInfo; aValue : TValue); begin case aPropInfo.PropType^.Kind of tkInteger : SetOrdProp(Instance,aPropInfo,aValue.AsInteger); tkInt64 : SetInt64Prop(Instance,aPropInfo,aValue.AsInt64); tkFloat : SetFloatProp(Instance,aPropInfo,aValue.AsExtended); tkChar : SetOrdProp(Instance,aPropInfo,aValue.AsOrdinal); {$IFDEF FPC} tkWString : SetWideStrProp(Instance,aPropInfo,aValue.AsString); tkSString, tkAString, {$ELSE} tkWString, {$ENDIF} tkLString : SetStrProp(Instance,aPropInfo,aValue.AsString); {$IFDEF FPC} tkBool : SetOrdProp(Instance,aPropInfo,aValue.AsOrdinal); tkSet : LoadSetProperty(Instance,aPropInfo,aValue.AsString); {$ENDIF} tkEnumeration : SetEnumProp(Instance,aPropInfo,aValue.AsString); {$IFNDEF FPC} tkClass : {$ELSE} tkObject : {$ENDIF} SetObjectProp(Instance,aPropInfo,aValue.AsObject); end; end; procedure TRTTIJson.LoadSetProperty(aInstance : TObject; aPropInfo: PPropInfo; const aValue: string); type TCardinalSet = set of 0..SizeOf(Cardinal) * 8 - 1; const Delims = [' ', ',', '[', ']']; var TypeInfo: PTypeInfo; W: Cardinal; I, N: Integer; Count: Integer; EnumName: string; begin W := 0; TypeInfo := GetTypeData(GetPropType(aPropInfo))^.CompType; Count := WordCount(aValue, Delims); for N := 1 to Count do begin EnumName := ExtractWord(N, aValue, Delims); try I := GetEnumValue(TypeInfo, EnumName); if I >= 0 then Include(TCardinalSet(W),I); except end; end; SetOrdProp(aInstance,aPropInfo,W); end; {$ENDIF} function TRTTIJson.SerializeObject(aObject: TObject): TJSONObject; var ctx: TRttiContext; {$IFNDEF FPC} attr : TCustomAttribute; comment : string; {$ENDIF} rType: TRttiType; rProp: TRttiProperty; jpair : TJSONPair; ExcludeSerialize : Boolean; propertyname : string; propvalue : TValue; begin if (aObject = nil) then begin Result := nil; Exit; end; Result := nil; try //if is GenericList if IsGenericList(aObject) then begin //get list array propvalue := GetPropertyValueFromObject(aObject,'List'); {$IFDEF DELPHIRX10_UP} Result := TJSONObject(SerializeDynArray(propvalue)); {$ELSE} Result := TJSONObject(SerializeValue(propvalue)); {$ENDIF} Exit; end {$IFNDEF FPC} else if IsStream(aObject) then begin Result := TJSONObject(SerializeStream(aObject)); Exit; end {$ENDIF} else Result := TJSONObject.Create; //if is standard object propertyname := ''; rType := ctx.GetType(aObject.ClassInfo); for rProp in TRTTI.GetProperties(rType,roFirstBase) do begin ExcludeSerialize := False; propertyname := rProp.Name; {$IFNDEF FPC} comment := ''; if not rProp.IsReadable then Continue; for attr in rProp.GetAttributes do begin if attr is TNotSerializableProperty then ExcludeSerialize := True else if attr is TCommentProperty then comment := TCommentProperty(attr).Comment else if attr is TCustomNameProperty then propertyname := TCustomNameProperty(attr).Name; end; if ((fSerializeLevel = slPublicProperty) and (rProp.PropertyType.IsPublicType)) or ((fSerializeLevel = slPublishedProperty) and ((IsPublishedProp(aObject,rProp.Name)) or (rProp.Name = 'List'))) then {$ENDIF} begin if (IsAllowedProperty(aObject,propertyname)) and (not ExcludeSerialize) then begin //add comment as pair {$IFNDEF FPC} if comment <> '' then Result.AddPair(TJSONPair.Create('#Comment#->'+propertyname,Comment)); {$ENDIF} begin propvalue := rProp.GetValue(aObject); jpair := TJSONPair.Create(propertyName,nil); // if (propvalue.IsObject) and (IsGenericList(propvalue.AsObject)) then // begin // jpair.JsonValue := SerializeValue(GetPropertyValueFromObject(propvalue.AsObject,'List')); // end if propvalue.IsObject then jpair.JsonValue := SerializeObject(propvalue.AsObject) {$IFNDEF FPC} else if (not propvalue.IsObject) and (IsGenericXArray(string(propvalue{$IFNDEF NEXTGEN}.TypeInfo.Name{$ELSE}.TypeInfo.NameFld.ToString{$ENDIF}))) then begin jpair.JsonValue := SerializeValue(GetFieldValueFromRecord(propvalue,'fArray')); end {$ENDIF} else begin {$IFNDEF FPC} jpair.JsonValue := SerializeValue(propvalue); {$ELSE} jpair.JsonValue := SerializeValue(propvalue);// SerializeObject(aObject,rProp.PropertyType.TypeKind,propertyname); {$ENDIF} end; //s := jpair.JsonValue.ToString; if jpair.JsonValue <> nil then begin Result.AddPair(jpair); end else jpair.Free; end; end; end; end; except on E : Exception do begin if Result <> nil then Result.Free; if not propertyname.IsEmpty then raise EJsonSerializeError.CreateFmt('Serialize Error -> Object property: "%s" (%s)',[propertyname,e.Message]) else raise EJsonSerializeError.CreateFmt('Serialize Error -> Object (%s)',[e.Message]); end; end; end; function TRTTIJson.GetValue(aAddr: Pointer; aType: TRTTIType): TValue; begin TValue.Make(aAddr,aType.Handle,Result); end; {$IFDEF FPC} function TRTTIJson.GetValue(aAddr: Pointer; aTypeInfo: PTypeInfo): TValue; begin TValue.Make(aAddr,aTypeInfo,Result); end; {$ENDIF} function TRTTIJson.SerializeValue(const aValue : TValue) : TJSONValue; begin Result := nil; case avalue.Kind of tkDynArray : begin {$IFNDEF FPC} Result := SerializeDynArray(aValue); {$ENDIF} end; tkClass : begin Result := TJSONValue(SerializeObject(aValue.AsObject)); end; tkInterface : begin {$IFDEF DELPHIRX10_UP} // Would not work with iOS/Android native interfaces Result := TJSONValue(SerializeObject(aValue.AsInterface as TObject)); {$ENDIF} end; tkString, tkLString, tkWString, tkUString : begin Result := TJSONString.Create(aValue.AsString); end; tkChar, tkWChar : begin Result := TJSONString.Create(aValue.AsString); end; tkInteger : begin Result := TJSONNumber.Create(aValue.AsInteger); end; tkInt64 : begin Result := TJSONNumber.Create(aValue.AsInt64); end; tkFloat : begin if aValue.TypeInfo = TypeInfo(TDateTime) then begin if aValue.AsExtended <> 0.0 then Result := TJSONString.Create(DateTimeToJsonDate(aValue.AsExtended)); end else if aValue.TypeInfo = TypeInfo(TDate) then begin if aValue.AsExtended <> 0.0 then Result := TJSONString.Create(DateToStr(aValue.AsExtended)); end else if aValue.TypeInfo = TypeInfo(TTime) then begin Result := TJSONString.Create(TimeToStr(aValue.AsExtended)); end else begin Result := TJSONNumber.Create(aValue.AsExtended); end; end; tkEnumeration : begin if (aValue.TypeInfo = System.TypeInfo(Boolean)) then begin {$IF Defined(DELPHIRX10_UP) OR Defined(FPC)} Result := TJSONBool.Create(aValue.AsBoolean); {$ELSE} if aValue.AsBoolean then Result := TJsonTrue.Create else Result := TJsonFalse.Create; {$ENDIF} end else begin //Result.JsonValue := TJSONString.Create(GetEnumName(aValue.TypeInfo,aValue.AsOrdinal)); if fUseEnumNames then Result := TJSONString.Create(aValue.ToString) else Result := TJSONNumber.Create(GetEnumValue(aValue.TypeInfo,aValue.ToString)); end; end; {$IFDEF FPC} tkBool : begin Result := TJSONBool.Create(aValue.AsBoolean); end; {$ENDIF} tkSet : begin Result := TJSONString.Create(aValue.ToString); end; tkRecord : begin {$IFNDEF FPC} Result := SerializeRecord(aValue); {$ENDIF} end; tkVariant : begin {$IFNDEF FPC} case VarType(aValue.AsVariant) and VarTypeMask of varInteger, varInt64 : Result := TJSONNumber.Create(aValue.AsInteger); varString, varUString, varEmpty : Result := TJSONString.Create(aValue.AsString); varDouble : Result := TJSONNumber.Create(aValue.AsExtended); end; {$ENDIF} end; tkMethod, tkPointer, tkClassRef, tkProcedure, tkUnknown : begin //skip these properties end else begin {$IFNDEF FPC} raise EJsonSerializeError.CreateFmt(cNotSupportedDataType,[GetTypeName(aValue.TypeInfo)]); {$ELSE} raise EJsonSerializeError.Create('Not supported Data Type'); {$ENDIF} end; end; if Result = nil then Result := TJSONNull.Create; end; function TRTTIJson.SerializeStream(aObject: TObject): TJSONValue; var stream : TStream; begin Result := nil; try stream := TStream(aObject); if fOptions.UseBase64Stream then Result := TJSONString.Create(Base64Encode(StreamToString(stream,TEncoding.Ansi))) else Result := TJSONString.Create(StreamToString(stream,TEncoding.Ansi)); except on E : Exception do begin EJsonSerializeError.CreateFmt('Serialize Error -> Stream (%s)',[e.Message]); end; end; end; {$IFNDEF FPC} function TRTTIJson.SerializeDynArray(const aValue: TValue; aMaxElements : Integer = -1) : TJsonArray; var ctx : TRttiContext; rDynArray : TRTTIDynamicArrayType; i : Integer; jValue : TJSONValue; element : Integer; list : TList<TJSONValue>; len : Integer; begin element := -1; Result := TJSONArray.Create; try rDynArray := ctx.GetType(aValue.TypeInfo) as TRTTIDynamicArrayType; //if aValue.IsObjectInstance then TList<TObject>(aValue.AsObject).TrimExcess; list := TList<TJSONValue>.Create; if aMaxElements = -1 then len := aValue.GetArrayLength else len := aMaxElements; list.Capacity := len; for i := 0 to len - 1 do begin if not GetValue(PPByte(aValue.GetReferenceToRawData)^ + rDynArray.ElementType.TypeSize * i, rDynArray.ElementType).IsEmpty then begin element := i; jValue := SerializeValue(GetValue(PPByte(aValue.GetReferenceToRawData)^ + rDynArray.ElementType.TypeSize * i, rDynArray.ElementType)); if jValue = nil then jValue := TJSONNull.Create; list.Add(jValue); end; end; Result.SetElements(list); except on E : Exception do begin if element > -1 then raise EJsonSerializeError.CreateFmt('Serialize Error -> Array[%d] (%s)',[element,e.Message]) else raise EJsonSerializeError.CreateFmt('Serialize Error -> Array (%s)',[e.Message]); end; end; end; function TRTTIJson.SerializeRecord(const aValue : TValue) : TJSONValue; var ctx : TRttiContext; json : TJSONObject; rRec : TRttiRecordType; rField : TRttiField; begin rField := nil; try rRec := ctx.GetType(aValue.TypeInfo).AsRecord; if aValue.TypeInfo = System.TypeInfo(TGUID) then begin Result := TJSONString.Create(GUIDToStringFormated(aValue.AsType<TGUID>)); end else begin json := TJSONObject.Create; for rField in rRec.GetFields do begin json.AddPair(rField.Name,SerializeValue(rField.GetValue(aValue.GetReferenceToRawData))); end; Result := json; end; except on E : Exception do begin if rField <> nil then raise EJsonSerializeError.CreateFmt('Serialize Error -> Record property "%s" (%s)',[rField.Name,e.Message]) else raise EJsonSerializeError.CreateFmt('Serialize Error -> Record (%s)',[e.Message]); end; end; end; {$ELSE} function TRTTIJson.GetPropType(aPropInfo: PPropInfo): PTypeInfo; begin Result := aPropInfo^.PropType; end; function TRTTIJson.FloatProperty(aObject : TObject; aPropInfo: PPropInfo): string; const Precisions: array[TFloatType] of Integer = (7, 15, 18, 18, 19); var fsettings : TFormatSettings; begin fsettings := FormatSettings; Result := StringReplace(FloatToStrF(GetFloatProp(aObject, aPropInfo), ffGeneral, Precisions[GetTypeData(GetPropType(aPropInfo))^.FloatType],0), '.',fsettings.DecimalSeparator,[rfReplaceAll]); end; function TRTTIJson.SerializeObject(aObject : TObject; aType : TTypeKind; const aPropertyName : string) : TJSONPair; var propinfo : PPropInfo; jArray : TJsonArray; jPair : TJsonPair; jValue : TJsonValue; i : Integer; pArr : Pointer; rValue : TValue; rItemValue : TValue; len : Integer; begin try Result := TJSONPair.Create(aPropertyName,nil); propinfo := GetPropInfo(aObject,aPropertyName); //case propinfo.PropType.Kind of case aType of tkDynArray : begin len := 0; jArray := TJSONArray.Create; try pArr := GetDynArrayProp(aObject,aPropertyName); TValue.Make(@pArr,propinfo.PropType, rValue); if rValue.IsArray then begin len := rValue.GetArrayLength; for i := 0 to len - 1 do begin rItemValue := rValue.GetArrayElement(i); jValue := SerializeValue(rItemValue); jArray.Add(jValue); end; end; Result.JsonValue := jArray; finally //DynArrayClear(pArr,propinfo.PropType); pArr := nil; end; end; tkClass : begin Result.JsonValue := TJSONValue(SerializeObject(GetObjectProp(aObject,aPropertyName))); end; tkString, tkLString, tkWString, tkUString, tkAString : begin Result.JsonValue := TJSONString.Create(GetStrProp(aObject,aPropertyName)); end; tkChar, tkWChar : begin Result.JsonValue := TJSONString.Create(Char(GetOrdProp(aObject,aPropertyName))); end; tkInteger : begin Result.JsonValue := TJSONNumber.Create(GetOrdProp(aObject,aPropertyName)); end; tkInt64 : begin Result.JsonValue := TJSONNumber.Create(GetOrdProp(aObject,aPropertyName)); end; tkFloat : begin if propinfo.PropType = TypeInfo(TDateTime) then begin Result.JsonValue := TJSONString.Create(DateTimeToJsonDate(GetFloatProp(aObject,aPropertyName))); end else if propinfo.PropType = TypeInfo(TDate) then begin Result.JsonValue := TJSONString.Create(DateToStr(GetFloatProp(aObject,aPropertyName))); end else if propinfo.PropType = TypeInfo(TTime) then begin Result.JsonValue := TJSONString.Create(TimeToStr(GetFloatProp(aObject,aPropertyName))); end else begin //Result.JsonValue := TJsonFloatNumber.Create(GetFloatProp(aObject,aPropertyName)); Result.JsonValue := TJsonFloatNumber.Create(StrToFloat(FloatProperty(aObject,propinfo))); end; end; tkEnumeration,tkBool : begin if (propinfo.PropType = System.TypeInfo(Boolean)) then begin Result.JsonValue := TJSONBool.Create(Boolean(GetOrdProp(aObject,aPropertyName))); end else begin if fUseEnumNames then Result.JsonValue := TJSONString.Create(GetEnumName(propinfo.PropType,GetOrdProp(aObject,aPropertyName))) else Result.JsonValue := TJSONNumber.Create(GetOrdProp(aObject,aPropertyName)); //Result.JsonValue := TJSONString.Create(aValue.ToString); end; end; tkSet : begin Result.JsonValue := TJSONString.Create(GetSetProp(aObject,aPropertyName)); end; {$IFNDEF FPC} tkRecord : begin Result.JsonValue := SerializeRecord(aValue); end; {$ENDIF} tkMethod, tkPointer, tkClassRef ,tkInterface, tkProcedure : begin //skip these properties //FreeAndNil(Result); end else begin //raise EJsonDeserializeError.CreateFmt('Not supported type "%s":%d',[aName,Integer(aValue.Kind)]); end; end; if Result.JsonValue = nil then Result.JsonValue := TJSONNull.Create; except on E : Exception do begin Result.Free; {$IFNDEF FPC} raise EJsonSerializeError.CreateFmt('Serialize error class "%s.%s" : %s',[aName,aValue.ToString,e.Message]); {$ENDIF} end; end; end; {$ENDIF} { TJsonSerializer} constructor TJsonSerializer.Create(aSerializeLevel: TSerializeLevel; aUseEnumNames : Boolean = True; aUseNullStringsAsEmpty : Boolean = False); begin {$IFDEF FPC} if aSerializeLevel = TSerializeLevel.slPublicProperty then raise EJsonSerializeError.Create('FreePascal RTTI only supports published properties'); {$ENDIF} fSerializeLevel := aSerializeLevel; fUseEnumNames := aUseEnumNames; fUseJsonCaseSense := False; fUseBase64Stream := True; fUseNullStringsAsEmpty := aUseNullStringsAsEmpty; fRTTIJson := TRTTIJson.Create(aSerializeLevel,aUseEnumNames); fRTTIJson.Options.UseJsonCaseSense := fUseJsonCaseSense; fRTTIJson.Options.UseBase64Stream := fUseBase64Stream; fRTTIJson.Options.UseNullStringsAsEmpty := fUseNullStringsAsEmpty; end; destructor TJsonSerializer.Destroy; begin fRTTIJson.Free; inherited; end; function TJsonSerializer.JsonToObject(aType: TClass; const aJson: string): TObject; var jvalue : TJSONValue; json: TJSONObject; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'JsonToObject',aType.ClassName); {$ENDIF} try {$IFDEF DELPHIRX10_UP} jvalue := TJSONObject.ParseJSONValue(aJson,True); if jvalue.ClassType = TJSONArray then json := TJSONObject(jvalue) else json := jvalue as TJSONObject; {$ELSE} {$IFDEF FPC} json := TJSONObject(TJSONObject.ParseJSONValue(aJson,True)); {$ELSE} json := TJsonObject.ParseJSONValue(TEncoding.UTF8.GetBytes(aJson),0,True) as TJSONObject; {$ENDIF} {$ENDIF} except raise EJsonDeserializeError.Create(cNotValidJson); end; try Result := fRTTIJson.DeserializeClass(aType,json); finally json.Free; end; end; function TJsonSerializer.JsonToObject(aObject: TObject; const aJson: string): TObject; var jvalue : TJSONValue; json: TJSONObject; begin; if aObject = nil then raise EJsonDeserializeError.Create('Object param cannot be null!'); {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'JsonToObject',aObject.ClassName); {$ENDIF} try {$IFDEF DELPHIRX10_UP} jvalue := TJSONObject.ParseJSONValue(aJson,True); if jvalue.ClassType = TJSONArray then json := TJSONObject(jvalue) else json := jvalue as TJSONObject; //json := TJSONObject.ParseJSONValue(aJson,True) as TJSONObject; {$ELSE} {$IFDEF FPC} json := TJSONObject(TJSONObject.ParseJSONValue(aJson,True)); {$ELSE} json := TJsonObject.ParseJSONValue(TEncoding.UTF8.GetBytes(aJson),0,True) as TJSONObject; {$ENDIF} {$ENDIF} except raise EJsonDeserializeError.Create(cNotValidJson); end; try Result := fRTTIJson.DeserializeObject(aObject,json); finally json.Free; end; end; function TJsonSerializer.ObjectToJson(aObject : TObject; aIndent : Boolean = False): string; var json: TJSONObject; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ObjectToJson',aObject.ClassName); {$ENDIF} json := fRTTIJson.SerializeObject(aObject); try if aIndent then Result := TJsonUtils.JsonFormat(json.ToJSON) else Result := json.ToJSON; finally json.Free; end; end; procedure TJsonSerializer.ObjectToJsonStream(aObject: TObject; aStream: TStream); var json : TJsonObject; ss : TStringStream; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ObjectToJsonStream',aObject.ClassName); {$ENDIF} if aStream = nil then raise EJsonSerializeError.Create('stream parameter cannot be nil!'); json := fRTTIJson.SerializeObject(aObject); try ss := TStringStream.Create(json.ToString,TEncoding.UTF8); try aStream.CopyFrom(ss,ss.Size); finally ss.Free; end; finally json.Free; end; end; function TJsonSerializer.ObjectToJsonString(aObject : TObject; aIndent : Boolean = False): string; var json: TJSONObject; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ObjectToJsonString',aObject.ClassName); {$ENDIF} json := fRTTIJson.SerializeObject(aObject); try if aIndent then Result := TJsonUtils.JsonFormat(json.ToString) else Result := json.ToString; finally json.Free; end; end; function TJsonSerializer.Options: TSerializerOptions; begin Result := fRTTIJson.Options; end; function TJsonSerializer.ValueToJson(const aValue: TValue; aIndent: Boolean): string; var json: TJSONValue; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ValueToJson',aValue.ToString); {$ENDIF} json:= fRTTIJson.SerializeValue(aValue); if json = nil then raise EJsonSerializerError.Create('Error serializing TValue'); try if aIndent then Result := TJsonUtils.JsonFormat(json{$IFNDEF FPC}.ToJSON{$ELSE}.AsJson{$ENDIF}) else Result := json{$IFNDEF FPC}.ToJSON{$ELSE}.AsJson{$ENDIF}; finally json.Free; end; end; function TJsonSerializer.ValueToJsonString(const aValue: TValue; aIndent: Boolean): string; var json: TJSONValue; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ValueToJsonString',aValue.ToString); {$ENDIF} json:= fRTTIJson.SerializeValue(aValue); if json = nil then raise EJsonSerializerError.Create('Error serializing TValue'); try if aIndent then Result := TJsonUtils.JsonFormat(json.ToString) else Result := json.ToString; finally json.Free; end; end; function TJsonSerializer.ArrayToJson<T>(aArray: TArray<T>; aIndent: Boolean): string; var json: TJSONValue; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ArrayToJson',''); {$ENDIF} json:= fRTTIJson.SerializeValue(TValue.From<TArray<T>>(aArray)); if json = nil then raise EJsonSerializerError.Create('Error serializing Array'); try if aIndent then Result := TJsonUtils.JsonFormat(json{$IFNDEF FPC}.ToJSON{$ELSE}.AsJson{$ENDIF}) else Result := json{$IFNDEF FPC}.ToJSON{$ELSE}.AsJson{$ENDIF}; finally json.Free; end; end; function TJsonSerializer.ArrayToJsonString<T>(aArray: TArray<T>; aIndent: Boolean): string; var json: TJSONValue; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'ArrayToJsonString',''); {$ENDIF} json:= fRTTIJson.SerializeValue(TValue.From<TArray<T>>(aArray)); if json = nil then raise EJsonSerializerError.Create('Error serializing Array'); try if aIndent then Result := TJsonUtils.JsonFormat(json.ToString) else Result := json.ToString; finally json.Free; end; end; function TJsonSerializer.JsonStreamToObject(aObject: TObject; aJsonStream: TStream): TObject; var json : string; begin {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'JsonStreamToObject',''); {$ENDIF} if aJsonStream = nil then raise EJsonDeserializeError.Create('JsonStream param cannot be nil!'); json := StreamToString(aJsonStream,TEncoding.UTF8); Result := JsonToObject(aObject,json); end; {$IFNDEF FPC} function TJsonSerializer.JsonToArray<T>(const aJson: string): TArray<T>; var jarray: TJSONArray; value : TValue; begin; {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'JsonToArray',''); {$ENDIF} try {$If Defined(FPC) OR Defined(DELPHIRX10_UP)} jarray := TJSONObject.ParseJSONValue(aJson,True) as TJSONArray; {$ELSE} jarray := TJsonObject.ParseJSONValue(TEncoding.UTF8.GetBytes(aJson),0,True) as TJSONArray; {$ENDIF} except raise EJsonDeserializeError.Create(cNotValidJson); end; try value := fRTTIJson.DeserializeDynArray(PTypeInfo(TypeInfo(TArray<T>)),nil,jarray); Result := value.AsType<TArray<T>>; finally jarray.Free; end; end; function TJsonSerializer.JsonToValue(const aJson: string): TValue; var json: TJSONObject; value : TValue; begin; {$IFDEF DEBUG_SERIALIZER} TDebugger.TimeIt(Self,'JsonToValue',''); {$ENDIF} try {$If Defined(FPC) OR Defined(DELPHIRX10_UP)} json := TJSONObject.ParseJSONValue(aJson,True) as TJSONObject; {$ELSE} json := TJsonObject.ParseJSONValue(TEncoding.UTF8.GetBytes(aJson),0,True) as TJSONObject; {$ENDIF} except raise EJsonDeserializeError.Create(cNotValidJson); end; try value := fRTTIJson.DeserializeRecord(value,nil,json); Result := value; // value.AsType<TArray<T>>; finally json.Free; end; end; {$ENDIF} procedure TJsonSerializer.SetSerializeLevel(const Value: TSerializeLevel); begin fSerializeLevel := Value; if Assigned(fRTTIJson) then fRTTIJson.fSerializeLevel := Value; end; procedure TJsonSerializer.SetUseBase64Stream(const Value: Boolean); begin fUseBase64Stream := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseBase64Stream := Value; end; procedure TJsonSerializer.SetUseEnumNames(const Value: Boolean); begin fUseEnumNames := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseEnumNames := Value; end; procedure TJsonSerializer.SetUseGUIDLowerCase(const Value: Boolean); begin fUseGUIDLowercase := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseGUIDLowerCase := Value; end; procedure TJsonSerializer.SetUseGUIDWithBrackets(const Value: Boolean); begin fUseGUIDWithBrackets := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseGUIDWithBrackets := Value; end; procedure TJsonSerializer.SetUseJsonCaseSense(const Value: Boolean); begin fRTTIJson.Options.UseJsonCaseSense := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseJsonCaseSense := Value; end; procedure TJsonSerializer.SetUseNullStringsAsEmpty(const Value: Boolean); begin fUseNullStringsAsEmpty := Value; if Assigned(fRTTIJson) then fRTTIJson.Options.UseNullStringsAsEmpty := Value; end; {$IFNDEF FPC} { TCommentProperty } constructor TCommentProperty.Create(const aComment: string); begin fComment := aComment; end; { TCustomNameProperty } constructor TCustomNameProperty.Create(const aName: string); begin fName := aName; end; {$ENDIF} {$IF NOT DEFINED(DELPHIXE7_UP) AND NOT DEFINED(FPC)} { TJSONArrayHelper } function TJSONArrayHelper.Count: Integer; begin Result := Self.Size; end; function TJSONArrayHelper.GetItem(aValue: Integer): TJSONValue; begin Result := Self.Get(aValue); end; procedure TJSONArrayHelper.SetElements(aElements: TList<TJSONValue>); var jvalue : TJSONValue; begin for jvalue in aElements do Self.AddElement(jvalue); aElements.Free; end; { TJSONValueHelper } function TJSONValueHelper.ToJson: string; begin Result := Self.ToString; end; { TJSONObjectHelper } function TJSONObjectHelper.Count: Integer; begin Result := Self.Size; end; function TJSONObjectHelper.GetValue(const aName: string): TJSONValue; var jPair : TJSONPair; begin Result := nil; for jPair in Self do begin if jPair.JsonString.ToString = aName then Exit(jPair.JsonValue); end; end; function TJSONObjectHelper.GetPair(aValue: Integer) : TJSONPair; begin Result := Self.Get(aValue); end; {$ENDIF} end.
unit CacheBackup; interface uses ActiveX; type TCacheBlockMethod = procedure (row, col : integer) of object; type TCacheBackup = class private fCacheStorage : IStorage; fCurrentStream : IStream; public constructor Create; public procedure SearchBlock(row, col : integer); procedure EnumCacheBlocks(Method : TCacheBlockMethod); procedure Flush; procedure WriteData(var Buffer; BufSize : integer); procedure ReadData(var Buffer; BufSize : integer); end; implementation uses Windows, SysUtils; const CacheFileName : widestring = 'cache.five'; // TCacheBackup constructor TCacheBackup.Create; begin inherited Create; if Failed(StgOpenStorage(pwidechar(CacheFileName), nil, STGM_READWRITE or STGM_TRANSACTED, nil, 0, fCacheStorage)) then if Failed(StgCreateDocFile(pwidechar(CacheFileName), STGM_CREATE or STGM_READWRITE or STGM_TRANSACTED, 0, fCacheStorage)) then raise Exception.Create('Can''''t create cache backup file'); end; procedure TCacheBackup.SearchBlock(row, col: integer); var BlockStreamName : widestring; begin if fCacheStorage <> nil then begin BlockStreamName := IntToStr(row) + '.' + IntToStr(col); if Failed(fCacheStorage.OpenStream(pwidechar(BlockStreamName), nil, STGM_READWRITE or STGM_DIRECT or STGM_SHARE_EXCLUSIVE, 0, fCurrentStream)) then if Failed(fCacheStorage.CreateStream(pwidechar(BlockStreamName), STGM_CREATE or STGM_READWRITE or STGM_DIRECT or STGM_SHARE_EXCLUSIVE, 0, 0, fCurrentStream)) then raise Exception.Create('Unknown error'); end; end; procedure TCacheBackup.EnumCacheBlocks(Method : TCacheBlockMethod); var Enumerator : IEnumStatStg; CurStatStg : TStatStg; cfetched : longint; row : integer; col : integer; namelen : integer; rowastext : string; colastext : string; commapos : integer; begin if Succeeded(fCacheStorage.EnumElements(0, nil, 0, Enumerator)) then begin while Enumerator.Next(1, CurStatStg, @cfetched) = S_OK do with CurStatStg do begin rowastext := pwcsName; colastext := pwcsName; namelen := length(pwcsName); commapos := Pos('.', pwcsName); delete(rowastext, commapos, namelen - commapos + 1); row := StrToInt(rowastext); delete(colastext, 1, commapos); col := StrToInt(colastext); Method(row, col); CoTaskMemFree(pwcsName); end; end; end; procedure TCacheBackup.Flush; begin fCacheStorage.Commit(STGC_DEFAULT); end; procedure TCacheBackup.ReadData(var Buffer; BufSize: integer); var BytesRead : integer; begin fCurrentStream.Read(@Buffer, BufSize, @BytesRead); end; procedure TCacheBackup.WriteData(var Buffer; BufSize: integer); var BytesWritten : integer; begin fCurrentStream.Write(@Buffer, BufSize, @BytesWritten); end; end.
unit GX_eChangeCase; interface implementation uses SysUtils, Classes, Windows, Menus, Forms, Controls, ToolsAPI, GX_EditorExpert, GX_GenericUtils, GX_OtaUtils, {$IFOPT D+} GX_DbugIntf, {$ENDIF} GX_dzVclUtils; type TChangeCase = (ccLowerCase, ccUpperCase, ccTitleCase, ccSentenceCase, ccToggleCase, ccNone); type TChangeCaseExpert = class(TEditorExpert) private FLastSelection: Integer; FPopup: TPopupMenu; FCodeList: TStringList; FKBHook: HHOOK; function IsEditorActive(out ctl: TWinControl): Boolean; procedure miChangeToLowerCaseClicked(Sender: TObject); procedure miChangeToUpperCaseClicked(Sender: TObject); procedure miChangeToTitleCaseClicked(Sender: TObject); procedure miChangeToSentenceCaseClicked(Sender: TObject); procedure miToggleCaseClicked(Sender: TObject); procedure ReplaceSelection; function BlockSelectionToLineEndType(SourceEditor: IOTASourceEditor; const Selection: string): Integer; protected function GetDisplayName: string; override; class function GetName: string; override; public constructor Create; override; destructor Destroy; override; procedure Execute(Sender: TObject); override; function GetDefaultShortCut: TShortCut; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; var EnterWasPressed: Boolean = False; // This keyboard hook is necessary because I found no other way to detect if the // user closed the popup menu by pressing the enter key or by some other means. // When pressing enter, the default menu item is executed, otherwise nothing. // So this hook checks whether the enter key is pressed and sets a global flag, // which is then checked in TChangeCaseExpert.Execute. function KeyboardHookProc(Code: Integer; WordParam: Word; LongParam: LongInt) : LongInt; stdcall; begin if WordParam = VK_RETURN then EnterWasPressed := True; // let Windows pass on the key Result := 0; end; { TChangeCaseExpert } constructor TChangeCaseExpert.Create; resourcestring SChangeToLowerCase = '&lowercase'; SChangeToUpperCase = '&UPPER CASE'; SChangeToTitleCase = '&Title Case'; SChangeToSentenceCase = '&Sentence case'; SToggleCase = 't&OGGLE cASE'; var mi: TMenuItem; begin inherited; FLastSelection := 0; FPopup := TPopupMenu.Create(nil); mi := TPopupMenu_AppendMenuItem(FPopup, SChangeToLowerCase, miChangeToLowerCaseClicked); mi.Tag := Ord(ccLowerCase); mi := TPopupMenu_AppendMenuItem(FPopup, SChangeToUpperCase, miChangeToUpperCaseClicked); mi.Tag := Ord(ccUpperCase); mi := TPopupMenu_AppendMenuItem(FPopup, SChangeToTitleCase, miChangeToTitleCaseClicked); mi.Tag := Ord(ccTitleCase); mi := TPopupMenu_AppendMenuItem(FPopup, SChangeToSentenceCase, miChangeToSentenceCaseClicked); mi.Tag := Ord(ccSentenceCase); mi := TPopupMenu_AppendMenuItem(FPopup, SToggleCase, miToggleCaseClicked); mi.Tag := Ord(ccToggleCase); FCodeList := TStringList.Create; FKBHook := SetWindowsHookEx(WH_KEYBOARD, TFNHookProc(@KeyboardHookProc), HInstance, GetCurrentThreadId()); end; destructor TChangeCaseExpert.Destroy; begin UnHookWindowsHookEx(FKBHook); FreeAndNil(FCodeList); FreeAndNil(FPopup); inherited; end; function TChangeCaseExpert.GetDefaultShortCut: TShortCut; begin Result := scShift + scAlt + Ord('C'); end; function TChangeCaseExpert.GetDisplayName: string; resourcestring SChangeCaseName = 'Change Case'; begin Result := SChangeCaseName; end; function TChangeCaseExpert.GetHelpString: string; resourcestring SChangeCaseHelp = ' This expert changes the character case for the selected block of ' + 'text in the editor. To use it, select any number of lines in the IDE code editor and ' + 'activate this expert.'; begin Result := SChangeCaseHelp; end; class function TChangeCaseExpert.GetName: string; begin Result := 'ChangeCase'; end; // WARNING: This is a hack. // GxOtaReplaceSelection has a problem with appending an // unwanted CRLF for multiline selections to the line end // The clean solution is just to call // GxOtaReplaceSelection(Editor, 0, CodeList.Text); // and have the problem solved elsewhere, but this is hard... // We don't remove the CRLF if the block ends in the first column, // because then we delete a necessary CRLF. // todo: This is copied from TSelectionEditorExpert, maybe this // should go to TEditorExpert or to some intermediate class. function TChangeCaseExpert.BlockSelectionToLineEndType(SourceEditor: IOTASourceEditor; const Selection: string): Integer; var View: IOTAEditView; CharPos: TOTACharPos; EditPos: TOTAEditPos; begin Result := 0; View := GxOtaGetTopMostEditView(SourceEditor); Assert(Assigned(View)); CharPos.Line := View.Block.EndingRow; CharPos.CharIndex := View.Block.EndingColumn; View.ConvertPos(False, EditPos, CharPos); // TODO 3 -cIssue -oAnyone: Why is a 2 necessary for this column check (tested in Delphi 6) if (Length(Selection) > 1) and (EditPos.Col > 2) then begin if Copy(Selection, Length(Selection) - 1, 2) = #13#10 then Result := 2 else if Selection[Length(Selection)] = #10 then Result := 1; end; end; procedure TChangeCaseExpert.ReplaceSelection; var SourceEditor: IOTASourceEditor; LineEndType: Integer; begin EnterWasPressed := False; if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then Exit; if FCodeList.Count = 1 then begin {$IFOPT D+}SendDebugFmt('Replacing selected editor text with "%s"', [FCodeList.Text]);{$ENDIF} GxOtaReplaceSelection(SourceEditor, 0, TrimRight(FCodeList.Text)); end else begin LineEndType := BlockSelectionToLineEndType(SourceEditor, FCodeList.Text); if LineEndType = 2 then GxOtaReplaceSelection(SourceEditor, 0, Copy(FCodeList.Text, 1, Length(FCodeList.Text) - 2)) else if LineEndType = 1 then GxOtaReplaceSelection(SourceEditor, 0, Copy(FCodeList.Text, 1, Length(FCodeList.Text) - 1)) else GxOtaReplaceSelection(SourceEditor, 0, FCodeList.Text); end; end; function TChangeCaseExpert.HasConfigOptions: Boolean; begin Result := False; end; function TChangeCaseExpert.IsEditorActive(out ctl: TWinControl): Boolean; begin ctl := Screen.ActiveControl; Result := Assigned(ctl) and (ctl.Name = 'Editor') and ctl.ClassNameIs('TEditControl'); end; procedure TChangeCaseExpert.miChangeToLowerCaseClicked(Sender: TObject); begin FCodeList.Text := AnsiLowerCase(FCodeList.Text); ReplaceSelection; FLastSelection := (Sender as TMenuItem).MenuIndex; end; procedure TChangeCaseExpert.miChangeToSentenceCaseClicked(Sender: TObject); begin FCodeList.Text := SentenceCase(FCodeList.Text); ReplaceSelection; FLastSelection := (Sender as TMenuItem).MenuIndex; end; procedure TChangeCaseExpert.miChangeToTitleCaseClicked(Sender: TObject); begin FCodeList.Text := TitleCase(FCodeList.Text); ReplaceSelection; FLastSelection := (Sender as TMenuItem).MenuIndex; end; procedure TChangeCaseExpert.miChangeToUpperCaseClicked(Sender: TObject); begin FCodeList.Text := AnsiUpperCase(FCodeList.Text); ReplaceSelection; FLastSelection := (Sender as TMenuItem).MenuIndex; end; procedure TChangeCaseExpert.miToggleCaseClicked(Sender: TObject); begin FCodeList.Text := ToggleCase(FCodeList.Text); ReplaceSelection; FLastSelection := (Sender as TMenuItem).MenuIndex; end; procedure TChangeCaseExpert.Execute(Sender: TObject); var ctl: TWinControl; pnt: TPoint; SourceEditor: IOTASourceEditor; begin if not IsEditorActive(ctl) then Exit; if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then Exit; FCodeList.Text := GxOtaGetCurrentSelection; if FCodeList.Count = 0 then begin GxOtaSelectCurrentIdent(SourceEditor, False); FCodeList.Text := GxOtaGetCurrentSelection; end; if FCodeList.Count = 0 then Exit; FPopup.Items[FLastSelection].Default := True; if not Windows.GetCaretPos(pnt) then pnt := Point(0, 0); pnt := ctl.ClientToScreen(pnt); EnterWasPressed := False; FPopup.Popup(pnt.X, pnt.Y); // This is a rather ugly hack to execute the default menu item when the user presses Enter: // We installed a keyboard hook that sets the global variable EnterWasPressed to true, // when (you guessed it:) the Enter key was pressed. Pressing Enter closes the popup // menu even if no item was selected. EnterWasPressed is set to false just before // showing the popup menu and also in ReplaceSelection which is called by all // menu item's OnClick handlers. So if EnterWasPressed is true, we know: // 1. Enter was pressed after the popup menu was shown // 2. No menu item was executed // so we execute the default item. // I said it was ugly, didn't I? // But it gets worse: In order to execute the Item's .OnClick method we have to call // Application.ProcessMessages before we can check for EnterWasPressed. If we don't do // that, selecting an entry with the arrow keys and Enter will result in duplicating // the selected text. I'm beginning to regret changing the selection from a dialog to // a popup menu. // If you have got any better idea, please feel free to change this code. // -- 2016-10-01 twm Application.ProcessMessages; if EnterWasPressed then FPopup.Items[FLastSelection].Click; end; initialization RegisterEditorExpert(TChangeCaseExpert); end.
unit uObservacaoVO; interface uses System.SysUtils, uTableName, uKeyField; type [TableName('Observacao')] TObservacaoVO = class private FAtivo: Boolean; FCodigo: Integer; FId: Integer; FNome: string; FDescricao: string; FPrograma: Integer; FPadrao: Boolean; FObsEmail: string; FEmailPadrao: Boolean; procedure SetAtivo(const Value: Boolean); procedure SetCodigo(const Value: Integer); procedure SetId(const Value: Integer); procedure SetNome(const Value: string); procedure SetDescricao(const Value: string); procedure SetPadrao(const Value: Boolean); procedure SetPrograma(const Value: Integer); procedure SetEmailPadrao(const Value: Boolean); procedure SetObsEmail(const Value: string); public [KeyField('Obs_Id')] property Id: Integer read FId write SetId; [FieldName('Obs_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('Obs_Nome')] property Nome: string read FNome write SetNome; [FieldName('Obs_Ativo')] property Ativo: Boolean read FAtivo write SetAtivo; [FieldName('Obs_Descricao')] property Descricao: string read FDescricao write SetDescricao; [FieldName('Obs_Padrao')] property Padrao: Boolean read FPadrao write SetPadrao; [FieldName('Obs_Programa')] property Programa: Integer read FPrograma write SetPrograma; [FieldName('Obs_EmailPadrao')] property EmailPadrao: Boolean read FEmailPadrao write SetEmailPadrao; [FieldName('Obs_ObsEmail')] property ObsEmail: string read FObsEmail write SetObsEmail; end; implementation { TObservacaoVO } procedure TObservacaoVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TObservacaoVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TObservacaoVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TObservacaoVO.SetEmailPadrao(const Value: Boolean); begin FEmailPadrao := Value; end; procedure TObservacaoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TObservacaoVO.SetNome(const Value: string); begin FNome := Value; end; procedure TObservacaoVO.SetObsEmail(const Value: string); begin FObsEmail := Value; end; procedure TObservacaoVO.SetPadrao(const Value: Boolean); begin FPadrao := Value; end; procedure TObservacaoVO.SetPrograma(const Value: Integer); begin FPrograma := Value; end; end.
inherited dmOcorrencias: TdmOcorrencias OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWCPGTFUN6' ' (REGISTRO, DATA_OCORRENCIA, SEQUENCIA, DESCRICAO, OPERADOR, DT' + '_ALTERACAO)' 'VALUES' ' (:REGISTRO, :DATA_OCORRENCIA, :SEQUENCIA, :DESCRICAO, :OPERADO' + 'R, :DT_ALTERACAO)') SQLDelete.Strings = ( 'DELETE FROM STWCPGTFUN6' 'WHERE' ' REGISTRO = :Old_REGISTRO AND DATA_OCORRENCIA = :Old_DATA_OCORR' + 'ENCIA AND SEQUENCIA = :Old_SEQUENCIA') SQLUpdate.Strings = ( 'UPDATE STWCPGTFUN6' 'SET' ' REGISTRO = :REGISTRO, DATA_OCORRENCIA = :DATA_OCORRENCIA, SEQU' + 'ENCIA = :SEQUENCIA, DESCRICAO = :DESCRICAO, OPERADOR = :OPERADOR' + ', DT_ALTERACAO = :DT_ALTERACAO' 'WHERE' ' REGISTRO = :Old_REGISTRO AND DATA_OCORRENCIA = :Old_DATA_OCORR' + 'ENCIA AND SEQUENCIA = :Old_SEQUENCIA') SQLRefresh.Strings = ( 'SELECT REGISTRO, DATA_OCORRENCIA, SEQUENCIA, DESCRICAO, OPERADOR' + ', DT_ALTERACAO FROM STWCPGTFUN6' 'WHERE' ' REGISTRO = :Old_REGISTRO AND DATA_OCORRENCIA = :Old_DATA_OCORR' + 'ENCIA AND SEQUENCIA = :Old_SEQUENCIA') SQLLock.Strings = ( 'SELECT NULL FROM STWCPGTFUN6' 'WHERE' 'REGISTRO = :Old_REGISTRO AND DATA_OCORRENCIA = :Old_DATA_OCORREN' + 'CIA AND SEQUENCIA = :Old_SEQUENCIA' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' REGISTRO, ' ' DATA_OCORRENCIA, ' ' SEQUENCIA, ' ' DESCRICAO, ' ' OPERADOR, ' ' DT_ALTERACAO ' 'FROM STWCPGTFUN6') object qryManutencaoREGISTRO: TFloatField FieldName = 'REGISTRO' Required = True end object qryManutencaoDATA_OCORRENCIA: TDateTimeField FieldName = 'DATA_OCORRENCIA' Required = True end object qryManutencaoSEQUENCIA: TIntegerField FieldName = 'SEQUENCIA' Required = True end object qryManutencaoDESCRICAO: TBlobField FieldName = 'DESCRICAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' Size = 30 end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' REGISTRO, ' ' DATA_OCORRENCIA, ' ' SEQUENCIA, ' ' DESCRICAO, ' ' OPERADOR, ' ' DT_ALTERACAO ' 'FROM STWCPGTFUN6') object qryLocalizacaoREGISTRO: TFloatField FieldName = 'REGISTRO' Required = True end object qryLocalizacaoDATA_OCORRENCIA: TDateTimeField FieldName = 'DATA_OCORRENCIA' Required = True end object qryLocalizacaoSEQUENCIA: TIntegerField FieldName = 'SEQUENCIA' Required = True end object qryLocalizacaoDESCRICAO: TBlobField FieldName = 'DESCRICAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' Size = 30 end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end end end
unit CollectionBackup; interface uses Collection, BackupInterfaces; type TCollectionBackupAgent = class(TBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; TNotifiedCollectionBackupAgent = class(TCollectionBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; TLockableCollectionBackupAgent = class(TCollectionBackupAgent) protected class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; TSortedCollectionBackupAgent = class(TCollectionBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; TNotifiedSortedCollectionBackupAgent = class(TSortedCollectionBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; procedure RegisterBackup; implementation uses SysUtils; // TCollectionBackupAgent class procedure TCollectionBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); var index : integer; begin with TCollection(Obj) do begin Stream.WriteInteger('Count', Count); Stream.WriteInteger('RelKind', integer(RelKind)); if RelKind = rkBelonguer then for index := 0 to pred(Count) do Stream.WriteObject(IntToStr(index), Items[index]) else for index := 0 to pred(Count) do Stream.WriteObjectRef(IntToStr(index), Items[index]); end; end; class procedure TCollectionBackupAgent.Read(Stream : IBackupReader; Obj : TObject); var cnt : integer; rel : TRelationshipKind; index : integer; begin cnt := Stream.ReadInteger('Count', 0); rel := TRelationshipKind(Stream.ReadInteger('RelKind', 0)); with TCollection(Obj) do begin friend_RelKind := rkUse; friend_Capacity := cnt; for index := 0 to pred(cnt) do Stream.ReadObject(IntToStr(index), friend_Items[index], nil); friend_Count := cnt; friend_RelKind := rel; end; end; // TNotifiedCollectionBackupAgent class procedure TNotifiedCollectionBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin inherited Read(Stream, Obj); Stream.ReadMethod('OnModified', TMethod(TNotifiedCollection(Obj).friend_OnModified), NULLPROC); end; class procedure TNotifiedCollectionBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); begin inherited Write(Stream, Obj); Stream.WriteMethod('OnModified', TMethod(TNotifiedCollection(Obj).OnModified)); end; // TLockableCollectionBackupAgent class procedure TLockableCollectionBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin inherited Read(Stream, Obj); TLockableCollection(Obj).InitLock; end; // TSortedCollectionBackupAgent class procedure TSortedCollectionBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin inherited Read(Stream, Obj); Stream.ReadMethod('CompFuct', TMethod(TSortedCollection(Obj).friend_CompFunct), NULLPROC); end; class procedure TSortedCollectionBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); begin inherited Write(Stream, Obj); Stream.WriteMethod('CompFuct', TMethod(TSortedCollection(Obj).friend_CompFunct)); end; // TNotifiedSortedCollectionBackupAgent class procedure TNotifiedSortedCollectionBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin inherited Read(Stream, Obj); Stream.ReadMethod('OnModified', TMethod(TNotifiedCollection(Obj).friend_OnModified), NULLPROC); end; class procedure TNotifiedSortedCollectionBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); begin inherited Write(Stream, Obj); Stream.WriteMethod('OnModified', TMethod(TNotifiedCollection(Obj).OnModified)); end; // RegisterCollections procedure RegisterBackup; begin TCollectionBackupAgent.Register([TCollection]); TNotifiedCollectionBackupAgent.Register([TNotifiedCollection]); TLockableCollectionBackupAgent.Register([TLockableCollection]); TSortedCollectionBackupAgent.Register([TSortedCollection]); TNotifiedSortedCollectionBackupAgent.Register([TNotifiedSortedCollection]); end; end.
unit uItemBonus; interface const BonusMax = 24; type TBonus = array [1..BonusMax] of Integer; const BonusLabel: array [0..BonusMax, 0..1] of string = { 0}((#0, #0), { 1}('Strength', #0), ('Dexterity', #0), ('Stamina', #0), ('Magic', #0), { 5}('Spirit', #0), ('LightRadius', '$Радиус обзора'), ('ReplenishLife', '$Регенерация жизни'), ('ReplenishMana', '$Регенерация маны'), { 9}('DamageCrash', '$Дробящий урон'), ('DamageSlash', '$Режущий урон'), ('DamagePierce', '$Колющий урон'), ('DamageIce', '$Урон холодом'), {13}('DamageLightning', '$Урон молнией'), ('DamageFire', '$Урон огнем'), ('DamagePoison', '$Урон ядом'), ('DamageAcid', '$Урон кислотой'), {17}('ProtectCrash', '$Защита от крушащего'), ('ProtectSlash', '$Защита от режущего'), ('ProtectPierce', '$Защита от колющего'), ('ProtectIce', '$Защита от холода'), {21}('ProtectLightning', '$Защита от молнии'), ('ProtectFire', '$Защита от огня'), ('ProtectPoison', '$Защита от яда'), ('ProtectAcid', '$Защита от кислоты') ); var Bonus: TBonus; BonusID: string = ''; BonusCount: Integer = 0; procedure RecBonus; procedure ClearBonus(var ABonus: TBonus); implementation procedure RecBonus; var I: Byte; begin for I := 1 to BonusMax do if (BonusID = BonusLabel[I][0]) then Inc(Bonus[I], BonusCount); end; procedure ClearBonus(var ABonus: TBonus); var I: Byte; begin for I := 1 to BonusMax do ABonus[I] := 0; end; end.
unit UPrincipal; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.MultiView, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Objects, System.IOUtils; type TFPrincipal = class(TForm) Layout1: TLayout; ToolBar1: TToolBar; MultiView1: TMultiView; btnMenu: TSpeedButton; RecTopMultiView: TRectangle; Rectangle2: TRectangle; Rectangle3: TRectangle; Layout2: TLayout; RecNovoTreino: TRectangle; ImgNovoTreino: TImage; lblNovoTreino: TLabel; RecLogout: TRectangle; ImgLogout: TImage; lblLogout: TLabel; RecConfiguracao: TRectangle; ImgConfiguracao: TImage; lblConfiguracao: TLabel; VertScrollBox1: TVertScrollBox; procedure RecNovoTreinoClick(Sender: TObject); procedure ImgNovoTreinoClick(Sender: TObject); procedure lblNovoTreinoClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure CriarRetangulo(CaptionLabel: String); end; var FPrincipal: TFPrincipal; implementation {$R *.fmx} uses UCadastroTreino; {$R *.NmXhdpiPh.fmx ANDROID} {$R *.Surface.fmx MSWINDOWS} procedure TFPrincipal.ImgNovoTreinoClick(Sender: TObject); begin lblNovoTreinoClick(Sender); end; procedure TFPrincipal.lblNovoTreinoClick(Sender: TObject); begin if not Assigned(FCadastroTreino) then Application.CreateForm(TFCadastroTreino, FCadastroTreino); FCadastroTreino.Show; end; procedure TFPrincipal.RecNovoTreinoClick(Sender: TObject); begin lblNovoTreinoClick(Sender); end; procedure TFPrincipal.CriarRetangulo(CaptionLabel: String); var Retangulos : TRectangle; Labels : TLabel; Imagem : TImage; begin Retangulos := TRectangle.Create(nil); Retangulos.Parent := VertScrollBox1; Retangulos.Name := 'Retangulo1'; Retangulos.Align := TAlignLayout.Top; Retangulos.Margins.Right := 5; Retangulos.Margins.Left := 5; Retangulos.Margins.Bottom := 5; Retangulos.Margins.Top := 5; Retangulos.Height := 80; Retangulos.Fill.Color := $FF6F7E75;//TAlphaColors.Blue; Imagem := TImage.Create(nil); Imagem.Parent := Retangulos; Imagem.Name := 'Imagem1'; Imagem.Align := TAlignLayout.Left; Imagem.Margins.Right := 5; Imagem.Margins.Left := 10; Imagem.Margins.Bottom := 10; Imagem.Margins.Top := 10; Imagem.MultiResBitmap[0].Bitmap.LoadFromFile(TPath.Combine(TPath.GetSharedDocumentsPath,'Imagem.png')); Imagem.MultiResBitmap[0].Scale := 1; Imagem.Width := 70; Imagem.Height := 60; Imagem.WrapMode := TImageWrapMode.Stretch; Imagem.MarginWrapMode := TImageWrapMode.Stretch; Labels := TLabel.Create(nil); Labels.Parent := Retangulos; Labels.Name := 'Label1'; Labels.Align := TAlignLayout.Client; Labels.Margins.Right := 5; Labels.Margins.Left := 5; Labels.Margins.Bottom := 10; Labels.Margins.Top := 10; Labels.Text := 'TREINO DA SEGUNDA'; MultiView1.HideMaster; end; end.
unit iOSapi.BaiduMapAPI_Navi; { *********************************************************** } { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2012-2014 Embarcadero Technologies, Inc. } { } { *********************************************************** } // // Delphi-Objective-C Bridge // Interfaces for Cocoa framework BaiduNaviSDK // interface uses Macapi.ObjectiveC, Macapi.ObjCRuntime, iOSapi.UIKit, iOSapi.CocoaTypes, iOSapi.CoreLocation, iOSapi.CoreData, iOSapi.MediaPlayer, iOSapi.Foundation; const BNAVI_ROUTEPLAN_ERROR_INVALIDSTARTENDNODE = 5000; //请设置完整的起终点 BNAVI_ROUTEPLAN_ERROR_INPUTERROR = 5001; //节点输入有误 BNAVI_ROUTEPLAN_ERROR_NODESTOONEAR = 5002;//节点之间距离太近 // 检索错误(5100开始) BNAVI_ROUTEPLAN_ERROR_SEARCHFAILED =5100; //检索失败 // 定位错误(5200开始) BNAVI_ROUTEPLAN_ERROR_LOCATIONFAILED = 5200; //获取地理位置失败 BNAVI_ROUTEPLAN_ERROR_LOCATIONSERVICECLOSED = 5201; //定位服务未开启 // 算路相关网络错误(5030开始) BNAVI_ROUTEPLAN_ERROR_NONETWORK = 5030; //网络不可用 BNAVI_ROUTEPLAN_ERROR_NETWORKABNORMAL = 5031;//网络异常,尝试联网线路规划失败。自动切换到本地线路规划(客户端预留定义) // 算路过程错误(5050开始) BNAVI_ROUTEPLAN_ERROR_ROUTEPLANFAILED = 5050; //无法发起算路(客户端请求算路返回id<0) BNAVI_ROUTEPLAN_ERROR_SETSTARTPOSFAILED = 5051;//起点失败 BNAVI_ROUTEPLAN_ERROR_SETENDPOSFAILED = 5052; //设置终点失败 BNAVI_ROUTEPLAN_ERROR_WAITAMOMENT = 5054; //上次算路取消了,需要等一会 BNAVI_ROUTEPLAN_ERROR_DATANOTREADY = 5055; //行政区域数据没有 BNAVI_ROUTEPLAN_ERROR_ENGINENOTINIT = 5056; //引擎未初始化 BNAVI_ROUTEPLAN_ERROR_LIGHTSEARCHERROR = 5057;//light检索未成功发送 BNRoutePlanMode_Invalid = $00000000 ; //**< 无效值 */ BNRoutePlanMode_Recommend = $00000001 ; //**< 推荐 */ BNRoutePlanMode_Highway = $00000002 ; //**< 高速优先 */ BNRoutePlanMode_NoHighway = $00000004 ; //**< 少走高速 */ BNRoutePlanMode_NoToll = $00000008 ; //**< 少收费 */ BNRoutePlanMode_AvoidTrafficJam = $00000010 ; //**< 躲避拥堵(在线规划独有) */ type BNAVI_ROUTEPLAN_ERROR = Cardinal; BNRoutePlanMode = Cardinal; //播报模式 BN_Speak_Mode_Enum = ( BN_Speak_Mode_High, //**< 新手模式 */ BN_Speak_Mode_Mid, //**< 专家模式 */ BN_Speak_Mode_Low //**< 静音模式 */ ); //白天,黑夜模式类型 BNDayNight_CFG_Type = ( BNDayNight_CFG_Type_Auto, //自动 BNDayNight_CFG_Type_Day, //白天模式 BNDayNight_CFG_Type_Night //黑夜模式 ); BNCoordinate_Type = ( BNCoordinate_OriginalGPS = 0,//**< 原始的经纬度坐标 */ BNCoordinate_BaiduMapSDK = 1 //**< 从百度地图中获取的sdk */ ); BNaviUIType = ( BNaviUI_Unknown = 0, BNaviUI_NormalNavi, //正常导航 BNaviUI_Declaration //声明页面 ); BNavi_ExitPage_Type = ( EN_BNavi_ExitTopVC, EN_BNavi_ExitAllVC ); TInitServicesBlock = procedure of object; TTrySetShowTrafficInNaviBlock = procedure of object; TGetCityIDByLocationSucessBlock = procedure(parame:Integer) of object; TGetCityIDByLocationFailBlock = procedure of object; BNLocation = interface; BNHeading = interface; BNCoreServices = interface; BNaviModel = interface; BNPosition = interface; BNRoutePlanNode =interface; BNRouteItem = interface; BNRouteDetailInfo = interface; BNaviCalcRouteTime = interface; BNUIManagerProtocol = interface; BNNaviUIManagerDelegate = interface; BNStrategyManagerProtocol = interface; BNRoutePlanManagerProtocol = interface; BNNaviRoutePlanDelegate = interface; BNLocationManagerProtocol = interface; BNLocationClass = interface(NSObjectClass) ['{B81FDBDA-9495-448D-900E-3B104625E70F}'] end; BNLocation = interface(NSObject) ['{3F6C4E00-E241-4940-8464-1783EC8EC834}'] //wgs84ll格式的经纬度 procedure setCoordinate(coordinate:CLLocationCoordinate2D); cdecl; function getCoordinate:CLLocationCoordinate2D; cdecl; //海拔,单位为米 procedure setAltitude(altitude:CLLocationDistance); cdecl; function getAltitude:CLLocationDistance; cdecl; //水平精度,单位为米 procedure setHorizontalAccuracy(horizontalAccuracy:CLLocationAccuracy); cdecl; function getHorizontalAccuracy:CLLocationAccuracy; cdecl; //垂直精度,单位为米 procedure setVerticalAccuracy(verticalAccuracy:CLLocationAccuracy); cdecl; function getVerticalAccuracy:CLLocationAccuracy; cdecl; //方向角度,单位为度,范围位0.0-359.9,0表示正北 procedure setCourse(course:CLLocationDirection); cdecl; function getCourse:CLLocationDirection; cdecl; //速度,单位为米/秒 procedure setSpeed(speed:CLLocationSpeed); cdecl; function getSpeed:CLLocationSpeed; cdecl; procedure setTimestamp(timestamp:NSDate); cdecl; function getTimestamp:NSDate; cdecl; end; TBNLocation = class(TOCGenericImport<BNLocationClass, BNLocation>)end; BNHeadingClass = interface(NSObjectClass) ['{9A7ACBFE-4593-42C6-9CEE-1226431F12B7}'] end; BNHeading = interface(NSObject) ['{29AC6F33-57DD-484A-8CEA-6545D39656FC}'] procedure setMagneticHeading(magneticHeading:CLLocationDirection); cdecl; function getMagneticHeading:CLLocationDirection; cdecl; //旋转角精度 procedure setHeadingAccuracy(headingAccuracy:CLLocationDirection); cdecl; function getHeadingAccuracy:CLLocationDirection; cdecl; //旋转角度大小,单位位度,范围位0-359.9,0表示正北 procedure setTrueHeading(trueHeading:CLLocationDirection); cdecl; function getTrueHeading:CLLocationDirection; cdecl; end; TBNHeading = class(TOCGenericImport<BNHeadingClass, BNHeading>)end; BNCoreServicesClass = interface(NSObjectClass) ['{3C4D4B4C-CE82-416A-A2A8-20B64757F7D1}'] function GetInstance:BNCoreServices; cdecl; procedure ReleaseInstance; cdecl; function libVersion:NSString; cdecl; function UIService:Pointer; cdecl; function RoutePlanService:Pointer; cdecl; function StrategyService:Pointer; cdecl; function LocationService:Pointer; cdecl; end; BNCoreServices = interface(NSObject) ['{485F517E-B514-49D2-892E-D9F7C2944479}'] procedure initServices(ak:NSString); cdecl; procedure setTTSAppId(appId:NSString); cdecl; procedure setAutoExitNavi(autoExit:Boolean); cdecl; function startServices:Boolean; cdecl; [MethodName('startServicesAsyn:fail:')] procedure startServicesAsyn(success:TInitServicesBlock; fail:TInitServicesBlock); cdecl; function isServicesInited:Boolean; cdecl; procedure stopServices; cdecl; function convertToBD09MCWithWGS84ll(coordinate:CLLocationCoordinate2D):CLLocationCoordinate2D; cdecl; end; TBNCoreServices = class(TOCGenericImport<BNCoreServicesClass, BNCoreServices>)end; BNaviModelClass = interface(NSObjectClass) ['{B9800974-3ACA-4805-8397-974D72766DCD}'] function getInstance:BNaviModel; cdecl; end; BNaviModel = interface(NSObject) ['{B7A4FF7F-8388-4C87-A9C2-3C2B5CF860E5}'] function getNaviViewController:UIViewController; cdecl; procedure exitNavi; cdecl; procedure resetNaviEndPoint(endNode:BNRoutePlanNode); cdecl; end; TBNaviModel = class(TOCGenericImport<BNaviModelClass, BNaviModel>)end; BNPositionClass = interface(NSObjectClass) ['{91339D2E-BF8F-4BFB-8784-D9A92C2C7212}'] end; BNPosition = interface(NSObject) ['{A79670A5-3B75-4D48-847F-A417A87B052E}'] procedure setX(x:double); cdecl; function getX:double; cdecl; procedure setY(y:double); cdecl; function getY:double; cdecl; procedure setEType(eType:BNCoordinate_Type); cdecl; function getEType:BNCoordinate_Type; cdecl; end; TBNPosition = class(TOCGenericImport<BNPositionClass, BNPosition>)end; BNRoutePlanNodeClass = interface(NSObjectClass) ['{764394AA-1A75-4307-8184-F0374FF39405}'] end; BNRoutePlanNode = interface(NSObject) ['{C0B65A7C-2E36-4C1D-AB0B-8091010B0559}'] procedure setPos(pos:BNPosition); cdecl; function getPos:BNPosition; cdecl; procedure setCityID(cityID:NSString); cdecl; function getCityID:NSString; cdecl; procedure setTitle(title:NSString); cdecl; function getTitle:NSString; cdecl; procedure setAddress(address:NSString); cdecl; function getAddress:NSString; cdecl; end; TBNRoutePlanNode = class(TOCGenericImport<BNRoutePlanNodeClass, BNRoutePlanNode>)end; BNRouteItemClass = interface(NSObjectClass) ['{AC2ED442-3274-46AB-9BB6-BDB95412ABFF}'] end; BNRouteItem = interface(NSObject) ['{F231D3AA-832D-479D-9CB9-2793816D8280}'] procedure setNextRoadName(nextRoadName:NSString); cdecl; function getNextRoadName:integer; cdecl; procedure setNLength(nLength:integer); cdecl; function getNLength:NSString; cdecl; procedure setNTime(nTime:integer); cdecl; function getNTime:integer; cdecl; procedure setCrossPos(crossPos:BNPosition); cdecl; function getCrossPos:BNPosition; cdecl; procedure setNShapePointIdx(nShapePointIdx:integer); cdecl; function getNShapePointIdx:integer; cdecl; procedure setNnOutLinkAngle(unOutLinkAngle:integer); cdecl; function getNnOutLinkAngle:integer; cdecl; end; TBNRouteItem = class(TOCGenericImport<BNRouteItemClass, BNRouteItem>)end; BNRouteDetailInfoClass = interface(NSObjectClass) ['{9942B722-C804-4626-B108-A1C7F454427B}'] end; BNRouteDetailInfo = interface(NSObject) ['{4792BDE8-60AB-46A9-B23C-A33109789B91}'] procedure setUnLabel(unLabel:integer); cdecl; function getUnLabel:integer; cdecl; procedure setUnLength(unLength:integer); cdecl; function getUnLength:integer; cdecl; procedure setUnPasstime(unPasstime:integer); cdecl; function getUnPasstime:integer; cdecl; procedure setRouteItemList(routeItemList:NSArray); cdecl; function getRouteItemList:NSArray; cdecl; procedure setBTolled(bTolled:boolean); cdecl; function getBTolled:boolean; cdecl; end; TBNRouteDetailInfo = class(TOCGenericImport<BNRouteDetailInfoClass, BNRouteDetailInfo>)end; BNaviCalcRouteTimeClass = interface(NSObjectClass) ['{F9A780AE-AFCD-4E67-90FF-13AB9850613D}'] end; BNaviCalcRouteTime = interface(NSObject) ['{D20F39A8-3638-4C9E-A829-F8F5C3722586}'] procedure setUnHour(unHour:integer); cdecl; function getUnHour:integer; cdecl; procedure setUnMin(unMin:integer); cdecl; function getUnMin:integer; cdecl; procedure setBValid(bValid:boolean); cdecl; function getBValid:boolean; cdecl; end; TBNaviCalcRouteTime = class(TOCGenericImport<BNaviCalcRouteTimeClass, BNaviCalcRouteTime>)end; (* BNUIManagerProtocolClass = interface(NSObjectClass) ['{83EC2B9A-4CAA-44B8-89ED-54C3029CEA1B}'] end; BNUIManagerProtocol = interface(NSObject) ['{1393677B-B2D9-47FD-B276-B12BC439899F}'] function navigationController:Pointer; cdecl; [MethodName('showPage:delegate:extParams:')] procedure showPage(pageType:BNaviUIType; delegate:Pointer; extParams:NSDictionary); cdecl; [MethodName('exitPage:animated:extraInfo:')] procedure exitPage(exitType:BNavi_ExitPage_Type; animated:Boolean; extraInfo:NSDictionary); cdecl; function isInNaviPage:Boolean; cdecl; end; TBNUIManagerProtocol = class(TOCGenericImport<BNUIManagerProtocolClass, BNUIManagerProtocol>)end; *) BNUIManagerProtocol = interface(IObjectiveC) ['{1393677B-B2D9-47FD-B276-B12BC439899F}'] function navigationController:Pointer; cdecl; [MethodName('showPage:delegate:extParams:')] procedure showPage(pageType:BNaviUIType; delegate:Pointer; extParams:NSDictionary); cdecl; [MethodName('exitPage:animated:extraInfo:')] procedure exitPage(exitType:BNavi_ExitPage_Type; animated:Boolean; extraInfo:NSDictionary); cdecl; function isInNaviPage:Boolean; cdecl; end; BNNaviUIManagerDelegate = interface(IObjectiveC) ['{24DED9C2-3501-478A-9896-5DCB36B19FD8}'] function naviPresentedViewController:Pointer; cdecl; [MethodName('extraInfo:extraInfo:')] procedure onExitPage(pageType:BNaviUIType; extraInfo:NSDictionary); cdecl; end; (* BNStrategyManagerProtocolClass = interface(NSObjectClass) ['{E752353F-A360-4EF0-8705-B34C881CDBAF}'] end; BNStrategyManagerProtocol = interface(NSObject) ['{31068385-1040-4CF3-BA29-623FC2E968EC}'] procedure reset; cdecl; procedure setParkInfo(parkInfo:Boolean); cdecl; function getParkInfo:Boolean; cdecl; procedure setDayNightType(dayNightType:BNDayNight_CFG_Type); cdecl; function getDayNightType:BNDayNight_CFG_Type; cdecl; procedure setSpeakMode(speakMode:BN_Speak_Mode_Enum); cdecl; function getSpeakMode:BN_Speak_Mode_Enum; cdecl; [MethodName('trySetShowTrafficInNavi:success:fail:')] procedure trySetShowTrafficInNavi(showTraffic:Boolean; success:TTrySetShowTrafficInNaviBlock; fail:TTrySetShowTrafficInNaviBlock); cdecl; end; TBNStrategyManagerProtocol = class(TOCGenericImport<BNStrategyManagerProtocolClass, BNStrategyManagerProtocol>)end; *) BNStrategyManagerProtocol = interface(IObjectiveC) ['{31068385-1040-4CF3-BA29-623FC2E968EC}'] procedure reset; cdecl; procedure setParkInfo(parkInfo:Boolean); cdecl; function getParkInfo:Boolean; cdecl; procedure setDayNightType(dayNightType:BNDayNight_CFG_Type); cdecl; function getDayNightType:BNDayNight_CFG_Type; cdecl; procedure setSpeakMode(speakMode:BN_Speak_Mode_Enum); cdecl; function getSpeakMode:BN_Speak_Mode_Enum; cdecl; [MethodName('trySetShowTrafficInNavi:success:fail:')] procedure trySetShowTrafficInNavi(showTraffic:Boolean; success:TTrySetShowTrafficInNaviBlock; fail:TTrySetShowTrafficInNaviBlock); cdecl; end; (* BNRoutePlanManagerProtocolClass = interface(NSObjectClass) ['{391E8C57-7FBE-40EA-9B25-909714F741B3}'] end; BNRoutePlanManagerProtocol = interface(NSObject) ['{A58C4EB2-62D0-458F-A17F-0EACB57E7CCB}'] [MethodName('startNaviRoutePlan:naviNodes:time:delegete:userInfo:')] procedure startNaviRoutePlan(eMode:BNRoutePlanMode; naviNodes:NSArray; naviTime:BNaviCalcRouteTime; delegate:Pointer; userInfo:NSDictionary); cdecl; function getCurNodeCount:NSInteger; cdecl; function getNaviNodeAtIndex(index:NSInteger):BNRoutePlanNode; cdecl; procedure setNaviNodes(naviNodes:NSArray); cdecl; function getCurRoutePlanMode:Integer; cdecl; function GetCurrentSelectRouteIdx:NSInteger; cdecl; function getCurrentRouteDetailInfo(stRouteIdx:Integer):BNRouteDetailInfo; cdecl; function getCurrentPreference:Integer; cdecl; procedure setDisableOpenUrl(disableOpenUrl:Boolean); cdecl; function getDisableOpenUrl:Boolean; cdecl; end; TBNRoutePlanManagerProtocol = class(TOCGenericImport<BNRoutePlanManagerProtocolClass, BNRoutePlanManagerProtocol>)end; *) BNRoutePlanManagerProtocol = interface(IObjectiveC) ['{A58C4EB2-62D0-458F-A17F-0EACB57E7CCB}'] [MethodName('startNaviRoutePlan:naviNodes:time:delegete:userInfo:')] procedure startNaviRoutePlan(eMode:BNRoutePlanMode; naviNodes:NSArray; naviTime:BNaviCalcRouteTime; delegate:Pointer; userInfo:NSDictionary); cdecl; function getCurNodeCount:NSInteger; cdecl; function getNaviNodeAtIndex(index:NSInteger):BNRoutePlanNode; cdecl; procedure setNaviNodes(naviNodes:NSArray); cdecl; function getCurRoutePlanMode:Integer; cdecl; function GetCurrentSelectRouteIdx:NSInteger; cdecl; function getCurrentRouteDetailInfo(stRouteIdx:Integer):BNRouteDetailInfo; cdecl; function getCurrentPreference:Integer; cdecl; procedure setDisableOpenUrl(disableOpenUrl:Boolean); cdecl; function getDisableOpenUrl:Boolean; cdecl; end; BNNaviRoutePlanDelegate = interface(IObjectiveC) ['{EBD69F8D-AAE8-4715-809A-23ED3B936C51}'] procedure routePlanDidFinished(userInfo:NSDictionary); cdecl; procedure searchDidFinished(userInfo:NSDictionary); cdecl; [MethodName('routePlanDidFailedWithError:andUserInfo:')] procedure routePlanDidFailedWithError(error:NSError; userInfo:NSDictionary); cdecl; procedure routePlanDidUserCanceled(userInfo:NSDictionary); cdecl; procedure updateRoadConditionDidFinished(pbData:NSData); cdecl; procedure updateRoadConditionFailed(pbData:NSData); cdecl; end; (* BNLocationManagerProtocolClass = interface(NSObjectClass) ['{0248EB89-AE97-4785-87A7-4A292CB5B0F3}'] end; BNLocationManagerProtocol = interface(NSObject) ['{C8B4AD58-A7F5-4BA0-A6BB-03315A7DC003}'] procedure startUpdate; cdecl; procedure stopUpdate; cdecl; function getLastLocation:CLLocation; cdecl; procedure getCityIDByLocation(location:CLLocationCoordinate2D; sucess:TGetCityIDByLocationSucessBlock; fail:TGetCityIDByLocationFailBlock); cdecl; procedure setGpsFromExternal(gpsFromExternal:Boolean); cdecl; function getGpsFromExternal:Boolean; cdecl; procedure setCurrentLocation(currentLocation:Boolean); cdecl; function getCurrentLocation:Boolean; cdecl; end; TBNLocationManagerProtocol = class(TOCGenericImport<BNLocationManagerProtocolClass, BNLocationManagerProtocol>)end; *) BNLocationManagerProtocol = interface(CLLocationManagerDelegate) ['{C8B4AD58-A7F5-4BA0-A6BB-03315A7DC003}'] procedure startUpdate; cdecl; procedure stopUpdate; cdecl; function getLastLocation:CLLocation; cdecl; procedure getCityIDByLocation(location:CLLocationCoordinate2D; sucess:TGetCityIDByLocationSucessBlock; fail:TGetCityIDByLocationFailBlock); cdecl; procedure setGpsFromExternal(gpsFromExternal:Boolean); cdecl; function getGpsFromExternal:Boolean; cdecl; procedure setCurrentLocation(currentLocation:Boolean); cdecl; function getCurrentLocation:Boolean; cdecl; end; implementation {$O-} //function BNCoreServices_FakeLoader:BNCoreServices; cdecl; external 'libbaiduNaviSDK.a' name 'OBJC_CLASS_$_BNCoreServices'; //function BNLocation_FakeLoader:BNLocation; cdecl; external 'libbaiduNaviSDK.a' name 'OBJC_CLASS_$_BNLocation'; //function BNRoutePlanNode_FakeLoader:BNRoutePlanNode; cdecl; external 'libbaiduNaviSDK.a' name 'OBJC_CLASS_$_BNRoutePlanNode'; {$O+} end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { 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 System.LogEvents; interface Uses {$IFDEF FMX} FMX.Forms, {$ELSE} VCL.Forms, {$ENDIF} System.Classes, System.Generics.Collections, System.SysUtils, System.SyncObjs, System.LogEvents.Progress; type TLogListItem = class private FonErro: TLogListEvent; Finstancia: TObject; FIdent: Integer; FOnProgress: TLogProgressEvent; procedure SetonErro(const Value: TLogListEvent); procedure Setinstancia(const Value: TObject); procedure SetIdent(const Value: Integer); procedure SetOnProgress(const Value: TLogProgressEvent); published public property Ident: Integer read FIdent write SetIdent; property instancia: TObject read Finstancia write Setinstancia; property OnErro: TLogListEvent read FonErro write SetonErro; property OnProgress: TLogProgressEvent read FOnProgress write SetOnProgress; end; TLogListItems = class(TObjectList<TLogListItem>) private FLock: TCriticalSection; FBuffer: AnsiString; FMostraDataHora: boolean; FEnabled: boolean; FSyncronized: boolean; procedure SetMostraDataHora(const Value: boolean); procedure SetEnabled(const Value: boolean); procedure DoProcessProc(sender: TObject; identific: Integer; ATipo: TLogEventType; msg: string; APosition: double = 0; nInteracoes: Integer = 1); procedure SetSyncronized(const Value: boolean); public property Enabled: boolean read FEnabled write SetEnabled; property Syncronized: boolean read FSyncronized write SetSyncronized; property MostraDataHora: boolean read FMostraDataHora write SetMostraDataHora; procedure register(sender: TObject; event: TLogListEvent; identific: Integer); overload; procedure register(sender: TObject; event: TLogProgressEvent; identific: Integer); overload; procedure unregister(sender: TObject); procedure DoErro(sender: TObject; identific: Integer; s: string; nInteracoes: Integer = 1); procedure DoMsg(sender: TObject; identific: Integer; s: string; nInteracoes: Integer = 1); procedure DoProgress(sender: TObject; identific: Integer; ATipo: TLogEventType; msg: string; APosition: double = 0; nInteracoes: Integer = 1); procedure SetMax(FValue: Integer); procedure Log(texto: string); constructor create(); destructor Destroy; override; procedure Run(proc: TProc); end; var LogEvents: TLogListItems; implementation {$IF CompilerVersion>28.0} uses System.Threading; {$ENDIF} procedure TLogListItem.SetIdent(const Value: Integer); begin FIdent := Value; end; procedure TLogListItem.Setinstancia(const Value: TObject); begin Finstancia := Value; end; procedure TLogListItem.SetonErro(const Value: TLogListEvent); begin FonErro := Value; end; procedure TLogListItem.SetOnProgress(const Value: TLogProgressEvent); begin FOnProgress := Value; end; { TLogListItems } constructor TLogListItems.create(); begin inherited create; FSyncronized := true; FMostraDataHora := true; FLock := TCriticalSection.create; Enabled := true; end; destructor TLogListItems.Destroy; begin freeAndNil(FLock); inherited; end; procedure TLogListItems.DoErro(sender: TObject; identific: Integer; s: string; nInteracoes: Integer = 1); begin // compatibilidade DoMsg(sender, identific, s, nInteracoes); end; procedure TLogListItems.DoMsg(sender: TObject; identific: Integer; s: string; nInteracoes: Integer); var it: TLogListItem; i, x: Integer; h, buf: AnsiString; begin Run( procedure var i: Integer; begin h := ''; try if not Enabled then exit; buf := FBuffer; FBuffer := ''; x := 0; if FMostraDataHora then h := FormatDateTime('DD/MM/YY hh:mm:ss', now) + ' '; FBuffer := ''; for i := 0 to Count - 1 do begin it := TLogListItem(items[i]); if (identific = 0) or (it.Ident = identific) then begin if assigned(it.FonErro) then begin it.FonErro(sender, h + s + buf); inc(x); end; end; if nInteracoes = 0 then continue; if x >= nInteracoes then break; end; finally end; end); end; procedure TLogListItems.DoProcessProc(sender: TObject; identific: Integer; ATipo: TLogEventType; msg: string; APosition: double = 0; nInteracoes: Integer = 1); var i, x: Integer; it: TLogListItem; begin try if not Enabled then exit; FBuffer := ''; x := 0; for i := 0 to Count - 1 do begin it := TLogListItem(items[i]); if (identific = 0) or (it.Ident = identific) then begin if assigned(it.OnProgress) then begin it.FOnProgress(sender, ATipo, msg, APosition); inc(x); end; end; if nInteracoes = 0 then continue; if x >= nInteracoes then break; end; finally end; end; procedure TLogListItems.DoProgress(sender: TObject; identific: Integer; ATipo: TLogEventType; msg: string; APosition: double = 0; nInteracoes: Integer = 1); begin Run( procedure begin DoProcessProc(sender, identific, ATipo, msg, APosition, nInteracoes); end); end; procedure TLogListItems.Log(texto: string); begin Run( procedure begin DoErro(self, 0, texto, 1); end); end; procedure TLogListItems.register(sender: TObject; event: TLogListEvent; identific: Integer); var it: TLogListItem; begin it := TLogListItem.create; Add(it); it.instancia := sender; it.OnErro := event; it.Ident := identific; end; procedure TLogListItems.register(sender: TObject; event: TLogProgressEvent; identific: Integer); var it: TLogListItem; begin it := TLogListItem.create; Add(it); it.instancia := sender; it.OnProgress := event; it.Ident := identific; end; procedure TLogListItems.Run(proc: TProc); begin if not FSyncronized then begin proc; exit; end else {$IF CompilerVersion>28.0} TTask.create( procedure begin try TThread.Queue(nil, procedure begin proc; end); except on e: exception do LogEvents.DoErro(nil, 0, e.message); end; end).start; {$ELSE} TThread.CreateAnonymousThread( procedure begin try TThread.Queue(nil, procedure begin proc; end); except on e: exception do LogEvents.DoErro(nil, 0, e.message); end; end).start; {$ENDIF} end; procedure TLogListItems.SetEnabled(const Value: boolean); begin FEnabled := Value; end; procedure TLogListItems.SetMax(FValue: Integer); begin end; procedure TLogListItems.SetMostraDataHora(const Value: boolean); begin FMostraDataHora := Value; end; procedure TLogListItems.SetSyncronized(const Value: boolean); begin FSyncronized := Value; end; procedure TLogListItems.unregister(sender: TObject); var i: Integer; begin for i := Count - 1 downto 0 do if TLogListItem(items[i]).instancia = sender then delete(i); end; initialization LogEvents := TLogListItems.create; finalization LogEvents.free; end.
unit ChangeLoanNumberDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TChangeLoanNumberDialog = class(TComponent) private FOldLoanNumber: string; FNewLoanNumber: string; FDlgCaption: string; procedure SetNewLoanNumber(const Value: string); procedure SetOldLoanNumber(const Value: string); procedure SetDlgCaption(const Value: string); { Private declarations } protected { Protected declarations } public { Public declarations } function Execute:boolean; published { Published declarations } property OldLoanNumber:string read FOldLoanNumber write SetOldLoanNumber; property NewLoanNumber:string read FNewLoanNumber write SetNewLoanNumber; property DlgCaption:string read FDlgCaption write SetDlgCaption; end; procedure Register; implementation uses ChangeLoanNumberForm; procedure Register; begin RegisterComponents('FFS Dialogs', [TChangeLoanNumberDialog]); end; { TChangeLoanNumberDialog } function TChangeLoanNumberDialog.Execute: boolean; var fChangeNumber : TfrmChangeLoanNumber; loancap : string; begin fChangeNumber := TfrmChangeLoanNumber.create(self); loancap := 'Change Loan Number'; if dlgCaption > '' then loancap := dlgCaption; fChangeNumber.caption := loancap; fChangeNumber.OldLoanNumber := OldLoanNumber; if fChangeNumber.showmodal = mrOk then begin result := true; NewLoanNumber := fChangeNumber.NewLoanNumber; end else begin result := false; NewLoanNumber := OldLoanNumber; end; fChangeNumber.Free; end; procedure TChangeLoanNumberDialog.SetDlgCaption(const Value: string); begin FDlgCaption := Value; end; procedure TChangeLoanNumberDialog.SetNewLoanNumber(const Value: string); begin FNewLoanNumber := Value; end; procedure TChangeLoanNumberDialog.SetOldLoanNumber(const Value: string); begin FOldLoanNumber := Value; end; end.
{ Copyright (C) 2013 Dimitar Paperov That source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This code is distributed not all hope is lost that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit motor_params_form; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Spin, mdTypes; type { TfrmRotorParams } TfrmRotorParams = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Gear: TFloatSpinEdit; gAngles: TGroupBox; gStartRamp: TGroupBox; gStopRamp: TGroupBox; gOther: TGroupBox; Label1: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Label16: TLabel; Label17: TLabel; Label18: TLabel; Label19: TLabel; Label2: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; Label24: TLabel; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label28: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; MaxAngle: TSpinEdit; MaxPower: TSpinEdit; StopAt: TSpinEdit; StopTime2: TSpinEdit; StopTime3: TSpinEdit; StopPower2: TSpinEdit; StopPower3: TSpinEdit; StartTime1: TSpinEdit; StartPower1: TSpinEdit; StartTime2: TSpinEdit; StartTime3: TSpinEdit; StartPower2: TSpinEdit; StartPower3: TSpinEdit; StopTime1: TSpinEdit; StopPower1: TSpinEdit; MinAngle: TSpinEdit; PulsesTimeout: TSpinEdit; gState: TRadioGroup; gType: TRadioGroup; gKing: TRadioGroup; gInput: TRadioGroup; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { private declarations } fReadOnly: boolean; public { public declarations } function ShowMe(aReadOnly: boolean): boolean; procedure ToInterface(var c: TMD_ROTOR_CONFIG); procedure FromInterface(var c: TMD_ROTOR_CONFIG); end; var frmRotorParams: TfrmRotorParams; implementation {$R *.lfm} { TfrmRotorParams } procedure TfrmRotorParams.Button1Click(Sender: TObject); begin if fReadOnly then ModalResult:=mrCancel else ModalResult := mrOk; end; procedure TfrmRotorParams.Button2Click(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmRotorParams.Button3Click(Sender: TObject); begin gType.ItemIndex := 0; gInput.ItemIndex := 1; if gKing.ItemIndex = 0 then begin MinAngle.Value := -180; MaxAngle.Value := 540; end else begin MinAngle.Value := -15; MaxAngle.Value := 195; end; Gear.Value := 0.09375; PulsesTimeout.Value := 4; MaxPower.Value := 100; StopAt.Value := 5; StartPower1.Value := 0; StartPower2.Value := 0; StartPower3.Value := 0; StartTime1.Value := 0; StartTime2.Value := 0; StartTime3.Value := 0; StopPower1.Value := 0; StopPower2.Value := 0; StopPower3.Value := 0; StopTime1.Value := 0; StopTime2.Value := 0; StopTime3.Value := 0; end; function TfrmRotorParams.ShowMe(aReadOnly: boolean): boolean; begin fReadOnly := aReadOnly; gState.Enabled:=false; // always readonly gType.Enabled:=false; // always readonly gKing.Enabled:=false; // always readonly gInput.Enabled:=not aReadOnly; gAngles.Enabled:=not aReadOnly; gStartRamp.Enabled:=not aReadOnly; gStopRamp.Enabled:=not aReadOnly; gOther.Enabled:=not aReadOnly; if aReadOnly then begin Button2.Visible:=false; Button3.Visible:=false; end else begin Button2.Visible:=true; Button3.Visible:=true; end; Result := ShowModal = mrOk; end; procedure TfrmRotorParams.ToInterface(var c: TMD_ROTOR_CONFIG); begin gState.ItemIndex := c.state; gType.ItemIndex := c.m_type; gKing.ItemIndex := c.kind; gInput.ItemIndex := c.input; MinAngle.Value := Round(c.min_angle); MaxAngle.Value := Round(c.max_angle); StartTime1.Value := c.start_time[0]; StartTime2.Value := c.start_time[1]; StartTime3.Value := c.start_time[2]; StartPower1.Value := c.start_power[0]; StartPower2.Value := c.start_power[1]; StartPower3.Value := c.start_power[2]; StopTime1.Value := c.stop_time[0]; StopTime2.Value := c.stop_time[1]; StopTime3.Value := c.stop_time[2]; StopPower1.Value := c.stop_power[0]; StopPower2.Value := c.stop_power[1]; StopPower3.Value := c.stop_power[2]; MaxPower.Value := c.max_power; StopAt.Value := Round(c.stop_at); PulsesTimeout.Value := c.puls_timeout; Gear.Value := c.gear; end; procedure TfrmRotorParams.FromInterface(var c: TMD_ROTOR_CONFIG); begin c.state := gState.ItemIndex; c.m_type := gType.ItemIndex; c.kind := gKing.ItemIndex; c.input := gInput.ItemIndex; c.min_angle := MinAngle.Value; c.max_angle := MaxAngle.Value; c.start_time[0] := StartTime1.Value; c.start_time[1] := StartTime2.Value; c.start_time[2] := StartTime3.Value; c.start_power[0] := StartPower1.Value; c.start_power[1] := StartPower2.Value; c.start_power[2] := StartPower3.Value; c.stop_time[0] := StopTime1.Value; c.stop_time[1] := StopTime2.Value; c.stop_time[2] := StopTime3.Value; c.stop_power[0] := StopPower1.Value; c.stop_power[1] := StopPower2.Value; c.stop_power[2] := StopPower3.Value; c.max_power := MaxPower.Value; c.stop_at := StopAt.Value; c.puls_timeout := PulsesTimeout.Value; c.gear := Gear.Value; end; end.
// This program is only intended to read the PGM files used in the // ORL Database of Faces, www.cam-orl.co.uk/facedatabase.html, and // ftp://ftp.orl.co.uk:pub/data/orl_faces.zip // This program is not necessarily general enough to read all types of PGM // files with a P5 "magic number." See www.wotsit.org/wgraphic/pgm.zip for // additional information about the PGM format. // efg, 4 August 1998 unit ScreenPGMP5; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtDlgs, StdCtrls, ExtCtrls; type TFormPGM = class(TForm) ImageORLFace: TImage; ButtonReadImage: TButton; OpenDialogPGM: TOpenDialog; procedure ButtonReadImageClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormPGM: TFormPGM; implementation {$R *.DFM} FUNCTION ReadPortableGrayMapP5(CONST filename: STRING): TBitmap; CONST MaxPixelCount = 65536; TYPE TRGBArray = ARRAY[0..MaxPixelCount-1] OF TRGBTriple; pRGBArray = ^TRGBArray; VAR i : CARDINAL; j : CARDINAL; Row : pRGBArray; s : STRING; PGMBuffer: ARRAY[0..MaxPixelCount-1] OF BYTE; PGMStream: TFileStream; PGMWidth : CARDINAL; PGMHeight: CARDINAL; FUNCTION GetNextPGMLine: STRING; VAR c: CHAR; BEGIN Result := ''; REPEAT PGMStream.Read(c, 1); IF c <> #$0A THEN RESULT := RESULT + c UNTIL c = #$0A; // Look for Line Feed used in UNIX file END {GetNextPGMLine}; BEGIN PGMStream := TFileStream.Create(filename, fmOpenRead); TRY PGMStream.Seek(0, soFromBeginning); s := GetNextPGMLine; ASSERT (s = 'P5'); // "Magic Number" for special PGM files s := GetNextPGMLine; PGMWidth := StrToInt(COPY(s,1,POS(' ',s)-1)); Delete(s, 1, POS(' ',s)); PGMHeight := StrToInt(s); RESULT := TBitmap.Create; RESULT.Width := PGMWidth; RESULT.Height := PGMHeight; RESULT.PixelFormat := pf24bit; // Easiest way to avoid palettes and // get 256 shades of gray, since Windows // reserves 20 of 256 colors in 256-color // mode. // Skip over file header by starting at the end and backing up by the // number of pixel bytes. PGMStream.Seek(PGMStream.Size - PGMHeight*PGMWidth, soFromBeginning); FOR j := 0 TO PGMHeight - 1 DO BEGIN PGMStream.Read(PGMBuffer, PGMWidth); Row := RESULT.Scanline[j]; FOR i := 0 TO PGMWidth -1 DO BEGIN WITH Row[i] DO BEGIN rgbtRed := PGMBuffer[i]; rgbtGreen := PGMBuffer[i]; rgbtBlue := PGMBuffer[i] END END END FINALLY PGMStream.Free END END {ReadPortableGrayMap}; procedure TFormPGM.ButtonReadImageClick(Sender: TObject); VAR Bitmap : TBitmap; begin IF OpenDialogPGM.Execute THEN BEGIN Bitmap := ReadPortableGrayMapP5(OpenDialogPGM.Filename); TRY ImageORLFace.Picture.Graphic := Bitmap FINALLY Bitmap.Free END END end; end.
{ Subroutine SST_DTYPE_ALIGN (DTYPE,RULE_ALIGN) * * Set the final alignment used for this data type. The following state will be * be used as input: * * RULE_ALIGN - The alignment rule to apply. This may be SST_ALIGN to * get the current default alignment rule. * * DTYPE.ALIGN_NAT - Alignment that this data type would have if naturally * aligned. * * DTYPE.SIZE_USED - Size of whole data type from first used bit to last used * bit. This value is the minimum number of machine address increments that * could possibly hold the data type. This is the value returned by the * SIZEOF function. * * The following state is set by this subroutine: * * DTYPE.ALIGN - Actual alignment chosen for this data type. This will be * a number >= 0, and therefore will not be a special flag value. * * DTYPE.SIZE_ALIGN - Size of whole data type in machine address increments, * rounded up to nearest multiple of its own alignment. This would be the * size to allocate for each array element if an array of this data type * was made. } module sst_DTYPE_ALIGN; define sst_dtype_align; %include 'sst2.ins.pas'; procedure sst_dtype_align ( {set data type alignment} in out dtype: sst_dtype_t; {data type to set alignment for} in rule_align: sys_int_machine_t); {alignment rule to apply} var dt_p: sst_dtype_p_t; {points to base data type} begin if rule_align = sst_align_natural_k then begin {alignment rule is NATURAL ALIGNMENT} dtype.align := dtype.align_nat; end else begin {alignment rule is explicit alignment} dtype.align := rule_align; end ; dt_p := addr(dtype); {resolve pointer to base data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype = sst_dtype_rec_k then begin {this data type is a record ?} if dtype.align_nat = 0 then begin {this is a packed record} dtype.align := max(dtype.align, sst_config.align_min_rec_pack); end else begin {this is a non-packed record} dtype.align := max(dtype.align, sst_config.align_min_rec); end ; end; if dtype.align <= 1 then begin {no unused addresses possible} dtype.size_align := dtype.size_used; end else begin {need to round to alignment multiple} dtype.size_align := dtype.align * ((dtype.size_used + dtype.align - 1) div dtype.align) end ; end;
unit UNetConnection; interface uses Classes, UTCPIP, UOperationBlock, UTickCount, UThread, UAccountKey, UNetProtocolVersion, UOrderedRawList, UOperationsHashTree, UNetHeaderData, UNetTransferType, UPCOperationsComp; type { TNetConnection } TNetConnection = Class private FIsConnecting: Boolean; FTcpIpClient : TNetTcpIpClient; FRemoteOperationBlock : TOperationBlock; FRemoteAccumulatedWork : UInt64; FLastDataReceivedTS : TTickCount; FLastDataSendedTS : TTickCount; FClientBufferRead : TStream; FIsWaitingForResponse : Boolean; FTimestampDiff : Integer; FIsMyselfServer : Boolean; FClientPublicKey : TAccountKey; FCreatedTime: TDateTime; FClientAppVersion: AnsiString; FDoFinalizeConnection : Boolean; FNetProtocolVersion: TNetProtocolVersion; FAlertedForNewProtocolAvailable : Boolean; FHasReceivedData : Boolean; FIsDownloadingBlocks : Boolean; FRandomWaitSecondsSendHello : Cardinal; FBufferLock : TPCCriticalSection; FBufferReceivedOperationsHash : TOrderedRawList; FBufferToSendOperations : TOperationsHashTree; FClientTimestampIp : AnsiString; function GetConnected: Boolean; procedure SetConnected(const Value: Boolean); procedure TcpClient_OnConnect(Sender: TObject); procedure TcpClient_OnDisconnect(Sender: TObject); Procedure DoProcess_Hello(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_Message(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetBlocks_Request(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetBlocks_Response(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetOperationsBlock_Request(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_NewBlock(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_AddOperations(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetSafeBox_Request(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetPendingOperations_Request(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetAccount_Request(HeaderData : TNetHeaderData; DataBuffer: TStream); Procedure DoProcess_GetPendingOperations; Function ReadTcpClientBuffer(MaxWaitMiliseconds : Cardinal; var HeaderData : TNetHeaderData; BufferData : TStream) : Boolean; function GetClient: TNetTcpIpClient; protected // procedure Notification(AComponent: TComponent; Operation: TOperation); override; Procedure Send(NetTranferType : TNetTransferType; operation, errorcode : Word; request_id : Integer; DataBuffer : TStream); public FNetLock : TPCCriticalSection; Constructor Create; // Constructor Create(AOwner : TComponent); override; Destructor Destroy; override; // Skybuck: moved to here to offer access to UNetServer procedure DoProcessBuffer; Procedure SetClient(Const Value : TNetTcpIpClient); Procedure SendError(NetTranferType : TNetTransferType; operation, request_id : Integer; error_code : Integer; error_text : AnsiString); // Skybuck: moved to here to offer access to UNetData Function DoSendAndWaitForResponse(operation: Word; RequestId: Integer; SendDataBuffer, ReceiveDataBuffer: TStream; MaxWaitTime : Cardinal; var HeaderData : TNetHeaderData) : Boolean; Procedure DisconnectInvalidClient(ItsMyself : Boolean; Const why : AnsiString); Function ConnectTo(ServerIP: String; ServerPort:Word) : Boolean; Property Connected : Boolean read GetConnected write SetConnected; Property IsConnecting : Boolean read FIsConnecting; Function Send_Hello(NetTranferType : TNetTransferType; request_id : Integer) : Boolean; Function Send_NewBlockFound(Const NewBlock : TPCOperationsComp) : Boolean; Function Send_GetBlocks(StartAddress, quantity : Cardinal; var request_id : Cardinal) : Boolean; Function Send_AddOperations(Operations : TOperationsHashTree) : Boolean; Function Send_Message(Const TheMessage : AnsiString) : Boolean; Function AddOperationsToBufferForSend(Operations : TOperationsHashTree) : Integer; Property Client : TNetTcpIpClient read GetClient; Function ClientRemoteAddr : AnsiString; property TimestampDiff : Integer read FTimestampDiff; property RemoteOperationBlock : TOperationBlock read FRemoteOperationBlock; // Property NetProtocolVersion : TNetProtocolVersion read FNetProtocolVersion; // Property IsMyselfServer : Boolean read FIsMyselfServer; Property CreatedTime : TDateTime read FCreatedTime; Property ClientAppVersion : AnsiString read FClientAppVersion write FClientAppVersion; // Skybuck: added to offer access for NetData Property DoFinalizeConnection : boolean read FDoFinalizeConnection; // Property NetLock : TPCCriticalSection read FNetLock; // Skybuck: *** problem *** FNetLock must be passed as a variable to some try lock function thus cannot use property, maybe if it's not a var may it work, there is probably no reason for it to be a var parameter, thus it's probably a design error, not sure yet though, documented it in UThread.pas see there for further reference. Property ClientPublicKey : TAccountKey read FClientPublicKey; Property TcpIpClient : TNetTcpIpClient read FTcpIpClient; Property HasReceivedData : Boolean read FHasReceivedData; // Skybuck: added property to offer access to UThreadGetNewBlockChainFromClient property RemoteAccumulatedWork : UInt64 read FRemoteAccumulatedWork; property IsDownloadingBlocks : boolean read FIsDownloadingBlocks; Procedure FinalizeConnection; End; implementation uses SysUtils, ULog, UNodeServerAddress, UConst, UNetData, UTime, UECDSA_Public, UPtrInt, UNetServerClient, UPlatform, UPCOperationClass, UPCOperation, UNode, UNetProtocolConst, UBlockAccount, URawBytes, UPCSafeBoxHeader, UStreamOp, UPascalCoinSafeBox, UCrypto, UPCChunk, UAccount, UAccountComp, UThreadGetNewBlockChainFromClient, UECIES, UNetClient, UPascalCoinBank; { TNetConnection } function TNetConnection.AddOperationsToBufferForSend(Operations: TOperationsHashTree): Integer; Var i : Integer; begin Result := 0; try FBufferLock.Acquire; Try for i := 0 to Operations.OperationsCount - 1 do begin if FBufferReceivedOperationsHash.IndexOf(Operations.GetOperation(i).Sha256)<0 then begin FBufferReceivedOperationsHash.Add(Operations.GetOperation(i).Sha256); If FBufferToSendOperations.IndexOfOperation(Operations.GetOperation(i))<0 then begin FBufferToSendOperations.AddOperationToHashTree(Operations.GetOperation(i)); Inc(Result); end; end; end; finally FBufferLock.Release; end; Except On E:Exception do begin TLog.NewLog(ltError,ClassName,'Error at AddOperationsToBufferForSend ('+E.ClassName+'): '+E.Message); Result := 0; end; end; end; function TNetConnection.ClientRemoteAddr: AnsiString; begin If Assigned(FTcpIpClient) then begin Result := FtcpIpClient.ClientRemoteAddr end else Result := 'NIL'; end; function TNetConnection.ConnectTo(ServerIP: String; ServerPort: Word) : Boolean; Var nsa : TNodeServerAddress; lns : TList; i : Integer; begin If FIsConnecting then Exit; Try FIsConnecting:=True; if Client.Connected then Client.Disconnect; TPCThread.ProtectEnterCriticalSection(Self,FNetLock); Try Client.RemoteHost := ServerIP; if ServerPort<=0 then ServerPort := CT_NetServer_Port; Client.RemotePort := ServerPort; TLog.NewLog(ltDebug,Classname,'Trying to connect to a server at: '+ClientRemoteAddr); PascalNetData.NodeServersAddresses.GetNodeServerAddress(Client.RemoteHost,Client.RemotePort,true,nsa); nsa.netConnection := Self; PascalNetData.NodeServersAddresses.SetNodeServerAddress(nsa); PascalNetData.NotifyNetConnectionUpdated; Result := Client.Connect; Finally FNetLock.Release; End; if Result then begin TLog.NewLog(ltDebug,Classname,'Connected to a possible server at: '+ClientRemoteAddr); PascalNetData.NodeServersAddresses.GetNodeServerAddress(Client.RemoteHost,Client.RemotePort,true,nsa); nsa.netConnection := Self; nsa.last_connection_by_me := (UnivDateTimeToUnix(DateTime2UnivDateTime(now))); PascalNetData.NodeServersAddresses.SetNodeServerAddress(nsa); Result := Send_Hello(ntp_request,PascalNetData.NewRequestId); end else begin TLog.NewLog(ltDebug,Classname,'Cannot connect to a server at: '+ClientRemoteAddr); end; finally FIsConnecting:=False; end; end; constructor TNetConnection.Create; begin inherited; FIsConnecting:=False; FIsDownloadingBlocks := false; FHasReceivedData := false; FNetProtocolVersion.protocol_version := 0; // 0 = unknown FNetProtocolVersion.protocol_available := 0; FAlertedForNewProtocolAvailable := false; FDoFinalizeConnection := false; FClientAppVersion := ''; FClientPublicKey := CT_TECDSA_Public_Nul; FCreatedTime := Now; FIsMyselfServer := false; FTimestampDiff := 0; FIsWaitingForResponse := false; FClientBufferRead := TMemoryStream.Create; FNetLock := TPCCriticalSection.Create('TNetConnection_NetLock'); FLastDataReceivedTS := 0; FLastDataSendedTS := 0; FRandomWaitSecondsSendHello := 90 + Random(60); FTcpIpClient := Nil; FRemoteOperationBlock := CT_OperationBlock_NUL; FRemoteAccumulatedWork := 0; SetClient( TBufferedNetTcpIpClient.Create ); PascalNetData.NetConnections.Add(Self); PascalNetData.NotifyNetConnectionUpdated; FBufferLock := TPCCriticalSection.Create('TNetConnection_BufferLock'); FBufferReceivedOperationsHash := TOrderedRawList.Create; FBufferToSendOperations := TOperationsHashTree.Create; FClientTimestampIp := ''; end; destructor TNetConnection.Destroy; begin Try TLog.NewLog(ltdebug,ClassName,'Destroying '+Classname+' '+IntToHex(PtrInt(Self),8)); Connected := false; PascalNetData.NodeServersAddresses.DeleteNetConnection(Self); Finally PascalNetData.NetConnections.Remove(Self); End; PascalNetData.UnRegisterRequest(Self,0,0); Try PascalNetData.NotifyNetConnectionUpdated; Finally FreeAndNil(FNetLock); FreeAndNil(FClientBufferRead); FreeAndNil(FTcpIpClient); FreeAndNil(FBufferLock); FreeAndNil(FBufferReceivedOperationsHash); FreeAndNil(FBufferToSendOperations); inherited; End; end; procedure TNetConnection.DisconnectInvalidClient(ItsMyself : Boolean; const why: AnsiString); Var include_in_list : Boolean; ns : TNodeServerAddress; begin FIsDownloadingBlocks := false; if ItsMyself then begin TLog.NewLog(ltInfo,Classname,'Disconecting myself '+ClientRemoteAddr+' > '+Why) end else begin TLog.NewLog(lterror,Classname,'Disconecting '+ClientRemoteAddr+' > '+Why); end; FIsMyselfServer := ItsMyself; include_in_list := (Not SameText(Client.RemoteHost,'localhost')) And (Not SameText(Client.RemoteHost,'127.0.0.1')) And (Not SameText('192.168.',Copy(Client.RemoteHost,1,8))) And (Not SameText('10.',Copy(Client.RemoteHost,1,3))); if include_in_list then begin If PascalNetData.NodeServersAddresses.GetNodeServerAddress(Client.RemoteHost,Client.RemotePort,true,ns) then begin ns.last_connection := UnivDateTimeToUnix(DateTime2UnivDateTime(now)); ns.its_myself := ItsMyself; ns.BlackListText := Why; ns.is_blacklisted := true; PascalNetData.NodeServersAddresses.SetNodeServerAddress(ns); end; end else if ItsMyself then begin If PascalNetData.NodeServersAddresses.GetNodeServerAddress(Client.RemoteHost,Client.RemotePort,true,ns) then begin ns.its_myself := ItsMyself; PascalNetData.NodeServersAddresses.SetNodeServerAddress(ns); end; end; Connected := False; PascalNetData.NotifyBlackListUpdated; PascalNetData.NotifyNodeServersUpdated; end; procedure TNetConnection.DoProcessBuffer; Var HeaderData : TNetHeaderData; ms : TMemoryStream; ops : AnsiString; begin if FDoFinalizeConnection then begin TLog.NewLog(ltdebug,Classname,'Executing DoFinalizeConnection at client '+ClientRemoteAddr); Connected := false; end; if Not Connected then exit; ms := TMemoryStream.Create; try if Not FIsWaitingForResponse then begin DoSendAndWaitForResponse(0,0,Nil,ms,0,HeaderData); end; finally ms.Free; end; If ((FLastDataReceivedTS>0) Or ( NOT (Self is TNetServerClient))) AND ((FLastDataReceivedTS+(1000*FRandomWaitSecondsSendHello)<TPlatform.GetTickCount) AND (FLastDataSendedTS+(1000*FRandomWaitSecondsSendHello)<TPlatform.GetTickCount)) then begin // Build 1.4 -> Changing wait time from 120 secs to a random seconds value If PascalNetData.PendingRequest(Self,ops)>=2 then begin TLog.NewLog(ltDebug,Classname,'Pending requests without response... closing connection to '+ClientRemoteAddr+' > '+ops); Connected := false; end else begin TLog.NewLog(ltDebug,Classname,'Sending Hello to check connection to '+ClientRemoteAddr+' > '+ops); Send_Hello(ntp_request,PascalNetData.NewRequestId); end; end else if (Self is TNetServerClient) AND (FLastDataReceivedTS=0) And (FCreatedTime+EncodeTime(0,1,0,0)<Now) then begin // Disconnecting client without data... TLog.NewLog(ltDebug,Classname,'Disconnecting client without data '+ClientRemoteAddr); Connected := false; end; end; procedure TNetConnection.DoProcess_AddOperations(HeaderData: TNetHeaderData; DataBuffer: TStream); var c,i : Integer; optype : Byte; opclass : TPCOperationClass; op : TPCOperation; operations : TOperationsHashTree; errors : AnsiString; DoDisconnect : Boolean; begin DoDisconnect := true; operations := TOperationsHashTree.Create; try if HeaderData.header_type<>ntp_autosend then begin errors := 'Not autosend'; exit; end; if DataBuffer.Size<4 then begin errors := 'Invalid databuffer size'; exit; end; DataBuffer.Read(c,4); for i := 1 to c do begin errors := 'Invalid operation '+inttostr(i)+'/'+inttostr(c); if not DataBuffer.Read(optype,1)=1 then exit; opclass := TPCOperationsComp.GetOperationClassByOpType(optype); if Not Assigned(opclass) then exit; op := opclass.Create; Try op.LoadFromNettransfer(DataBuffer); operations.AddOperationToHashTree(op); Finally op.Free; End; end; DoDisconnect := false; finally try if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end else begin // Add to received buffer FBufferLock.Acquire; Try for i := 0 to operations.OperationsCount - 1 do begin op := operations.GetOperation(i); FBufferReceivedOperationsHash.Add(op.Sha256); c := FBufferToSendOperations.IndexOfOperation(op); if (c>=0) then begin FBufferToSendOperations.Delete(c); end; end; Finally FBufferLock.Release; End; PascalCoinNode.AddOperations(Self,operations,Nil,errors); end; finally operations.Free; end; end; end; procedure TNetConnection.DoProcess_GetBlocks_Request(HeaderData: TNetHeaderData; DataBuffer: TStream); Var b,b_start,b_end:Cardinal; op : TPCOperationsComp; db : TMemoryStream; c : Cardinal; errors : AnsiString; DoDisconnect : Boolean; posquantity : Int64; begin DoDisconnect := true; try if HeaderData.header_type<>ntp_request then begin errors := 'Not request'; exit; end; // DataBuffer contains: from and to errors := 'Invalid structure'; if (DataBuffer.Size-DataBuffer.Position<8) then begin exit; end; DataBuffer.Read(b_start,4); DataBuffer.Read(b_end,4); if (b_start<0) Or (b_start>b_end) then begin errors := 'Invalid structure start or end: '+Inttostr(b_start)+' '+Inttostr(b_end); exit; end; if (b_end>=PascalCoinSafeBox.BlocksCount) then begin b_end := PascalCoinSafeBox.BlocksCount-1; if (b_start>b_end) then begin // No data: db := TMemoryStream.Create; try c := 0; db.Write(c,4); Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,db); Exit; finally db.Free; end; end; end; DoDisconnect := false; db := TMemoryStream.Create; try op := TPCOperationsComp.Create; try c := b_end - b_start + 1; posquantity := db.position; db.Write(c,4); c := 0; b := b_start; for b := b_start to b_end do begin inc(c); If PascalCoinBank.LoadOperations(op,b) then begin op.SaveBlockToStream(false,db); end else begin SendError(ntp_response,HeaderData.operation,HeaderData.request_id,CT_NetError_InternalServerError,'Operations of block:'+inttostr(b)+' not found'); exit; end; // Build 1.0.5 To prevent high data over net in response (Max 2 Mb of data) if (db.size>(1024*1024*2)) then begin // Stop db.position := posquantity; db.Write(c,4); // BUG of Build 1.0.5 !!! Need to break bucle OH MY GOD! db.Position := db.Size; break; end; end; Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,db); finally op.Free; end; finally db.Free; end; TLog.NewLog(ltdebug,Classname,'Sending operations from block '+inttostr(b_start)+' to '+inttostr(b_end)); finally if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_GetBlocks_Response(HeaderData: TNetHeaderData; DataBuffer: TStream); var op : TPCOperationsComp; opcount,i : Cardinal; newBlockAccount : TBlockAccount; errors : AnsiString; DoDisconnect : Boolean; begin DoDisconnect := true; try if HeaderData.header_type<>ntp_response then begin errors := 'Not response'; exit; end; If HeaderData.is_error then begin DoDisconnect := false; exit; // end; // DataBuffer contains: from and to errors := 'Invalid structure'; op := TPCOperationsComp.Create; Try if DataBuffer.Size-DataBuffer.Position<4 then begin DisconnectInvalidClient(false,'DoProcess_GetBlocks_Response invalid format: '+errors); exit; end; DataBuffer.Read(opcount,4); DoDisconnect :=false; for I := 1 to opcount do begin if Not op.LoadBlockFromStream(DataBuffer,errors) then begin errors := 'Error decoding block '+inttostr(i)+'/'+inttostr(opcount)+' Errors:'+errors; DoDisconnect := true; exit; end; if (op.OperationBlock.block=PascalCoinSafeBox.BlocksCount) then begin if (PascalCoinBank.AddNewBlockChainBlock(op,PascalNetData.NetworkAdjustedTime.GetMaxAllowedTimestampForNewBlock, newBlockAccount,errors)) then begin // Ok, one more! end else begin // Is not a valid entry???? // Perhaps an orphan blockchain: Me or Client! TLog.NewLog(ltinfo,Classname,'Distinct operation block found! My:'+ TPCOperationsComp.OperationBlockToText(PascalCoinSafeBox.Block(PascalCoinSafeBox.BlocksCount-1).blockchainInfo)+ ' remote:'+TPCOperationsComp.OperationBlockToText(op.OperationBlock)+' Errors: '+errors); end; end else begin // Receiving an unexpected operationblock TLog.NewLog(lterror,classname,'Received a distinct block, finalizing: '+TPCOperationsComp.OperationBlockToText(op.OperationBlock)+' (My block: '+TPCOperationsComp.OperationBlockToText(PascalCoinBank.LastOperationBlock)+')' ); FIsDownloadingBlocks := false; exit; end; end; FIsDownloadingBlocks := false; if ((opcount>0) And (FRemoteOperationBlock.block>=PascalCoinSafeBox.BlocksCount)) then begin Send_GetBlocks(PascalCoinSafeBox.BlocksCount,100,i); end else begin // No more blocks to download, download Pending operations DoProcess_GetPendingOperations; end; PascalCoinNode.NotifyBlocksChanged; Finally op.Free; End; Finally if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_GetOperationsBlock_Request(HeaderData: TNetHeaderData; DataBuffer: TStream); Const CT_Max_Positions = 10; Var inc_b,b,b_start,b_end, total_b:Cardinal; db,msops : TMemoryStream; errors, blocksstr : AnsiString; DoDisconnect : Boolean; ob : TOperationBlock; begin blocksstr := ''; DoDisconnect := true; try if HeaderData.header_type<>ntp_request then begin errors := 'Not request'; exit; end; errors := 'Invalid structure'; if (DataBuffer.Size-DataBuffer.Position<8) then begin exit; end; DataBuffer.Read(b_start,4); DataBuffer.Read(b_end,4); if (b_start<0) Or (b_start>b_end) Or (b_start>=PascalCoinSafeBox.BlocksCount) then begin errors := 'Invalid start ('+Inttostr(b_start)+') or end ('+Inttostr(b_end)+') of count ('+Inttostr(PascalCoinSafeBox.BlocksCount)+')'; exit; end; DoDisconnect := false; if (b_end>=PascalCoinSafeBox.BlocksCount) then b_end := PascalCoinSafeBox.BlocksCount-1; inc_b := ((b_end - b_start) DIV CT_Max_Positions)+1; msops := TMemoryStream.Create; try b := b_start; total_b := 0; repeat ob := PascalCoinSafeBox.Block(b).blockchainInfo; If TPCOperationsComp.SaveOperationBlockToStream(ob,msops) then begin blocksstr := blocksstr + inttostr(b)+','; b := b + inc_b; inc(total_b); end else begin errors := 'ERROR DEV 20170522-1 block:'+inttostr(b); SendError(ntp_response,HeaderData.operation,HeaderData.request_id,CT_NetError_InternalServerError,errors); exit; end; until (b > b_end); db := TMemoryStream.Create; try db.Write(total_b,4); db.WriteBuffer(msops.Memory^,msops.Size); Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,db); finally db.Free; end; finally msops.Free; end; TLog.NewLog(ltdebug,Classname,'Sending '+inttostr(total_b)+' operations block from block '+inttostr(b_start)+' to '+inttostr(b_end)+' '+blocksstr); finally if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_GetSafeBox_Request(HeaderData: TNetHeaderData; DataBuffer: TStream); Var _blockcount : Cardinal; _safeboxHash : TRawBytes; _from,_to : Cardinal; sbStream : TStream; responseStream : TStream; antPos : Int64; sbHeader : TPCSafeBoxHeader; errors : AnsiString; begin { This call is used to obtain a chunk of the safebox Request: BlockCount (4 bytes) - The safebox checkpoint SafeboxHash (AnsiString) - The safeboxhash of that checkpoint StartPos (4 bytes) - The start index (0..BlockCount-1) EndPos (4 bytes) - The final index (0..BlockCount-1) If valid info: - If available will return a LZIP chunk of safebox - If not available (requesting for an old safebox) will retun not available If not valid will disconnect } DataBuffer.Read(_blockcount,SizeOf(_blockcount)); TStreamOp.ReadAnsiString(DataBuffer,_safeboxHash); DataBuffer.Read(_from,SizeOf(_from)); DataBuffer.Read(_to,SizeOf(_to)); // sbStream := PascalCoinBank.Storage.CreateSafeBoxStream(_blockcount); try responseStream := TMemoryStream.Create; try If Not Assigned(sbStream) then begin SendError(ntp_response,HeaderData.operation,CT_NetError_SafeboxNotFound,HeaderData.request_id,Format('Safebox for block %d not found',[_blockcount])); exit; end; antPos := sbStream.Position; TPCSafeBox.LoadSafeBoxStreamHeader(sbStream,sbHeader); If sbHeader.safeBoxHash<>_safeboxHash then begin DisconnectInvalidClient(false,Format('Invalid safeboxhash on GetSafeBox request (Real:%s > Requested:%s)',[TCrypto.ToHexaString(sbHeader.safeBoxHash),TCrypto.ToHexaString(_safeboxHash)])); exit; end; // Response: sbStream.Position:=antPos; If not TPCChunk.SaveSafeBoxChunkFromSafeBox(sbStream,responseStream,_from,_to,errors) then begin TLog.NewLog(ltError,Classname,'Error saving chunk: '+errors); exit; end; // Sending Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,responseStream); TLog.NewLog(ltInfo,ClassName,Format('Sending Safebox(%d) chunk[%d..%d] to %s Bytes:%d',[_blockcount,_from,_to,ClientRemoteAddr,responseStream.Size])); finally responseStream.Free; end; finally FreeAndNil(sbStream); end; end; procedure TNetConnection.DoProcess_GetPendingOperations_Request(HeaderData: TNetHeaderData; DataBuffer: TStream); var responseStream : TMemoryStream; i,start,max : Integer; b : Byte; c : Cardinal; DoDisconnect : Boolean; errors : AnsiString; opht : TOperationsHashTree; begin { This call is used to obtain pending operations not included in blockchain Request: - Request type (1 byte) - Values - Value 1: Returns Count - Value 2: - start (4 bytes) - max (4 bytes) Returns Pending operations (from start to start+max) in a TOperationsHashTree Stream } errors := ''; DoDisconnect := true; responseStream := TMemoryStream.Create; try if HeaderData.header_type<>ntp_request then begin errors := 'Not request'; exit; end; DataBuffer.Read(b,1); if (b=1) then begin // Return count c := PascalCoinNode.Operations.Count; responseStream.Write(c,SizeOf(c)); end else if (b=2) then begin // Return from start to start+max DataBuffer.Read(c,SizeOf(c)); // Start 4 bytes start:=c; DataBuffer.Read(c,SizeOf(c)); // max 4 bytes max:=c; // if (start<0) Or (max<0) then begin errors := 'Invalid start/max value'; Exit; end; opht := TOperationsHashTree.Create; Try PascalCoinNode.Operations.Lock; Try if (start >= PascalCoinNode.Operations.Count) Or (max=0) then begin end else begin if (start + max >= PascalCoinNode.Operations.Count) then max := PascalCoinNode.Operations.Count - start; for i:=start to (start + max -1) do begin opht.AddOperationToHashTree(PascalCoinNode.Operations.OperationsHashTree.GetOperation(i)); end; end; finally PascalCoinNode.Operations.Unlock; end; opht.SaveOperationsHashTreeToStream(responseStream,False); Finally opht.Free; End; end else begin errors := 'Invalid call type '+inttostr(b); Exit; end; DoDisconnect:=False; Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,responseStream); finally responseStream.Free; if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_GetPendingOperations; Var dataSend, dataReceived : TMemoryStream; request_id, cStart, cMax, cTotal, cTotalByOther, cReceived, cAddedOperations : Cardinal; b : Byte; headerData : TNetHeaderData; opht : TOperationsHashTree; errors : AnsiString; i : Integer; begin {$IFDEF PRODUCTION} If FNetProtocolVersion.protocol_available<=6 then Exit; // Note: GetPendingOperations started on protocol_available=7 {$ENDIF} request_id := 0; cAddedOperations := 0; if Not Connected then exit; // First receive operations from dataSend := TMemoryStream.Create; dataReceived := TMemoryStream.Create; try b := 1; dataSend.Write(b,1); request_id := PascalNetData.NewRequestId; If Not DoSendAndWaitForResponse(CT_NetOp_GetPendingOperations,request_id,dataSend,dataReceived,20000,headerData) then begin Exit; end; dataReceived.Position:=0; cTotalByOther := 0; If (dataReceived.Read(cTotalByOther,SizeOf(cTotal))<SizeOf(cTotal)) then begin DisconnectInvalidClient(False,'Invalid data returned on GetPendingOperations'); Exit; end; cTotal := cTotalByOther; if (cTotal>5000) then begin // Limiting max pending operations to 5000 cTotal := 5000; end; cReceived:=0; cStart := 0; While (Connected) And (cReceived<cTotal) do begin dataSend.Clear; dataReceived.Clear; b := 2; dataSend.Write(b,1); dataSend.Write(cStart,SizeOf(cStart)); cMax := 1000; // Limiting in 1000 by round dataSend.Write(cMax,SizeOf(cMax)); request_id := PascalNetData.NewRequestId; If Not DoSendAndWaitForResponse(CT_NetOp_GetPendingOperations,request_id,dataSend,dataReceived,50000,headerData) then begin Exit; end; dataReceived.Position:=0; // opht := TOperationsHashTree.Create; try If Not opht.LoadOperationsHashTreeFromStream(dataReceived,False,0,Nil,errors) then begin DisconnectInvalidClient(False,'Invalid operations hash tree stream: '+errors); Exit; end; If (opht.OperationsCount>0) then begin inc(cReceived,opht.OperationsCount); i := PascalCoinNode.AddOperations(Self,opht,Nil,errors); inc(cAddedOperations,i); end else Break; // No more inc(cStart,opht.OperationsCount); finally opht.Free; end; end; TLog.NewLog(ltInfo,Classname,Format('Processed GetPendingOperations to %s obtaining %d (available %d) operations and added %d to Node', [Self.ClientRemoteAddr,cTotal,cTotalByOther,cAddedOperations])); finally dataSend.Free; dataReceived.Free; end; end; procedure TNetConnection.DoProcess_GetAccount_Request(HeaderData: TNetHeaderData; DataBuffer: TStream); Const CT_Max_Accounts_per_call = 1000; var responseStream : TMemoryStream; i,start,max : Integer; b : Byte; c : Cardinal; acc : TAccount; DoDisconnect : Boolean; errors : AnsiString; begin { This call is used to obtain an Account data - Also will return current node block number - If a returned data has updated_block value = (current block+1) that means that Account is currently affected by a pending operation in the pending operations Request: Request type (1 byte) - Values - Value 1: Single account - Value 2: From account start to start+max LIMITED AT MAX 1000 - Value 3: Multiple accounts LIMITED AT MAX 1000 On 1: - account (4 bytes) On 2: - start (4 bytes) - max (4 bytes) On 3: - count (4 bytes) - for 1 to count read account (4 bytes) Returns: - current block number (4 bytes): Note, if an account has updated_block > current block means that has been updated and is in pending state - count (4 bytes) - for 1 to count: TAccountComp.SaveAccountToAStream } errors := ''; DoDisconnect := true; responseStream := TMemoryStream.Create; try // Response first 4 bytes are current block number c := PascalCoinSafeBox.BlocksCount-1; responseStream.Write(c,SizeOf(c)); // if HeaderData.header_type<>ntp_request then begin errors := 'Not request'; exit; end; if (DataBuffer.Size-DataBuffer.Position<5) then begin errors := 'Invalid structure'; exit; end; DataBuffer.Read(b,1); if (b in [1,2]) then begin if (b=1) then begin DataBuffer.Read(c,SizeOf(c)); start:=c; max:=1; // Bug 3.0.1 (was c instead of fixed 1) end else begin DataBuffer.Read(c,SizeOf(c)); start:=c; DataBuffer.Read(c,SizeOf(c)); max:=c; end; If max>CT_Max_Accounts_per_call then max := CT_Max_Accounts_per_call; if (start<0) Or (max<0) then begin errors := 'Invalid start/max value'; Exit; end; if (start >= PascalCoinSafeBox.AccountsCount) Or (max=0) then begin c := 0; responseStream.Write(c,SizeOf(c)); end else begin if (start + max >= PascalCoinSafeBox.AccountsCount) then max := PascalCoinSafeBox.AccountsCount - start; c := max; responseStream.Write(c,SizeOf(c)); for i:=start to (start + max -1) do begin acc := PascalCoinNode.Operations.SafeBoxTransaction.Account(i); TAccountComp.SaveAccountToAStream(responseStream,acc); end; end; end else if (b=3) then begin DataBuffer.Read(c,SizeOf(c)); if (c>CT_Max_Accounts_per_call) then c := CT_Max_Accounts_per_call; responseStream.Write(c,SizeOf(c)); max := c; for i:=1 to max do begin DataBuffer.Read(c,SizeOf(c)); if (c>=0) And (c<PascalCoinSafeBox.AccountsCount) then begin acc := PascalCoinNode.Operations.SafeBoxTransaction.Account(c); TAccountComp.SaveAccountToAStream(responseStream,acc); end else begin errors := 'Invalid account number '+Inttostr(c); Exit; end; end; end else begin errors := 'Invalid call type '+inttostr(b); Exit; end; DoDisconnect:=False; Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,responseStream); finally responseStream.Free; if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_Hello(HeaderData: TNetHeaderData; DataBuffer: TStream); var op, myLastOp : TPCOperationsComp; errors : AnsiString; connection_has_a_server : Word; i,c : Integer; nsa : TNodeServerAddress; rid : Cardinal; connection_ts : Cardinal; Duplicate : TNetConnection; RawAccountKey : TRawBytes; other_version : AnsiString; isFirstHello : Boolean; lastTimestampDiff : Integer; Begin FRemoteAccumulatedWork := 0; op := TPCOperationsComp.Create; try DataBuffer.Position:=0; if DataBuffer.Read(connection_has_a_server,2)<2 then begin DisconnectInvalidClient(false,'Invalid data on buffer: '+TNetData.HeaderDataToText(HeaderData)); exit; end; If TStreamOp.ReadAnsiString(DataBuffer,RawAccountKey)<0 then begin DisconnectInvalidClient(false,'Invalid data on buffer. No Public key: '+TNetData.HeaderDataToText(HeaderData)); exit; end; FClientPublicKey := TAccountComp.RawString2Accountkey(RawAccountKey); If Not TAccountComp.IsValidAccountKey(FClientPublicKey,errors) then begin DisconnectInvalidClient(false,'Invalid Public key: '+TNetData.HeaderDataToText(HeaderData)+' errors: '+errors); exit; end; if DataBuffer.Read(connection_ts,4)<4 then begin DisconnectInvalidClient(false,'Invalid data on buffer. No TS: '+TNetData.HeaderDataToText(HeaderData)); exit; end; lastTimestampDiff := FTimestampDiff; FTimestampDiff := Integer( Int64(connection_ts) - Int64(PascalNetData.NetworkAdjustedTime.GetAdjustedTime) ); If FClientTimestampIp='' then begin isFirstHello := True; FClientTimestampIp := FTcpIpClient.RemoteHost; PascalNetData.NetworkAdjustedTime.AddNewIp(FClientTimestampIp,connection_ts); if (Abs(PascalNetData.NetworkAdjustedTime.TimeOffset)>CT_MaxFutureBlockTimestampOffset) then begin PascalCoinNode.NotifyNetClientMessage(Nil,'The detected network time is different from this system time in '+ IntToStr(PascalNetData.NetworkAdjustedTime.TimeOffset)+' seconds! Please check your local time/timezone'); end; if (Abs(FTimestampDiff) > CT_MaxFutureBlockTimestampOffset) then begin TLog.NewLog(ltDebug,ClassName,'Detected a node ('+ClientRemoteAddr+') with incorrect timestamp: '+IntToStr(connection_ts)+' offset '+IntToStr(FTimestampDiff) ); end; end else begin isFirstHello := False; PascalNetData.NetworkAdjustedTime.UpdateIp(FClientTimestampIp,connection_ts); end; If (Abs(lastTimestampDiff) > CT_MaxFutureBlockTimestampOffset) And (Abs(FTimestampDiff) <= CT_MaxFutureBlockTimestampOffset) then begin TLog.NewLog(ltDebug,ClassName,'Corrected timestamp for node ('+ClientRemoteAddr+') old offset: '+IntToStr(lastTimestampDiff)+' current offset '+IntToStr(FTimestampDiff) ); end; if (connection_has_a_server>0) And (Not SameText(Client.RemoteHost,'localhost')) And (Not SameText(Client.RemoteHost,'127.0.0.1')) And (Not SameText('192.168.',Copy(Client.RemoteHost,1,8))) And (Not SameText('10.',Copy(Client.RemoteHost,1,3))) And (Not TAccountComp.EqualAccountKeys(FClientPublicKey,PascalNetData.NodePrivateKey.PublicKey)) then begin nsa := CT_TNodeServerAddress_NUL; nsa.ip := Client.RemoteHost; nsa.port := connection_has_a_server; nsa.last_connection := UnivDateTimeToUnix(DateTime2UnivDateTime(now)); PascalNetData.AddServer(nsa); end; if op.LoadBlockFromStream(DataBuffer,errors) then begin FRemoteOperationBlock := op.OperationBlock; if (DataBuffer.Size-DataBuffer.Position>=4) then begin DataBuffer.Read(c,4); for i := 1 to c do begin nsa := CT_TNodeServerAddress_NUL; TStreamOp.ReadAnsiString(DataBuffer,nsa.ip); DataBuffer.Read(nsa.port,2); DataBuffer.Read(nsa.last_connection_by_server,4); If (nsa.last_connection_by_server>0) And (i<=CT_MAX_NODESERVERS_ON_HELLO) then // Protect massive data PascalNetData.AddServer(nsa); end; if TStreamOp.ReadAnsiString(DataBuffer,other_version)>=0 then begin // Captures version ClientAppVersion := other_version; if (DataBuffer.Size-DataBuffer.Position>=SizeOf(FRemoteAccumulatedWork)) then begin DataBuffer.Read(FRemoteAccumulatedWork,SizeOf(FRemoteAccumulatedWork)); TLog.NewLog(ltdebug,ClassName,'Received HELLO with height: '+inttostr(op.OperationBlock.block)+' Accumulated work '+IntToStr(FRemoteAccumulatedWork)); end; end; // if (FRemoteAccumulatedWork>PascalCoinSafeBox.WorkSum) Or ((FRemoteAccumulatedWork=0) And (PascalNetData.MaxRemoteOperationBlock.block<FRemoteOperationBlock.block)) then begin PascalNetData.MaxRemoteOperationBlock := FRemoteOperationBlock; if TPCThread.ThreadClassFound(TThreadGetNewBlockChainFromClient,nil)<0 then begin TThreadGetNewBlockChainFromClient.Create; end; end; end; TLog.NewLog(ltdebug,Classname,'Hello received: '+TPCOperationsComp.OperationBlockToText(FRemoteOperationBlock)); if (HeaderData.header_type in [ntp_request,ntp_response]) then begin // Response: if (HeaderData.header_type=ntp_request) then begin Send_Hello(ntp_response,HeaderData.request_id); end; // Protection of invalid timestamp when is a new incoming connection due to wait time if (isFirstHello) And (Self is TNetServerClient) and (HeaderData.header_type=ntp_request) and (Abs(FTimestampDiff) > CT_MaxFutureBlockTimestampOffset) then begin TLog.NewLog(ltDebug,ClassName,'Sending HELLO again to ('+ClientRemoteAddr+') in order to check invalid current Timestamp offset: '+IntToStr(FTimestampDiff) ); Send_Hello(ntp_request,PascalNetData.NewRequestId); end; if (TAccountComp.EqualAccountKeys(FClientPublicKey,PascalNetData.NodePrivateKey.PublicKey)) then begin DisconnectInvalidClient(true,'MySelf disconnecting...'); exit; end; Duplicate := PascalNetData.FindConnectionByClientRandomValue(Self); if (Duplicate<>Nil) And (Duplicate.Connected) then begin DisconnectInvalidClient(true,'Duplicate connection with '+Duplicate.ClientRemoteAddr); exit; end; PascalNetData.NotifyReceivedHelloMessage; end else begin DisconnectInvalidClient(false,'Invalid header type > '+TNetData.HeaderDataToText(HeaderData)); end; // If (isFirstHello) And (HeaderData.header_type = ntp_response) then begin DoProcess_GetPendingOperations; end; end else begin TLog.NewLog(lterror,Classname,'Error decoding operations of HELLO: '+errors); DisconnectInvalidClient(false,'Error decoding operations of HELLO: '+errors); end; finally op.Free; end; end; procedure TNetConnection.DoProcess_Message(HeaderData: TNetHeaderData; DataBuffer: TStream); Var errors : AnsiString; decrypted,messagecrypted : AnsiString; DoDisconnect : boolean; begin errors := ''; DoDisconnect := true; try if HeaderData.header_type<>ntp_autosend then begin errors := 'Not autosend'; exit; end; If TStreamOp.ReadAnsiString(DataBuffer,messagecrypted)<0 then begin errors := 'Invalid message data'; exit; end; If Not ECIESDecrypt(PascalNetData.NodePrivateKey.EC_OpenSSL_NID,PascalNetData.NodePrivateKey.PrivateKey,false,messagecrypted,decrypted) then begin errors := 'Error on decrypting message'; exit; end; DoDisconnect := false; if TCrypto.IsHumanReadable(decrypted) then TLog.NewLog(ltinfo,Classname,'Received new message from '+ClientRemoteAddr+' Message ('+inttostr(length(decrypted))+' bytes): '+decrypted) else TLog.NewLog(ltinfo,Classname,'Received new message from '+ClientRemoteAddr+' Message ('+inttostr(length(decrypted))+' bytes) in hexadecimal: '+TCrypto.ToHexaString(decrypted)); Try PascalCoinNode.NotifyNetClientMessage(Self,decrypted); Except On E:Exception do begin TLog.NewLog(lterror,Classname,'Error processing received message. '+E.ClassName+' '+E.Message); end; end; finally if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; procedure TNetConnection.DoProcess_NewBlock(HeaderData: TNetHeaderData; DataBuffer: TStream); var bacc : TBlockAccount; op : TPCOperationsComp; errors : AnsiString; DoDisconnect : Boolean; begin errors := ''; DoDisconnect := true; try if HeaderData.header_type<>ntp_autosend then begin errors := 'Not autosend'; exit; end; op := TPCOperationsComp.Create; try if Not op.LoadBlockFromStream(DataBuffer,errors) then begin errors := 'Error decoding new account: '+errors; exit; end else begin DoDisconnect := false; if DataBuffer.Size - DataBuffer.Position >= SizeOf(FRemoteAccumulatedWork) then begin DataBuffer.Read(FRemoteAccumulatedWork,SizeOf(FRemoteAccumulatedWork)); TLog.NewLog(ltdebug,ClassName,'Received NEW BLOCK with height: '+inttostr(op.OperationBlock.block)+' Accumulated work '+IntToStr(FRemoteAccumulatedWork)); end else FRemoteAccumulatedWork := 0; FRemoteOperationBlock := op.OperationBlock; // if FRemoteAccumulatedWork=0 then begin // Old version. No data if (op.OperationBlock.block>PascalCoinSafeBox.BlocksCount) then begin PascalNetData.GetNewBlockChainFromClient(Self,Format('BlocksCount:%d > my BlocksCount:%d',[op.OperationBlock.block+1,PascalCoinSafeBox.BlocksCount])); end else if (op.OperationBlock.block=PascalCoinSafeBox.BlocksCount) then begin // New block candidate: If Not PascalCoinNode.AddNewBlockChain(Self,op,bacc,errors) then begin // Received a new invalid block... perhaps I'm an orphan blockchain PascalNetData.GetNewBlockChainFromClient(Self,'Has a distinct block. '+errors); end; end; end else begin if (FRemoteAccumulatedWork>PascalCoinSafeBox.WorkSum) then begin if (op.OperationBlock.block=PascalCoinSafeBox.BlocksCount) then begin // New block candidate: If Not PascalCoinNode.AddNewBlockChain(Self,op,bacc,errors) then begin // Really is a new block? (Check it) if (op.OperationBlock.block=PascalCoinSafeBox.BlocksCount) then begin // Received a new invalid block... perhaps I'm an orphan blockchain PascalNetData.GetNewBlockChainFromClient(Self,'Higher Work with same block height. I''m a orphan blockchain candidate'); end; end; end else begin // Received a new higher work PascalNetData.GetNewBlockChainFromClient(Self,Format('Higher Work and distinct blocks count. Need to download BlocksCount:%d my BlocksCount:%d',[op.OperationBlock.block+1,PascalCoinSafeBox.BlocksCount])); end; end; end; end; finally op.Free; end; finally if DoDisconnect then begin DisconnectInvalidClient(false,errors+' > '+TNetData.HeaderDataToText(HeaderData)+' BuffSize: '+inttostr(DataBuffer.Size)); end; end; end; function TNetConnection.DoSendAndWaitForResponse(operation: Word; RequestId: Integer; SendDataBuffer, ReceiveDataBuffer: TStream; MaxWaitTime: Cardinal; var HeaderData: TNetHeaderData): Boolean; var tc : TTickCount; was_waiting_for_response : Boolean; iDebugStep : Integer; reservedResponse : TMemoryStream; begin iDebugStep := 0; Try Result := false; HeaderData := CT_NetHeaderData; If FIsWaitingForResponse then begin TLog.NewLog(ltdebug,Classname,'Is waiting for response ...'); exit; end; iDebugStep := 100; If Not Assigned(FTcpIpClient) then exit; if Not Client.Connected then exit; iDebugStep := 110; tc := TPlatform.GetTickCount; If TPCThread.TryProtectEnterCriticalSection(Self,MaxWaitTime,FNetLock) then begin Try iDebugStep := 120; was_waiting_for_response := RequestId>0; try if was_waiting_for_response then begin iDebugStep := 200; FIsWaitingForResponse := true; Send(ntp_request,operation,0,RequestId,SendDataBuffer); end; iDebugStep := 300; Repeat iDebugStep := 400; if (MaxWaitTime > TPlatform.GetTickCount - tc) then MaxWaitTime := MaxWaitTime - (TPlatform.GetTickCount - tc) else MaxWaitTime := 1; If (MaxWaitTime>60000) then MaxWaitTime:=60000; tc := TPlatform.GetTickCount; if (ReadTcpClientBuffer(MaxWaitTime,HeaderData,ReceiveDataBuffer)) then begin iDebugStep := 500; PascalNetData.NodeServersAddresses.UpdateNetConnection(Self); iDebugStep := 800; TLog.NewLog(ltDebug,Classname,'Received '+CT_NetTransferType[HeaderData.header_type]+' operation:'+TNetData.OperationToText(HeaderData.operation)+' id:'+Inttostr(HeaderData.request_id)+' Buffer size:'+Inttostr(HeaderData.buffer_data_length) ); if (RequestId=HeaderData.request_id) And (HeaderData.header_type=ntp_response) then begin Result := true; end else begin iDebugStep := 1000; case HeaderData.operation of CT_NetOp_Hello : Begin iDebugStep := 1100; DoProcess_Hello(HeaderData,ReceiveDataBuffer); End; CT_NetOp_Message : Begin DoProcess_Message(HeaderData,ReceiveDataBuffer); End; CT_NetOp_GetBlocks : Begin if HeaderData.header_type=ntp_request then DoProcess_GetBlocks_Request(HeaderData,ReceiveDataBuffer) else if HeaderData.header_type=ntp_response then DoProcess_GetBlocks_Response(HeaderData,ReceiveDataBuffer) else DisconnectInvalidClient(false,'Not resquest or response: '+TNetData.HeaderDataToText(HeaderData)); End; CT_NetOp_GetBlockHeaders : Begin if HeaderData.header_type=ntp_request then DoProcess_GetOperationsBlock_Request(HeaderData,ReceiveDataBuffer) else TLog.NewLog(ltdebug,Classname,'Received old response of: '+TNetData.HeaderDataToText(HeaderData)); End; CT_NetOp_NewBlock : Begin DoProcess_NewBlock(HeaderData,ReceiveDataBuffer); End; CT_NetOp_AddOperations : Begin DoProcess_AddOperations(HeaderData,ReceiveDataBuffer); End; CT_NetOp_GetSafeBox : Begin if HeaderData.header_type=ntp_request then DoProcess_GetSafeBox_Request(HeaderData,ReceiveDataBuffer) else DisconnectInvalidClient(false,'Received '+TNetData.HeaderDataToText(HeaderData)); end; CT_NetOp_GetPendingOperations : Begin if (HeaderData.header_type=ntp_request) then DoProcess_GetPendingOperations_Request(HeaderData,ReceiveDataBuffer) else TLog.NewLog(ltdebug,Classname,'Received old response of: '+TNetData.HeaderDataToText(HeaderData)); end; CT_NetOp_GetAccount : Begin if (HeaderData.header_type=ntp_request) then DoProcess_GetAccount_Request(HeaderData,ReceiveDataBuffer) else TLog.NewLog(ltdebug,Classname,'Received old response of: '+TNetData.HeaderDataToText(HeaderData)); end; CT_NetOp_Reserved_Start..CT_NetOp_Reserved_End : Begin // This will allow to do nothing if not implemented reservedResponse := TMemoryStream.Create; Try PascalNetData.DoProcessReservedAreaMessage(Self,HeaderData,ReceiveDataBuffer,reservedResponse); if (HeaderData.header_type=ntp_request) then begin if (reservedResponse.Size>0) then begin Send(ntp_response,HeaderData.operation,0,HeaderData.request_id,reservedResponse); end else begin // If is a request, and DoProcessReservedAreaMessage didn't filled reservedResponse, will response with ERRORCODE_NOT_IMPLEMENTED Send(ntp_response,HeaderData.operation, CT_NetOp_ERRORCODE_NOT_IMPLEMENTED ,HeaderData.request_id,Nil); end; end; finally reservedResponse.Free; end; end else DisconnectInvalidClient(false,'Invalid operation: '+TNetData.HeaderDataToText(HeaderData)); end; end; end else sleep(1); iDebugStep := 900; Until (Result) Or (TPlatform.GetTickCount>(MaxWaitTime+tc)) Or (Not Connected) Or (FDoFinalizeConnection); finally if was_waiting_for_response then FIsWaitingForResponse := false; end; iDebugStep := 990; Finally FNetLock.Release; End; end; Except On E:Exception do begin E.Message := E.Message+' DoSendAndWaitForResponse step '+Inttostr(iDebugStep)+' Header.operation:'+Inttostr(HeaderData.operation); Raise; end; End; end; procedure TNetConnection.FinalizeConnection; begin If FDoFinalizeConnection then exit; TLog.NewLog(ltdebug,ClassName,'Executing FinalizeConnection to '+ClientRemoteAddr); FDoFinalizeConnection := true; end; function TNetConnection.GetClient: TNetTcpIpClient; begin if Not Assigned(FTcpIpClient) then begin TLog.NewLog(ltError,Classname,'TcpIpClient=NIL'); raise Exception.Create('TcpIpClient=NIL'); end; Result := FTcpIpClient; end; function TNetConnection.GetConnected: Boolean; begin Result := Assigned(FTcpIpClient) And (FTcpIpClient.Connected); end; function TNetConnection.ReadTcpClientBuffer(MaxWaitMiliseconds: Cardinal; var HeaderData: TNetHeaderData; BufferData: TStream): Boolean; var auxstream : TMemoryStream; tc : TTickCount; last_bytes_read, t_bytes_read : Int64; // IsValidHeaderButNeedMoreData : Boolean; deletedBytes : Int64; begin t_bytes_read := 0; Result := false; HeaderData := CT_NetHeaderData; BufferData.Size := 0; TPCThread.ProtectEnterCriticalSection(Self,FNetLock); try tc := TPlatform.GetTickCount; repeat If not Connected then exit; if Not Client.Connected then exit; last_bytes_read := 0; FClientBufferRead.Position := 0; Result := TNetData.ExtractHeaderInfo(FClientBufferRead,HeaderData,BufferData,IsValidHeaderButNeedMoreData); if Result then begin FNetProtocolVersion := HeaderData.protocol; // Build 1.0.4 accepts net protocol 1 and 2 if HeaderData.protocol.protocol_version>CT_NetProtocol_Available then begin PascalCoinNode.NotifyNetClientMessage(Nil,'Detected a higher Net protocol version at '+ ClientRemoteAddr+' (v '+inttostr(HeaderData.protocol.protocol_version)+' '+inttostr(HeaderData.protocol.protocol_available)+') '+ '... check that your version is Ok! Visit official download website for possible updates: https://sourceforge.net/projects/pascalcoin/'); DisconnectInvalidClient(false,Format('Invalid Net protocol version found: %d available: %d',[HeaderData.protocol.protocol_version,HeaderData.protocol.protocol_available])); Result := false; exit; end else begin if (FNetProtocolVersion.protocol_available>CT_NetProtocol_Available) And (Not FAlertedForNewProtocolAvailable) then begin FAlertedForNewProtocolAvailable := true; PascalCoinNode.NotifyNetClientMessage(Nil,'Detected a new Net protocol version at '+ ClientRemoteAddr+' (v '+inttostr(HeaderData.protocol.protocol_version)+' '+inttostr(HeaderData.protocol.protocol_available)+') '+ '... Visit official download website for possible updates: https://sourceforge.net/projects/pascalcoin/'); end; // Remove data from buffer and save only data not processed (higher than stream.position) auxstream := TMemoryStream.Create; try if FClientBufferRead.Position<FClientBufferRead.Size then begin auxstream.CopyFrom(FClientBufferRead,FClientBufferRead.Size-FClientBufferRead.Position); end; FClientBufferRead.Size := 0; FClientBufferRead.CopyFrom(auxstream,0); finally auxstream.Free; end; end; end else begin sleep(1); if Not Client.WaitForData(100) then begin exit; end; auxstream := (Client as TBufferedNetTcpIpClient).ReadBufferLock; try last_bytes_read := auxstream.size; if last_bytes_read>0 then begin FLastDataReceivedTS := TPlatform.GetTickCount; FRandomWaitSecondsSendHello := 90 + Random(60); FClientBufferRead.Position := FClientBufferRead.size; // Go to the end auxstream.Position := 0; FClientBufferRead.CopyFrom(auxstream,last_bytes_read); FClientBufferRead.Position := 0; auxstream.Size := 0; t_bytes_read := t_bytes_read + last_bytes_read; end; finally (Client as TBufferedNetTcpIpClient).ReadBufferUnlock; end; end; until (Result) Or ((TPlatform.GetTickCount > (tc+MaxWaitMiliseconds)) And (last_bytes_read=0)); finally Try if (Connected) then begin if (Not Result) And (FClientBufferRead.Size>0) And (Not IsValidHeaderButNeedMoreData) then begin deletedBytes := FClientBufferRead.Size; TLog.NewLog(lterror,ClassName,Format('Deleting %d bytes from TcpClient buffer of %s after max %d miliseconds. Elapsed: %d', [deletedBytes, Client.ClientRemoteAddr,MaxWaitMiliseconds,TPlatform.GetTickCount-tc])); FClientBufferRead.Size:=0; DisconnectInvalidClient(false,'Invalid data received in buffer ('+inttostr(deletedBytes)+' bytes)'); end else if (IsValidHeaderButNeedMoreData) then begin TLog.NewLog(ltDebug,ClassName,Format('Not enough data received - Received %d bytes from TcpClient buffer of %s after max %d miliseconds. Elapsed: %d - HeaderData: %s', [FClientBufferRead.Size, Client.ClientRemoteAddr,MaxWaitMiliseconds,TPlatform.GetTickCount-tc,TNetData.HeaderDataToText(HeaderData)])); end; end; Finally FNetLock.Release; End; end; if t_bytes_read>0 then begin if Not FHasReceivedData then begin FHasReceivedData := true; if (Self is TNetClient) then PascalNetData.IncStatistics(0,0,0,1,t_bytes_read,0) else PascalNetData.IncStatistics(0,0,0,0,t_bytes_read,0); end else begin PascalNetData.IncStatistics(0,0,0,0,t_bytes_read,0); end; end; if (Result) And (HeaderData.header_type=ntp_response) then begin PascalNetData.UnRegisterRequest(Self,HeaderData.operation,HeaderData.request_id); end; end; procedure TNetConnection.Send(NetTranferType: TNetTransferType; operation, errorcode: Word; request_id: Integer; DataBuffer: TStream); Var l : Cardinal; w : Word; Buffer : TStream; s : AnsiString; begin Buffer := TMemoryStream.Create; try l := CT_MagicNetIdentification; Buffer.Write(l,4); case NetTranferType of ntp_request: begin w := CT_MagicRequest; Buffer.Write(w,2); Buffer.Write(operation,2); w := 0; Buffer.Write(w,2); Buffer.Write(request_id,4); end; ntp_response: begin w := CT_MagicResponse; Buffer.Write(w,2); Buffer.Write(operation,2); Buffer.Write(errorcode,2); Buffer.Write(request_id,4); end; ntp_autosend: begin w := CT_MagicAutoSend; Buffer.Write(w,2); Buffer.Write(operation,2); w := errorcode; Buffer.Write(w,2); l := 0; Buffer.Write(l,4); end else raise Exception.Create('Invalid encoding'); end; l := CT_NetProtocol_Version; Buffer.Write(l,2); l := CT_NetProtocol_Available; Buffer.Write(l,2); if Assigned(DataBuffer) then begin l := DataBuffer.Size; Buffer.Write(l,4); DataBuffer.Position := 0; Buffer.CopyFrom(DataBuffer,DataBuffer.Size); s := '(Data:'+inttostr(DataBuffer.Size)+'b) '; end else begin l := 0; Buffer.Write(l,4); s := ''; end; Buffer.Position := 0; TPCThread.ProtectEnterCriticalSection(Self,FNetLock); Try TLog.NewLog(ltDebug,Classname,'Sending: '+CT_NetTransferType[NetTranferType]+' operation:'+ TNetData.OperationToText(operation)+' id:'+Inttostr(request_id)+' errorcode:'+InttoStr(errorcode)+ ' Size:'+InttoStr(Buffer.Size)+'b '+s+'to '+ ClientRemoteAddr); (Client as TBufferedNetTcpIpClient).WriteBufferToSend(Buffer); FLastDataSendedTS := TPlatform.GetTickCount; FRandomWaitSecondsSendHello := 90 + Random(60); Finally FNetLock.Release; End; PascalNetData.IncStatistics(0,0,0,0,0,Buffer.Size); finally Buffer.Free; end; end; procedure TNetConnection.SendError(NetTranferType: TNetTransferType; operation, request_id: Integer; error_code: Integer; error_text: AnsiString); var buffer : TStream; begin buffer := TMemoryStream.Create; Try TStreamOp.WriteAnsiString(buffer,error_text); Send(NetTranferType,operation,error_code,request_id,buffer); Finally buffer.Free; End; end; function TNetConnection.Send_AddOperations(Operations : TOperationsHashTree) : Boolean; Var data : TMemoryStream; c1, request_id : Cardinal; i, nOpsToSend : Integer; optype : Byte; begin Result := false; if Not Connected then exit; FNetLock.Acquire; try nOpsToSend := 0; FBufferLock.Acquire; Try If Assigned(Operations) then begin for i := 0 to Operations.OperationsCount - 1 do begin if FBufferReceivedOperationsHash.IndexOf(Operations.GetOperation(i).Sha256)<0 then begin FBufferReceivedOperationsHash.Add(Operations.GetOperation(i).Sha256); If FBufferToSendOperations.IndexOfOperation(Operations.GetOperation(i))<0 then begin FBufferToSendOperations.AddOperationToHashTree(Operations.GetOperation(i)); end; end; end; nOpsToSend := Operations.OperationsCount; end; if FBufferToSendOperations.OperationsCount>0 then begin TLog.NewLog(ltdebug,ClassName,Format('Sending %d Operations to %s (inProc:%d, Received:%d)',[FBufferToSendOperations.OperationsCount,ClientRemoteAddr,nOpsToSend,FBufferReceivedOperationsHash.Count])); data := TMemoryStream.Create; try request_id := PascalNetData.NewRequestId; c1 := FBufferToSendOperations.OperationsCount; data.Write(c1,4); for i := 0 to FBufferToSendOperations.OperationsCount-1 do begin optype := FBufferToSendOperations.GetOperation(i).OpType; data.Write(optype,1); FBufferToSendOperations.GetOperation(i).SaveToNettransfer(data); end; Send(ntp_autosend,CT_NetOp_AddOperations,0,request_id,data); FBufferToSendOperations.ClearHastThree; finally data.Free; end; end else TLog.NewLog(ltdebug,ClassName,Format('Not sending any operations to %s (inProc:%d, Received:%d, Sent:%d)',[ClientRemoteAddr,nOpsToSend,FBufferReceivedOperationsHash.Count,FBufferToSendOperations.OperationsCount])); finally FBufferLock.Release; end; finally FNetLock.Release; end; Result := Connected; end; function TNetConnection.Send_GetBlocks(StartAddress, quantity : Cardinal; var request_id : Cardinal) : Boolean; Var data : TMemoryStream; c1,c2 : Cardinal; begin Result := false; request_id := 0; if (FRemoteOperationBlock.block<PascalCoinSafeBox.BlocksCount) Or (FRemoteOperationBlock.block=0) then exit; if Not Connected then exit; // First receive operations from data := TMemoryStream.Create; try if PascalCoinSafeBox.BlocksCount=0 then c1:=0 else c1:=StartAddress; if (quantity=0) then begin if FRemoteOperationBlock.block>0 then c2 := FRemoteOperationBlock.block else c2 := c1+100; end else c2 := c1+quantity-1; // Build 1.0.5 BUG - Always query for ONLY 1 if Build is lower or equal to 1.0.5 if ((FClientAppVersion='') Or ( (length(FClientAppVersion)=5) And (FClientAppVersion<='1.0.5') )) then begin c2 := c1; end; data.Write(c1,4); data.Write(c2,4); request_id := PascalNetData.NewRequestId; PascalNetData.RegisterRequest(Self,CT_NetOp_GetBlocks,request_id); TLog.NewLog(ltdebug,ClassName,Format('Send GET BLOCKS start:%d quantity:%d (from:%d to %d)',[StartAddress,quantity,StartAddress,quantity+StartAddress])); FIsDownloadingBlocks := quantity>1; Send(ntp_request,CT_NetOp_GetBlocks,0,request_id,data); Result := Connected; finally data.Free; end; end; function TNetConnection.Send_Hello(NetTranferType : TNetTransferType; request_id : Integer) : Boolean; { HELLO command: - Operation stream - My Active server port (0 if no active). (2 bytes) - A Random Longint (4 bytes) to check if its myself connection to my server socket - My Unix Timestamp (4 bytes) - Registered node servers count (For each) - ip (string) - port (2 bytes) - last_connection UTS (4 bytes) - My Server port (2 bytes) - If this is a response: - If remote operation block is lower than me: - Send My Operation Stream in the same block thant requester } var data : TStream; i : Integer; nsa : TNodeServerAddress; nsarr : TNodeServerAddressArray; w : Word; currunixtimestamp : Cardinal; begin Result := false; if Not Connected then exit; // Send Hello command: data := TMemoryStream.Create; try if NetTranferType=ntp_request then begin PascalNetData.RegisterRequest(Self,CT_NetOp_Hello,request_id); end; If PascalCoinNode.NetServer.Active then w := PascalCoinNode.NetServer.Port else w := 0; // Save active server port (2 bytes). 0 = No active server port data.Write(w,2); // Save My connection public key TStreamOp.WriteAnsiString(data,TAccountComp.AccountKey2RawString(PascalNetData.NodePrivateKey.PublicKey)); // Save my Unix timestamp (4 bytes) currunixtimestamp := UnivDateTimeToUnix(DateTime2UnivDateTime(now)); data.Write(currunixtimestamp,4); // Save last operations block TPCOperationsComp.SaveOperationBlockToStream(PascalCoinBank.LastOperationBlock,data); nsarr := PascalNetData.NodeServersAddresses.GetValidNodeServers(true,CT_MAX_NODESERVERS_ON_HELLO); i := length(nsarr); data.Write(i,4); for i := 0 to High(nsarr) do begin nsa := nsarr[i]; TStreamOp.WriteAnsiString(data, nsa.ip); data.Write(nsa.port,2); data.Write(nsa.last_connection,4); end; // Send client version TStreamOp.WriteAnsiString(data,CT_ClientAppVersion{$IFDEF LINUX}+'l'{$ELSE}+'w'{$ENDIF}{$IFDEF FPC}{$IFDEF LCL}+'L'{$ELSE}+'F'{$ENDIF}{$ENDIF}); // Build 1.5 send accumulated work data.Write(PascalCoinSafeBox.WorkSum,SizeOf(PascalCoinSafeBox.WorkSum)); // Send(NetTranferType,CT_NetOp_Hello,0,request_id,data); Result := Client.Connected; finally data.Free; end; end; function TNetConnection.Send_Message(const TheMessage: AnsiString): Boolean; Var data : TStream; cyp : TRawBytes; begin Result := false; if Not Connected then exit; data := TMemoryStream.Create; Try // Cypher message: cyp := ECIESEncrypt(FClientPublicKey,TheMessage); TStreamOp.WriteAnsiString(data,cyp); Send(ntp_autosend,CT_NetOp_Message,0,0,data); Result := true; Finally data.Free; End; end; function TNetConnection.Send_NewBlockFound(const NewBlock: TPCOperationsComp ): Boolean; var data : TStream; request_id : Integer; begin Result := false; if Not Connected then exit; FNetLock.Acquire; Try // Clear buffers FBufferLock.Acquire; Try FBufferReceivedOperationsHash.Clear; FBufferToSendOperations.ClearHastThree; finally FBufferLock.Release; end; // Checking if operationblock is the same to prevent double messaging... If (TPCOperationsComp.EqualsOperationBlock(FRemoteOperationBlock,NewBlock.OperationBlock)) then begin TLog.NewLog(ltDebug,ClassName,'This connection has the same block, does not need to send'); exit; end; if (PascalCoinSafeBox.BlocksCount<>NewBlock.OperationBlock.block+1) then begin TLog.NewLog(ltDebug,ClassName,'The block number '+IntToStr(NewBlock.OperationBlock.block)+' is not equal to current blocks stored in bank ('+IntToStr(PascalCoinSafeBox.BlocksCount)+'), finalizing'); exit; end; data := TMemoryStream.Create; try request_id := PascalNetData.NewRequestId; NewBlock.SaveBlockToStream(false,data); data.Write(PascalCoinSafeBox.WorkSum,SizeOf(PascalCoinSafeBox.WorkSum)); Send(ntp_autosend,CT_NetOp_NewBlock,0,request_id,data); finally data.Free; end; Finally FNetLock.Release; End; Result := Connected; end; // *** Skybuck: CHECK THIS LATER IF THIS METHOD STILL NECESSARY or can be removed *** procedure TNetConnection.SetClient(const Value: TNetTcpIpClient); Var old : TNetTcpIpClient; begin if FTcpIpClient<>Value then begin if Assigned(FTcpIpClient) then begin FTcpIpClient.OnConnect := Nil; FTcpIpClient.OnDisconnect := Nil; // FTcpIpClient.RemoveFreeNotification(Self); end; PascalNetData.UnRegisterRequest(Self,0,0); old := FTcpIpClient; FTcpIpClient := Value; if Assigned(old) then begin // if old.Owner=Self then begin old.Free; // end; end; end; if Assigned(FTcpIpClient) then begin // FTcpIpClient.FreeNotification(Self); FTcpIpClient.OnConnect := TcpClient_OnConnect; FTcpIpClient.OnDisconnect := TcpClient_OnDisconnect; end; PascalNetData.NotifyNetConnectionUpdated; end; procedure TNetConnection.SetConnected(const Value: Boolean); begin if (Value = GetConnected) then exit; if Value then ConnectTo(Client.RemoteHost,Client.RemotePort) else begin FinalizeConnection; Client.Disconnect; end; end; procedure TNetConnection.TcpClient_OnConnect(Sender: TObject); begin PascalNetData.IncStatistics(1,0,1,0,0,0); TLog.NewLog(ltInfo,Classname,'Connected to a server '+ClientRemoteAddr); PascalNetData.NotifyNetConnectionUpdated; end; procedure TNetConnection.TcpClient_OnDisconnect(Sender: TObject); begin if self is TNetServerClient then PascalNetData.IncStatistics(-1,-1,0,0,0,0) else begin if FHasReceivedData then PascalNetData.IncStatistics(-1,0,-1,-1,0,0) else PascalNetData.IncStatistics(-1,0,-1,0,0,0); end; TLog.NewLog(ltInfo,Classname,'Disconnected from '+ClientRemoteAddr); PascalNetData.NotifyNetConnectionUpdated; if (FClientTimestampIp<>'') then begin PascalNetData.NetworkAdjustedTime.RemoveIp(FClientTimestampIp); end; end; end.
unit Collections; interface uses System.SysUtils, Math, System.Generics.Collections, System.Generics.Defaults, Data, Interfaces, Rtti; type TList = class(TData, ICountable) protected Items : TList<DataRef>; function GetSize() : Integer; function GetItem(n : Integer) : DataRef; public Executable : Boolean; property Size : Integer read GetSize; property DataItems[n : Integer] : DataRef read GetItem; default; procedure Add(item : DataRef); function ValueEquals(b : TData) : Boolean; override; constructor Create(); overload; constructor Create(Items : array of DataRef; executable : Boolean = True); overload; destructor Destroy(); override; function Copy() : TData; override; function GetEnumerator : TEnumerator<DataRef>; function ToString : string; override; function ToTValue() : TValue; override; function Count : Integer; end; TLispListEnumerator = class(TEnumerator<DataRef>) private FList : TList; FCurrent : Ref<TData>; FIndex : Integer; public constructor Create(list : TList); function DoGetCurrent : Ref<TData>; override; function DoMoveNext : Boolean; override; end; ListRef = Ref<TList>; DataComparer = class(TInterfacedObject, IEqualityComparer<DataRef>) function Equals(const Left, Right : DataRef) : Boolean; reintroduce; function GetHashCode(const Value : DataRef) : Integer; reintroduce; end; TDictionary = class(TData) protected FContent : TDictionary<DataRef, DataRef>; public constructor Create(); overload; constructor Create(list : TList); overload; destructor Destroy(); override; function Contains(key : DataRef) : Boolean; procedure Add(key : DataRef; Value : DataRef); function Get(key : DataRef) : DataRef; function ToString : string; override; function Copy() : TData; override; end; function CreateListRef(Data : TList) : DataRef; implementation function CreateListRef(Data : TList) : DataRef; begin Result := TRef<TData>.Create(Data); end; { TLispListEnumerator } constructor TLispListEnumerator.Create(list : TList); begin Self.FList := list; Self.FCurrent := nil; Self.FIndex := 0; end; function TLispListEnumerator.DoGetCurrent : Ref<TData>; begin Result := FList[FIndex]; end; function TLispListEnumerator.DoMoveNext : Boolean; begin Result := FIndex < FList.Size; end; { TParseList } procedure TList.Add(item : Ref<TData>); begin Items.Add(item); end; function TList.Copy : TData; var item : DataRef; list : TList; begin list := TList.Create(); for item in Items do begin list.Add(CreateRef(item().Copy())); end; Result := list; end; function TList.Count : Integer; begin Result := Items.Count; end; constructor TList.Create(Items : array of DataRef; executable : Boolean); var I : Integer; begin inherited Create(); Self.Items := TList<DataRef>.Create(); self.Executable := executable; for I := 0 to Length(Items) - 1 do Add(Items[I]); end; constructor TList.Create; begin inherited; Items := TList<DataRef>.Create(); Executable := true; end; destructor TList.Destroy; begin Items.Free; inherited; end; function TList.GetEnumerator : TEnumerator<Ref<TData>>; begin Result := TLispListEnumerator.Create(Self); end; function TList.GetItem(n : Integer) : Ref<TData>; begin Result := Ref<TData>(Items[n]); end; function TList.GetSize : Integer; begin Result := Items.Count; end; function TList.ToString : string; var I : Integer; DataRef : Ref<TData>; Data : TData; begin Result := '('; for I := 0 to Items.Count - 1 do begin if I > 0 then Result := Result + ' '; DataRef := Ref<TData>(Items[I]); Data := DataRef(); Result := Result + Data.ToString; end; Result := Result + ')'; end; function TList.ToTValue : TValue; var list : TList<TValue>; I : Integer; begin list := TList<TValue>.Create(); for I := 0 to Self.Size - 1 do list[I] := Items[I]().ToTValue(); Result := TValue.From(list); end; function TList.ValueEquals(b : TData) : Boolean; var other : TList; I : Integer; begin other := b as TList; Result := true; for I := 0 to Min(Size - 1, other.Size - 1) do begin if not Items[I]().ValueEquals(other[I]()) then Exit(False); end; end; { TDictionary } procedure TDictionary.Add(key : DataRef; Value : DataRef); begin FContent.AddOrSetValue(key, Value); end; constructor TDictionary.Create; begin FContent := TDictionary<DataRef, DataRef>.Create(DataComparer.Create()); end; constructor TDictionary.Create(list : TList); var I : Integer; begin Create(); Assert(list.Size = 2); I := 0; while I < list.Size do begin FContent.Add(list[I], list[I + 1]); I := I + 2; end; end; destructor TDictionary.Destroy; begin FContent.Free; inherited; end; function TDictionary.Contains(key : DataRef) : Boolean; begin Result := FContent.ContainsKey(key); end; function TDictionary.Copy: TData; var dict : TDictionary; pair: TPair<DataRef,DataRef>; begin dict := TDictionary.Create(); for pair in FContent do begin dict.Add(pair.Key, pair.Value); end; Result := dict; end; function TDictionary.Get(key : DataRef) : DataRef; begin Result := FContent[key]; end; function TDictionary.ToString : string; var I : Integer; pair : TPair<DataRef, DataRef>; begin Result := '{ '; for pair in FContent do begin Result := Result + pair.key().ToString + ' ' + pair.Value().ToString + ', '; end; Result := Result + '}'; end; { DataComparer } function DataComparer.Equals(const Left, Right : DataRef) : Boolean; begin Result := Left().ValueEquals(Right()); end; function DataComparer.GetHashCode(const Value : DataRef) : Integer; begin Result := Value().GetHashCode; end; end.
unit PT4Common; { Некоторые полезные общие функции } {$mode objfpc}{$H+} interface uses Classes, SysUtils, {$IFDEF WIN32} Windows {$ELSE} System {$ENDIF}; type TProc = procedure; TProcS = procedure (S: PChar); stdcall; PInt = ^integer; TInitTaskProc = procedure(N: integer); PNode = ^TNode; TNode = record Data: integer; Next: PNode; Prev: PNode; Left: PNode; Right: PNode; Parent: PNode; end; const {$IFDEF WIN32} RootPath = 'C:\PABCWork.NET\'; PT4LibPath = 'C:\Program Files\PascalABC.NET\PT4\PT4pabc.dll'; LibSuffix = '.dll'; NewLine = chr($0D) + chr($0A); {$ELSE} RootPath = '~/PABCWork.NET/'; PT4LibPath = '/usr/lib/PT4/PT4pabc.so'; LibSuffix = '.so'; NewLine = chr($0A); {$ENDIF} function isdigit(x : char) : boolean; function GetLocaleID : integer; function GetLibPath(S : string) : string; implementation function isdigit(x : char) : boolean; begin isdigit := (ord(x) <= ord('9')) and (ord(x) >= ord('0')); end; function GetLocaleID : integer; begin {$IFDEF WIN32} GetLocaleID := GetThreadLocale; {$ELSE} GetLocaleID := $409; // English, 419 - русский {$ENDIF} end; function GetLibPath(S : string) : string; begin GetLibPath := RootPath + 'PT4' + S + LibSuffix; end; end.
const base = 100000000; basedigits = 8; maxsize = 25; type tlarge = array [0..maxsize] of integer; procedure LargeAdd(var a : tlarge; const b : tlarge); var i : integer; rem : integer; begin if (a[0] < b[0]) then a[0] := b[0]; rem := 0; for i := 1 to a[0] do begin rem := rem + a[i] + b[i]; a[i] := rem mod base; rem := rem div base; end; if (rem <> 0) then begin inc(a[0]); a[a[0]] := rem; end; end; procedure LargeMulInt(var a : tlarge; b : integer); var i : integer; rem : int64; begin rem := 0; for i := 1 to a[0] do begin rem := int64(a[i]) * b + rem; a[i] := rem mod base; rem := rem div base; end; if (rem <> 0) then begin inc(a[0]); a[a[0]] := rem; end; end; procedure LargeWrite(const a : tlarge); var s : string [basedigits]; i : integer; begin Write(a[a[0]]); for i := a[0] - 1 downto 1 do begin Str(a[i], s); while (Length(s) <> basedigits) do s := '0' + s; Write(s); end; end; var n, k, i : integer; a, b, c : tlarge; begin Read(n, k); Fillchar(a, sizeof(a), 0); a[0] := 1; a[1] := 1; Fillchar(b, sizeof(b), 0); b[0] := 1; b[1] := k - 1; for i := 1 to n do begin c := b; LargeAdd(b, a); LargeMulInt(b, k - 1); a := c; end; LargeWrite(a); end.
unit FIniFile; interface uses Windows; procedure DelIniKey(const fn: WideString; const section, key: WideString); procedure SetIniKey(const fn: WideString; const section, key, value: WideString); overload; procedure SetIniKey(const fn: WideString; const section, key: WideString; value: integer); overload; procedure SetIniKey(const fn: WideString; const section, key: WideString; value: boolean); overload; function GetIniKey(const fn: WideString; const section, key, default: WideString): WideString; overload; function GetIniKey(const fn: WideString; const section, key: WideString; default: integer): integer; overload; function GetIniKey(const fn: WideString; const section, key: WideString; default: boolean): boolean; overload; implementation uses SysUtils; function IntToStr(n: integer): string; begin Str(n:0, Result); end; function StrToIntDef(const s: string; default: integer): integer; var code: integer; begin Val(s, Result, code); if code>0 then Result:= default; end; procedure DelIniKey(const fn: WideString; const section, key: WideString); begin if Win32Platform=VER_PLATFORM_WIN32_NT then WritePrivateProfileStringW(PWChar(section), PWChar(key), nil, PWChar(fn)) else WritePrivateProfileStringA(PChar(string(section)), PChar(string(key)), nil, PChar(string(fn))); end; procedure SetIniKey(const fn: WideString; const section, key, value: WideString); begin if Win32Platform=VER_PLATFORM_WIN32_NT then WritePrivateProfileStringW(PWChar(section), PWChar(key), PWChar(value), PWChar(fn)) else WritePrivateProfileStringA(PChar(string(section)), PChar(string(key)), PChar(string(value)), PChar(string(fn))); end; procedure SetIniKey(const fn: WideString; const section, key: WideString; value: integer); begin if Win32Platform=VER_PLATFORM_WIN32_NT then WritePrivateProfileStringW(PWChar(section), PWChar(key), PWChar(WideString(IntToStr(value))), PWChar(fn)) else WritePrivateProfileStringA(PChar(string(section)), PChar(string(key)), PChar(IntToStr(value)), PChar(string(fn))); end; procedure SetIniKey(const fn: WideString; const section, key: WideString; value: boolean); begin SetIniKey(fn, section, key, integer(value)); end; function GetIniKey(const fn: WideString; const section, key, default: WideString): WideString; const bufSize = 5*1024; var bufA: array[0..bufSize-1] of char; bufW: array[0..bufSize-1] of WideChar; begin if Win32Platform=VER_PLATFORM_WIN32_NT then begin FillChar(bufW, SizeOf(bufW), 0); GetPrivateProfileStringW(PWChar(section), PWChar(key), PWChar(default), bufW, SizeOf(bufW) div 2, PWChar(fn)); Result:= bufW; end else begin FillChar(bufA, SizeOf(bufA), 0); GetPrivateProfileStringA(PChar(string(section)), PChar(string(key)), PChar(string(default)), bufA, SizeOf(bufA), PChar(string(fn))); Result:= string(bufA); end; end; function GetIniKey(const fn: WideString; const section, key: WideString; default: integer): integer; var s: string; begin s:= GetIniKey(fn, section, key, IntToStr(default)); Result:= StrToIntDef(s, 0); end; function GetIniKey(const fn: WideString; const section, key: WideString; default: boolean): boolean; begin Result:= boolean(GetIniKey(fn, section, key, integer(default))); end; end.
program Main; uses UFile, UTipe, UTanggal, USimulasi, UInventori, UResep; {Kamus} var MasukanUser:string; InputTerproses:UserInput; OpsiAngka:integer; KodeError:integer; isInputValid, isSimulasiAktif: boolean; i: integer; ResepBaru: Resep; HargaResep: longint; StringInput: string; Error : boolean; DeltaUang:longint; NamaTxt:string; const HARGAUPGRADE = 1000; procedure loadInventori(nomor:string); {I.S. : Ada file inventori dan diberi nomor inventori} {F.S. : File inventori terload} begin LoadSukses:=true; NamaTxt := 'inventori_bahan_mentah_'+nomor+'.txt'; InventoriM := getInventoriBahanMentah(parse(NamaTxt)); NamaTxt := 'inventori_bahan_olahan_'+nomor+'.txt'; InventoriO := getInventoriBahanOlahan(parse(NamaTxt)); end; procedure prompt(var Diketik:string); {I.S. : isSimulasiAktif terdefinisi} {F.S. : variabel userInput yang menyimpan masukan command dari pengguna terisi} begin if (isSimulasiAktif = false) then begin write('> '); readln(Diketik); end else begin write('>> '); readln(Diketik); end; end; procedure hentikanSimulasi(); {I.S. Simulasi berjalan} {F.S. Simulasi berhenti} begin lihatStatistik(); isInputValid := true; isSimulasiAktif := false; tulisInventori(InventoriM,InventoriO,SimulasiAktif.Nomor); SemuaSimulasi.Isi[SimulasiAktif.Nomor]:=SimulasiAktif; end; function bacaInput(Input:string):UserInput; {memecah Input ke perintah, opsi1, dan opsi2} {Kamus lokal} var i: integer; Indeks: integer; x: string; Hasil:UserInput; {Algoritma} begin x:= ''; i:=1; Indeks:=1; Hasil.Perintah := ''; Hasil.Opsi1 := ''; Hasil.Opsi2 := ''; while (i<=length(Input)) do begin if ((Input[i]=' ') or (i=length(Input))) then begin if(i=length(Input))then begin x := x + Input[i]; end; case Indeks of 1 : begin Hasil.Perintah:=x; end; 2 : begin Hasil.Opsi1:=x; end; 3 : begin Hasil.Opsi2:=x; end; end; Indeks:=Indeks+1; x:=''; end else begin x:=x + Input[i]; end; i:=i+1; end; bacaInput:=Hasil; end; procedure formatUserInput(var Diketik:string); {I.S. : terdefinisi input Diketik} {F.S. : Mengubah menjadi format ProperCase} var n: integer; begin if (length(Diketik) > 0) then begin Diketik[1] := UpCase(Diketik[1]); n := 2; while (n <= length(Diketik)) do begin Diketik[n] := LowerCase(Diketik[n]); if (Diketik[n] = ' ') then begin Diketik[n+1] := UpCase(Diketik[n+1]); n := n + 2; end else begin n := n + 1; end; end; end; end; procedure loadData(); {I.S. : variabel di unit-unit kosong} {F.S. : Variabel di unit-unit terisi} begin LoadSukses:=true; DaftarBahanM := getBahanMentah(parse('bahan_mentah.txt')); DaftarBahanO := getBahanOlahan(parse('bahan_olahan.txt')); ResepResep := getResep(parse('resep.txt')); SemuaSimulasi:= getSimulasi(parse('simulasi.txt')); end; procedure showHelp(); {I.S. : Tampilan layar kosong} {F.S. : Dicetak help} begin writeln('Perintah tersedia'); writeln('load Memuat data dari file'); writeln('exit Keluar'); writeln('start Memulai simulasi'); writeln('stop Mengentikan simulasi'); writeln('lihatinventori Menampilkan inventori'); writeln('lihatresep Menampilkan daftar resep'); writeln('cariresep Mencari resep'); writeln('tambahresep Menambah resep ke daftar'); writeln(); writeln('Perintah khusus dalam simulasi'); writeln('belibahan Membeli bahan mentah'); writeln('olahbahan Mengolah bahan mentah jadi olahan'); writeln('jualolahan Menjual bahan hasil olahan'); writeln('jualresep Membuat dan menjual makanan sesuai resep'); writeln('tidur Memajukan hari dan mengembalikan energi serta menghapus item kadaluarsa'); writeln('makan Menambah 3 energi'); writeln('istirahat Menambah 1 energi'); writeln('lihatstatistik Melihat statistik'); end; {Algoritma} begin isSimulasiAktif:=false; LoadSukses:=false; while(true)do begin prompt(MasukanUser); InputTerproses := bacaInput(MasukanUser); if(not(isSimulasiAktif))then begin isInputValid := true; case LowerCase(InputTerproses.Perintah) of 'load' : begin loadData(); if(LoadSukses)then begin writeln('Load data berhasil'); end; end; 'exit' : begin if(LoadSukses)then begin tulisBalik(DaftarBahanM,DaftarBahanO,ResepResep,SemuaSimulasi); end; Halt(); end; 'start' : begin if(LoadSukses)then begin if (InputTerproses.Opsi1 = '') then begin write('Nomor simulasi: '); readln(InputTerproses.Opsi1); end; Val(InputTerproses.Opsi1,OpsiAngka,KodeError); if(KodeError<>0)then begin writeln('ERROR : Main -> Input opsi bukan angka'); end else begin loadInventori(InputTerproses.Opsi1); if(LoadSukses)then begin startSimulasi(OpsiAngka,Error); if(not(Error)) then begin isSimulasiAktif:=true; end; end else begin writeln('ERROR : Main -> Loading inventori gagal'); end; end; end else begin writeln('ERROR : Main -> Loading belum sukses'); end; end; else begin isInputValid := false; end; end; end else begin isInputValid := true; case LowerCase(InputTerproses.Perintah) of 'stop' : begin hentikanSimulasi(); end; 'belibahan' : begin if (InputTerproses.Opsi1 = '') then begin write('Nama bahan: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); if (InputTerproses.Opsi2 = '') then begin write('Jumlah bahan: '); readln(InputTerproses.Opsi2); end; Val(InputTerproses.Opsi2,OpsiAngka,KodeError); if(KodeError<>0)then begin writeln('ERROR : Main -> Jumlah bahan harus berupa angka'); end else begin pakeEnergi(Error); if(not(Error)) then begin DeltaUang := beliBahan(InputTerproses.Opsi1, OpsiAngka); if(DeltaUang<>-1)then begin pakaiUang(DeltaUang+1, Error); ubahStatistik(1, OpsiAngka); writeln('Berhasil membeli ', InputTerproses.Opsi1); end; end; end; end; 'olahbahan' : begin if (InputTerproses.Opsi1 = '') then begin write('Nama bahan olahan: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); pakeEnergi(Error); if(not(Error)) then begin olahBahan(InputTerproses.Opsi1, Error); if not(Error) then begin ubahStatistik(2,1); writeln('Berhasil membuat ', InputTerproses.Opsi1); end; end; end; 'jualolahan' : begin if (InputTerproses.Opsi1 = '') then begin write(InputTerproses.Opsi1); write('Nama bahan olahan: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); if (InputTerproses.Opsi2 = '') then begin write('Jumlah bahan olahan untuk dijual: '); readln(InputTerproses.Opsi2); end; Val(InputTerproses.Opsi2,OpsiAngka,KodeError); if(KodeError<>0)then begin writeln('ERROR : Main -> Jumlah bahan untuk dijual harus berupa angka.'); end else begin pakeEnergi(Error); if(not(Error)) then begin DeltaUang:=jualOlahan(InputTerproses.Opsi1, OpsiAngka); if (DeltaUang<>-1) then begin tambahUang(DeltaUang+1); ubahStatistik(3,OpsiAngka); writeln('Berhasil menjual ', InputTerproses.Opsi1); end; end; end; end; 'jualresep' : begin if (InputTerproses.Opsi1 = '') then begin write('Nama resep: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); pakeEnergi(Error); if(not(Error)) then begin DeltaUang:=jualResep(InputTerproses.Opsi1); if (DeltaUang <> -1) then begin tambahUang(DeltaUang+1); ubahStatistik(4, 1); writeln('Berhasil menjual ', InputTerproses.Opsi1); end; end; end; 'makan' : begin makan(); end; 'istirahat' : begin istirahat(); end; 'tidur' : begin tidur(Error); if(not(Error))then begin writeln('Berhasil tidur'); hapusKadaluarsa(); if(SimulasiAktif.JumlahHidup=10)then begin writeln('Simulasi selesai (10 hari)'); hentikanSimulasi(); end end; end; 'lihatstatistik' : begin lihatStatistik(); end; 'statistik' : begin lihatStatistik(); end; else begin isInputValid := false; end; end; end; isInputValid := not(isInputValid); case LowerCase(InputTerproses.Perintah) of 'upgradeinventori':begin upgradeInventori(Error); if (not(Error)) then begin pakaiUang(HARGAUPGRADE, Error); writeln('Berhasil menambah kapasitas inventori menjadi ', SimulasiAktif.Kapasitas); end; end; 'lihatresep':begin sortResep(); lihatresep(); end; 'help':begin writeln('Engi''s Kitchen'); showHelp(); end; 'lihatinventori' : begin if(not(isSimulasiAktif))then begin if (InputTerproses.Opsi1 = '') then begin write('Nomor Inventori: '); readln(InputTerproses.Opsi1); end; Val(InputTerproses.Opsi1,OpsiAngka,KodeError); if(KodeError<>0)then begin writeln('ERROR : Main -> Nomor inventori harus berupa angka.'); end else begin loadInventori(InputTerproses.Opsi1); if(LoadSukses)then begin sortArray(); lihatInventori(); end else begin writeln('ERROR : Main -> Load inventori gagal'); end; end; end else begin sortArray(); lihatInventori(); end; end; 'cariresep' : begin if (InputTerproses.Opsi1 = '') then begin write('Nama resep: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); cariResep(InputTerproses.Opsi1); end; 'tambahresep' : begin if(InputTerproses.Opsi1 = '') then begin write('Nama resep: '); readln(InputTerproses.Opsi1); end; formatUserInput(InputTerproses.Opsi1); ResepBaru.Nama := InputTerproses.Opsi1; write('Harga: '); readln(StringInput); Val(StringInput,HargaResep,KodeError); if(KodeError<>0) then begin writeln('ERROR : Main -> Harga harus berupa angka'); end else begin ResepBaru.Harga := HargaResep; write('Jumlah bahan: '); readln(StringInput); Val(StringInput,OpsiAngka,KodeError); if(KodeError<>0) then begin writeln('ERROR : Main -> Jumlah bahan harus berupa angka'); end else begin ResepBaru.JumlahBahan := OpsiAngka; writeln('Daftar bahan: '); for i := 1 to ResepBaru.JumlahBahan do begin write(' ', i, '. '); readln(ResepBaru.Bahan[i]); formatUserInput(ResepBaru.Bahan[i]); end; tambahResep(ResepBaru, Error); if (not(Error)) then begin writeln('Berhasil menambahkan resep ', ResepBaru.Nama); end; end; end; end; else begin isInputValid := not(isInputValid); end; end; if(not(isInputValid))then begin writeln('ERROR : Main -> Perintah tidak valid'); showHelp(); end; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Editor.Items; interface uses DesignEditors, DesignMenus, DesignIntf, System.Classes, System.Generics.Collections, FGX.Designer.Items, FGX.Items; resourcestring rsItemsEditor = 'Items Editor...'; type { TfgItemsEditor } TfgItemsEditor = class(TComponentEditor) protected FAllowChild: Boolean; FItemsClasses: TList<TfgItemInformation>; FForm: TfgFormItemsDesigner; procedure DoCreateItem(Sender: TObject); virtual; public constructor Create(AComponent: TComponent; ADesigner: IDesigner); override; destructor Destroy; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure PrepareItem(Index: Integer; const AItem: IMenuItem); override; procedure Edit; override; end; implementation { TItemsEditor } uses System.SysUtils, FMX.Types, FGX.Toolbar; constructor TfgItemsEditor.Create(AComponent: TComponent; ADesigner: IDesigner); begin inherited; FItemsClasses := TList<TfgItemInformation>.Create; end; destructor TfgItemsEditor.Destroy; begin FItemsClasses.Free; inherited; end; procedure TfgItemsEditor.DoCreateItem(Sender: TObject); begin end; procedure TfgItemsEditor.Edit; begin ExecuteVerb(0); end; procedure TfgItemsEditor.ExecuteVerb(Index: Integer); begin case Index of 0: if Supports(Component, IItemsContainer) then begin if FForm = nil then FForm := TfgFormItemsDesigner.Create(nil); FForm.Designer := Designer; FForm.Component := Component as IItemsContainer; FForm.Show; end; end; end; function TfgItemsEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := rsItemsEditor; end; end; function TfgItemsEditor.GetVerbCount: Integer; begin Result := 1; end; procedure TfgItemsEditor.PrepareItem(Index: Integer; const AItem: IMenuItem); begin inherited; end; end.
unit MruMenu; (* TMruMenu Component: Most-Recently-Used file list by Timothy Weber Supports Delphi 1, 2, 3, 5, 7, 2010, and XE3. Usage: Fill in the BeforeItem and AfterItem properties. Then call AddFile whenever a file is opened, and respond to OnClick as you would to a File|Open command. BeforeItem: The menu item that comes before the MRU items. Usually a separator item. AfterItem: The menu item that comes after the MRU items. Usually the Exit item. OnClick: This event is called when the user chooses one of the MRU items. Handle it like you would a File|Open event that's passed the given file name. AddFile: Call this from your normal File|Open handler, to register the opened file. Don't call it from within OnClick. LastOpened: This contains the name of the file last added with AddFile or reported with OnClick. It can be set as well. It will be loaded from the registry on initialization, so if it is non-blank, your application can load it again. Product: Used for the top-level registry key under Software. Defaults to the application name. Company: Optional. RelativePath: Optional place to put the information under the application's key. Defaults to WindowPos\<window caption>. Version: Version number for the application, so position information for different versions is kept separate. Defaults to "1.0a". Enabled: Enables and disables all the MRU menu items. *) interface uses {$ifdef DELPHI} WinProcs, Messages, {$endif} SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus; type TMruClickEvent = procedure(name: String) of Object; TMruMenu = class(TComponent) private { Private declarations } fBeforeItem: TMenuItem; fAfterItem: TMenuItem; fOnClick: TMruClickEvent; fCompany: String; fProduct: String; fVersion: String; fEnabled: Boolean; fSaveState: Boolean; procedure SetBeforeItem(item: TMenuItem); procedure SetAfterItem(item: TMenuItem); { These implement TMenuItem.MenuIndex for Win16. } function BeforeIndex: Integer; function AfterIndex: Integer; procedure SaveItemsToRegistry; procedure ClearAllItems; procedure LoadItemsFromRegistry; function AddNewItem(accelerator: Integer; itemName: String; index: Integer): TMenuItem; procedure ItemClicked(Sender: TObject); function StartKey: String; function GetLastOpened: String; procedure SetLastOpened(FileName: String); procedure SetEnabled(const Value: Boolean); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; procedure AddFile(FileName: String); procedure Clear; { ClearAllItems(); } property LastOpened: String read GetLastOpened write SetLastOpened; published { Published declarations } property BeforeItem: TMenuItem read fBeforeItem write SetBeforeItem; property AfterItem: TMenuItem read fAfterItem write SetAfterItem; property OnClick: TMruClickEvent read fOnClick write fOnClick; property Company: String read fCompany write fCompany; property Product: String read fProduct write fProduct; property Version: String read fVersion write fVersion; property Enabled: Boolean read fEnabled write SetEnabled default true; property SaveState: Boolean read fSaveState write fSaveState default true; end; procedure Register; implementation uses {$ifdef win32} Registry, {$else} IniFiles, {$endif} CType, TjwStrUtil; const MainKey = 'MRU Files'; LastOpenedKey = 'Last Opened'; procedure Register; begin RegisterComponents('TJW', [TMruMenu]); end; {$ifndef win32} function FindMenuIndex(item: TMenuItem): Integer; var i: Integer; begin Result := -1; for i := 0 to item.Parent.Count - 1 do if item.Parent.Items[i] = item then begin Result := i; Break; end; end; {$endif} { Returns the integer that starts the caption string for this menu item. Returns -1 if there is none. Assumes that the number starts with a leading ampersand. } function GetIndexVal(item: TMenuItem): Integer; begin if item.Caption[1] <> '&' then Result := -1 else Result := StrToIntDef(item.Caption[2], -1); end; function ItemToFileName(item: TMenuItem): String; begin Result := item.Caption; Result := RemovePrefix(Result, '&'); while IsNumber(Result[1]) do Result := DeleteFirstChar(Result); Result := Trim(Result); end; { Replaces a leading numeric string in the item's caption with the specified value. } procedure ReplaceIndexVal(item: TMenuItem; newValue: Integer); begin { add the new number, with a new ampersand. } item.Caption := '&' + IntToStr(newValue) + ' ' + ItemToFileName(item); end; constructor TMruMenu.Create(AOwner: TComponent); begin inherited; fEnabled := true; fSaveState := true; end; procedure TMruMenu.SetBeforeItem(item: TMenuItem); begin if fBeforeItem <> item then begin ClearAllItems; fBeforeItem := item; LoadItemsFromRegistry; end; end; procedure TMruMenu.SetAfterItem(item: TMenuItem); begin if fAfterItem <> item then begin ClearAllItems; fAfterItem := item; LoadItemsFromRegistry; end; end; function TMruMenu.BeforeIndex: Integer; begin {$ifdef win32} Result := fBeforeItem.MenuIndex; {$else} Result := FindMenuIndex(fBeforeItem); {$endif} end; function TMruMenu.AfterIndex: Integer; begin {$ifdef win32} Result := fAfterItem.MenuIndex; {$else} Result := FindMenuIndex(fAfterItem); {$endif} end; procedure TMruMenu.SaveItemsToRegistry; var parent: TMenuItem; iniFile: {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}; i, index: Integer; item: TMenuItem; begin if (fBeforeItem <> nil) and (fAfterItem <> nil) and not (csDesigning in ComponentState) and fSaveState then begin { assert(fBeforeItem->Parent == fAfterItem->Parent); } parent := fBeforeItem.Parent; { open the registry } iniFile := {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}.Create(StartKey); try { erase existing entries } iniFile.EraseSection(MainKey); { write current entries, indexed by their numbers } for i := BeforeIndex + 1 to AfterIndex - 1 do begin item := parent.Items[i]; index := GetIndexVal(item); if index >= 0 then iniFile.WriteString(MainKey, IntToStr(index), ItemToFileName(item)); end; finally iniFile.Free; end; end; end; procedure TMruMenu.ClearAllItems; var parent, item: TMenuItem; i: Integer; begin if (fBeforeItem <> nil) and (fAfterItem <> nil) then begin { assert(fBeforeItem->Parent == fAfterItem->Parent); } parent := fBeforeItem.Parent; { delete entries } for i := BeforeIndex + 1 to AfterIndex - 1 do begin item := parent.Items[i]; parent.Remove(item); item.Free; end; end; end; procedure TMruMenu.LoadItemsFromRegistry; var iniFile: {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}; accelerator, { number in the list } index: Integer; { index in the parent menu } fileName: String; begin if (fBeforeItem <> nil) and (fAfterItem <> nil) and not (csDesigning in ComponentState) then begin { open the registry } iniFile := {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}.Create(StartKey); try { read and insert items, indexed by their numbers } index := BeforeIndex + 1; { index in the parent menu } { assert(index = AfterIndex); } if index <> AfterIndex then raise Exception.Create('MRU menu items not initialized correctly'); for accelerator := 1 to 9 do begin { see if this item is in the registry } fileName := iniFile.ReadString(MainKey, IntToStr(accelerator), ''); if fileName <> '' then begin { add the item } AddNewItem(accelerator, fileName, index); Inc(index); end; end; { add the separator at the end, if there were any items. } if index > BeforeIndex + 1 then AddNewItem(-1, '-', AfterIndex); finally iniFile.Free; end; end; end; { If accelerator is less than zero, just uses the given name; otherwise, } { constructs a name with the appropriate accelerator. } function TMruMenu.AddNewItem(accelerator: Integer; itemName: String; index: Integer): TMenuItem; begin { assert(fBeforeItem); } Result := TMenuItem.Create(fBeforeItem.Owner); if accelerator >= 0 then begin Result.Caption := '&' + IntToStr(accelerator) + ' ' + itemName; Result.OnClick := ItemClicked; Result.Hint := 'Open this file'; end else Result.Caption := itemName; fBeforeItem.Parent.Insert(index, Result); end; procedure TMruMenu.ItemClicked(Sender: TObject); var FileName: String; begin if Assigned(fOnClick) then begin FileName := ItemToFileName(Sender as TMenuItem); fOnClick(FileName); SetLastOpened(FileName); end; end; function TMruMenu.StartKey: String; begin {$ifdef win32} Result := 'Software\'; if fCompany <> '' then Result := Result + fCompany + '\'; if fProduct <> '' then Result := Result + fProduct + '\' else Result := Result + Application.Title + '\'; if fVersion <> '' then Result := Result + fVersion + '\' else Result := Result + fVersion + 'v1.0a\'; {$else} Result := fProduct + '.ini'; {$endif} end; procedure TMruMenu.AddFile(FileName: String); var parent, item, newItem: TMenuItem; accelerator, i, currentVal: Integer; begin { assert(fBeforeItem); } { assert(fAfterItem); } { assert(fBeforeItem->Parent == fAfterItem->Parent); } parent := fBeforeItem.Parent; { expand the file path. } FileName := ExpandFileName(FileName); { insert a new item with index 1 for this name } newItem := AddNewItem(1, FileName, BeforeIndex + 1); { renumber the items in the file menu. } { remove any with numbers greater than 9. } { also remove any with the same name as this one. } accelerator := 1; i := BeforeIndex + 2; while i < AfterIndex do begin item := parent.Items[i]; currentVal := GetIndexVal(item); if currentVal >= 0 then begin { valid menu item? } if (accelerator >= 9) { aged out? } or (ItemToFileName(item) = ItemToFileName(newItem)) { same name? } then begin { remove it from the menu. } parent.Remove(item); item.Free; end else begin { replace its accelerator. } ReplaceIndexVal(item, accelerator); Inc(accelerator); Inc(i); end; end else Inc(i); end; { ensure that there's a separator before afterItem } if parent.Items[AfterIndex - 1].Caption <> '-' then AddNewItem(-1, '-', AfterIndex); { save the list } SaveItemsToRegistry; SetLastOpened(FileName); end; procedure TMruMenu.Clear; begin ClearAllItems; end; function TMruMenu.GetLastOpened: String; var iniFile: {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}; begin { open the registry } iniFile := {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}.Create(StartKey); try { read the last-opened file name } Result := iniFile.ReadString(MainKey, LastOpenedKey, ''); finally iniFile.Free; end; end; procedure TMruMenu.SetLastOpened(FileName: String); var iniFile: {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}; begin if fSaveState then begin { open the registry } iniFile := {$ifdef win32} TRegIniFile {$else} TIniFile {$endif}.Create(StartKey); try { write the last-opened file name } iniFile.WriteString(MainKey, LastOpenedKey, FileName); finally iniFile.Free; end; end; end; procedure TMruMenu.SetEnabled(const Value: Boolean); var i: Integer; parent, item: TMenuItem; begin if Value <> fEnabled then begin fEnabled := Value; parent := fBeforeItem.Parent; for i := BeforeIndex + 1 to AfterIndex - 1 do begin item := parent.Items[i]; item.Enabled := fEnabled; end; end; end; end.
unit vcmCustomizeUtils; //////////////////////////////////////////////////////////////////////////////// // Библиотека : VCM // Назначение : Общие утилиты для настройки // Версия : $Id: vcmCustomizeUtils.pas,v 1.8 2013/08/05 12:21:59 morozov Exp $ //////////////////////////////////////////////////////////////////////////////// (*------------------------------------------------------------------------------- $Log: vcmCustomizeUtils.pas,v $ Revision 1.8 2013/08/05 12:21:59 morozov {RequestLink:471774446} Revision 1.7 2013/07/26 10:32:43 morozov {RequestLink: 471774401} Revision 1.6 2013/07/05 14:34:53 lulin - переименовал свойство про возможность редактирования тулбара и немного переделал правки Виктора касательно редактирования тулбаров во внутренней версии. Revision 1.5 2013/04/25 13:44:53 morozov {RequestLink:363571639} Revision 1.4 2013/04/25 13:20:27 morozov {RequestLink:363571639} Revision 1.3 2008/09/15 11:19:50 oman - fix: Хакерски не непереведенное (К-115803119) Revision 1.2 2008/06/25 11:23:44 mmorozov - new: Оптимизация панелей инструментов ... Список форм при настройке доступных операций (CQ: OIT5-28281); Revision 1.1 2008/06/25 09:24:51 mmorozov - new: Оптимизация панелей инструментов ---|> в списке доступных форм показываем только объединенные панели инструментов + рефакторинг + список форм проекта при редактировании доступных для выбора операций (CQ: OIT5-28281); -------------------------------------------------------------------------------*) interface uses StdCtrls, vcmInterfaces, vcmEntityForm, Classes, vcmUserTypeDescr ; type vcmFormCustomize = class {* Утилиты для настройки формы. } {-} class function MakeVirtualForm(const aUserType : IvcmUserTypeDef; out NeedFreeForm : Boolean): TvcmEntityForm; {-} class function FindUserTypeByCaption(const aSettingsCaption: String): IvcmUserTypeDef; overload; {-} class function FindUserTypeByCaption(const aSettingsCaption : String; aFormClass : TClass): IvcmUserTypeDef; overload; {-} class function GetUserTypeDescrList(const aUserType : IvcmUserTypeDef; out aItemIndex : Integer): TvcmUserTypeDescrList; {-} class function MakeUserTypeCaption(const aUserTypeCaption : String; aFormClass : TClass; aToolbar : TComponent = nil; anInternal : Boolean = False): String; {-} end;//vcmFormCustomize implementation uses SysUtils, l3Types, l3Base, l3String, vcmBase, vcmBaseMenuManager, vcmMenuManager, vcmStringList, vcmContainerForm ; const cUntranslatedCaption = 'Translation is not available'; { vcmFormCustomize } class function vcmFormCustomize.MakeVirtualForm(const aUserType : IvcmUserTypeDef; out NeedFreeForm : Boolean): TvcmEntityForm; begin Result := g_MenuManager.BuildVirtualForm(RvcmEntityForm(aUserType.FormClass), NeedFreeForm, aUserType.ID); Assert(Result <> nil); end; class function vcmFormCustomize.FindUserTypeByCaption( const aSettingsCaption: String): IvcmUserTypeDef; begin Result := (g_MenuManager As TvcmCustomMenuManager). UserTypeByCaption(aSettingsCaption); Assert(Result <> nil); end; class function vcmFormCustomize.FindUserTypeByCaption(const aSettingsCaption : String; aFormClass : TClass): IvcmUserTypeDef; begin Result := (g_MenuManager As TvcmCustomMenuManager). UserTypeByCaption(aSettingsCaption, aFormClass); Assert(Result <> nil); end; class function vcmFormCustomize.GetUserTypeDescrList(const aUserType: IvcmUserTypeDef; out aItemIndex: Integer): TvcmUserTypeDescrList; function lp_FindDuplicateCaption(const aCaption: String; aList: TvcmUserTypeDescrList; out aDuplicateIndex: Integer): Boolean; var l_DupIndex: Integer; begin Result := False; aDuplicateIndex := -1; for l_DupIndex := 0 to aList.Count - 1 do if aList.Items[l_DupIndex].SettingsCaption = aCaption then begin Result := True; aDuplicateIndex := l_DupIndex; end; end; procedure lp_CorrectDupUTCaption(aFirst: TvcmUserTypeDescr; aSecond: TvcmUserTypeDescr); begin if (aFirst.FormClass.InheritsFrom(aSecond.FormClass)) then aFirst.SettingsCaption := aFirst.SettingsCaption + ' (основные операции)' else if (aSecond.FormClass.InheritsFrom(aFirst.FormClass)) then lp_CorrectDupUTCaption(aSecond, aFirst); end; var l_Index: Integer; l_List: TvcmUserTypeDescrList; l_UT: IvcmUserTypeDef; l_UTDescr: TvcmUserTypeDescr; l_DupIndex: Integer; l_DupUTDescr: TvcmUserTypeDescr; l_Caption: String; begin l_List := TvcmUserTypeDescrList.Create; l_List.Sorted := True; l_List.Duplicates := l3_dupAccept; with (g_MenuManager As TvcmCustomMenuManager).UserTypes do for l_Index := 0 to Hi do begin l_UT := IvcmUserTypeDef(Items[l_Index]); if not l_UT.UseToolbarAnotherUserType then if (l_UT.UserVisibleOpCount > 0) then if TvcmUserTypeInfo.AllowCustomizeToolbars(l_UT) then if (l_UT.SettingsCaption <> cUntranslatedCaption) then begin l_UTDescr.IsCustomizationInternal := TvcmUserTypeInfo.IsCustomizationInternal(l_UT); l_UTDescr.SettingsCaption := l_UT.SettingsCaption; l_UTDescr.FormClass := l_UT.FormClass; l_List.Add(l_UTDescr); end; end;//for l_Index if (l_List.Count > 0) then begin if (aUserType <> nil) then begin l_UTDescr.FormClass := aUserType.FormClass; l_UTDescr.SettingsCaption := aUserType.SettingsCaption; aItemIndex := l_List.IndexOf(l_UTDescr); end else aItemIndex := 0; end; Result := l_List; end; class function vcmFormCustomize.MakeUserTypeCaption( const aUserTypeCaption: String; aFormClass: TClass; aToolbar: TComponent; anInternal: Boolean): String; const c_ToolBarCaptionDelimiter = '-'; (* c_ContainerCaption = '(Контейнер)'; *) c_InternalCaption = '(Служебные настройки)'; var l_UserTypeCaption: String; begin l_UserTypeCaption := aUserTypeCaption; (* if (aFormClass.InheritsFrom(TvcmContainerForm)) then l_UserTypeCaption := Format('%s %s', [l_UserTypeCaption, c_ContainerCaption]); *) if (aToolbar <> nil) AND (aToolbar Is TvcmToolbarDef) AND not l3Starts(vcmCStr(TvcmToolbarDef(aToolbar).Caption), l3CStr(aUserTypeCaption), true) then l_UserTypeCaption := Format('%s %s %s', [l_UserTypeCaption, c_ToolBarCaptionDelimiter, TvcmToolbarDef(aToolbar).Caption]); if anInternal then l_UserTypeCaption := Format('%s %s', [l_UserTypeCaption, c_InternalCaption]); Result := l_UserTypeCaption; end; end.
unit ASpellLanguages; interface uses Classes; Type TASpellLangMap = class(TObject) Language: string; Code: string; end; var LanguageMap: TStringList; implementation const Languages: array[0..188] of string = ('Afar', 'Afrikaans', 'Akan', 'Amharic', 'Arabic', 'Assamese', 'Asturian / Bable', 'Avar', 'Aymara', 'Azerbaijani', 'Bashkir', 'Balinese', 'Belarusian', 'Bemba', 'Bulgarian', 'Bihari', 'Bislama', 'Bambara', 'Bengali', 'Tibetan', 'Breton', 'Bosnian', 'Catalan / Valencian', 'Chechen', 'Cebuano', 'Chamorro', 'Chuukese', 'Corsican', 'Czech', 'Kashubian', 'Chuvash', 'Welsh', 'Danish', 'German', 'Ewe', 'Greek', 'English', 'Esperanto', 'Spanish', 'Estonian', 'Basque', 'Persian', 'Fulah', 'Finnish', 'Fijian', 'Faroese', 'French', 'Friulian', 'Frisian', 'Irish', 'Scottish Gaelic', 'Gallegan', 'Guarani', 'Gujarati', 'Manx Gaelic', 'Hausa', 'Hawaiian', 'Hebrew', 'Hindi', 'Hiligaynon', 'Hiri Motu', 'Croatian', 'Upper Sorbian', 'Haitian Creole', 'Hungarian', 'Armenian', 'Herero', 'Interlingua (IALA)', 'Iban', 'Indonesian', 'Igbo', 'Sichuan Yi', 'Iloko', 'Ido', 'Icelandic', 'Italian', 'Javanese', 'Georgian', 'Kachin', 'Kongo', 'Khasi', 'Kikuyu / Gikuyu', 'Kwanyama', 'Kazakh', 'Kalaallisut / Greenlandic', 'Kannada', 'Konkani', 'Kanuri', 'Kashmiri', 'Kurdish', 'Komi', 'Cornish', 'Kirghiz', 'Latin', 'Luxembourgish', 'Ganda', 'Limburgian', 'Lingala', 'Lozi', 'Lithuanian', 'Luba-Katanga', 'Luo (Kenya and Tanzania)', 'Latvian', 'Malagasy', 'Marshallese', 'Maori', 'Minangkabau', 'Macedonian', 'Malayalam', 'Mongolian', 'Moldavian', 'Marathi', 'Malay', 'Maltese', 'Burmese', 'Norwegian Bokmal', 'North Ndebele', 'Low Saxon', 'Nepali', 'Ndonga', 'Niuean', 'Dutch', 'Norwegian Nynorsk', 'South Ndebele', 'Northern Sotho', 'Navajo', 'Nyanja', 'Occitan / Provencal', 'Oromo', 'Oriya', 'Ossetic', 'Punjabi', 'Pampanga', 'Papiamento', 'Polish', 'Pushto', 'Portuguese', 'Quechua', 'Rarotongan', 'Rundi', 'Romanian', 'Russian', 'Kinyarwanda', 'Sardinian', 'Sindhi', 'Northern Sami', 'Sango', 'Sinhalese', 'Slovak', 'Slovenian', 'Samoan', 'Shona', 'Somali', 'Albanian', 'Serbian', 'Swati', 'Southern Sotho', 'Sundanese', 'Swedish', 'Swahili', 'Tamil', 'Telugu', 'Tetum', 'Tajik', 'Tigrinya', 'Turkmen', 'Tokelau', 'Tagalog', 'Tswana', 'Tonga', 'Tok Pisin', 'Turkish', 'Tsonga', 'Tatar', 'Twi', 'Tahitian', 'Uighur', 'Ukrainian', 'Urdu', 'Uzbek', 'Venda', 'Vietnamese', 'Walloon', 'Wolof', 'Xhosa', 'Yiddish', 'Yoruba', 'Zhuang', 'Zulu'); Abbreviations: array[0..188] of string = ('aa', 'af', 'ak', 'am', 'ar', 'as', 'ast', 'av', 'ay', 'az', 'ba', 'ban', 'be', 'bem', 'bg', 'bh', 'bi', 'bm', 'bn', 'bo', 'br', 'bs', 'ca', 'ce', 'ceb', 'ch', 'chk', 'co', 'cs', 'csb', 'cv', 'cy', 'da', 'de', 'ee', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fa', 'ff', 'fi', 'fj', 'fo', 'fr', 'fur', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'gv', 'ha', 'haw', 'he', 'hi', 'hil', 'ho', 'hr', 'hsb', 'ht', 'hu', 'hy', 'hz', 'ia', 'iba', 'id', 'ig', 'ii', 'ilo', 'io', 'is', 'it', 'jv', 'ka', 'kac', 'kg', 'kha', 'ki', 'kj', 'kk', 'kl', 'kn', 'kok', 'kr', 'ks', 'ku', 'kv', 'kw', 'ky', 'la', 'lb', 'lg', 'li', 'ln', 'loz', 'lt', 'lu', 'luo', 'lv', 'mg', 'mh', 'mi', 'min', 'mk', 'ml', 'mn', 'mo', 'mr', 'ms', 'mt', 'my', 'nb', 'nd', 'nds', 'ne', 'ng', 'niu', 'nl', 'nn', 'nr', 'nso', 'nv', 'ny', 'oc', 'om', 'or', 'os', 'pa', 'pam', 'pap', 'pl', 'ps', 'pt', 'qu', 'rar', 'rn', 'ro', 'ru', 'rw', 'sc', 'sd', 'se', 'sg', 'si', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'ss', 'st', 'su', 'sv', 'sw', 'ta', 'te', 'tet', 'tg', 'ti', 'tk', 'tkl', 'tl', 'tn', 'to', 'tpi', 'tr', 'ts', 'tt', 'tw', 'ty', 'ug', 'uk', 'ur', 'uz', 've', 'vi', 'wa', 'wo', 'xh', 'yi', 'yo', 'za', 'zu'); procedure FillLangMap; var Index: integer; Item: TASpellLangMap; begin LanguageMap := TStringList.Create; LanguageMap.Sorted := True; LanguageMap.Duplicates := dupError; for Index := 0 to Length(Languages) -1 do begin Item := TASpellLangMap.Create; Item.Language := Languages[Index]; Item.Code := Abbreviations[Index]; LanguageMap.AddObject(Item.Language, Item); end; end; procedure FreeLangMap; var Index: integer; begin for Index := LanguageMap.Count -1 downto 0 do begin LanguageMap.Objects[Index].Free; end; LanguageMap.Free; end; initialization FillLangMap; finalization FreeLangMap; end.
unit RegPrep; {=========================================================================== Copyright (c) 2002 Dmitry Gribov. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice immediately at the beginning of the file, without modification, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Absolutely no warranty of function or purpose is made by the author Dmitry Gribov. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ===========================================================================} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin; type TForm1 = class(TForm) Button2: TButton; Edit1: TEdit; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; Button1: TButton; Edit2: TEdit; Button4: TButton; Button3: TButton; Edit3: TEdit; Button5: TButton; Edit4: TEdit; Button6: TButton; Edit5: TEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; CheckBox1: TCheckBox; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} Type TRocketFnt= Record //четыре переменные неизвестного назначения, всегда одинаковые, //поэтому могут использоваться как сигнатура формата iUnknA01:Word; //неизв., всегда 0x0EE0 iUnknA02:Word; //неизв., всегда 0x0DF0 iUnknA03:Word; //неизв., всегда 0x0003 iUnknA04:Word; //неизв., всегда 0x0000 FontName:String[63]; //текстовое название шрифта CharSize:Integer; //0, +0x48, размер битмапа символа в байтах Points:Integer; //1, +0x4C, размер шрифта в пойнтах Height:Integer; //2, +0x50, высота битмапа символа в пикселах iUnknB01:Integer; //3, +0x54, неизв. iUnknB02:Integer; //4, +0x58, неизв. iUnknB03:Integer; //5, +0x5C, неизв. iUnknB04:Integer; //6, +0x60, неизв. WidthsShift:Integer; //7, +0x64, смещение массива ширин символов BitsShift:Integer; //8, +0x68, смещение массива битмапов символов iUnknB05:Integer; //9, +0x6C, неизв. iUnknB06:Integer; //A, +0x70, неизв. end; procedure TForm1.Button2Click(Sender: TObject); Type TFontInfo=array [0..3] of Record FileName:String; FontWrite:String; end; Var F:TFileStream; FntHead:TRocketFnt; T:TextFile; D:Array[0..2000] of Byte; I,I1:Integer; MaxWidths: Record CharWidth:Integer; Count:Integer; end; LengthCounts:Array[0..255] of integer; FS,FB:String; Arr:TFontInfo; OutDat:String; Function GetChar(N:Integer):String; Begin Result:=Char(I); if Result[1] in ['"','&','<','>',#$98] then Result:='&#'+IntToStr(I)+';'; end; begin If Edit1.Text='' then Begin MessageBox(Handle,'Enter font name','Error',mb_Ok or mb_IconError); exit; end; Arr[0].FontWrite:='normal'; Arr[0].FileName:=Edit2.Text; Arr[1].FontWrite:='strong'; Arr[1].FileName:=Edit3.Text; Arr[2].FontWrite:='emphasis'; Arr[2].FileName:=Edit4.Text; Arr[3].FontWrite:='strongemphasis'; Arr[3].FileName:=Edit5.Text; if CheckBox1.Checked then FS:='Large' else FS:='Small'; OutDat:='<?xml version="1.0" encoding="WINDOWS-1251"?><font-size name="'+FS+'">'; For I1:=0 to 3 do Begin if Arr[I1].FileName='' then Continue; F:=TFileStream.Create(Arr[I1].FileName,fmOpenRead); F.Read(FntHead,SizeOf(FntHead)); F.Seek(FntHead.WidthsShift,soFromBeginning); F.Read(D[0],255); F.Free; fillchar(LengthCounts,SizeOf(LengthCounts),#0); For I:=32 to 255 do LengthCounts[D[I-32]]:=LengthCounts[D[I-32]]+1; MaxWidths.Count:=0; For I:=0 to 255 do If LengthCounts[I]>MaxWidths.Count then Begin MaxWidths.Count:=LengthCounts[I]; MaxWidths.CharWidth:=I; end; OutDat:=OutDat+'<'+Arr[I1].FontWrite+' default-width="'+IntToStr(MaxWidths.CharWidth)+'">'; For I:=32 to 255 do If (MaxWidths.CharWidth<>D[I-32]) then OutDat:=OutDat+'<c c="'+GetChar(I)+'">'+IntToStr(D[I-32])+'</c>'#10; // OutDat:=OutDat+'<c c="&#'+IntToStr(I)+';">'+IntToStr(D[I-32])+'</c>'#10; OutDat:=OutDat+'</'+Arr[I1].FontWrite+'>'; end; OutDat:=OutDat+'</font-size>'; If not SaveDialog1.Execute then Exit; AssignFile(T,SaveDialog1.FileName); Rewrite(T); WriteLn(T,OutDat); CloseFile(T); end; procedure TForm1.Button1Click(Sender: TObject); begin MessageBox(handle,'Grib''s RBF->REG v1.0. Allows to use custom Rocket fonts in ClearTXT.'#13'Creates REG file from RBF. For more info go to '#13+ 'http://www.df.ru/~grib'#13'or e-mail my: grib@df.ru','Info: About program',MB_ICONINFORMATION or mb_OK); end; procedure TForm1.Button3Click(Sender: TObject); begin if OpenDialog1.Execute then Edit3.Text:=OpenDialog1.FileName end; procedure TForm1.Button4Click(Sender: TObject); begin if OpenDialog1.Execute then Edit2.Text:=OpenDialog1.FileName end; procedure TForm1.Button5Click(Sender: TObject); begin if OpenDialog1.Execute then Edit4.Text:=OpenDialog1.FileName end; procedure TForm1.Button6Click(Sender: TObject); begin if OpenDialog1.Execute then Edit5.Text:=OpenDialog1.FileName end; end. { 0 - разрыв страницы 1-32 вообще не отображаются прямо 33-126 Полное сответствие Win 127 Пусто }
unit MFichas.Model.Usuario.Funcoes.Validacao.ValidarUsuarioESenha; interface uses System.SysUtils, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Usuario.Interfaces; type TModelUsuarioFuncoesValidarUES = class(TInterfacedObject, iModelUsuarioFuncoesValidarUES) private [weak] FParent : iModelUsuario; FUsuario: String; FSenha : String; FConexao: iModelConexaoSQL; constructor Create(AParent: iModelUsuario); public destructor Destroy; override; class function New(AParent: iModelUsuario): iModelUsuarioFuncoesValidarUES; function NomeDoUsuario(AValue: String): iModelUsuarioFuncoesValidarUES; function Senha(AValue: String) : iModelUsuarioFuncoesValidarUES; function &End : iModelUsuarioFuncoes; end; implementation { TModelUsuarioFuncoesValidarUES } function TModelUsuarioFuncoesValidarUES.&End: iModelUsuarioFuncoes; const _SQL = ' SELECT * FROM USUARIO '; _WHERE = ' WHERE LOGIN = ''%s'' AND SENHA = ''%s'''; begin Result := FParent.Funcoes; FConexao.Query.Active := False; FConexao.Query.SQL.Text := ''; FConexao.Query.SQL.Text := _SQL + Format(_WHERE, [FUsuario, FSenha]); FConexao.Query.Active := True; if FConexao.Query.RecordCount = 0 then raise Exception.Create( 'A senha informada é inválida ou foi digitada incorretamente.' + sLineBreak + 'Verifique-a e tente novamente.' ); end; constructor TModelUsuarioFuncoesValidarUES.Create(AParent: iModelUsuario); begin FParent := AParent; FConexao := TModelConexaoFactory.New.ConexaoSQL; end; destructor TModelUsuarioFuncoesValidarUES.Destroy; begin inherited; end; class function TModelUsuarioFuncoesValidarUES.New(AParent: iModelUsuario): iModelUsuarioFuncoesValidarUES; begin Result := Self.Create(AParent); end; function TModelUsuarioFuncoesValidarUES.NomeDoUsuario( AValue: String): iModelUsuarioFuncoesValidarUES; begin Result := Self; if AValue.IsNullOrWhiteSpace(AValue) then raise Exception.Create( 'Por favor, selecione um usuário antes de prosseguir.' ); FUsuario := AValue.ToUpper; end; function TModelUsuarioFuncoesValidarUES.Senha( AValue: String): iModelUsuarioFuncoesValidarUES; begin Result := Self; if AValue.IsNullOrWhiteSpace(AValue) then raise Exception.Create( 'Por favor, digite uma senha antes de prosseguir.' ); FSenha := AValue; end; end.
unit uSurfEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MGR32_Image,Udda,SurfaceUtils, StdCtrls, Menus; type TFrmSurfEdit = class(TForm) View: TMPaintBox32; BtnRefresh: TButton; LblCoord: TLabel; LblColor: TLabel; MainMenu1: TMainMenu; Edit1: TMenuItem; Effect1: TMenuItem; Crop1: TMenuItem; ErodeBorder1: TMenuItem; op1: TMenuItem; Bottom1: TMenuItem; Left1: TMenuItem; Right1: TMenuItem; Resize1: TMenuItem; Blur1: TMenuItem; Sharpen1: TMenuItem; AutoLevels1: TMenuItem; LblColSel: TLabel; procedure FormResize(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnRefreshClick(Sender: TObject); procedure ViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Erode(Sender: TObject); procedure Crop1Click(Sender: TObject); procedure ViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private Sprite:TSprite; OrigSprite:PSprite; Procedure SetPixelP8(x,y:integer;Color:Byte); function GetPixelP8(x,y:integer):byte; Procedure SetPixelA8R8G8B8(x,y:integer;Color:cardinal); public procedure SetSprite(EditSprite:PSprite); Procedure ReFreshView; end; var FrmSurfEdit: TFrmSurfEdit; Pal:PPalette; SelectedColor:Cardinal; implementation uses globals; {$R *.dfm} Procedure TFrmSurfEdit.SetPixelP8(x,y:integer;Color:Byte); var Ptr:PByte; begin Ptr:=Sprite.Data; inc(Ptr,(y*Sprite.Width+x)); Ptr^:=Color; end; function TFrmSurfEdit.GetPixelP8(x,y:integer):byte; var Ptr:PByte; begin Ptr:=Sprite.Data; inc(Ptr,(y*Sprite.Width+x)); Result:=Ptr^; end; Procedure TFrmSurfEdit.SetPixelA8R8G8B8(x,y:integer;Color:cardinal); var Ptr:PCardinal; begin Ptr:=PCardinal(Sprite.Data); inc(Ptr,(y*Sprite.Width+x)); Ptr^:=Color; end; procedure TFrmSurfEdit.BtnRefreshClick(Sender: TObject); begin ReFreshView; end; procedure TFrmSurfEdit.FormResize(Sender: TObject); begin View.Height:=self.ClientHeight-64; View.Buffer.Height:=View.Height; ReFreshView; end; procedure TFrmSurfEdit.FormShow(Sender: TObject); begin ReFreshView; end; procedure TFrmSurfEdit.Crop1Click(Sender: TObject); var Data:pointer; begin // GetMem(Data,Sprite.DataSize); Move(Sprite.Data^,Data^,Sprite.DataSize); CutSpriteP8(@Sprite,Data); ReFreshView; end; procedure TFrmSurfEdit.Erode(Sender: TObject); var i:integer; TransCol:byte; begin if Sprite.SurfFormat=SurfFormat_P8 then begin Transcol:=0; if Sprite.Offset<> nil then TransCol:=Sprite.Offset^.TransCol; case (sender as TMenuItem).Tag of 0:begin //top for i:=0 to Sprite.Width-1 do SetPixelP8(i,0,TransCol); end; 1:begin //bottom for i:=0 to Sprite.Width-1 do SetPixelP8(i,Sprite.Height-1,TransCol); end; 2:begin //left for i:=0 to Sprite.Height-1 do SetPixelP8(0,i,TransCol); end; 3:begin //right for i:=0 to Sprite.Height-1 do SetPixelP8(Sprite.Width-1,i,TransCol); end; end; end; ReFreshView; end; procedure TFrmSurfEdit.ReFreshView; var i,j:longint; Ptr:PByte; Ptr32:PCardinal; begin View.Buffer.clear(0); case Sprite.SurfFormat of SurfFormat_P8: begin Ptr:=Sprite.Data; for j:=0 to Sprite.Height-1 do for i:=0 to Sprite.Width-1 do begin View.Buffer.PixelS[i,j]:=MakeColor32(Pal.Rgb[Ptr^].r,Pal.Rgb[Ptr^].g,Pal.Rgb[Ptr^].b); inc(Ptr); end; end; SurfFormat_A8R8G8B8: begin Ptr32:=PCardinal(Sprite.Data); for j:=0 to Sprite.Height-1 do for i:=0 to Sprite.Width-1 do begin View.Buffer.PixelS[i,j]:=Ptr32^; inc(Ptr32); end; end; end; View.Invalidate; end; procedure TFrmSurfEdit.SetSprite(EditSprite: PSprite); var data:pointer; begin if ((Sprite.SurfFormat<>SurfFormat_P8) and (Sprite.SurfFormat<>SurfFormat_A8R8G8B8)) then begin exit; end; //keep the original pointer OrigSprite:=EditSprite; //Make a local copy (data included) TODO Sprite:=EditSprite^; Data:=UncompressSprite(@Sprite); //that create a new pointer Sprite.Data:=Data; //crush the pointer Sprite.CompType:=Comp_NoComp; Sprite.DataSize:=Sprite.Width*Sprite.Height*GetFormatSize(Sprite.SurfFormat); if (Sprite.SurfFormat=SurfFormat_P8) then Pal:=Index.PalHash.SearchByName(Sprite.Offset.PaletteName); end; procedure TFrmSurfEdit.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:=true; if MessageBox(0,'Do you want to keep changes?','Warning !',MB_OKCANCEL)=mrOk then begin //recompress the sprite if OrigSprite.CompType=Comp_Zlib then begin CompressSpriteZlib(@Sprite); end; if OrigSprite.CompType=Comp_Lzma then begin CompressSpriteLzma(@Sprite); end; //crush the original sprite //free memory 1st FreeMem(OrigSprite^.Data); //dataCopy OrigSprite^:=Sprite; end; end; procedure TFrmSurfEdit.ViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (x<Sprite.Width) and (y<Sprite.Height) then begin if Sprite.SurfFormat=SurfFormat_P8 then begin if ssAlt in shift then begin SelectedColor:=GetPixelP8(x,y); LblColSel.Caption:='Selected Color : '+IntToStr(SelectedColor); end; if ssShift in Shift then SetPixelP8(x,y,SelectedColor); end; end; end; procedure TFrmSurfEdit.ViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var Color:Cardinal; begin LblCoord.Caption:='Mouse Pos : '+IntToStr(x)+ ':'+IntToStr(y); if x<Sprite.Width then if y<Sprite.Height then begin if (Sprite.SurfFormat=SurfFormat_P8) then begin LblColor.Caption:='Color : '+IntToStr(PByte(cardinal(Sprite.Data)+y*Sprite.Width+x)^); end else if (Sprite.SurfFormat=SurfFormat_A8R8G8B8)then begin Color:=PCardinal(cardinal(Sprite.Data)+y*(Sprite.Width*4)+(x*4))^; LblColor.Caption:='Color : A:'+IntToStr(Color shr 24) +' R:'+IntToStr((Color shr 16)and $ff) +' G:'+IntToStr((Color shr 8)and $ff) +' B:'+IntToStr((Color)and $ff); end; end; end; end.
unit ControllersBase; interface uses MVCFramework, CustomersServices, CustomersTDGU; type TBaseController = class abstract(TMVCController) strict private FDM: TCustomersTDG; FCustomersService: TCustomersService; function GetDataModule: TCustomersTDG; strict protected function GetCustomersService: TCustomersService; public destructor Destroy; override; end; implementation uses System.SysUtils; { TBaseController } destructor TBaseController.Destroy; begin FCustomersService.Free; FDM.Free; inherited; end; function TBaseController.GetCustomersService: TCustomersService; begin if not Assigned(FCustomersService) then FCustomersService := TCustomersService.Create(GetDataModule); Result := FCustomersService; end; function TBaseController.GetDataModule: TCustomersTDG; begin if not Assigned(FDM) then FDM := TCustomersTDG.Create(nil); Result := FDM; end; end.
unit popeye_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,ay_8910,rom_engine, misc_functions,pal_engine,sound_engine,qsnapshot; function iniciar_popeye:boolean; implementation const popeye_rom:array[0..3] of tipo_roms=( (n:'tpp2-c_f.7a';l:$2000;p:0;crc:$9af7c821),(n:'tpp2-c_f.7b';l:$2000;p:$2000;crc:$c3704958), (n:'tpp2-c_f.7c';l:$2000;p:$4000;crc:$5882ebf9),(n:'tpp2-c_f.7e';l:$2000;p:$6000;crc:$ef8649ca)); popeye_pal:array[0..3] of tipo_roms=( (n:'tpp2-c.4a';l:$20;p:0;crc:$375e1602),(n:'tpp2-c.3a';l:$20;p:$20;crc:$e950bea1), (n:'tpp2-c.5b';l:$100;p:$40;crc:$c5826883),(n:'tpp2-c.5a';l:$100;p:$140;crc:$c576afba)); popeye_char:tipo_roms=(n:'tpp2-v.5n';l:$1000;p:0;crc:$cca61ddd); popeye_sprites:array[0..3] of tipo_roms=( (n:'tpp2-v.1e';l:$2000;p:0;crc:$0f2cd853),(n:'tpp2-v.1f';l:$2000;p:$2000;crc:$888f3474), (n:'tpp2-v.1j';l:$2000;p:$4000;crc:$7e864668),(n:'tpp2-v.1k';l:$2000;p:$6000;crc:$49e1d170)); //Dip popeye_dip_a:array [0..2] of def_dip=( (mask:$f;name:'Coinage';number:9;dip:((dip_val:$8;dip_name:'6 Coin - 1 Credit'),(dip_val:$5;dip_name:'5 Coin - 1 Credit'),(dip_val:$9;dip_name:'4 Coin - 1 Credit'),(dip_val:$a;dip_name:'3 Coin - 1 Credit'),(dip_val:$d;dip_name:'2 Coin - 1 Credit'),(dip_val:$f;dip_name:'1 Coin - 1 Credit'),(dip_val:$e;dip_name:'1 Coin - 2 Credit'),(dip_val:$3;dip_name:'1 Coin - 3 Credit'),(dip_val:$0;dip_name:'Freeplay'),(),(),(),(),(),(),())), (mask:$60;name:'Copyright';number:3;dip:((dip_val:$40;dip_name:'Nintendo'),(dip_val:$20;dip_name:'Nintendo Co.,Ltd'),(dip_val:$60;dip_name:'Nintendo of America'),(),(),(),(),(),(),(),(),(),(),(),(),())),()); popeye_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'1 Live'),(dip_val:$2;dip_name:'2 Lives'),(dip_val:$1;dip_name:'3 Lives'),(dip_val:$0;dip_name:'4 Lives'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Difficulty';number:4;dip:((dip_val:$c;dip_name:'Easy'),(dip_val:$8;dip_name:'Medium'),(dip_val:$4;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$30;dip_name:'40000'),(dip_val:$20;dip_name:'60000'),(dip_val:$10;dip_name:'80000'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Demo Sounds';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var prot0,prot1,prot_shift,palette_bank,scroll_y,dswbit,field:byte; fondo_write:array[0..$1fff] of boolean; scroll_x:word; nmi_enabled:boolean; procedure update_video_popeye; var f,color,nchar,x,y:word; i,atrib,atrib2:byte; punto:array[0..7] of word; begin if scroll_y=0 then fill_full_screen(3,0) else begin //Fondo con scroll (lo escribe directo) for f:=0 to $1fff do begin if fondo_write[f] then begin x:=8*(f mod 64); y:=4*(f div 64); for i:=0 to 7 do punto[i]:=paleta[memoria[f+$c000] and $0f]; for i:=0 to 3 do putpixel(x,y+i,8,@punto[0],1); fondo_write[f]:=false; end; end; scroll_x_y(1,3,199-scroll_x,2*scroll_y); end; //Sprites for f:=0 to $9e do begin atrib:=memoria[$8c07+(f*4)]; atrib2:=memoria[$8c06+(f*4)]; nchar:=((atrib2 and $7f)+((atrib and $10) shl 3)+((atrib and $04) shl 6)) xor $1ff; color:=((atrib and $7)+(palette_bank and $07) shl 3) shl 2; put_gfx_sprite(nchar,color+48,(atrib2 and $80)<>0,(atrib and $08)<>0,1); x:=(memoria[$8c04+(f*4)] shl 1)-8; y:=(256-memoria[$8c05+(f*4)]) shl 1; actualiza_gfx_sprite(x,y,3,1); end; //Chars for f:=$0 to $3ff do begin if gfx[0].buffer[f] then begin x:=f mod 32; y:=f div 32; nchar:=memoria[$a000+f]; color:=((memoria[$a400+f]) and $f) shl 1; put_gfx_trans(x*16,y*16,nchar,color+16,2,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,512,512,2,0,0,512,512,3); actualiza_trozo_final(0,32,512,448,3); end; procedure eventos_popeye; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $Fb); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $F7); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); //P2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $Fb); if arcade_input.down[1] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $F7); if arcade_input.left[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.right[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); //SYSTEM if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $80) else marcade.in2:=(marcade.in2 and $7f); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.start[1] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); end; end; procedure popeye_principal; var frame:single; f:word; begin init_controls(false,false,false,true); frame:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 511 do begin z80_0.run(frame); frame:=frame+z80_0.tframes-z80_0.contador; if f=479 then begin update_video_popeye; if nmi_enabled then z80_0.change_nmi(ASSERT_LINE); field:=field xor $10; end; end; eventos_popeye; video_sync; end; end; function popeye_getbyte(direccion:word):byte; begin case direccion of $0000..$8bff,$8c04..$8fff,$a000..$a7ff,$c000..$dfff:popeye_getbyte:=memoria[direccion]; $8c00:popeye_getbyte:=scroll_x and $ff; $8c01:popeye_getbyte:=scroll_y; $8c02:popeye_getbyte:=scroll_x shr 8; $8c03:popeye_getbyte:=palette_bank; $e000:popeye_getbyte:=((prot1 shl prot_shift) or (prot0 shr (8-prot_shift))) and $ff; $e001:popeye_getbyte:=0; end; end; procedure popeye_putbyte(direccion:word;valor:byte); procedure cambiar_paleta(valor:byte); var f,ctemp1,ctemp2,ctemp3,ctemp4:byte; colores:tcolor; begin for f:=0 to 15 do begin ctemp4:=buffer_paleta[f+$10*valor]; // red component */ ctemp1:=(ctemp4 shr 0) and $01; ctemp2:=(ctemp4 shr 1) and $01; ctemp3:=(ctemp4 shr 2) and $01; colores.r:=$1c*ctemp1+$31*ctemp2+$47*ctemp3; // green component */ ctemp1:=(ctemp4 shr 3) and $01; ctemp2:=(ctemp4 shr 4) and $01; ctemp3:=(ctemp4 shr 5) and $01; colores.g:=$1c*ctemp1+$31*ctemp2+$47*ctemp3; // blue component */ ctemp1:=(ctemp4 shr 6) and $01; ctemp2:=(ctemp4 shr 7) and $01; colores.b:=$31*ctemp1+$47*ctemp2; set_pal_color(colores,f); end; fillchar(fondo_write,$2000,1); end; begin case direccion of 0..$7fff:; $8000..$8bff,$8c04..$8fff:memoria[direccion]:=valor; $8c00:scroll_x:=(scroll_x and $ff00) or valor; $8c01:scroll_y:=valor; $8c02:scroll_x:=(scroll_x and $ff) or (valor shl 8); $8c03:if palette_bank<>valor then begin palette_bank:=valor; cambiar_paleta((valor shr 3) and 1); end; $a000..$a7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $c000..$dfff:if memoria[direccion]<>valor then begin fondo_write[direccion and $1fff]:=true; memoria[direccion]:=valor; end; $e000:prot_shift:=valor and $07; $e001:begin prot0:=prot1; prot1:=valor; end; end; end; function popeye_inbyte(puerto:word):byte; begin case (puerto and $ff) of 0:popeye_inbyte:=marcade.in0; 1:popeye_inbyte:=marcade.in1; 2:popeye_inbyte:=marcade.in2 or (field xor $10); 3:popeye_inbyte:=ay8910_0.read; end; end; procedure popeye_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:ay8910_0.control(valor); 1:ay8910_0.write(valor); end; end; procedure popeye_nmi_clear(estados_t:word); var main_z80_reg:npreg_z80; temp_nmi:boolean; begin main_z80_reg:=z80_0.get_internal_r; temp_nmi:=(main_z80_reg.i and 1)<>0; if nmi_enabled<>temp_nmi then begin nmi_enabled:=temp_nmi; if not(temp_nmi) then z80_0.change_nmi(CLEAR_LINE); end; end; function popeye_portar:byte; begin popeye_portar:=marcade.dswa or (marcade.dswb shl (7-dswbit)) and $80; end; procedure popeye_portbw(valor:byte); begin main_screen.flip_main_screen:=(valor and 1)<>0; dswbit:=(valor and $e) shr 1; //El bit que quiere leer end; procedure popeye_sound_update; begin ay8910_0.update; end; procedure popeye_qsave(nombre:string); var data:pbyte; size:word; buffer:array[0..7] of byte; begin open_qsnapshot_save('popeye'+nombre); getmem(data,200); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=ay8910_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$8000],$8000); //MISC buffer[0]:=prot0; buffer[1]:=prot1; buffer[2]:=prot_shift; buffer[3]:=palette_bank; buffer[4]:=scroll_y; buffer[5]:=dswbit; buffer[6]:=scroll_x and $ff; buffer[7]:=scroll_x shr 8; savedata_qsnapshot(@buffer,8); freemem(data); close_qsnapshot; end; procedure popeye_qload(nombre:string); var data:pbyte; buffer:array[0..7] of byte; begin if not(open_qsnapshot_load('popeye'+nombre)) then exit; getmem(data,200); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); ay8910_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$8000]); //MISC loaddata_qsnapshot(@buffer); prot0:=buffer[0]; prot1:=buffer[1]; prot_shift:=buffer[2]; palette_bank:=buffer[3]; scroll_y:=buffer[4]; dswbit:=buffer[5]; scroll_x:=buffer[6] or (buffer[7] shl 8); freemem(data); close_qsnapshot; fillchar(fondo_write,$2000,1); fillchar(gfx[0].buffer,$400,1); end; //Main procedure reset_popeye; begin z80_0.reset; ay8910_0.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; palette_bank:=0; prot0:=0; prot1:=0; prot_shift:=0; scroll_y:=0; dswbit:=0; scroll_x:=0; field:=0; fillchar(fondo_write[0],$2000,1); nmi_enabled:=true; end; function iniciar_popeye:boolean; var colores:tcolor; f,pos:word; ctemp1,ctemp2,ctemp3,ctemp4:byte; memoria_temp:array[0..$7fff] of byte; const ps_x:array[0..15] of dword=(7+($2000*8),6+($2000*8),5+($2000*8),4+($2000*8), 3+($2000*8),2+($2000*8),1+($2000*8),0+($2000*8),7,6,5,4,3,2,1,0); ps_y:array[0..15] of dword=(15*8, 14*8, 13*8, 12*8, 11*8, 10*8, 9*8, 8*8, 7*8, 6*8, 5*8, 4*8, 3*8, 2*8, 1*8, 0*8 ); pc_x:array[0..15] of dword=(7,7, 6,6, 5,5, 4,4, 3,3, 2,2, 1,1, 0,0); pc_y:array[0..15] of dword=(0*8,0*8, 1*8,1*8, 2*8,2*8, 3*8,3*8, 4*8,4*8, 5*8,5*8, 6*8,6*8, 7*8,7*8); begin llamadas_maquina.bucle_general:=popeye_principal; llamadas_maquina.reset:=reset_popeye; llamadas_maquina.save_qsnap:=popeye_qsave; llamadas_maquina.load_qsnap:=popeye_qload; iniciar_popeye:=false; iniciar_audio(false); screen_init(1,512,512); screen_mod_scroll(1,512,512,511,512,512,511); screen_init(2,512,512,true); screen_init(3,512,512,false,true); iniciar_video(512,448); //Main CPU z80_0:=cpu_z80.create(4000000,512); z80_0.change_ram_calls(popeye_getbyte,popeye_putbyte); z80_0.change_io_calls(popeye_inbyte,popeye_outbyte); z80_0.change_despues_instruccion(popeye_nmi_clear); z80_0.init_sound(popeye_sound_update); //Audio chips ay8910_0:=ay8910_chip.create(2000000,AY8910,1); ay8910_0.change_io_calls(popeye_portar,nil,nil,popeye_portbw); //cargar roms y decodificarlas if not(roms_load(@memoria_temp,popeye_rom)) then exit; for f:=0 to $7fff do begin pos:=bitswap16(f,15,14,13,12,11,10,8,7,6,3,9,5,4,2,1,0); memoria[f]:=bitswap8(memoria_temp[pos xor $3f],3,4,2,5,1,6,0,7); end; //convertir chars if not(roms_load(@memoria_temp,popeye_char)) then exit; init_gfx(0,16,16,256); gfx[0].trans[0]:=true; gfx_set_desc_data(1,0,8*8,0); convert_gfx(0,0,@memoria_temp[$800],@pc_x,@pc_y,false,false); //convertir sprites if not(roms_load(@memoria_temp,popeye_sprites)) then exit; init_gfx(1,16,16,512); gfx[1].trans[0]:=true; for f:=0 to 1 do begin gfx_set_desc_data(2,2,16*8,(0+f*$1000)*8,($4000+f*$1000)*8); convert_gfx(1,256*f*16*16,@memoria_temp[0],@ps_x[0],@ps_y[0],false,false); end; //poner la paleta chars if not(roms_load(@memoria_temp,popeye_pal)) then exit; for f:=0 to $23f do memoria_temp[f]:=memoria_temp[f] xor $ff; for f:=0 to $1f do buffer_paleta[f]:=memoria_temp[f]; for f:=0 to 15 do begin ctemp4:=f or ((f and 8) shl 1); // address bits 3 and 4 are tied together // red component ctemp1:=(memoria_temp[ctemp4+$20] shr 0) and $01; ctemp2:=(memoria_temp[ctemp4+$20] shr 1) and $01; ctemp3:=(memoria_temp[ctemp4+$20] shr 2) and $01; colores.r:=$21*ctemp1+$47*ctemp2+$97*ctemp3; // green component ctemp1:=(memoria_temp[ctemp4+$20] shr 3) and $01; ctemp2:=(memoria_temp[ctemp4+$20] shr 4) and $01; ctemp3:=(memoria_temp[ctemp4+$20] shr 5) and $01; colores.g:=$21*ctemp1+$47*ctemp2+$97*ctemp3; // blue component ctemp1:=0; ctemp2:=(memoria_temp[ctemp4+$20] shr 6) and $01; ctemp3:=(memoria_temp[ctemp4+$20] shr 7) and $01; colores.b:=$21*ctemp1+$47*ctemp2+$97*ctemp3; set_pal_color(colores,16+(2*f)+1); end; //Poner la paleta sprites for f:=0 to $ff do begin // red component ctemp1:=(memoria_temp[$40+f] shr 0) and $01; ctemp2:=(memoria_temp[$40+f] shr 1) and $01; ctemp3:=(memoria_temp[$40+f] shr 2) and $01; colores.r:=$21*ctemp1+$47*ctemp2+$97*ctemp3; // green component ctemp1:=(memoria_temp[$40+f] shr 3) and $01; ctemp2:=(memoria_temp[$140+f] shr 0) and $01; ctemp3:=(memoria_temp[$140+f] shr 1) and $01; colores.g:=$21*ctemp1+$47*ctemp2+$97*ctemp3; // blue component ctemp1:=0; ctemp2:=(memoria_temp[$140+f] shr 2) and $01; ctemp3:=(memoria_temp[$140+f] shr 3) and $01; colores.b:=$21*ctemp1+$47*ctemp2+$97*ctemp3; set_pal_color(colores,48+f); end; //DIP marcade.dswa:=$5f; marcade.dswb:=$3d; marcade.dswa_val:=@popeye_dip_a; marcade.dswb_val:=@popeye_dip_b; //final reset_popeye; iniciar_popeye:=true; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIDerExternal; {$I ..\Include\CryptoLib.inc} interface uses ClpIDerInteger, ClpIDerObjectIdentifier, ClpIProxiedInterface; type IDerExternal = interface(IAsn1Object) ['{9AC333C2-0F64-4A5F-BE0A-EBCC2A4E2A00}'] function GetDataValueDescriptor: IAsn1Object; function GetDirectReference: IDerObjectIdentifier; function GetEncoding: Int32; function GetExternalContent: IAsn1Object; function GetIndirectReference: IDerInteger; procedure SetDataValueDescriptor(const Value: IAsn1Object); procedure SetDirectReference(const Value: IDerObjectIdentifier); procedure SetEncoding(const Value: Int32); procedure SetExternalContent(const Value: IAsn1Object); procedure SetIndirectReference(const Value: IDerInteger); property dataValueDescriptor: IAsn1Object read GetDataValueDescriptor write SetDataValueDescriptor; property directReference: IDerObjectIdentifier read GetDirectReference write SetDirectReference; property encoding: Int32 read GetEncoding write SetEncoding; property ExternalContent: IAsn1Object read GetExternalContent write SetExternalContent; property indirectReference: IDerInteger read GetIndirectReference write SetIndirectReference; end; implementation end.
unit PipeOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,Misc,Math; type TFormPipeOptions = class(TForm) gbDDS: TGroupBox; BtnOk: TButton; BtnCancel: TButton; BtnApply: TButton; StaticText2: TStaticText; edWaveSpeed: TEdit; BtnCalcWaveSpeed: TButton; StaticText3: TStaticText; edDDSLineLen: TEdit; gbAlarm: TGroupBox; cbAlarmSingle: TCheckBox; cbAlarmNoSound: TCheckBox; cbAlarmNoData: TCheckBox; cbAlarmSpeaker: TCheckBox; cbAlarmMedia: TCheckBox; btnMediaFile: TButton; OpenDialog: TOpenDialog; procedure BtnOkClick(Sender: TObject); procedure BtnApplyClick(Sender: TObject); procedure BtnCalcWaveSpeedClick(Sender: TObject); procedure btnMediaFileClick(Sender: TObject); private { Private declarations } public { Public declarations } DDSLineLen:Integer; CalcWaveSpeed,WaveSpeed:Double; PipeLength:Double; function Validate:Boolean; function ValidateWaveSpeed:Boolean; end; var FormPipeOptions: TFormPipeOptions; implementation {$R *.DFM} { TFormPipeOptions } function TFormPipeOptions.Validate: Boolean; var AC:TWinControl; begin Result:=False; AC:=ActiveControl; try try DDSLineLen:=StrToInt(edDDSLineLen.Text); if DDSLineLen<2 then ErrorMsg('Длина ограничивающих линий должна быть не меньше 2 сек.'); except edDDSLineLen.SetFocus; raise; end; if not ValidateWaveSpeed then exit; except exit; end; ActiveControl:=AC; Result:=True; end; procedure TFormPipeOptions.BtnOkClick(Sender: TObject); begin if Validate then ModalResult:=mrOk; end; procedure TFormPipeOptions.BtnApplyClick(Sender: TObject); begin if Validate then ModalResult:=mrRetry; end; procedure TFormPipeOptions.BtnCalcWaveSpeedClick(Sender: TObject); begin edWaveSpeed.Text:=Format('%g',[CalcWaveSpeed]); end; function TFormPipeOptions.ValidateWaveSpeed: Boolean; begin try CheckMinMax(WaveSpeed,1,99999,edWaveSpeed); except Result:=False; exit; end; Result:=True; end; procedure TFormPipeOptions.btnMediaFileClick(Sender: TObject); begin if OpenDialog.Execute then begin btnMediaFile.Caption:=OpenDialog.FileName; cbAlarmMedia.Checked:=True; end; end; end.
unit FireBirdDBManager; interface uses Classes, iniFiles, DB, Variants, HashMap, DCL_intf, ADODB, StrUtils, SysUtils, DBManager, DBTables, QueryReader, Data.SqlExpr, uib, Uni, InterBaseUniProvider; type //-----------------------------------------------------------------+ // 클래스명: TFireBirdDBManager // 주요역할: FireBird DB를 제어할 때 쓰임. //-----------------------------------------------------------------+ TFireBirdDBManager = Class(TAbsEmbededDB) private FConnect: TUniConnection;//TUIBDataBase; //FTransact: TUIBTransaction; FQuery: TUniQuery;//TUIBQuery; FProvider: TInterbaseUniProvider; protected procedure DoInsertColumnNames(dataset: TDataSet); procedure Init; public Constructor Create(); overload; constructor Create(username, password: String); overload; Destructor Destroy(); override; procedure SetTableNames(); override; procedure SetColumnNames(); override; function ExecuteQuery(query: String): TDataSet; override; function ExecuteNonQuery(query: String): Integer; override; function Backup(backupPath: String): Boolean; override; function Open(): Boolean; override; function IsOpen(): Boolean; override; procedure Close(); override; function GetDBList(isFilter: Boolean): TStringList; override; function GetDBFileExt: String; override; function GetDBMSName: String; override; end; implementation uses Winapi.Windows, SimpleDS, uibdataset, uiblib, FMX.Forms, FileManager; { TFireBirdDBManager } //-----------------------------------------------------------------+ // 지정한 경로에 DB를 백업 한다. //-----------------------------------------------------------------+ function TFireBirdDBManager.Backup(backupPath: String): Boolean; begin result := DBFileCopy( DBFile, backupPath ); end; //-----------------------------------------------------------------+ // 열려진 DB를 닫는다. //-----------------------------------------------------------------+ procedure TFireBirdDBManager.Close; begin inherited; FConnect.Connected := false; FQuery.Close; end; constructor TFireBirdDBManager.Create(username, password: String); begin Init; FConnect.Username := username; FConnect.Password := password; end; //-----------------------------------------------------------------+ // 생성자. 내부 맴버를 생성하고 초기화 한다. //-----------------------------------------------------------------+ constructor TFireBirdDBManager.Create; begin Init; end; //-----------------------------------------------------------------+ // 소멸자. 현재 DB 관리자를 메모리에서 제거 한다. //-----------------------------------------------------------------+ destructor TFireBirdDBManager.Destroy; begin self.Close; FConnect.Free; FQuery.Close; FDataSource.Free; FProvider.Free; //FTransact.Free; end; procedure TFireBirdDBManager.DoInsertColumnNames(dataset: TDataSet); var enumerator: TStringsEnumerator; fieldTable, fieldCol: TField; List_Columns: TStringList; begin enumerator := FTableNames.GetEnumerator; while enumerator.MoveNext do begin List_Columns := TStringList.Create; while dataset.Eof = false do begin fieldTable := dataset.Fields.FieldByName( 'tname' ); fieldCol := dataset.Fields.FieldByName( 'cname' ); if enumerator.Current = fieldTable.Value then begin List_Columns.Add( fieldCol.Value ); end; dataset.Next; end; dataset.First; FColumnNames.PutValue( enumerator.Current , List_Columns); end; dataset.Free; end; //-----------------------------------------------------------------+ // Select문을 제외한 모든 쿼리문을 수행 한다. // 리턴값이 -1일 경우는 오류가 난 것이다. //-----------------------------------------------------------------+ function TFireBirdDBManager.ExecuteNonQuery(query: String): Integer; begin try FQuery.SQL.Clear; FQuery.SQL.Add( query ); FQuery.ExecSQL; result := 0; except on e: Exception do begin WriteErrorMessage( query + '::::' + e.Message ); result := -1; end; end; end; //-----------------------------------------------------------------+ // Select문과 같이 검색 결과가 있는 쿼리문을 수행 한다. //-----------------------------------------------------------------+ function TFireBirdDBManager.ExecuteQuery(query: String): TDataSet; var objQuery: TUniQuery;//TUIBDataSet; begin try objQuery := TUniQuery.Create( nil );//TUIBDataSet.Create( nil ); objQuery.Connection := FConnect; //objQuery.Transaction := FTransact; //query := StringReplace( query, '|', '#124', [ rfReplaceAll ] ); objQuery.SQL.Add( query ); objQuery.Execute; result := objQuery except on e: Exception do begin WriteErrorMessage( query + '::::' + e.Message ); result := nil; end; end; end; function TFireBirdDBManager.GetDBFileExt: String; begin result := '.fdb'; end; //-----------------------------------------------------------------+ // 현재 등록된 모든 Database의 이름들을 얻는다. //-----------------------------------------------------------------+ function TFireBirdDBManager.GetDBList(isFilter: Boolean): TStringList; var sQuery: String; sList: TStringList; field: TField; data: TDataSet; iEndOfList: Integer; recFiles: TSearchRec; begin sList := TStringList.Create; iEndOfList := FindFirst( DEFAULT_EMBEDED_DBPATH + '*' + GetDBFileExt, faAnyFile, recFiles ); while iEndOfList = 0 do begin sList.Add( recFiles.Name ) end; result := sList; end; function TFireBirdDBManager.GetDBMSName: String; begin result := 'firebird'; end; //-----------------------------------------------------------------+ // DB가 열린 상태인지 확인 한다. //-----------------------------------------------------------------+ procedure TFireBirdDBManager.Init; begin FConnStr := DEFAULT_MSSQL_CONN_STR; FConnect := TUniConnection.Create( nil );//TUIBDatabase.Create( nil ); //FTransact := TUIBTransaction.Create( nil ); FDataSource := TUniDataSource.Create( nil ); FQuery := TUniQuery.Create( nil );//TUIBQuery.Create( nil ); FProvider := TInterBaseUniProvider.Create( nil ); FConnect.ProviderName := 'InterBase'; FConnect.Database := 'd:\theson.fdb'; FConnect.SpecificOptions.Add( 'InterBase.ClientLibrary=' + GetCurrentDir + '\fbembed.dll' ); FConnect.SpecificOptions.Add( 'InterBase.CodePage=UTF8' ); // FConnect.SpecificOptions.Add( 'InterBase.Charset=WIN1251' ); // FConnect.SpecificOptions.Add( 'InterBase.UseUnicode=WIN1251' ); //FConnect.//DatabaseName := 'd:\theson.fdb'; FConnect.UserName := 'INSIGHT'; FConnect.PassWord := 'insight'; //FConnect.CharacterSet := TCharacterSet.csWIN1251; //FTransact.DataBase := FConnect; FQuery.Connection := FConnect; //FQuery.Transaction := FTransact; FDataSource.DataSet := FQuery; end; function TFireBirdDBManager.IsOpen: Boolean; begin result := FConnect.Connected; end; //-----------------------------------------------------------------+ // DB를 연다. //-----------------------------------------------------------------+ function TFireBirdDBManager.Open: Boolean; begin try if ( FConnect.Database <> DBFile ) or ( FConnect.Connected = false ) then begin FConnect.Connected := false; FConnect.Database := DBFile; FConnect.Connected := true; end; result := true; except on e: Exception do WriteErrorMessage( e.Message ); end; result := false; end; //-----------------------------------------------------------------+ // DB내의 각 Table 이름별 열이름을 설정 한다. //-----------------------------------------------------------------+ procedure TFireBirdDBManager.SetColumnNames; var sQuery: String; enumerator: Classes.TStringsEnumerator; dataset: TDataSet; begin inherited; if FTableNames = nil then self.SetTableNames; if FColumnNames <> nil then FColumnNames.Clear; FColumnNames := TStrHashMap.Create; sQuery := 'select f.rdb$relation_name as tname, f.rdb$field_name as cname ' + 'from rdb$relation_fields f ' + 'join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name ' + 'and r.rdb$view_blr is null ' + 'and (r.rdb$system_flag is null or r.rdb$system_flag = 0) ' + 'order by 1, f.rdb$field_position;'; dataset := ExecuteQuery( sQuery ); DoInsertColumnNames( dataset ); end; //-----------------------------------------------------------------+ // DB내 모든 Table의 이름을 설정한다. //-----------------------------------------------------------------+ procedure TFireBirdDBManager.SetTableNames; var sQuery: String; sCompQuery: String; sTableName: String; field: TField; dataset: TDataSet; begin inherited; if FTableNames <> Nil then FTableNames.Free; FTableNames := TStringList.Create; sQuery := 'select rdb$relation_name as name from rdb$relations where rdb$flags IS NOT NULL;'; dataset := ExecuteQuery( sQuery ); field := dataset.Fields.FieldByName( 'name' ); while dataset.Eof = false do begin FTableNames.Add( field.Value ); dataset.Next; end; dataset.Free; end; end.
unit upd7759; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} sound_engine; const CLOCK_UPD=640000; FRAC_BITS=20; FRAC_ONE=(1 shl FRAC_BITS); FRAC_MASK=(FRAC_ONE-1); // chip states STATE_IDLE=0; STATE_DROP_DRQ=1; STATE_START=2; STATE_FIRST_REQ=3; STATE_LAST_SAMPLE=4; STATE_DUMMY1=5; STATE_ADDR_MSB=6; STATE_ADDR_LSB=7; STATE_DUMMY2=8; STATE_BLOCK_HEADER=9; STATE_NIBBLE_COUNT=10; STATE_NIBBLE_MSN=11; STATE_NIBBLE_LSN=12; upd7759_step:array[0..15,0..15] of integer=( ( 0, 0, 1, 2, 3, 5, 7, 10, 0, 0, -1, -2, -3, -5, -7, -10 ), ( 0, 1, 2, 3, 4, 6, 8, 13, 0, -1, -2, -3, -4, -6, -8, -13 ), ( 0, 1, 2, 4, 5, 7, 10, 15, 0, -1, -2, -4, -5, -7, -10, -15 ), ( 0, 1, 3, 4, 6, 9, 13, 19, 0, -1, -3, -4, -6, -9, -13, -19 ), ( 0, 2, 3, 5, 8, 11, 15, 23, 0, -2, -3, -5, -8, -11, -15, -23 ), ( 0, 2, 4, 7, 10, 14, 19, 29, 0, -2, -4, -7, -10, -14, -19, -29 ), ( 0, 3, 5, 8, 12, 16, 22, 33, 0, -3, -5, -8, -12, -16, -22, -33 ), ( 1, 4, 7, 10, 15, 20, 29, 43, -1, -4, -7, -10, -15, -20, -29, -43 ), ( 1, 4, 8, 13, 18, 25, 35, 53, -1, -4, -8, -13, -18, -25, -35, -53 ), ( 1, 6, 10, 16, 22, 31, 43, 64, -1, -6, -10, -16, -22, -31, -43, -64 ), ( 2, 7, 12, 19, 27, 37, 51, 76, -2, -7, -12, -19, -27, -37, -51, -76 ), ( 2, 9, 16, 24, 34, 46, 64, 96, -2, -9, -16, -24, -34, -46, -64, -96 ), ( 3, 11, 19, 29, 41, 57, 79, 117, -3, -11, -19, -29, -41, -57, -79, -117 ), ( 4, 13, 24, 36, 50, 69, 96, 143, -4, -13, -24, -36, -50, -69, -96, -143 ), ( 4, 16, 29, 44, 62, 85, 118, 175, -4, -16, -29, -44, -62, -85, -118, -175 ), ( 6, 20, 36, 54, 76, 104, 144, 214, -6, -20, -36, -54, -76, -104, -144, -214 )); upd7759_state_table:array[0..15] of integer=( -1, -1, 0, 0, 1, 2, 2, 3, -1, -1, 0, 0, 1, 2, 2, 3); type tcall_drq=procedure(drq:byte); upd7759_chip=class(snd_chip_class) constructor create(amp:single;slave:byte=1;call_drq:tcall_drq=nil); destructor free; public procedure update; procedure reset; function get_rom_addr:pbyte; procedure start_w(data:byte); procedure port_w(data:byte); procedure reset_w(data:byte); function busy_r:byte; private // internal clock to output sample rate mapping */ pos:dword; // current output sample position */ step:dword; // step value per output sample */ //attotime clock_period; /* clock period */ //emu_timer *timer; /* timer */ // I/O lines */ fifo_in:byte; // last data written to the sound chip */ reset_pin:byte; // current state of the RESET line */ start:byte; // current state of the START line */ drq:byte; // current state of the DRQ line */ // internal state machine */ state:byte; // current overall chip state */ clocks_left:integer; // number of clocks left in this state */ nibbles_left:word; // number of ADPCM nibbles left to process */ repeat_count:byte; // number of repeats remaining in current repeat block */ post_drq_state:shortint; // state we will be in after the DRQ line is dropped */ post_drq_clocks:integer; // clocks that will be left after the DRQ line is dropped */ req_sample:byte; // requested sample number */ last_sample:byte; // last sample number available */ block_header:byte; // header byte * sample_rate:byte; // number of UPD clocks per ADPCM nibble */ first_valid_header:byte; // did we get our first valid header yet? */ offset:dword; // current ROM offset */ repeat_offset:dword; // current ROM repeat offset */ start_delay:dword; // ADPCM processing */ adpcm_state:shortint; // ADPCM state index */ adpcm_data:byte; // current byte of ADPCM data */ sample:integer; // current sample value */ // ROM access rom:pbyte; // pointer to ROM data or NULL for slave mode */ resample_pos:single; resample_inc:single; drq_call:tcall_drq; procedure update_adpcm(data:integer); procedure advance_state; end; var upd7759_0:upd7759_chip; implementation constructor upd7759_chip.create(amp:single;slave:byte=1;call_drq:tcall_drq=nil); begin // compute the stepping rate based on the chip's clock speed self.step:=4*FRAC_ONE; // compute the ROM base or allocate a timer if slave=1 then getmem(self.rom,$20000); // set the DRQ callback */ self.drq_call:=call_drq; // assume /RESET and /START are both high self.reset_pin:=1; self.start:=1; self.resample_inc:=CLOCK_UPD/4/FREQ_BASE_AUDIO; // toggle the reset line to finish the reset self.tsample_num:=init_channel; self.amp:=amp; self.reset; end; destructor upd7759_chip.free; begin if self.rom<>nil then freemem(self.rom); self.rom:=nil; end; procedure upd7759_chip.reset; begin self.pos := 0; //self.fifo_in := 0; self.state := STATE_IDLE; self.clocks_left := 0; self.nibbles_left := 0; self.repeat_count := 0; self.post_drq_state := STATE_IDLE; self.post_drq_clocks := 0; self.req_sample := 0; self.last_sample := 0; self.block_header := 0; self.sample_rate := 0; self.first_valid_header:= 0; self.offset := 0; self.repeat_offset := 0; self.adpcm_state := 0; self.adpcm_data := 0; self.sample := 0; self.drq:=0; end; function upd7759_chip.get_rom_addr:pbyte; begin get_rom_addr:=self.rom; end; procedure upd7759_chip.update_adpcm(data:integer); begin // update the sample and the state */ self.sample:=self.sample+upd7759_step[self.adpcm_state,data]; self.adpcm_state:=self.adpcm_state+upd7759_state_table[data]; // clamp the state to 0..15 */ if (self.adpcm_state<0) then self.adpcm_state:=0 else if (self.adpcm_state>15) then self.adpcm_state:=15; end; procedure upd7759_chip.advance_state; var ptemp:pbyte; begin case self.state of // Idle state: we stick around here while there's nothing to do */ STATE_IDLE:self.clocks_left:=4; // drop DRQ state: update to the intended state */ STATE_DROP_DRQ:begin self.drq:=0; self.clocks_left:=self.post_drq_clocks; self.state:=self.post_drq_state; end; // Start state: we begin here as soon as a sample is triggered */ STATE_START:begin if self.rom<>nil then self.req_sample:=self.fifo_in else self.req_sample:=$10; { 35+ cycles after we get here, the /DRQ goes low * (first byte (number of samples in ROM) should be sent in response) * * (35 is the minimum number of cycles I found during heavy tests. * Depending on the state the self was in just before the /MD was set to 0 (reset, standby * or just-finished-playing-previous-sample) this number can range from 35 up to ~24000). * It also varies slightly from test to test, but not much - a few cycles at most.) } self.clocks_left:=70+self.start_delay; // 35 - breaks cotton */ self.state:=STATE_FIRST_REQ; end; // First request state: issue a request for the first byte */ // The expected response will be the index of the last sample */ STATE_FIRST_REQ:begin self.drq:=1; // 44 cycles later, we will latch this value and request another byte */ self.clocks_left:=44; self.state:=STATE_LAST_SAMPLE; end; // Last sample state: latch the last sample value and issue a request for the second byte */ // The second byte read will be just a dummy */ STATE_LAST_SAMPLE:begin if self.rom<>nil then self.last_sample:=self.rom^ else self.last_sample:=self.fifo_in; self.drq:= 1; // 28 cycles later, we will latch this value and request another byte */ self.clocks_left:=28; // 28 - breaks cotton */ if (self.req_sample>self.last_sample) then self.state:=STATE_IDLE else self.state:=STATE_DUMMY1; end; // First dummy state: ignore any data here and issue a request for the third byte */ // The expected response will be the MSB of the sample address */ STATE_DUMMY1:begin self.drq:=1; // 32 cycles later, we will latch this value and request another byte */ self.clocks_left:= 32; self.state:=STATE_ADDR_MSB; end; // Address MSB state: latch the MSB of the sample address and issue a request for the fourth byte */ // The expected response will be the LSB of the sample address */ STATE_ADDR_MSB:begin if self.rom<>nil then begin ptemp:=self.rom; inc(ptemp,self.req_sample*2+5); self.offset:=ptemp^ shl 9 //sample_offset_shift!!!!! end else self.offset:=self.fifo_in shl 9; self.drq:=1; // 44 cycles later, we will latch this value and request another byte */ self.clocks_left:=44; self.state:=STATE_ADDR_LSB; end; // Address LSB state: latch the LSB of the sample address and issue a request for the fifth byte */ // The expected response will be just a dummy */ STATE_ADDR_LSB:begin if self.rom<>nil then begin ptemp:=self.rom; inc(ptemp,self.req_sample*2+6); self.offset:=self.offset or (ptemp^ shl 1) end else self.offset:=self.offset or (self.fifo_in shl 1); self.drq:=1; // 36 cycles later, we will latch this value and request another byte */ self.clocks_left:=36; self.state:=STATE_DUMMY2; end; // Second dummy state: ignore any data here and issue a request for the the sixth byte */ // The expected response will be the first block header */ STATE_DUMMY2:begin self.offset:=self.offset+1; self.first_valid_header:=0; self.drq:=1; // 36?? cycles later, we will latch this value and request another byte */ self.clocks_left:=36; self.state:=STATE_BLOCK_HEADER; end; // Block header state: latch the header and issue a request for the first byte afterwards */ STATE_BLOCK_HEADER:begin // if we're in a repeat loop, reset the offset to the repeat point and decrement the count */ if (self.repeat_count<>0) then begin self.repeat_count:=self.repeat_count-1; self.offset:=self.repeat_offset; end; if self.rom<>nil then begin ptemp:=self.rom; inc(ptemp,self.offset and $1ffff); self.block_header:=ptemp^ end else self.block_header:=self.fifo_in; self.offset:=self.offset+1; self.drq:=1; // our next step depends on the top two bits */ case (self.block_header and $c0) of $00:begin // silence */ self.clocks_left:=1024*((self.block_header and $3f)+1); if ((self.block_header=0) and ((self.first_valid_header and 1)<>0)) then self.state:=STATE_IDLE else self.state:=STATE_BLOCK_HEADER; self.sample:=0; self.adpcm_state:=0; end; $40:begin // 256 nibbles */ self.sample_rate:=(self.block_header and $3f)+1; self.nibbles_left:= 256; self.clocks_left:=36; // just a guess */ self.state:=STATE_NIBBLE_MSN; end; $80:begin // n nibbles */ self.sample_rate:=(self.block_header and $3f)+1; self.clocks_left:=36; // just a guess */ self.state:=STATE_NIBBLE_COUNT; end; $c0:begin // repeat loop */ self.repeat_count:=(self.block_header and 7)+1; self.repeat_offset:=self.offset; self.clocks_left:=36; // just a guess */ self.state:=STATE_BLOCK_HEADER; end; end; // set a flag when we get the first non-zero header */ if (self.block_header<>0) then self.first_valid_header:=1; end; // Nibble count state: latch the number of nibbles to play and request another byte */ // The expected response will be the first data byte */ STATE_NIBBLE_COUNT:begin if (self.rom<>nil) then begin ptemp:=self.rom; inc(ptemp,self.offset and $1ffff); self.nibbles_left:=ptemp^+1 end else self.nibbles_left:=self.fifo_in+1; self.offset:=self.offset+1; self.drq:= 1; // 36?? cycles later, we will latch this value and request another byte */ self.clocks_left:=36; // just a guess */ self.state:=STATE_NIBBLE_MSN; end; // MSN state: latch the data for this pair of samples and request another byte */ // The expected response will be the next sample data or another header */ STATE_NIBBLE_MSN:begin if self.rom<>nil then begin ptemp:=self.rom; inc(ptemp,self.offset and $1ffff); self.adpcm_data:=ptemp^; end else self.adpcm_data:=self.fifo_in; self.offset:=self.offset+1; self.update_adpcm(self.adpcm_data shr 4); self.drq:=1; // we stay in this state until the time for this sample is complete */ self.clocks_left:=self.sample_rate*4; self.nibbles_left:=self.nibbles_left-1; if self.nibbles_left=0 then self.state:=STATE_BLOCK_HEADER else self.state:=STATE_NIBBLE_LSN; end; // LSN state: process the lower nibble */ STATE_NIBBLE_LSN:begin self.update_adpcm(self.adpcm_data and 15); // we stay in this state until the time for this sample is complete */ self.clocks_left:=self.sample_rate*4; self.nibbles_left:=self.nibbles_left-1; if (self.nibbles_left=0) then self.state:=STATE_BLOCK_HEADER else self.state:=STATE_NIBBLE_MSN; end; end; // if there's a DRQ, fudge the state */ if ((self.drq and 1)<>0) then begin self.post_drq_state:=self.state; self.post_drq_clocks:=self.clocks_left-21; self.state:=STATE_DROP_DRQ; self.clocks_left:=21; end; end; procedure upd7759_chip.reset_w(data:byte); var oldreset:byte; begin // update the reset value */ oldreset:=self.reset_pin; if (data<>0) then self.reset_pin:=1 else self.reset_pin:=0; // on the falling edge, reset everything */ if ((oldreset<>0) and ((not(self.reset_pin) and 1)<>0)) then self.reset; end; procedure upd7759_chip.start_w(data:byte); var oldstart:byte; begin // update the start value */ oldstart:=self.start; if (data<>0) then self.start:=1 else self.start:=0; // on the rising edge, if we're idle, start going, but not if we're held in reset */ if ((self.state=STATE_IDLE) and ((not(oldstart) and 1)<>0) and ((self.start and 1)<>0) and ((self.reset_pin and 1)<>0)) then begin self.state:=STATE_START; // for slave mode, start the timer going */ { if (chip->timer) timer_adjust_oneshot(chip->timer, attotime_zero, 0);} end; end; procedure upd7759_chip.port_w(data:byte); begin // update the FIFO value */ self.fifo_in:=data; end; function upd7759_chip.busy_r:byte; begin // return /BUSY */ if self.state=STATE_IDLE then busy_r:=1 else busy_r:=0; end; procedure upd7759_chip.update; var clocks_this_time,clocks_left:integer; step,pos:dword; out_:integer; num_samples,old_drq:byte; begin clocks_left:=self.clocks_left; step:=self.step; pos:=self.pos; out_:=0; self.resample_pos:=self.resample_pos+self.resample_inc; num_samples:=trunc(self.resample_pos); self.resample_pos:=self.resample_pos-num_samples; // loop until done */ if (self.state<>STATE_IDLE) then begin while (num_samples<>0) do begin // store the current sample */ out_:=self.sample shl 7; // advance by the number of clocks/output sample */ pos:=pos+step; // handle clocks, but only in standalone mode */ while (pos>=FRAC_ONE) do begin clocks_this_time:=pos shr FRAC_BITS; if (clocks_this_time>clocks_left) then clocks_this_time:=clocks_left; // clock once */ pos:=pos-(clocks_this_time*FRAC_ONE); clocks_left:=clocks_left-clocks_this_time; // if we're out of clocks, time to handle the next state */ if (clocks_left=0) then begin // advance one state; if we hit idle, bail */ old_drq:=self.drq; self.advance_state; if old_drq<>self.drq then begin if @self.drq_call<>nil then self.drq_call(self.drq); end; if (self.state=STATE_IDLE) then break; // reimport the variables that we cached */ clocks_left:=self.clocks_left; out_:=(out_+(self.sample*64)) div 2; end; end; num_samples:=num_samples-1; end; end; // flush the state back */ self.clocks_left:= clocks_left; self.pos:=pos; if out_>32767 then out_:=32767 else if out_<-32768 then out_:=-32768; tsample[self.tsample_num,sound_status.posicion_sonido]:=trunc(out_*self.amp); if sound_status.stereo then tsample[self.tsample_num,sound_status.posicion_sonido+1]:=trunc(out_*self.amp); end; end.
unit Settings; interface uses SettingsInterface, System.Classes, System.SysUtils; type TMessageThreadSettings = class(TComponent, IMessageThreadSettings) strict private function GetIntervals: TArray<Cardinal>; private FIntervals: TArray<Cardinal>; public property Intervals: TArray<Cardinal> read FIntervals write FIntervals; end; TLoggerSettings = class(TComponent, ILoggerSettings) strict private function GetDataLifeTime: Cardinal; function GetFileName: string; function GetTruncateFileInterval: Cardinal; private FDataLifeTime: Cardinal; FFileName: String; FTruncateFileInterval: Integer; public property DataLifeTime: Cardinal read FDataLifeTime write FDataLifeTime; property FileName: String read FFileName write FFileName; property TruncateFileInterval: Integer read FTruncateFileInterval write FTruncateFileInterval; end; TSettings = class(TComponent, ISettings) private FLogger: TLoggerSettings; FMessageThread: TMessageThreadSettings; function GetLogger: ILoggerSettings; function GetMessageThread: IMessageThreadSettings; procedure ParseJSON(const AJsonStr: string); public constructor Create(AOwner: TComponent; const AFileName: String); reintroduce; end; EJSONSettings = class(Exception) public constructor Create(const AField: String); end; implementation uses System.JSON, System.IOUtils, System.Generics.Collections, Validator; constructor TSettings.Create(AOwner: TComponent; const AFileName: String); var AData: string; begin inherited Create(AOwner); FLogger := TLoggerSettings.Create(Self); FMessageThread := TMessageThreadSettings.Create(Self); try AData := TFile.ReadAllText(AFileName) except raise Exception.CreateFmt('Error reading configuration from file %s', [AFileName]); end; ParseJSON(AData); end; function TSettings.GetLogger: ILoggerSettings; begin Result := FLogger; end; function TSettings.GetMessageThread: IMessageThreadSettings; begin Result := FMessageThread; end; procedure TSettings.ParseJSON(const AJsonStr: string); var ADataLifeTime: Cardinal; AFileName: String; AInterval: Cardinal; AIntervals: TList<Cardinal>; ATruncateFileInterval: Cardinal; I: Integer; JSON: TJSONObject; JSONArray: TJSONArray; JsonNestedObject: TJSONObject; JsonValue: TJSONValue; begin try JSON := TJSONObject.ParseJSONValue(AJsonStr) as TJSONObject; if JSON = nil then raise EAbort.Create(''); try if not JSON.TryGetValue<TJSONObject>('Logger', JsonNestedObject) then raise EJSONSettings.Create('Logger'); if not JsonNestedObject.TryGetValue<String>('FileName', AFileName) then raise EJSONSettings.Create('FileName'); ValidateFilename(AFileName); if not JsonNestedObject.TryGetValue<Cardinal>('DataLifeTimeMin', ADataLifeTime) then raise EJSONSettings.Create('DataLifeTimeMin'); if not JsonNestedObject.TryGetValue<Cardinal>('TruncateFileInterval', ATruncateFileInterval) then raise EJSONSettings.Create('TruncateFileInterval'); FLogger.FileName := AFileName; FLogger.DataLifeTime := ADataLifeTime; FLogger.TruncateFileInterval := ATruncateFileInterval; if not JSON.TryGetValue<TJSONObject>('MessageThread', JsonNestedObject) then raise EJSONSettings.Create('MessageThread'); if not JsonNestedObject.TryGetValue<TJSONArray>('Intervals', JSONArray) then raise EJSONSettings.Create('Intervals'); AIntervals := TList<Cardinal>.Create(); try for I := 0 to JSONArray.Count - 1 do begin if not JSONArray.Items[I].TryGetValue<Cardinal>(AInterval) then raise Exception.Create('Interval value is incorrect'); AIntervals.Add(AInterval); end; FMessageThread.Intervals := AIntervals.ToArray; finally FreeAndNil(AIntervals); end; finally FreeAndNil(JSON); end; except on E: Exception do raise Exception.Create('Error reading configuration.' + sLineBreak + E.Message); end; end; function TMessageThreadSettings.GetIntervals: TArray<Cardinal>; begin Result := FIntervals; end; function TLoggerSettings.GetDataLifeTime: Cardinal; begin Result := FDataLifeTime; end; function TLoggerSettings.GetFileName: string; begin Result := FFileName; end; function TLoggerSettings.GetTruncateFileInterval: Cardinal; begin Result := FTruncateFileInterval; end; constructor EJSONSettings.Create(const AField: String); begin inherited CreateFmt('%s value is undefined or invalid', [AField]); end; end.
unit DataModule; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, Data.FMTBcd, Data.DB, Data.SqlExpr, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.Dialogs; type TdmWKTeste = class(TDataModule) FDConnection1: TFDConnection; FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink; tblItensPedido: TFDMemTable; tblItensPedidocodigoProduto: TIntegerField; tblItensPedidodescricaoProduto: TStringField; tblItensPedidoquantidade: TFloatField; tblItensPedidovlrUnitario: TCurrencyField; tblItensPedidovlrTotal: TCurrencyField; qryAux: TFDQuery; qryLocProduto: TFDQuery; procedure tblItensPedidoBeforePost(DataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure tblItensPedidocodigoProdutoChange(Sender: TField); private { Private declarations } public { Public declarations } end; var dmWKTeste: TdmWKTeste; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TdmWKTeste.DataModuleCreate(Sender: TObject); begin try FDConnection1.Open(); tblItensPedido.Open; except on E: Exception do ShowMessage('Erro ao conectar ao banco de dados: ' + E.Message); end; end; procedure TdmWKTeste.DataModuleDestroy(Sender: TObject); begin tblItensPedido.Close; FDConnection1.Close; end; procedure TdmWKTeste.tblItensPedidoBeforePost(DataSet: TDataSet); begin tblItensPedido.FieldByName('vlrTotal').AsCurrency := tblItensPedido.FieldByName('quantidade').AsFloat * tblItensPedido.FieldByName('vlrUnitario').AsFloat; end; procedure TdmWKTeste.tblItensPedidocodigoProdutoChange(Sender: TField); begin if Sender.IsNull then Exit; qryLocProduto.ParamByName('codigo').AsInteger := Sender.AsInteger; tblItensPedido.FieldByName('descricaoProduto').AsString := ''; try qryLocProduto.Open(); if qryLocProduto.IsEmpty then begin ShowMessage('Produto não localizado'); Abort; end; tblItensPedido.FieldByName('descricaoProduto').AsString := qryLocProduto.FieldByName('descricao').AsString; finally qryLocProduto.Close; end; end; end.
unit DirectoryViewFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VirtualTrees, System.UITypes; type TGetImageIndexEvent = procedure(Source: string; SourceFileAttribute: Integer; var ImageIndex: Integer) of object; TNodeDblClickEvent = procedure(Source: string; SourceFileAttribute: Integer) of object; TGetFileExtEvent = procedure(Source: string; SourceFileAttribute: Integer; var CanAddToTree: Boolean) of object; TFrmDirectoryView = class(TFrame) VST: TVirtualStringTree; procedure VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); procedure VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); private FCurrentDirectory: string; FOnGetImageIndex: TGetImageIndexEvent; FOnNodeDblClick: TNodeDblClickEvent; FOnGetFileExt: TGetFileExtEvent; procedure SetDirectory(Value: string); function GetSelected(Index: Integer): string; function GetSelectedCount: Integer; function GetIsDirectory(Index: Integer): Boolean; procedure UpdateContent(ParentDirectory: string; ParentNode: PVirtualNode); protected procedure UpdateView; public property Directory: string read FCurrentDirectory write SetDirectory; property Selected[Index: Integer]: string read GetSelected; property SelectedIsDirectory[Index: Integer]: Boolean read GetIsDirectory; property SelectedCount: Integer read GetSelectedCount; property OnNodeDblClick: TNodeDblClickEvent read FOnNodeDblClick write FOnNodeDblClick; property OnGetFileExt: TGetFileExtEvent read FOnGetFileExt write FOnGetFileExt; property OnGetImageIndex: TGetImageIndexEvent read FOnGetImageIndex write FOnGetImageIndex; end; implementation {$R *.dfm} type PNodeData = ^TNodeData; TNodeData = record Value: string; Attrib: Integer; FullName: string; end; { TFrmDirectoryView } function TFrmDirectoryView.GetIsDirectory(Index: Integer): Boolean; var Node: PVirtualNode; NodeData: PNodeData; J: Integer; begin Result := False; J := 0; for Node in VST.Nodes do begin if VST.Selected[Node] then begin if (Index = J) then begin NodeData := VST.GetNodeData(Node); Exit(NodeData.Attrib and faDirectory = faDirectory); end; Inc(J); end; end; end; function TFrmDirectoryView.GetSelected(Index: Integer): string; var Node: PVirtualNode; NodeData: PNodeData; J: Integer; begin J := 0; for Node in VST.Nodes do begin if VST.Selected[Node] then begin if (Index = J) then begin NodeData := VST.GetNodeData(Node); Exit(NodeData.FullName); end; Inc(J); end; end; end; function TFrmDirectoryView.GetSelectedCount: Integer; begin Result := VST.SelectedCount; end; procedure TFrmDirectoryView.SetDirectory(Value: string); begin if not DirectoryExists(Value) then begin VST.Clear; Exit; end; {$WARNINGS OFF} Value := IncludeTrailingBackslash(Value); FCurrentDirectory := Value; UpdateView; {$WARNINGS ON} end; procedure TFrmDirectoryView.UpdateContent(ParentDirectory: string; ParentNode: PVirtualNode); var SR: TSearchRec; Node: PVirtualNode; Data: PNodeData; CanAdd: Boolean; begin if FindFirst(ParentDirectory + '*', faAnyFile, SR) = 0 then begin repeat if (SR.Name = '.') or (SR.Name = '..') then Continue; CanAdd := True; if Assigned(FOnGetFileExt) then FOnGetFileExt(ParentDirectory + SR.Name, SR.Attr, CanAdd); if not CanAdd then Continue; Node := VST.AddChild(ParentNode); Data := VST.GetNodeData(Node); Data.Attrib := SR.Attr; Data.Value := SR.Name; Data.FullName := ParentDirectory + SR.Name; if SR.Attr and faDirectory = faDirectory then begin Data.FullName := Data.FullName + '\'; UpdateContent(Data.FullName, Node); end; until FindNext(SR) <> 0; FindClose(SR); end; end; procedure TFrmDirectoryView.UpdateView; begin VST.Clear; UpdateContent(FCurrentDirectory, nil); end; procedure TFrmDirectoryView.VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PNodeData; begin Data := VST.GetNodeData(Node); Data.Value := ''; Data.Attrib := 0; Data.FullName := ''; end; procedure TFrmDirectoryView.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); var Data: PNodeData; begin Data := Sender.GetNodeData(Node); if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Data.Value, Data.Attrib, Integer(ImageIndex)); end; procedure TFrmDirectoryView.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TNodeData); end; procedure TFrmDirectoryView.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var Data: PNodeData; begin Data := Sender.GetNodeData(Node); CellText := Data.Value; end; procedure TFrmDirectoryView.VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); var Data: PNodeData; begin Data := VST.GetNodeData(HitInfo.HitNode); if Assigned(FOnNodeDblClick) then begin VST.Expanded[HitInfo.HitNode] := not VST.Expanded[HitInfo.HitNode]; FOnNodeDblClick(Data.FullName, Data.Attrib); end; end; end.
{ CoreGraphics - CGShading.h * Copyright (c) 2001-2002 Apple Computer, Inc. * All rights reserved. } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGShading; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase,CGColorSpace,CGFunction,CGGeometry,CFBase; {$ALIGN POWER} type CGShadingRef = ^SInt32; { an opaque 32-bit type } {! @function CGShadingGetTypeID * Return the CFTypeID for CGShadingRefs. } function CGShadingGetTypeID: CFTypeID; external name '_CGShadingGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGShadingCreateAxial * * Create a shading defining a color blend which varies along a linear axis * between two endpoints and extends indefinitely perpendicular to that * axis. The shading may optionally extend beyond either endpoint by * continuing the boundary colors indefinitely. * * @param colorspace * The colorspace in which color values are expressed. * @param start * The starting point of the axis, in the shading's target coordinate space. * @param end * The ending point of the axis, in the shading's target coordinate space. * @param function * A 1-in, N-out function, where N is one more (for alpha) than the * number of color components in the shading's colorspace. The input * value 0 corresponds to the color at the starting point of the shading; * the input value 1 corresponds to the color at the ending point of the * shading. * @param extendStart * A boolean specifying whether to extend the shading beyond the starting * point of the axis. * @param extendEnd * A boolean specifying whether to extend the shading beyond the ending * point of the axis. } function CGShadingCreateAxial( colorspace: CGColorSpaceRef; start: CGPoint; finish: CGPoint; func: CGFunctionRef; extendStart: CBool; extendEnd: CBool ): CGShadingRef; external name '_CGShadingCreateAxial'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGShadingCreateRadial * * Create a shading defining a color blend which varies between two * circles. The shading may optionally extend beyond either circle by * continuing the boundary colors. * * @param colorspace * The colorspace in which color values are expressed. * @param start * The center of the starting circle, in the shading's target coordinate * space. * @param startRadius * The radius of the starting circle, in the shading's target coordinate * space. * @param end * The center of the ending circle, in the shading's target coordinate * space. * @param endRadius * The radius of the ending circle, in the shading's target coordinate * space. * @param function * A 1-in, N-out function, where N is one more (for alpha) than the * number of color components in the shading's colorspace. The input * value 0 corresponds to the color of the starting circle; the input * value 1 corresponds to the color of the ending circle. * @param extendStart * A boolean specifying whether to extend the shading beyond the starting * circle. * @param extendEnd * A boolean specifying whether to extend the shading beyond the ending * circle. } function CGShadingCreateRadial( colorspace: CGColorSpaceRef; start: CGPoint; startRadius: Float32; finish: CGPoint; endRadius: Float32; func: CGFunctionRef; extendStart: CBool; extendEnd: CBool ): CGShadingRef; external name '_CGShadingCreateRadial'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGShadingRetain * * Equivalent to <tt>CFRetain(shading)</tt>. } function CGShadingRetain( shading: CGShadingRef ): CGShadingRef; external name '_CGShadingRetain'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGShadingRelease * * Equivalent to <tt>CFRelease(shading)</tt>. } procedure CGShadingRelease( shading: CGShadingRef ); external name '_CGShadingRelease'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) end.
unit flower_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine,timer_engine,flower_audio; function iniciar_flower:boolean; implementation const flower_rom:tipo_roms=(n:'1.5j';l:$8000;p:0;crc:$a4c3af78); flower_rom2:tipo_roms=(n:'2.5f';l:$8000;p:0;crc:$7c7ee2d8); flower_rom_snd:tipo_roms=(n:'3.d9';l:$4000;p:0;crc:$8866c2b0); flower_char:tipo_roms=(n:'10.13e';l:$2000;p:0;crc:$62f9b28c); flower_tiles:array[0..3] of tipo_roms=( (n:'8.10e';l:$2000;p:0;crc:$f85eb20f),(n:'6.7e';l:$2000;p:$2000;crc:$3e97843f), (n:'9.12e';l:$2000;p:$4000;crc:$f1d9915e),(n:'15.9e';l:$2000;p:$6000;crc:$1cad9f72)); flower_sprites:array[0..3] of tipo_roms=( (n:'14.19e';l:$2000;p:0;crc:$11b491c5),(n:'13.17e';l:$2000;p:$2000;crc:$ea743986), (n:'12.16e';l:$2000;p:$4000;crc:$e3779f7f),(n:'11.14e';l:$2000;p:$6000;crc:$8801b34f)); flower_samples:tipo_roms=(n:'4.12a';l:$8000;p:0;crc:$851ed9fd); flower_vol:tipo_roms=(n:'5.16a';l:$4000;p:0;crc:$42fa2853); flower_prom:array[0..2] of tipo_roms=( (n:'82s129.k3';l:$100;p:0;crc:$5aab7b41),(n:'82s129.k2';l:$100;p:$100;crc:$ababb072), (n:'82s129.k1';l:$100;p:$200;crc:$d311ed0d)); //DIP flower_dipa:array [0..5] of def_dip=( (mask:$8;name:'Energy Decrease';number:2;dip:((dip_val:$8;dip_name:'Slow'),(dip_val:$0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Invulnerability';number:2;dip:((dip_val:$10;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Keep Weapons When Destroyed';number:2;dip:((dip_val:$20;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Difficulty';number:2;dip:((dip_val:$40;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Shot Range';number:2;dip:((dip_val:$80;dip_name:'Short'),(dip_val:$0;dip_name:'Long'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); flower_dipb:array [0..5] of def_dip=( (mask:$7;name:'Lives';number:8;dip:((dip_val:$7;dip_name:'1'),(dip_val:$6;dip_name:'2'),(dip_val:$5;dip_name:'3'),(dip_val:$4;dip_name:'4'),(dip_val:$3;dip_name:'5'),(dip_val:$6;dip_name:'2'),(dip_val:$1;dip_name:'7'),(dip_val:$0;dip_name:'Infinite'),(),(),(),(),(),(),(),())), (mask:$18;name:'Coinage';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$18;dip_name:'1C 1C'),(dip_val:$10;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$20;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Demo Sounds';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Bonus Life';number:2;dip:((dip_val:$80;dip_name:'30K 50K+'),(dip_val:$0;dip_name:'50K 80K+'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); CPU_SYNC=4; CPU_DIV=5; var sound_latch,scrollfg,scrollbg:byte; nmi_audio:boolean; procedure update_video_flower; var yoffs,xoffs,tile_offs,yi,xi,x_div,y_div,x_size,y_size,atrib,atrib2,atrib3,nchar,color,sx,sy:byte; ypixels,xpixels,f,offs,x,y:word; flipx,flipy:boolean; x_zoom,y_zoom:single; begin for x:=0 to 35 do begin for y:=0 to 27 do begin sx:=29-y; sy:=x-2; if (sy and $20)<>0 then offs:=sx+((sy and $1f) shl 5) else offs:=sy+(sx shl 5); if gfx[0].buffer[offs] then begin nchar:=memoria[$e000+offs]; color:=memoria[$e400+offs] and $fc; put_gfx_trans(x*8,(27-y)*8,nchar,color,1,0); gfx[0].buffer[offs]:=false; end; end; end; for f:=$0 to $ff do begin x:=f mod 16; y:=f div 16; if gfx[1].buffer[f] then begin nchar:=memoria[$f800+f]; color:=memoria[$f900+f] and $f0; put_gfx(((x*16)+16) and $ff,y*16,nchar,color,2,1); gfx[1].buffer[f]:=false; end; if gfx[1].buffer[f+$100] then begin nchar:=memoria[$f000+f]; color:=memoria[$f100+f] and $f0; put_gfx_trans(((x*16)+16) and $ff,y*16,nchar,color,3,1); gfx[1].buffer[f+$100]:=false; end; end; fill_full_screen(4,$400); scroll__y(2,4,scrollbg+16); scroll__y(3,4,scrollfg+16); //Sprites for f:=$3f downto 0 do begin atrib:=memoria[$de08+(f*8)+2]; atrib2:=memoria[$de08+(f*8)+1]; atrib3:=memoria[$de08+(f*8)+3]; nchar:=(atrib2 and $3f) or ((atrib and 1) shl 6) or ((atrib and 8) shl 4); color:=memoria[$de08+(f*8)+6]; x:=(memoria[$de08+(f*8)+4] or (memoria[$de08+(f*8)+5] shl 8))-39; y:=225-memoria[$de08+(f*8)+0]; flipy:=(atrib2 and $80)<>0; flipx:=(atrib2 and $40)<>0; y_size:=((atrib3 and $80) shr 7)+1; x_size:=((atrib3 and $08) shr 3)+1; if y_size=2 then y_div:=1 else y_div:=2; if x_size=2 then x_div:=1 else x_div:=2; y_zoom:=0.125*(((atrib3 and $70) shr 4)+1); x_zoom:=0.125*(((atrib3 and $07) shr 0)+1); ypixels:=trunc(y_zoom*16); xpixels:=trunc(x_zoom*16); if (y_size=2) then y:=y-16; for yi:=0 to (y_size-1) do begin yoffs:=(16-ypixels) div y_div; for xi:=0 to (x_size-1) do begin xoffs:=(16-xpixels) div x_div; if flipx then tile_offs:=(x_size-xi-1)*8 else tile_offs:=xi*8; if flipy then tile_offs:=tile_offs+(y_size-yi-1) else tile_offs:=tile_offs+yi; put_gfx_sprite_zoom(nchar+tile_offs,color,flipx,flipy,2,x_zoom,y_zoom); actualiza_gfx_sprite_zoom(x+xi*xpixels+xoffs,y+yi*ypixels+yoffs,4,2,x_zoom,y_zoom); end; end; end; actualiza_trozo(0,0,288,224,1,0,0,288,224,4); actualiza_trozo_final(0,0,288,224,4); end; procedure eventos_flower; begin if event.arcade then begin //p1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or 4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or 8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //p2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or 1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or 2); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or 4); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or 8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); //System if arcade_input.coin[0] then begin z80_0.change_nmi(PULSE_LINE); marcade.in2:=(marcade.in2 and $fe); end else begin marcade.in2:=(marcade.in2 or 1); end; if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or 2); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or 4); end; end; procedure flower_principal; var frame_m,frame_sub,frame_sound:single; f:word; h:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_sub:=z80_1.tframes; frame_sound:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin for h:=1 to CPU_SYNC do begin //Main CPU z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sub CPU z80_1.run(frame_sub); frame_sub:=frame_sub+z80_1.tframes-z80_1.contador; //Sound CPU z80_2.run(frame_sound); frame_sound:=frame_sound+z80_2.tframes-z80_2.contador; end; if f=239 then begin z80_0.change_irq(ASSERT_LINE); z80_1.change_irq(ASSERT_LINE); update_video_flower; end; end; eventos_flower; video_sync; end; end; function flower_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$dfff,$e000..$f1ff,$f800..$f9ff:flower_getbyte:=memoria[direccion]; $a100:flower_getbyte:=marcade.in0; $a101:flower_getbyte:=marcade.in1; $a102:flower_getbyte:=marcade.in2 or marcade.dswa; $a103:flower_getbyte:=marcade.dswb; $f200:flower_getbyte:=scrollfg; $fa00:flower_getbyte:=scrollbg; end; end; procedure flower_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; //ROM $c000..$dfff,$e800..$efff:memoria[direccion]:=valor; $a000..$a007:case (direccion and 7) of 0,5..7:; 1:main_screen.flip_main_screen:=(valor and 1)<>0; 2:if (valor and 1)=0 then z80_0.change_irq(CLEAR_LINE); 3:if (valor and 1)=0 then z80_1.change_irq(CLEAR_LINE); 4:; //Coin Counter end; $a400:begin sound_latch:=valor; if nmi_audio then z80_2.change_nmi(PULSE_LINE); end; $e000..$e7ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $f000..$f1ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[1].buffer[(direccion and $ff)+$100]:=true; end; $f200:scrollfg:=valor; $f800..$f9ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[1].buffer[direccion and $ff]:=true; end; $fa00:scrollbg:=valor; end; end; function flower_getbyte_sub(direccion:word):byte; begin case direccion of 0..$7fff:flower_getbyte_sub:=mem_misc[direccion]; else flower_getbyte_sub:=flower_getbyte(direccion); end; end; function snd_getbyte(direccion:word):byte; begin case direccion of 0..$3fff,$c000..$c7ff:snd_getbyte:=mem_snd[direccion]; $6000:snd_getbyte:=sound_latch; end; end; procedure snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $4001:nmi_audio:=(valor and 1)<>0; $8000..$803f:flower_0.write(direccion,valor); $a000..$a03f:flower_0.write(direccion or $40,valor); $c000..$c7ff:mem_snd[direccion]:=valor; end; end; procedure flower_snd_irq; begin z80_2.change_irq(HOLD_LINE); end; procedure flower_update_sound; begin flower_0.update; end; //Main procedure flower_reset; begin z80_0.reset; z80_1.reset; z80_2.reset; flower_0.reset; reset_audio; nmi_audio:=false; sound_latch:=0; scrollfg:=0; scrollbg:=0; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=7; end; function iniciar_flower:boolean; const pc_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 8*8*2+0,8*8*2+1,8*8*2+2, 8*8*2+3,8*8*2+8,8*8*2+9,8*8*2+10,8*8*2+11); pc_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*8*4+16*0, 8*8*4+16*1, 8*8*4+2*16, 8*8*4+3*16, 8*8*4+4*16, 8*8*4+5*16, 8*8*4+6*16, 8*8*4+7*16); var memoria_temp:array[0..$7fff] of byte; colores:tpaleta; f:word; begin llamadas_maquina.bucle_general:=flower_principal; llamadas_maquina.reset:=flower_reset; llamadas_maquina.fps_max:=60.6060606060606; iniciar_flower:=false; iniciar_audio(false); screen_init(1,288,224,true); screen_init(2,256,256); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,true); screen_mod_scroll(3,256,256,255,256,256,255); screen_init(4,512,256,false,true); iniciar_video(288,224); //Main CPU //Si pongo 3Mhz, a veces en la demo la nave muere, pero no se da cuenta y entra en un bucle sin fin y ya no responde a nada z80_0:=cpu_z80.create(18432000 div CPU_DIV,264*CPU_SYNC); z80_0.change_ram_calls(flower_getbyte,flower_putbyte); //Sub CPU z80_1:=cpu_z80.create(18432000 div CPU_DIV,264*CPU_SYNC); z80_1.change_ram_calls(flower_getbyte_sub,flower_putbyte); //Sound CPU z80_2:=cpu_z80.create(18432000 div CPU_DIV,264*CPU_SYNC); z80_2.change_ram_calls(snd_getbyte,snd_putbyte); z80_2.init_sound(flower_update_sound); timers.init(z80_2.numero_cpu,18432000/CPU_DIV/90,flower_snd_irq,nil,true); //Sound //cargar roms if not(roms_load(@memoria,flower_rom)) then exit; //cargar roms sub if not(roms_load(@mem_misc,flower_rom2)) then exit; //cargar roms sound if not(roms_load(@mem_snd,flower_rom_snd)) then exit; //Sound chip flower_0:=flower_chip.create(96000); if not(roms_load(@flower_0.sample_rom,flower_samples)) then exit; if not(roms_load(@flower_0.sample_vol,flower_vol)) then exit; //convertir chars if not(roms_load(@memoria_temp,flower_char)) then exit; for f:=0 to $1fff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(0,8,8,$200); gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,8*8*2,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //convertir tiles if not(roms_load(@memoria_temp,flower_tiles)) then exit; for f:=0 to $7fff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(1,16,16,$100); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,16*16*2,0,4,16*16*2*$100,16*16*2*$100+4); convert_gfx(1,0,@memoria_temp,@pc_x,@pc_y,false,false); //sprites if not(roms_load(@memoria_temp,flower_sprites)) then exit; for f:=0 to $7fff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(2,16,16,$100); gfx[2].trans[15]:=true; convert_gfx(2,0,@memoria_temp,@pc_x,@pc_y,false,false); //Pal if not(roms_load(@memoria_temp,flower_prom)) then exit; for f:=0 to $ff do begin colores[f].r:=pal4bit(memoria_temp[f]); colores[f].g:=pal4bit(memoria_temp[f+$100]); colores[f].b:=pal4bit(memoria_temp[f+$200]); end; set_pal(colores,$100); //DIP marcade.dswa:=$f8; marcade.dswa_val:=@flower_dipa; marcade.dswb:=$9d; marcade.dswb_val:=@flower_dipb; //final flower_reset; iniciar_flower:=true; end; end.
unit Utiles; interface uses Windows, Messages, SysUtils, Classes, Controls, Dialogs, Forms, IniFiles, DateUtils; // devuelve fechas de consulta de sistema // corresponde a ultima consulta hecha por usuario function GetFechaIni: TDatetime; function GetFechaFin: TDatetime; {: Returns a string with all occurrences of a given Character removed } function StripChar (const S: string; Ch: Char): string; {: Returns the substring consisting of the first N characters of S. If N > Length (S) then the substring = S. } function LeftStr (const S : string; const N : Integer): string; // establece fechas de consulta procedure SetFechas( fecIni, FecFin: TDateTime ); var fs: TformatSettings; DecimalSeparator: char; implementation var FIni: TIniFile; function GetFechaIni: TDatetime; begin FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'Conf\Config.Ini' ); try Result := FIni.ReadDateTime( 'FECHAS', 'FECINI', StartofTheMonth( date-25)); finally FIni.Free; end; end; function GetFechaFin: TDatetime; begin FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'Conf\Config.Ini' ); try Result := FIni.ReadDateTime( 'FECHAS', 'FECFIN', EndOfTheMonth(date-25)); finally FIni.Free; end; end; procedure SetFechas( FecIni, FecFin: TDateTime ); begin FIni := TIniFile.create( ExtractFilePath( Application.ExeName ) + 'Conf\Config.Ini' ); try FIni.WriteDateTime( 'FECHAS', 'FECINI', FecIni ); FIni.WriteDateTime( 'FECHAS', 'FECFIN', FecFin ); finally FIni.free; end; end; function StripChar (const S: string; Ch: Char): string; var P: Integer; begin Result := S; repeat P := Pos (Ch, Result); if P > 0 then Result := LeftStr (Result, P - 1) + Copy (Result, P + 1, Length (Result) - P); until P = 0; end; function LeftStr (const S : string; const N : Integer): string; begin Result := Copy (S, 1, N); end; initialization fs := Tformatsettings.Create; DecimalSeparator := fs.DecimalSeparator; end.
{$include lem_directives.inc} unit LemPiece; interface uses Classes, SysUtils, UTools; type // abstract ancestor for object, terrain and steel TPieceClass = class of TPiece; TPiece = class(TCollectionItem) private protected fLeft : Integer; fTop : Integer; public procedure Assign(Source: TPersistent); override; published property Left: Integer read fLeft write fLeft; property Top: Integer read fTop write fTop; end; type // basically ancestor for object and terrain TIdentifiedPiece = class(TPiece) private protected fIdentifier: Integer; public procedure Assign(Source: TPersistent); override; published property Identifier: Integer read fIdentifier write fIdentifier; end; type // basically ancestor for steel TSizedPiece = class(TPiece) private protected fHeight: Integer; fWidth: Integer; public procedure Assign(Source: TPersistent); override; published property Width: Integer read fWidth write fWidth; property Height: Integer read fHeight write fHeight; end; type TPieces = class(TCollectionEx) public constructor Create(aItemClass: TPieceClass); end; implementation { TPieces } constructor TPieces.Create(aItemClass: TPieceClass); begin inherited Create(aItemClass); end; { TPiece } procedure TPiece.Assign(Source: TPersistent); var P: TPiece absolute Source; begin if Source is TPiece then begin Left := P.Left; Top := P.Top; end else inherited Assign(Source); end; { TIdentifiedPiece } procedure TIdentifiedPiece.Assign(Source: TPersistent); var IP: TIdentifiedPiece absolute Source; begin if Source is TIdentifiedPiece then begin inherited Assign(Source); Identifier := IP.Identifier; end else inherited Assign(Source); end; { TSizedPiece } procedure TSizedPiece.Assign(Source: TPersistent); var SP: TSizedPiece absolute Source; begin if Source is TSizedPiece then begin inherited Assign(Source); Width := SP.Width; Height := SP.Height; end else inherited Assign(Source); end; end. (* definitions of: characters, pieces, objects, terrains, animations TDescriptor--------------------------------------------------------------------- TMetaPiece(TDescriptor)------------------------------------------------------- -width -height TMetaObject(TMetaPiece)----------------------------------------------------- -picture -data fetch info -animationcount -triggerarea -triggereffect -loop information -preview index -sound ---LoadFromStream ---SaveToStream TMetaTerrain(TMetaPiece)---------------------------------------------------- TSteelDescriptor------------------------------------------------------------ TMetaAnimationFrame----------------------------------------------------------- -deltax -deltay ---LoadFromStream ---SaveToStream TMetaAnimation---------------------------------------------------------------- -width -height -deltax -deltay -animationcount ---LoadFromStream ---SaveToStream TDescriptors ---LoadFromStream ---SaveToStream *)
{******************************************************************************* 作者: dmzn@163.com 2011-10-28 描述: 运行状态控制 *******************************************************************************} unit UFrameRunStatus; {$I link.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, StdCtrls, ExtCtrls; type TfFrameRunStatus = class(TfFrameBase) GroupBox1: TGroupBox; BtnTCP: TButton; BtnHttp: TButton; Label1: TLabel; Label2: TLabel; GroupBox2: TGroupBox; CheckAutoStart: TCheckBox; CheckAutoMin: TCheckBox; GroupBox3: TGroupBox; EditAdmin: TLabeledEdit; EditPwd: TLabeledEdit; BtnLogin: TButton; BtnSave: TButton; Timer1: TTimer; procedure BtnLoginClick(Sender: TObject); procedure BtnSaveClick(Sender: TObject); procedure CheckAutoStartClick(Sender: TObject); procedure BtnTCPClick(Sender: TObject); procedure BtnHttpClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } FNumber: Integer; procedure AdminChange(const nIsAdmin: Boolean); //初始化 public { Public declarations } procedure OnCreateFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses UMgrControl, USysConst, UROModule, ULibFun; const cNo = 0; cYes = 1; //------------------------------------------------------------------------------ class function TfFrameRunStatus.FrameID: integer; begin Result := cFI_FrameRunStatus; end; procedure TfFrameRunStatus.OnCreateFrame; begin BtnTCP.Tag := cNo; BtnHttp.Tag := cNo; BtnLogin.Tag := cNo; FNumber := 0; FVerCentered := True; CheckAutoStart.Checked := gSysParam.FAutoStart; CheckAutoMin.Checked := gSysParam.FAutoMin; AddAdminStatusChangeListener(AdminChange); AdminChange(False); {$IFDEF DEBUG} Timer1.Enabled := False; {$ELSE} Timer1.Enabled := CheckAutoMin.Checked; {$ENDIF} end; procedure TfFrameRunStatus.AdminChange(const nIsAdmin: Boolean); begin BtnTCP.Enabled := nIsAdmin; BtnHttp.Enabled := nIsAdmin; BtnSave.Enabled := nIsAdmin; if nIsAdmin then begin BtnLogin.Caption := '注销'; BtnLogin.Tag := cYes; end else begin BtnLogin.Caption := '登录'; BtnLogin.Tag := cNo; end; with ROModule.LockModuleStatus^ do try if FSrvTCP then begin BtnTCP.Caption := '停止TCP'; BtnTCP.Tag := cYes; end else begin BtnTCP.Caption := '启动TCP'; BtnTCP.Tag := cNo; end; if FSrvHttp then begin BtnHttp.Caption := '停止HTTP'; BtnHttp.Tag := cYes; end else begin BtnHttp.Caption := '启动HTTP'; BtnHttp.Tag := cNo; end; finally ROModule.ReleaseStatusLock; end; end; procedure TfFrameRunStatus.CheckAutoStartClick(Sender: TObject); begin if TWinControl(Sender).Focused then begin gSysParam.FAutoStart := CheckAutoStart.Checked; gSysParam.FAutoMin := CheckAutoMin.Checked; end; end; //Desc: 管理员登录 procedure TfFrameRunStatus.BtnLoginClick(Sender: TObject); begin if (EditAdmin.Text = gSysParam.FUserID) and (EditPwd.Text = gSysParam.FUserPwd) then begin if BtnLogin.Tag = cNo then BtnLogin.Tag := cYes else BtnLogin.Tag := cNo; AdminStatusChange(BtnLogin.Tag = cYes); end else ShowMsg('账户或密码错误', sHint); end; //Desc: 保存账户 procedure TfFrameRunStatus.BtnSaveClick(Sender: TObject); begin gSysParam.FUserID := Trim(EditAdmin.Text); gSysParam.FUserPwd := Trim(EditPwd.Text); ShowMessage('新账户已生效'); end; //Desc: 启动TCP procedure TfFrameRunStatus.BtnTCPClick(Sender: TObject); var nStr: string; begin ROModule.ActiveServer([stTcp], BtnTCP.Tag = cNo, nStr); if nStr <> '' then ShowDlg(nStr, sWarn); end; //Desc: 启动HTTP procedure TfFrameRunStatus.BtnHttpClick(Sender: TObject); var nStr: string; begin ROModule.ActiveServer([stHttp], BtnHttp.Tag = cNo, nStr); if nStr <> '' then ShowDlg(nStr, sWarn); end; //Desc: 自动启动服务 procedure TfFrameRunStatus.Timer1Timer(Sender: TObject); var nStr: string; begin Inc(FNumber); if FNumber = 2 then begin ROModule.ActiveServer([stTcp, stHttp], BtnTCP.Tag = cNo, nStr); if nStr <> '' then begin Timer1.Enabled := False; ShowDebugLog(nStr, True); end; end else if FNumber >= 3 then begin with ROModule.LockModuleStatus^ do try if FSrvTCP or FSrvHttp then begin Timer1.Enabled := False; PostMessage(Application.Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0); end; finally ROModule.ReleaseStatusLock; end; end; end; initialization gControlManager.RegCtrl(TfFrameRunStatus, TfFrameRunStatus.FrameID); end.
program ArrayHelpers; {$Mode delphi} uses SysUtils, Quick.Commons, Quick.Console, Quick.Arrays.Helper; var myarray : TStringArray; begin try myarray.Add('one'); myarray.Add('two'); myarray.Add('three'); coutFmt('count: %d',[myarray.Count],etInfo); if myarray.Contains('two') then cout('found "two" in array',etInfo) else cout('not found',etInfo); coutFmt('"three" in position %d',[myarray.IndexOf('three')],etInfo); TArrayHelper<string>.Add(myarray,'four'); cout('Press <Enter> to Exit',ccYellow); ConsoleWaitForEnterKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
unit tmsUXlsWorkbookGlobals; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsUXlsBaseRecords, tmsUXlsBaseRecordLists, tmsUXlsOtherRecords, tmsUXlsChart, tmsUXlsSST, tmsXlsMessages, tmsUXlsSections, tmsUXlsReferences, tmsUSheetNameList, tmsUXlsEscher, tmsUXlsFormula, tmsUEscherRecords, tmsUXlsPalette, tmsUXlsXF, tmsUFlxMessages, tmsUOle2Impl; type TBoundSheetList = class private FSheetNames: TSheetNameList; //Cache with all the sheet names to speed up searching FBoundSheets: TBoundSheetRecordList; public property BoundSheets: TBoundSheetRecordList read FBoundSheets; constructor Create; destructor Destroy; override; procedure Clear; procedure Add(const aRecord: TBoundSheetRecord); procedure SaveToStream(const DataStream: TOle2File); procedure SaveRangeToStream(const DataStream: TOle2File; const SheetIndex: integer); function TotalSize:int64; function TotalRangeSize(const SheetIndex: integer): int64; procedure InsertSheet(const BeforeSheet: integer; const OptionFlags: word; const SheetName: UTF16String); procedure DeleteSheet(const SheetIndex: integer); end; TWorkbookGlobals = class(TBaseSection) private FSST: TSST; FReferences: TReferences; FBoundSheets: TBoundSheetList; FMiscRecords: TBaseRecordList; FNames : TNameRecordList; FDrawingGroup: TDrawingGroup; FWindow1: TWindow1Record; F1904: T1904Record; FBookBool: TBookBoolRecord; FPrecision: TPrecisionRecord; FXF: TXFRecordList; FFonts: TFontRecordList; FFormats: TFormatRecordList; FPaletteCache: TPaletteRecord; FPaletteIndex: integer; FHasMacro: boolean; FIsXltTemplate: boolean; FCodeName: UTF16String; function GetSheetCount: integer; function GetSheetName(const index: integer): UTF16String; procedure SetSheetName(const index: integer; const Value: UTF16String); function GetSheetVisible(const index: integer): TXlsSheetVisible; procedure SetSheetVisible(const index: integer; const Value: TXlsSheetVisible); function GetSheetOptionFlags(const index: integer): word; function GetActivesheet: integer; procedure SetActiveSheet(const Value: integer); function GetColorPalette(Index: integer): LongWord; procedure SetColorPalette(Index: integer; const Value: LongWord); function GetIs1904: boolean; function GetPrecisionAsDisplayed: boolean; function GetSaveExternalLinkValues: boolean; procedure SetIs1904(const Value: boolean); procedure SetPrecisionAsDisplayed(const Value: boolean); procedure SetSaveExternalLinkValues(const Value: boolean); public property SST: TSST read FSST; property SheetName[const index: integer]: UTF16String read GetSheetName write SetSheetName; procedure SetFirstSheetVisible(const index: integer); property SheetVisible[const index: integer]: TXlsSheetVisible read GetSheetVisible write SetSheetVisible; property SheetCount: integer read GetSheetCount; property SheetOptionFlags[const index: integer]: word read GetSheetOptionFlags; procedure SheetSetOffset(const index: integer; const Offset: LongWord); property ActiveSheet: integer read GetActivesheet write SetActiveSheet; property DrawingGroup: TDrawingGroup read FDrawingGroup; property References: TReferences read FReferences; property Names: TNameRecordList read FNames; property HasMacro: boolean read FHasMacro; property CodeName: UTF16String read FCodeName; property IsXltTemplate: boolean read FIsXltTemplate write FIsXltTemplate; constructor Create; destructor Destroy; override; function TotalSize:int64; override; function TotalRangeSize(const SheetIndex: integer; const CellRange: TXlsCellRange): int64; override; procedure Clear; override; procedure LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TBOFRecord; const SST: TSST); override; procedure SaveToStream(const DataStream: TOle2File);override; procedure SaveRangeToStream(const DataStream: TOle2File; const SheetIndex: integer; const CellRange: TXlsCellRange);override; procedure InsertAndCopyRowsAndCols(const FirstRow, LastRow, DestRow, aRowCount, FirstCol, LastCol, DestCol, aColCount: integer; const SheetInfo: TSheetInfo); procedure DeleteRowsAndCols(const aRow, aRowCount, aCol, aColCount: word;const SheetInfo: TSheetInfo); procedure DeleteSheets(const SheetIndex, SheetCount: integer); procedure InsertSheets(const CopyFrom: integer; BeforeSheet: integer; const OptionFlags: word; const Name: UTF16String; const SheetCount: integer); property ColorPalette[Index: integer]: LongWord read GetColorPalette write SetColorPalette; property XF:TXFRecordList read FXF; property Fonts:TFontRecordList read FFonts; property Formats:TFormatRecordList read FFormats; property Is1904: boolean read GetIs1904 write SetIs1904; property PrecisionAsDisplayed: boolean read GetPrecisionAsDisplayed write SetPrecisionAsDisplayed; property SaveExternalLinkValues: boolean read GetSaveExternalLinkValues write SetSaveExternalLinkValues; procedure DeleteCountry; class function IsValidRangeName(const Name: UTF16String; var OptionFlags: Integer): Boolean; procedure CheckInternalNames(const OptionFlags: integer); procedure AddName(var Range: TXlsNamedRange; const CellList: pointer); function GetName(const sheet: Int32; const aName: UTF16String): TNameRecord; end; implementation { TBoundSheetList } procedure TBoundSheetList.Add(const aRecord: TBoundSheetRecord); begin FSheetNames.Add(aRecord.SheetName); FBoundSheets.Add(aRecord); //Last end; procedure TBoundSheetList.Clear; begin if FSheetNames<>nil then FSheetNames.Clear; if FBoundSheets<>nil then FBoundSheets.Clear; end; procedure TBoundSheetList.DeleteSheet(const SheetIndex: integer); begin FSheetNames.DeleteSheet(FBoundSheets.SheetName[SheetIndex]); FBoundSheets.Delete(SheetIndex); end; constructor TBoundSheetList.Create; begin inherited; FSheetNames:= TSheetNameList.Create; FBoundSheets:= TBoundSheetRecordList.Create; end; destructor TBoundSheetList.Destroy; begin FreeAndNil(FSheetNames); FreeAndNil(FBoundSheets); inherited; end; procedure TBoundSheetList.InsertSheet(const BeforeSheet: integer; const OptionFlags: word; const SheetName: UTF16String); var NewName: UTF16String; begin NewName:= FSheetNames.AddUniqueName(SheetName); FBoundSheets.Insert(BeforeSheet, TBoundSheetRecord.CreateNew(OptionFlags, NewName)); end; procedure TBoundSheetList.SaveRangeToStream(const DataStream: TOle2File; const SheetIndex: integer); begin if (SheetIndex>=FBoundSheets.Count)or (SheetIndex<0) then raise Exception.CreateFmt(ErrInvalidSheetNo, [SheetIndex,0,FBoundSheets.Count-1]); FBoundSheets[SheetIndex].SaveToStream(DataStream); end; procedure TBoundSheetList.SaveToStream(const DataStream: TOle2File); begin FBoundSheets.SaveToStream(DataStream); end; function TBoundSheetList.TotalSize: int64; begin TotalSize:= FBoundSheets.TotalSize; end; function TBoundSheetList.TotalRangeSize(const SheetIndex: integer): int64; begin if (SheetIndex>=FBoundSheets.Count)or (SheetIndex<0) then raise Exception.CreateFmt(ErrInvalidSheetNo, [SheetIndex,0,FBoundSheets.Count-1]); Result:=FBoundSheets[SheetIndex].TotalSize; end; { TWorkbookGlobals } procedure TWorkbookGlobals.Clear; begin inherited; if FSST<>nil then FSST.Clear; if FReferences<>nil then FReferences.Clear; if FBoundSheets<>nil then FBoundSheets.Clear; if FMiscRecords<>nil then FMiscRecords.Clear; if FNames<>nil then FNames.Clear; if FDrawingGroup<>nil then FDrawingGroup.Clear; if FXF<>nil then FXF.Clear; if FFonts<>nil then FFonts.Clear; if FFormats<>nil then FFormats.Clear; FPaletteCache:=nil; FWindow1:=nil; F1904:=nil; FBookBool:=nil; FPrecision:=nil; FHasMacro:=false; FIsXltTemplate:=false; FCodeName:=''; end; constructor TWorkbookGlobals.Create; begin inherited; FSST:= TSST.Create; FReferences:= TReferences.Create; FBoundSheets:= TBoundSheetList.Create; FMiscRecords:= TBaseRecordList.Create; FNames:=TNameRecordList.Create; FDrawingGroup:= TDrawingGroup.Create; FXF:= TXFRecordList.Create; FFonts:= TFontRecordList.Create; FFormats:= TFormatRecordList.Create; FPaletteCache:=nil; FWindow1:=nil; F1904:=nil; FBookBool:=nil; FPrecision:=nil; FHasMacro:=false; FIsXltTemplate:=false; FCodeName:=''; end; procedure TWorkbookGlobals.DeleteRowsAndCols(const aRow, aRowCount, aCol, aColCount: word; const SheetInfo: TSheetInfo); begin FNames.ArrangeInsertRowsAndCols(aRow, -aRowCount, aCol, -aColCount, SheetInfo); end; procedure TWorkbookGlobals.DeleteSheets(const SheetIndex, SheetCount: integer); var i: integer; begin if HasMacro then raise Exception.Create(ErrCantDeleteSheetWithMacros); //If we delete a sheet that has a corresponding macro on the vba stream, Excel 2000 will crash when opening the file. Excel Xp seems to handle this ok. for i:=0 to SheetCount-1 do FBoundSheets.DeleteSheet(SheetIndex); FReferences.InsertSheets(SheetIndex, -SheetCount); FNames.DeleteSheets(SheetIndex, SheetCount); end; destructor TWorkbookGlobals.Destroy; begin FreeAndNil(FSST); FreeAndNil(FReferences); FreeAndNil(FBoundSheets); FreeAndNil(FMiscRecords); FreeAndNil(FNames); FreeAndNil(FDrawingGroup); FreeAndNil(FXF); FreeAndNil(FFonts); FreeAndNil(FFormats); inherited; end; function TWorkbookGlobals.GetActivesheet: integer; begin if FWindow1<>nil then Result:= FWindow1.ActiveSheet else Result:=0; end; function TWorkbookGlobals.GetColorPalette(Index: integer): LongWord; begin if FPaletteCache=nil then Result:=StandardPalette(Index) else Result:=FPaletteCache.Color[Index]; end; function TWorkbookGlobals.GetIs1904: boolean; begin if F1904<>nil then Result:=F1904.Is1904 else Result:=false; end; function TWorkbookGlobals.GetPrecisionAsDisplayed: boolean; begin if FPrecision<>nil then Result:=FPrecision.PrecisionAsDisplayed else Result:=false; end; function TWorkbookGlobals.GetSaveExternalLinkValues: boolean; begin if FBookBool<>nil then Result:=FBookBool.SaveExternalLinkValues else Result:=false; end; function TWorkbookGlobals.GetSheetCount: integer; begin Result:= FBoundSheets.BoundSheets.Count; end; function TWorkbookGlobals.GetSheetName(const index: integer): UTF16String; begin Result:= FBoundSheets.BoundSheets.SheetName[index]; end; function TWorkbookGlobals.GetSheetOptionFlags(const index: integer): word; begin Result:= FBoundSheets.BoundSheets[index].OptionFlags; end; function TWorkbookGlobals.GetSheetVisible(const index: integer): TXlsSheetVisible; begin Result:= FBoundSheets.BoundSheets.SheetVisible[index]; end; procedure TWorkbookGlobals.InsertAndCopyRowsAndCols(const FirstRow, LastRow, DestRow, aRowCount, FirstCol, LastCol, DestCol, aColCount: integer; const SheetInfo: TSheetInfo); begin FNames.ArrangeInsertRowsAndCols(DestRow, (LastRow -FirstRow +1)* aRowCount, DestCol, (LastCol -FirstCol +1)* aColCount, SheetInfo); end; procedure TWorkbookGlobals.InsertSheets(const CopyFrom: integer; BeforeSheet: integer; const OptionFlags: word; const Name: UTF16String; const SheetCount: integer); var i, ofs: integer; SheetInfo: TSheetInfo; begin for i:=0 to SheetCount-1 do FBoundSheets.InsertSheet(BeforeSheet, OptionFlags, Name); FReferences.InsertSheets(BeforeSheet, SheetCount); SheetInfo.InsSheet:=-1; if CopyFrom>=BeforeSheet then ofs:=SheetCount else ofs:=0; SheetInfo.FormulaSheet:=CopyFrom + ofs; SheetInfo.GetSheet:= FReferences.GetSheet; SheetInfo.SetSheet:= FReferences.SetSheet; SheetInfo.Names:=nil; FNames.InsertSheets(CopyFrom, BeforeSheet, SheetCount, SheetInfo ); end; procedure TWorkbookGlobals.LoadFromStream(const DataStream: TOle2File; var RecordHeader: TRecordHeader; const First: TBOFRecord; const SST: TSST); var R: TBaseRecord; RecordId: integer; begin Clear; repeat RecordId := RecordHeader.Id; R:=LoadRecords(DataStream, RecordHeader); try if (R is TXFRecord) and (FXF.Count=0) then FMiscRecords.Add(TSubListRecord.CreateAndAssign(FXF)); if (R is TFontRecord) and (FFonts.Count=0) then FMiscRecords.Add(TSubListRecord.CreateAndAssign(FFonts)); if (R is TFormatRecord) and (FFormats.Count=0) then FMiscRecords.Add(TSubListRecord.CreateAndAssign(FFormats)); if (R is TPaletteRecord) then FPaletteCache:=(R as TPaletteRecord); if (R is TXFRecord) or (R is TStyleRecord) then FPaletteIndex:=FMiscRecords.Count; //After the last Style record if (R is TObProjRecord) then FHasMacro:=true; if (R is TCodeNameRecord) then FCodeName:=(R as TCodeNameRecord).SheetName; if (R is TBofRecord) then raise Exception.Create(ErrExcelInvalid) else if (R is TIgnoreRecord) then FreeAndNil(R) else if (R is TBoundSheetRecord) then FBoundSheets.Add(R as TBoundSheetRecord) else if (R is TNameRecord) then FNames.Add(R as TNameRecord) else if (R is TXFRecord) then FXF.Add(R as TXFRecord) else if (R is TFontRecord) then FFonts.Add(R as TFontRecord) else if (R is TFormatRecord) then FFormats.Add(R as TFormatRecord) else if (R is TEOFRecord) then sEOF:=(R as TEOFRecord) else if (R is TSSTRecord) then begin FSST.Load(R as TSSTRecord); FreeAndNil(R);end else if (R is TSupBookRecord) then FReferences.AddSupbook(R as TSupBookRecord) else if (R is TExternNameRecord) then begin; FReferences.AddExternName(R as TExternNameRecord);end else if (R is TExternSheetRecord) then begin; FReferences.AddExternRef(R as TExternSheetRecord); FreeAndNil(R);end else if (R is TDrawingGroupRecord) then FDrawingGroup.LoadFromStream(DataStream, RecordHeader, R as TDrawingGroupRecord) else if (R is TWindow1Record) then begin; FWindow1:=R as TWindow1Record; FMiscRecords.Add(R); end else if (R is T1904Record) then begin; F1904:=R as T1904Record; FMiscRecords.Add(R); end else if (R is TBookBoolRecord) then begin; FBookbool:=R as TBookBoolRecord; FMiscRecords.Add(R); end else if (R is TPrecisionRecord) then begin; FPrecision:=R as TPrecisionRecord; FMiscRecords.Add(R); end else if (R is TTemplateRecord) then begin; FreeAndNil(R); FIsXltTemplate:=true; end else FMiscRecords.Add(R); except FreeAndNil(R); Raise; end; //Finally until RecordId = xlr_EOF; sBOF:=First; //Last statement end; procedure TWorkbookGlobals.SaveRangeToStream(const DataStream: TOle2File; const SheetIndex: integer; const CellRange: TXlsCellRange); begin //Someday this can be optimized to only save texts on the range //But even Excel does not do it... if (sBOF=nil)or(sEOF=nil) then raise Exception.Create(ErrSectionNotLoaded); sBOF.SaveToStream(DataStream); if (FIsXltTemplate) then TTemplateRecord.SaveNewRecord(DataStream); FMiscRecords.SaveToStream(DataStream); //FXF, FFonts and FFormats are saved in FMiscRecords.SaveToStream; FBoundSheets.SaveRangeToStream(DataStream, SheetIndex); FReferences.SaveToStream(DataStream); FNames.SaveToStream(DataStream); //Should be after FBoundSheets.SaveToStream //Images are not saved to the clipboard by excel //FDrawingGroup.SaveToStream(DataStream); FSST.SaveToStream(DataStream); sEOF.SaveToStream(DataStream); end; procedure TWorkbookGlobals.SaveToStream(const DataStream: TOle2File); begin if (sBOF=nil)or(sEOF=nil) then raise Exception.Create(ErrSectionNotLoaded); sBOF.SaveToStream(DataStream); if (FIsXltTemplate) then TTemplateRecord.SaveNewRecord(DataStream); FMiscRecords.SaveToStream(DataStream); //FXF, FFonts and FFormats are saved in FMiscRecords.SaveToStream; FBoundSheets.SaveToStream(DataStream); FReferences.SaveToStream(DataStream); FNames.SaveToStream(DataStream); //Should be after FBoundSheets.SaveToStream FDrawingGroup.SaveToStream(DataStream); FSST.SaveToStream(DataStream); sEOF.SaveToStream(DataStream); end; procedure TWorkbookGlobals.SetActiveSheet(const Value: integer); begin if FWindow1<>nil then FWindow1.ActiveSheet:=Value; end; procedure TWorkbookGlobals.SetColorPalette(Index: integer; const Value: LongWord); begin if FPaletteCache=nil then begin //We have to create a standard palette first. FMiscRecords.Insert(FPaletteIndex, TPaletteRecord.CreateStandard); FPaletteCache:=FMiscRecords[FPaletteIndex] as TPaletteRecord; end; FPaletteCache.Color[Index]:= Value; end; procedure TWorkbookGlobals.SetFirstSheetVisible(const index: integer); begin if FWindow1<>nil then FWindow1.FirstSheetVisible:=index; end; procedure TWorkbookGlobals.SetIs1904(const Value: boolean); begin if F1904<>nil then F1904.Is1904:=value; end; procedure TWorkbookGlobals.SetPrecisionAsDisplayed(const Value: boolean); begin if FPrecision<>nil then FPrecision.PrecisionAsDisplayed:=value; end; procedure TWorkbookGlobals.SetSaveExternalLinkValues(const Value: boolean); begin if FBookBool<>nil then FBookBool.SaveExternalLinkValues:=value; end; procedure TWorkbookGlobals.SetSheetName(const index: integer; const Value: UTF16String); var RealName: UTF16String; begin RealName:=TSheetNameList.MakeValidSheetName(Value); FBoundSheets.FSheetNames.Rename(FBoundSheets.BoundSheets.SheetName[index], RealName); FBoundSheets.BoundSheets.SheetName[index]:=RealName; end; procedure TWorkbookGlobals.SetSheetVisible(const index: integer; const Value: TXlsSheetVisible); begin FBoundSheets.BoundSheets.SheetVisible[index]:=Value; end; procedure TWorkbookGlobals.SheetSetOffset(const index: integer; const Offset: LongWord); begin FBoundSheets.BoundSheets[index].SetOffset(Offset); end; function TWorkbookGlobals.TotalRangeSize(const SheetIndex: integer; const CellRange: TXlsCellRange): int64; begin Result:= inherited TotalRangeSize(SheetIndex, CellRange) + TTemplateRecord.GetSize(FIsXltTemplate) + FSST.TotalSize + FReferences.TotalSize + FBoundSheets.TotalRangeSize(SheetIndex) + FMiscRecords.TotalSize + FNames.TotalSize+ //Excel doesnt save images to the clipboard //FDrawingGroup.TotalSize+ //FXF.TotalSize, FFonts.TotalSize and FFormats.TotalSize are not included in FMiscRecords.TotalSize; FXF.TotalSize+ FFonts.TotalSize+ FFormats.TotalSize; end; function TWorkbookGlobals.TotalSize: int64; begin Result:= inherited TotalSize + TTemplateRecord.GetSize(FIsXltTemplate) + FSST.TotalSize + FReferences.TotalSize + FBoundSheets.TotalSize + FMiscRecords.TotalSize + FNames.TotalSize+ FDrawingGroup.TotalSize+ //FXF.TotalSize, FFonts.TotalSize and FFormats.TotalSize are not included in FMiscRecords.TotalSize; FXF.TotalSize+ FFonts.TotalSize+ FFormats.TotalSize; end; procedure TWorkbookGlobals.CheckInternalNames(const OptionFlags: Integer); begin //If a name is added and it is internal, we can't trust the ordering and need to delete the country record. if (OptionFlags and 32) <> 0 then DeleteCountry; end; function ContainsAny(const Name: UTF16String; const Chars: WideCharArray): boolean; var i, k: integer; begin for i:=1 to Length(Name) do begin for k:=0 to Length(Chars)-1 do begin if Name[i] = Chars[k] then begin Result:= true; exit; end; end; end; Result:= false; end; class function TWorkbookGlobals.IsValidRangeName(const Name: UTF16String; var OptionFlags: integer): Boolean; var InvalidChars: WideCharArray; i: integer; begin if ((Length(Name) < 1)) or (Length(Name) > 254) then begin Result := false; exit; end; if (Name = 'R') or (Name = 'r') then begin Result := false; exit; end; if (Length(Name) = 1) and (integer(Name[1 + 0]) <= 13) then //Internal name. begin OptionFlags:= OptionFlags or 32; begin Result := true; exit; end; end; SetLength (InvalidChars, (65 + 192) - 127); FillChar(InvalidChars[0], Length(InvalidChars) * 2, 0); for i := 0 to 64 do InvalidChars[i] := UTF16Char(i); InvalidChars[48] := '{'; InvalidChars[49] := '/'; InvalidChars[50] := '}'; InvalidChars[51] := '['; InvalidChars[52] := ']'; InvalidChars[53] := '~'; InvalidChars[54] := UTF16Char(160); InvalidChars[55] := '{'; InvalidChars[56] := '{'; InvalidChars[57] := '{'; InvalidChars[63] := '{'; for i := 127 to 191 do InvalidChars[(65 + i) - 127] := UTF16Char(i); InvalidChars[(65 + 181) - 127] := '{'; if ContainsAny(Name, InvalidChars) then begin Result := false; exit; end; if Name[1 + 0] < 'A' then begin Result := false; exit; end; //Check it is not a valid cell reference. if (ord((Name[1])) in [ord('A')..ord('Z'),ord('a')..ord('z')]) then begin if (Length(Name) < 2) then begin Result := true; exit; end; if (ord((Name[2])) in [ord('A')..ord('Z'),ord('a')..ord('z')]) then begin if (Length(Name) < 3) then begin Result := true; exit; end; for i:=3 to Length(Name) do if not(ord(Name[i]) in [ord('0')..ord('9')]) then begin Result := true; exit; end; end else begin if (Length(Name) < 2) then begin Result := true; exit; end; for i:=2 to Length(Name) do if not(ord(Name[i]) in [ord('0')..ord('9')]) then begin Result := true; exit; end; end; Result := false; exit; end; Result:= true; end; procedure TWorkbookGlobals.AddName(var Range: TXlsNamedRange; const CellList: pointer); var Options: Integer; ValidName: Boolean; i: integer; rSheet: integer; begin Options := Range.OptionFlags; ValidName := IsValidRangeName(Range.Name, Options); Range.OptionFlags := Options; for i := 0 to FNames.Count - 1 do begin rSheet := FNames[i].RangeSheet; if (rSheet = Range.NameSheetIndex) and (WideUpperCase98(FNames[i].Name) = WideUpperCase98(Range.Name)) then begin //no need to free the record, the collection will do it. FNames[i] := TNameRecord.CreateFromData(Range, Self, CellList); exit; end; end; if not ValidName then raise Exception.CreateFmt(ErrInvalidNameForARange, [Range.Name]); FNames.Add(TNameRecord.CreateFromData(Range, Self, CellList)); CheckInternalNames(Range.OptionFlags); end; function TWorkbookGlobals.GetName(const sheet: Int32; const aName: UTF16String): TNameRecord; var i: Int32; begin for i := FNames.Count - 1 downto 0 do begin if (FNames[i].RangeSheet = sheet) and (WideUpperCase98(FNames[i].Name) = WideUpperCase98(aName)) then begin Result := FNames[i]; exit; end; end; Result := nil; end; procedure TWorkbookGlobals.DeleteCountry; var i: integer; begin for i:= FMiscRecords.Count - 1 downto 0 do begin if TBaseRecord(FMiscRecords[i]).Id = xlr_Country then begin FMiscRecords.Delete(i); exit; end; end; end; end.
unit cparserexp; interface uses SysUtils, cparsertypes; type TIdentType = (itIdent, itIndex, itFuncCall, itField, itSubSel); TExpDir = ( // Expression Direction describes what relative fields should be initialzed // for the expression node. edValue // "none" - this should be a leaf of the expression graph , edPrefix // "right" , edPostfix // "left" for the host. "inner" is used for arrays and function calls // "left" ( "inner" ) , edInfix // "left" and "right" are mandatory. used for all binary operators! , edTernary // used for ? operator. "main", "left", "right" are used, "main" ? "left" : "right" , edSequence // used for , operator (and parameters). "left" and "right" are used ); TExp = class(TObject) left : TExp; right : TExp; main : TExp; inner : TExp; pr : Integer; op : string; val : string; dir : TExpDir; casttype : string; identtype : TIdentType; constructor Create(apr: Integer; const aop: string =''; adir: TExpDir = edInfix); end; const CIdentClose : array [TIdentType] of string = ('', ']',')', '', ''); CIdentOpen : array [TIdentType] of string = ('', '[','(', '.', '->'); function ParseCExprEx(p: TTextParser): TExp; function ValuatePreprocExp(exp: TExp; macros: TCMacroHandler): Integer; overload; function ValuatePreprocExp(const exp: string; macros: TCMacroHandler): Integer; overload; function isCTypeCast(exp: TExp; tinfo: TCTypeInfo): Boolean; implementation function isCTypeCast(exp: TExp; tinfo: TCTypeInfo): Boolean; var hasType: Boolean; begin Result:=false; while Assigned(exp) do begin if exp.dir = edPostfix then begin exp:=exp.left; end else if exp.dir = edPrefix then begin exp:=exp.right; end else if (exp.dir = edValue) then begin if isStdCType(exp.val) then hastype:=true else begin hasType:=Assigned(tinfo) and (tinfo.isType(exp.val)); if not hasType then Exit // an identify that's not a type end; exp:=nil; end else begin // nothing else os allowed in typecast Exit; end; end; Result:=hasType; end; function Rotate(core: TExp): TExp; begin if Assigned(core.right) and (core.right.dir<>edValue) and (core.right.pr>=core.pr) then begin Result:=core.right; core.right:=Result.left; Result.left:=core; // additional rotate Result.left:=Rotate(core); end else Result:=core; end; function isIdentSep(const t: string; var it: TIdentType): Boolean; begin Result:=true; if t='(' then it:=itFuncCall else if t = '[' then it:=itIndex else if t = '.' then it:=itField else if t = '->' then it:=itSubSel else Result:=false; end; function level2(p: TTextParser): TExp; var exp : TExp; res : Boolean; it : TIdentType; e : TExp; begin Result:=nil; if p.TokenType=tt_Numeric then begin exp := TExp.Create(2, '', edValue); exp.val:=p.Token; p.NextToken; Result:=exp; end else if p.TokenType=tt_Ident then begin exp := TExp.Create(2, '', edValue); exp.val:=p.Token; p.NextToken; res:=isIdentSep(p.Token, it); if res then begin e:=TExp.Create(2, p.Token, edPostfix); e.left:=exp; e.identtype:=it; exp:=e; p.NextToken; if it in [itField, itSubSel] then exp.right:=level2(p) else if it in [itFuncCall, itIndex] then begin exp.inner:=ParseCExprEx(p); if p.Token = CIdentClose[it] then p.NextToken else begin // error! end; end; end else if (p.Token='++') or (p.Token='--') then begin e:=TExp.Create(2, p.Token, edPostfix); e.left:=exp; exp:=e; p.NextToken; end; Result:=exp; end; end; function level3(p: TTextParser): TExp; var exp : TExp; ct : TExp; begin exp:=level2(p); if not Assigned(exp) then begin Result:=nil; // typecast if (p.Tokentype=tt_Symbol) and (p.Token='(') then begin p.NextToken; ct:=ParseCExprEx(p); if (p.TokenType=tt_Symbol) and (p.Token = ')') then p.NextToken; if not isCTypeCast(ct, p.CTypeInfo) then begin // not a typecast! ct.pr:=1; Result:=ct; end else begin Result:=TExp.Create(3, 'typecast', edInfix); Result.inner:=ct; Result.right:=ParseCExprEx(p); Result:=Rotate(REsult); end; end else if (p.Token='sizeof') or (p.Token='++') or (p.Token='--') or ((length(p.Token) = 1) and (p.Token[1] in ['&','*','~','!','-','+'])) then begin Result:=TExp.Create(3, p.Token, edPrefix); p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end end else Result:=exp; end; function level5(p: TTextParser): TExp; var e : TExp; begin e:=level3(p); if Assigned(e) then begin if (p.TokenType = tt_Symbol) and ( (length(p.Token)=1) and (p.Token[1] in ['*','/','%'])) then begin Result:=TExp.Create(5, p.Token, edInfix); p.NextToken; Result.left:=e; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level6(p: TTextParser): TExp; var e : TExp; begin e:=level5(p); if Assigned(e) then begin if (p.TokenType = tt_Symbol) and ( (length(p.Token)=1) and (p.Token[1] in ['+','-'])) then begin Result:=TExp.Create(6, p.Token, edInfix); p.NextToken; Result.left:=e; // a * b + c Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level7(p: TTextParser): TExp; var e : TExp; begin e:=level6(p); if Assigned(e) then begin if (p.TokenType = tt_Symbol) and ( (p.Token = '<<') or (p.Token='>>')) then begin Result:=TExp.Create(7, p.Token, edInfix); p.NextToken; Result.left:=e; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level8(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level7(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and ((tk='<') or (tk='<=') or (tk='>=') or (tk='>')) then begin Result:=TExp.Create(8, p.Token, edInfix); p.NextToken; Result.left:=e; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level9(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level8(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and ((tk='==') or (tk='!=')) then begin Result:=TExp.Create(9, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level10(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level9(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and (tk='&') then begin Result:=TExp.Create(10, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level11(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level10(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and (tk='^') then begin Result:=TExp.Create(11, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level12(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level11(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and (tk='|') then begin Result:=TExp.Create(12, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level13(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level12(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and (tk='&&') then begin Result:=TExp.Create(13, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level14(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level13(p); if Assigned(e) then begin tk:=p.Token; if (p.TokenType = tt_Symbol) and (tk='||') then begin Result:=TExp.Create(14, p.Token, edInfix); Result.left:=e; p.NextToken; Result.right:=ParseCExprEx(p); Result:=Rotate(Result); end else Result:=e; end else Result:=nil; end; function level15(p: TTextParser): TExp; var e : TExp; tk : string; begin e:=level14(p); if Assigned(e) then begin if p.Token='?' then begin p.NextToken; Result:=TExp.Create(15, '?', edTernary); Result.main:=e; Result.left:=ParseCExprEx(p); if p.Token = ':' then p.NextToken; Result.right:=ParseCExprEx(p); end else Result:=e; end else Result:=nil; end; function level16(p: TTextParser): TExp; var tk : string; e : TExp; begin e:=level15(p); if Assigned(e) then begin tk:=p.Token; if (tk='=') or (tk='+=') or (tk='-=') or (tk='*=') or (tk='/=') or (tk='%=') or (tk='<<=') or (tk='>>=') or (tk='&=') or (tk='^=') or (tk='|=') then begin Result:=TExp.Create(16, tk, edInfix); Result.right:=e; p.NextToken; Result.left:=ParseCExprEx(p); end else Result:=e; end else Result:=nil; end; function level17(p: TTextParser): TExp; var tk : string; e : TExp; begin Result:=level16(p); if Assigned(Result) and (p.TokenType=tt_Symbol) and (p.Token=',') then begin e:=Result; p.NextToken; Result:=TExp.Create(17, ',', edSequence); Result.left:=e; Result.right:=ParseCExprEx(p); end; end; function ParseCExprEx(p: TTextParser): TExp; begin Result:=level17(p); end; { TExp } constructor TExp.Create(apr: Integer; const aop: string; adir: TExpDir = edInfix); begin inherited Create; pr:=apr; op:=aop; dir:=adir; end; function PreProcVal(exp: TExp; m: TCMacroHandler): Integer; var code : Integer; l, r : Integer; lt : TExp; rt : TExp; nm : string; s : string; v : string; const IntRes : array [boolean] of integer = (0,1); begin Result:=0; if (exp.identtype = itFuncCall) and (exp.dir=edPostfix) then begin if Assigned(exp.left) and (exp.left.identtype=itIdent) then nm:=exp.left.val else nm:=''; if Assigned(exp.inner) and (exp.inner.identtype=itIdent) then s:=exp.inner.val else s:=''; if (nm='defined') and Assigned(m) then Result:=IntRes[ m.isMacroDefined(s)] else Result:=0; end else if exp.dir = edPrefix then begin r:=PreProcVal(exp.right, m); //writeln('koko! ', PtrUInt(exp.right)); if exp.op='!' then begin if r = 0 then Result:=1 else Result:=0; end; // it should be end else if exp.dir = edInfix then begin l:=PreProcVal(exp.left,m); r:=PreProcVal(exp.right,m); if exp.op = '+' then Result:=l+r else if exp.op = '-' then Result:=l-r else if exp.op = '/' then Result:=l div r else if exp.op = '%' then Result:=l mod r else if exp.op = '*' then Result:=l * r else if exp.op = '&' then Result:=l and r else if exp.op = '|' then Result:=l or r else if exp.op = '<<' then Result:=l shr r else if exp.op = '>>' then Result:=l shl r else if exp.op = '|' then Result:=l or r else if exp.op = '&' then Result:=l and r else if exp.op = '||' then Result:=IntRes[(l or r) > 0] else if exp.op = '&&' then Result:=IntRes[(l and r) > 0] else if exp.op = '==' then Result:=IntRes[l = r] else if exp.op = '!=' then Result:=IntRes[l <> r] else if exp.op = '>=' then Result:=IntRes[l >= r] else if exp.op = '<=' then Result:=IntRes[l <= r] else if exp.op = '>' then Result:=IntRes[l > r] else if exp.op = '<' then Result:=IntRes[l < r]; end else begin v:=trim(exp.val); if Assigned(m) and (m.isMacroDefined(v)) then v:=m.GetMacroReplaceStr(v); Val(v, Result, code); end; end; function ValuatePreprocExp(exp: TExp; macros: TCMacroHandler): Integer; begin Result:=PreProcVal(Exp, macros); end; function ValuatePreprocExp(const exp: string; macros: TCMacroHandler): Integer; var prs : TTextParser; expObj : TExp; begin prs := CreateCParser(exp, false); try //no macros are defined for pre-compiler, they would be used in evaluation instead! //prs.MacroHandler:=macros; if prs.NextToken then begin expObj:=ParseCExprEx(prs); if Assigned(expObj) then Result:=ValuatePreprocExp(expObj, macros) else Result:=0; end else Result:=0; finally prs.Free; end; end; end.
unit hcManager; {------------------------------------------------------------------------------} { Библиотека : Тестовый слой; } { Автор : Морозов М.А. } { Начат : 26.03.2006 16.48; } { Модуль : hcManager } { Описание : Для тестирования запросов на консультацию: } { - получение запроса на консультацию; } { - получение оценки консультации; } { - выдача ответа на консультацию; } {------------------------------------------------------------------------------} // $Id: hcManager.pas,v 1.17 2008/09/25 10:21:06 oman Exp $ // $Log: hcManager.pas,v $ // Revision 1.17 2008/09/25 10:21:06 oman // - new: Обрабатываем новый код ошибки (К-119473134) // // Revision 1.16 2008/06/26 07:54:37 mmorozov // - new: подпись консультации (CQ: OIT5-23252); // // Revision 1.15 2008/03/25 05:15:53 mmorozov // - new: модуль взаимодействия с библиотекой в динамическом варианте; // // Revision 1.14 2008/02/26 13:15:49 mmorozov // - new: реализация удаления запросов (CQ: OIT5-28426); // // Revision 1.13 2008/01/16 12:35:18 mmorozov // - работа с новым адаптером; // // Revision 1.12 2008/01/10 07:31:51 oman // Переход на новый адаптер // // Revision 1.11.4.1 2007/12/07 09:01:05 oman // Перепиливаем на новый адаптер // // Revision 1.11 2007/01/22 14:17:19 mmorozov // - MERGE WITH B_NEMESIS_6_4 (CQ: OIT5-24141); // // Revision 1.10.4.1 2007/01/22 13:49:56 mmorozov // - new: показ статусов выбранных консультаций (CQ: OIT5-24141); // // Revision 1.10 2006/10/06 11:40:35 mmorozov // - new: используем l3; // - new behaviour: ожидаем от dll-ли при запуске не только типизированных, но и не типизированных исключений, завершаем работу с сообщением если такое случилось; // // Revision 1.9 2006/08/10 06:40:31 dolgop // - bugfix: формирование запроса вручную; // // Revision 1.8 2006/08/07 08:50:47 mmorozov // - new: формирование запроса вручную (CQ: OIT500022171); // // Revision 1.7 2006/08/03 04:35:34 mmorozov // - new behaviour: IConsultingRequests получаем один раз, по первому требоавнию; // // Revision 1.6 2006/06/02 14:40:44 mmorozov // - new: загрузка DLL-ли по новому; // - new: обработка результов работы методов dll-ли; // // Revision 1.5 2006/06/02 10:44:50 migel // - change: перегенерация с новым шаблоном. // - fix: совместимость с новыми перегенеренными файлами. // // Revision 1.4 2006/04/04 07:59:12 mmorozov // - new: использование фабрики потока + в случае успешного получения данных завершаем вызовом DataReceived; // // Revision 1.3 2006/04/03 14:05:30 mmorozov // - new: вычитывание оценки; // // Revision 1.2 2006/04/03 10:49:25 mmorozov // - new: выделена функция tstFileToStream; // interface uses Classes, ActiveX, l3Base, HCInterfacesUnit, HCAdapter, hcInterfaces ; type ThcManager = class(Tl3Base, IhcManager) private // internal methods f_Adapter : IHCAdapterDll; f_Requests : IConsultingRequests; private // methods procedure SaveToFile(const aFileName : String; const aData : String); {* - сохранить в файл. } private // property methods function pm_GetRequests: IConsultingRequests; {-} private // IhcManager function NextQuery: String; {* - получить очередной запрос. } procedure SetAnswer(const aFileName: String); {-} function NextMark: String; {* - получить оценку. } function MakeQueryManual(const aCardId : String; const aProductId : String; const aQuery : String): String; {* - сформировать XML для запроса полученного не через сервер консультации. } function PrintQueryStatus(const aFileName: String): String; {* - получить статусы консультаций в формате XML. } function DeleteQuery(const aFileName: String): String; {* - получить статусы консультаций в формате XML. } procedure SignImportConsultation(const aSourceFile : String; const aDestFile : String); {* - подписать импортируемую консультацию. } protected // methods procedure Cleanup; override; {-} protected // property property Requests: IConsultingRequests read pm_GetRequests; {-} public // public methods constructor Create; reintroduce; {-} class function Make: IhcManager; {-} end;//ThcManager implementation uses SysUtils, tstUtils, hcConst ; procedure hcCheckResult(const aValue: TResultValue); begin case aValue of RV_BAD_XML: raise EhcBadXml.Create(c_hcBadXML); RV_DUPLICATED: raise EhcDuplicateAnswer.Create(c_hcDuplicateAnswer); RV_ERROR: raise EhcError.Create(c_hcError); end;//case aValue of end;//hcCheckResult function mgReadStream(const aRequests : IConsultingRequests; const aType : ThcStreamType): String; var l_Data : IConsultingData; l_Stream : IStream; l_Success : Boolean; l_Result : TResultValue; begin Result := ''; if Assigned(aRequests) then begin l_Data := nil; l_Result := RV_EMPTY; case aType of stNextMark: l_Result := aRequests.GetNextMark(l_Data); stNextQuery: l_Result := aRequests.GetNextQuery(l_Data); end;//case aType of hcCheckResult(l_Result); if l_Result in [RV_SUCCESS, RV_COMPLECT_REMOVED_ERROR] then try l_Data.GetData(l_Stream); if Assigned(l_Stream) then try Result := tstReadStream(l_Stream, @l_Success); if l_Success then l_Data.DataReceived; finally l_Stream := nil; end;{try..finally} finally l_Data := nil; end;{try..finally} end;{try..finally} end;//hcStream type ThcAdapter = class(THCAdapterDll) protected // methods procedure AfterConstruction; override; {-} destructor Destroy; override; {-} public // methods class function Make: IHCAdapterDll; reintroduce; {-} end;//ThcAdapter { ThcManager } procedure ThcManager.Cleanup; begin f_Requests := nil; f_Adapter := nil; inherited; end; constructor ThcManager.Create; begin inherited Create; f_Adapter := ThcAdapter.Make; end; class function ThcManager.Make: IhcManager; var l_Class: ThcManager; begin l_Class := Create; try Result := l_Class; finally FreeAndNil(l_Class); end; end;//Make procedure ThcManager.SignImportConsultation(const aSourceFile : String; const aDestFile : String); {* - подписать импортируемую консультацию. } var l_Source : IStream; l_Dest : IStream; l_Signed : String; begin l_Source := f_Adapter.MakeStream; try if FileExists(aSourceFile) and tstFileToStream(aSourceFile, l_Source) then begin hcCheckResult(Requests.SignQuery(l_Source, l_Dest)); try l_Signed := tstReadStream(l_Dest); SaveToFile(aDestFile, l_Signed); finally l_Dest := nil; end; end; finally l_Source := nil; end; end;//SignImportConsultation function ThcManager.DeleteQuery(const aFileName: String): String; {* - получить статусы консультаций в формате XML. } var l_Stream : IStream; l_Status : IStream; begin Result := ''; l_Stream := f_Adapter.MakeStream; try if tstFileToStream(aFileName, l_Stream) then begin hcCheckResult(Requests.EraseQueriesById(l_Stream, l_Status)); try Result := tstReadStream(l_Status); finally l_Status := nil; end;{try..finally} end;//if tstFileToStream(aFileName, l_Stream) then finally l_Stream := nil; end;{try..finally} end; function ThcManager.PrintQueryStatus(const aFileName: String): String; {* - получить статусы консультаций в формате XML. } var l_Stream : IStream; l_Status : IStream; begin Result := ''; l_Stream := f_Adapter.MakeStream; try if tstFileToStream(aFileName, l_Stream) then begin hcCheckResult(Requests.GetStatusStatistic(l_Stream, l_Status)); try Result := tstReadStream(l_Status); finally l_Status := nil; end;{try..finally} end;//if tstFileToStream(aFileName, l_Stream) then finally l_Stream := nil; end;{try..finally} end;//PrintQueryStatus function ThcManager.MakeQueryManual(const aCardId : String; const aProductId : String; const aQuery : String): String; {* - сформировать XML для запроса полученного не через сервер консультации. } var l_Data : IConsultingData; l_XML : IStream; begin Result := ''; case Requests.GetOfflineQuery(PAnsiChar(aCardId), PAnsiChar(aProductId), PAnsiChar(aQuery), l_Data) of RV_EMPTY: raise EhcInvalidNumber.Create('Неправильный номер карточки или продукта'); RV_ERROR: raise EhcAccessDenied.Create('Ошибка при доступе к АРМ-у или СК'); end;//case f_Requests.GetOfflineQuery( l_Data.GetData(l_XML); Result := tstReadStream(l_XML); end;//MakeQueryManual function ThcManager.NextMark: String; {* - получить оценку. } begin Result := mgReadStream(Requests, stNextMark); end;//NextMark function ThcManager.NextQuery: String; begin Result := mgReadStream(Requests, stNextQuery); end;//NextQuery procedure ThcManager.SaveToFile(const aFileName : String; const aData : String); {* - сохранить в файл. } var l_F : TextFile; l_Buffer : PAnsiChar; begin AssignFile(l_F, aFileName); try Rewrite(l_F); GetMem(l_Buffer, Length(aData)); try StrPCopy(l_Buffer, aData); Write(l_F, l_Buffer); finally FreeMem(l_Buffer); end; finally CloseFile(l_F); end; end; function ThcManager.pm_GetRequests: IConsultingRequests; begin if not Assigned(f_Requests) then f_Requests := f_Adapter.MakeConsultingRequests; Result := f_Requests; end; procedure ThcManager.SetAnswer(const aFileName: String); var l_Stream : IStream; begin if FileExists(aFileName) and Assigned(Requests) then begin l_Stream := f_Adapter.MakeStream; try if tstFileToStream(aFileName, l_Stream) then try hcCheckResult(Requests.SetAnswer(l_Stream)); finally l_Stream := nil; end;{try..finally} finally l_Stream := nil; end;{try..finally} end;//if FileExists(aFileName) then end;//SetAnswer { ThcAdapter } procedure ThcAdapter.AfterConstruction; begin inherited; MakeBusinessLogicLifeCycle.Start; end; destructor ThcAdapter.Destroy; var l_Business: IBusinessLogicLifeCycle; begin // Здесь действительно нужна локальная переменная, т.к. интерфейс бизнес // объекта должен быть освобожден раньше самой бибилиотеке (dll): l_Business := MakeBusinessLogicLifeCycle; try l_Business.Stop; finally l_Business := nil; end;//try..finally inherited; end;//Cleanup class function ThcAdapter.Make: IHCAdapterDll; begin Result := Create(CLibraryVersion); end;//Make end.
{$include lem_directives.inc} unit GameOptionsScreen; interface uses Windows, Classes, SysUtils, Controls, UMisc, Gr32, Gr32_Image, Gr32_Layers, LemCore, LemTypes, LemStrings, LemLevelSystem, LemGame, GameControl, GameBaseScreen; type TGameOptionsScreen = class(TGameBaseScreen) private fLineCount: Integer; function GetScreenText: string; procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Form_KeyPress(Sender: TObject; var Key: Char); procedure Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure HandleMouseClick(Button: TMouseButton); function GetLineStr(aLine: Integer): string; procedure DrawLines(aBitmap: TBitmap32; const aLines: TByteSet = []); protected procedure PrepareGameParams(Params: TDosGameParams); override; procedure BuildScreen; override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; published end; implementation uses Forms, LemStyle; { TDosGamePreview } procedure TGameOptionsScreen.PrepareGameParams(Params: TDosGameParams); begin inherited; end; procedure TGameOptionsScreen.BuildScreen; var Temp: TBitmap32; // DstRect: TRect; begin //fSection := aSection; //fLevelNumber := aLevelNumber; //fGameResult := aResult; ScreenImg.BeginUpdate; Temp := TBitmap32.Create; try InitializeImageSizeAndPosition(640, 350); ExtractBackGround; ExtractPurpleFont; Temp.SetSize(640, 350); Temp.Clear(0); TileBackgroundBitmap(0, 0, Temp); BackBuffer.Assign(Temp); // DrawPurpleText(Temp, GetScreenText, 16, 16); DrawLines(Temp, [0..9]); ScreenImg.Bitmap.Assign(Temp); finally ScreenImg.EndUpdate; Temp.Free; end; end; constructor TGameOptionsScreen.Create(aOwner: TComponent); begin inherited Create(aOwner); Stretched := True; OnKeyDown := Form_KeyDown; OnKeyPress := Form_KeyPress; OnMouseDown := Form_MouseDown; ScreenImg.OnMouseDown := Img_MouseDown; fLineCount := 10; end; destructor TGameOptionsScreen.Destroy; begin inherited Destroy; end; function TGameOptionsScreen.GetScreenText: string; begin Result := 'Gradient Bridges: on'; end; procedure TGameOptionsScreen.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Shift <> [] then Exit; case Key of VK_ESCAPE: CloseScreen(gstMenu); // VK_RETURN: CloseScreen(gstPreview); end; end; procedure TGameOptionsScreen.Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin HandleMouseClick(Button); end; procedure TGameOptionsScreen.Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin HandleMouseClick(Button); end; procedure TGameOptionsScreen.HandleMouseClick(Button: TMouseButton); begin if Button = mbLeft then CloseScreen(gstPreview) else if Button = mbRight then CloseScreen(gstMenu); end; procedure TGameOptionsScreen.Form_KeyPress(Sender: TObject; var Key: Char); begin case Key of '1': begin end; end; end; procedure TGameOptionsScreen.DrawLines(aBitmap: TBitmap32; const aLines: TByteSet = []); {------------------------------------------------------------------------------- draws all the options -------------------------------------------------------------------------------} var x, y, i: Integer; begin for i := 0 to fLineCount - 1 do if i in aLines then begin DrawPurpleText(aBitmap, GetLineStr(i), 16, 32 * i + 16); end; end; function TGameOptionsScreen.GetLineStr(aLine: Integer): string; begin Result := Chr(Ord('A') + aLine) + '. ' + 'Gradient Bridges: ' + ' on'; end; end.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcSysUtils.pas } { File version: 5.04 } { Description: System utility functions } { } { Copyright: Copyright (c) 1999-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2018/08/13 5.01 Initial version from other units. } { 2019/07/29 5.02 FPC/Linux fixes. } { 2020/06/08 5.03 Ensure zero terminated string has terminating zero. } { 2020/07/07 5.04 GetOSHomePath. EnsureOSPathSuffix. } { GetApplicationFilename. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} unit flcSysUtils; interface { OS Errors } function GetLastOSErrorCode: NativeInt; function GetLastOSErrorMessage: String; { Path utilities } {$IFDEF MSWINDOWS} const OSDirectorySeparatorChar = '\'; {$ENDIF} {$IFDEF POSIX} const OSDirectorySeparatorChar = '/'; {$ENDIF} procedure EnsureOSPathSuffix(var APath: String); { System paths } function GetOSHomePath: String; { Application path } function GetFullApplicationFilename: String; implementation {$IFNDEF DELPHIXE2_UP} {$IFDEF MSWINDOWS} {$DEFINE GetHomePath_WinAPI} {$DEFINE UseSHFolder} {$ENDIF} {$ENDIF} uses {$IFDEF MSWINDOWS} Windows, {$IFDEF UseSHFolder} SHFolder, {$ENDIF} {$ENDIF} {$IFDEF POSIX} {$IFDEF DELPHI} Posix.Errno, Posix.Unistd, {$ENDIF} {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF UNIX} BaseUnix, Unix, {$ENDIF} {$ENDIF} SysUtils; {$IFDEF MSWINDOWS} function GetLastOSErrorCode: NativeInt; begin Result := NativeInt(Windows.GetLastError); end; {$ENDIF} {$IFDEF DELPHI} {$IFDEF POSIX} function GetLastOSErrorCode: NativeInt; begin Result := NativeInt(GetLastError); end; {$ENDIF} {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF UNIX} function GetLastOSErrorCode: NativeInt; begin Result := NativeInt(GetLastOSError); end; {$ENDIF} {$ENDIF} resourcestring SSystemError = 'System error #%d'; {$IFDEF MSWINDOWS} {$IFDEF StringIsUnicode} function GetLastOSErrorMessage: String; const MAX_ERRORMESSAGE_LENGTH = 256; var Err : Windows.DWORD; Buf : array[0..MAX_ERRORMESSAGE_LENGTH] of Word; Len : Windows.DWORD; begin Err := Windows.GetLastError; FillChar(Buf, Sizeof(Buf), #0); Len := Windows.FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nil, Err, 0, @Buf, MAX_ERRORMESSAGE_LENGTH, nil); if Len <= 0 then Result := Format(SSystemError, [Err]) else begin Buf[MAX_ERRORMESSAGE_LENGTH] := 0; Result := StrPas(PWideChar(@Buf)); end; end; {$ELSE} function GetLastOSErrorMessage: String; const MAX_ERRORMESSAGE_LENGTH = 256; var Err : Windows.DWORD; Buf : array[0..MAX_ERRORMESSAGE_LENGTH] of Byte; Len : Windows.DWORD; begin Err := Windows.GetLastError; FillChar(Buf, Sizeof(Buf), #0); Len := Windows.FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, nil, Err, 0, @Buf, MAX_ERRORMESSAGE_LENGTH, nil); if Len <= 0 then Result := Format(SSystemError, [Err]) else begin Buf[MAX_ERRORMESSAGE_LENGTH] := 0; Result := StrPas(PAnsiChar(@Buf)); end; end; {$ENDIF} {$ENDIF} {$IFDEF DELPHI} {$IFDEF POSIX} function GetLastOSErrorMessage: String; begin Result := SysErrorMessage(GetLastError); end; {$ENDIF} {$ENDIF} {$IFDEF FREEPASCAL} {$IFDEF UNIX} function GetLastOSErrorMessage: String; begin Result := SysErrorMessage(GetLastOSError); end; {$ENDIF} {$ENDIF} { Path utilities } procedure EnsureOSPathSuffix(var APath: String); var L : NativeInt; begin L := Length(APath); if L = 0 then exit; if APath[L] = OSDirectorySeparatorChar then exit; Inc(L); SetLength(APath, L); APath[L] := OSDirectorySeparatorChar; end; { System paths } {$IFDEF GetHomePath_WinAPI} function GetOSHomePath: String; var Buf : array[0..MAX_PATH] of AnsiChar; begin SetLastError(ERROR_SUCCESS); if SHGetFolderPath(0, CSIDL_APPDATA, 0, 0, @Buf) = S_OK then Result := StrPas(PAnsiChar(@Buf)) else Result := ''; end; {$ELSE} function GetOSHomePath: String; var Path : String; begin Path := SysUtils.GetHomePath; Result := Path; end; {$ENDIF} { Application path } function GetFullApplicationFilename: String; var Filename : String; begin Filename := ParamStr(0); if Filename <> '' then Filename := ExpandFileName(Filename); Result := Filename; end; end.
unit Plotter; interface uses Persistent, BackupInterfaces; const PlotterPointCount = 12; PlotterMaxPoint = PlotterPointCount - 1; type PPlotterArray = ^TPlotterArray; TPlotterArray = array[0..PlotterMaxPoint] of byte; type TPlotter = class( TPersistent ) private fPoints : TPlotterArray; fMin : int64; fMax : int64; private function GetPoints : PPlotterArray; function GetMaxPoint : integer; function GetZero : byte; public property Points : PPlotterArray read GetPoints; property MinVal : int64 read fMin; property MaxVal : int64 read fMax; property Zero : byte read GetZero; property MaxPoint : integer read GetMaxPoint; private function GetRealVal( index : integer ) : int64; public property RealVal[index : integer] : int64 read GetRealVal; public procedure Plot( Min, Max, Value : int64 ); procedure Assign( Plotter : TPlotter ); virtual; function Serialize : string; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; procedure RegisterBackup; implementation uses MathUtils, SysUtils; function TPlotter.GetPoints : PPlotterArray; begin result := @fPoints; end; function TPlotter.GetMaxPoint : integer; begin result := PlotterMaxPoint; end; function TPlotter.GetZero : byte; begin if fMin < 0 then result := (0 - fMin)*high(byte) div (fMax - fMin) else result := 0; end; function TPlotter.GetRealVal( index : integer ) : int64; begin result := (MaxVal - MinVal)*Points[index] + MinVal; end; procedure TPlotter.Plot( min, max, Value : int64 ); var i : integer; aux : int64; OldMin : int64; OldMax : int64; OldVal : int64; begin try move( fPoints[1], fPoints[0], MaxPoint ); aux := min; min := MathUtils.minI64( min, max ); max := MathUtils.maxI64( aux, max ); OldMin := fMin; OldMax := fMax; fMin := MathUtils.minI64( min, fMin ); fMax := MathUtils.maxI64( max, fMax ); if (fMin < OldMin) or (fMax > OldMax) then for i := 0 to pred(MaxPoint) do begin OldVal := fPoints[i]*(OldMax - OldMin) div high(byte) + OldMin; fPoints[i] := (OldVal - fMin)*high(byte) div (fMax - fMin); end; if fMax - fMin > 0 then fPoints[MaxPoint] := round( realmin( high(fPoints[MaxPoint]), 1.0*(Value - fMin)*high(byte)/(1.0*(fMax - fMin)) ) ) else fPoints[MaxPoint] := 0; except end; end; procedure TPlotter.Assign( Plotter : TPlotter ); begin if Plotter <> nil then begin move( Plotter.fPoints, fPoints, sizeof(fPoints) ); fMin := Plotter.fMin; fMax := Plotter.fMax; end; end; function TPlotter.Serialize : string; var i : integer; begin result := IntToStr(PlotterPointCount) + ',' + IntToStr(fMin) + ',' + IntToStr(fMax) + ','; for i := 0 to pred(PlotterPointCount) do result := result + IntToStr(fPoints[i]) + ','; end; procedure TPlotter.LoadFromBackup( Reader : IBackupReader ); var i : integer; begin inherited; fMin := Reader.ReadInt64('Min', 0); fMax := Reader.ReadInt64('Max', 0); for i := 0 to pred(PlotterPointCount) do fPoints[i] := Reader.ReadByte( 'p' + IntToStr(i), 0 ); end; procedure TPlotter.StoreToBackup( Writer : IBackupWriter ); var i : integer; aux : string; begin inherited; Writer.WriteInt64('Min', fMin); Writer.WriteInt64('Max', fMax); for i := 0 to pred(PlotterPointCount) do begin aux := 'p' + IntToStr(i); Writer.WriteByte( aux, fPoints[i] ); end; aux := ''; end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TPlotter ); end; end.
unit atListener; // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atListener.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatListener" MUID: (4807838102C9) interface uses l3IntfUses , atInterfaces , Classes , SyncObjs ; type TatListener = class(TInterfacedObject, IatListener) private f_Notifiers: TInterfaceList; f_CS: TCriticalSection; private function IsListen(const notifier: IatNotifier): Boolean; protected procedure DoFire(sender: TObject; const notification: IatNotification); virtual; abstract; procedure StartListen(const notifier: IatNotifier); procedure StopListen; overload; procedure StopListen(const notifier: IatNotifier); overload; procedure Fire(sender: TObject; const notification: IatNotification); public constructor Create; reintroduce; destructor Destroy; override; end;//TatListener implementation uses l3ImplUses , SysUtils //#UC START# *4807838102C9impl_uses* //#UC END# *4807838102C9impl_uses* ; function TatListener.IsListen(const notifier: IatNotifier): Boolean; //#UC START# *480783E2019D_4807838102C9_var* //#UC END# *480783E2019D_4807838102C9_var* begin //#UC START# *480783E2019D_4807838102C9_impl* Result := (f_Notifiers.IndexOf(notifier) <> -1); //#UC END# *480783E2019D_4807838102C9_impl* end;//TatListener.IsListen constructor TatListener.Create; //#UC START# *480783FD009B_4807838102C9_var* //#UC END# *480783FD009B_4807838102C9_var* begin //#UC START# *480783FD009B_4807838102C9_impl* inherited; // f_Notifiers := TInterfaceList.Create; f_CS := TCriticalSection.Create; //#UC END# *480783FD009B_4807838102C9_impl* end;//TatListener.Create procedure TatListener.StartListen(const notifier: IatNotifier); //#UC START# *48077F3F01F9_4807838102C9_var* //#UC END# *48077F3F01F9_4807838102C9_var* begin //#UC START# *48077F3F01F9_4807838102C9_impl* f_CS.Enter; try // проверяем, может мы его уже слушаем if IsListen(notifier) then Exit; // слушаем, ничего делать не надо // не слушаем // добавляем в список f_Notifiers.Add(notifier); // дергаем нотификатор, чтобы он начал уведомлять notifier.StartNotify(Self); finally f_CS.Leave; end; //#UC END# *48077F3F01F9_4807838102C9_impl* end;//TatListener.StartListen procedure TatListener.StopListen; //#UC START# *48077F4B02E8_4807838102C9_var* var notifier : IatNotifier; //#UC END# *48077F4B02E8_4807838102C9_var* begin //#UC START# *48077F4B02E8_4807838102C9_impl* f_CS.Enter; try while (true) do begin if (f_Notifiers.Count = 0) then Exit; // и так никого не слушаем notifier := f_Notifiers.First as IatNotifier; StopListen(notifier); end; finally f_CS.Leave; end; //#UC END# *48077F4B02E8_4807838102C9_impl* end;//TatListener.StopListen procedure TatListener.StopListen(const notifier: IatNotifier); //#UC START# *48077F540156_4807838102C9_var* //#UC END# *48077F540156_4807838102C9_var* begin //#UC START# *48077F540156_4807838102C9_impl* f_CS.Enter; try // проверяем, может мы не слушаем if NOT IsListen(notifier) then Exit; // не слушаем, ничего делать не надо // слушаем // удаляем из списка f_Notifiers.Remove(notifier); // дергаем нотификатор, чтобы перестал уведомлять notifier.StopNotify(Self); finally f_CS.Leave; end; //#UC END# *48077F540156_4807838102C9_impl* end;//TatListener.StopListen procedure TatListener.Fire(sender: TObject; const notification: IatNotification); //#UC START# *48077F6101B4_4807838102C9_var* //#UC END# *48077F6101B4_4807838102C9_var* begin //#UC START# *48077F6101B4_4807838102C9_impl* DoFire(sender, notification); //#UC END# *48077F6101B4_4807838102C9_impl* end;//TatListener.Fire destructor TatListener.Destroy; //#UC START# *48077504027E_4807838102C9_var* //#UC END# *48077504027E_4807838102C9_var* begin //#UC START# *48077504027E_4807838102C9_impl* StopListen; FreeAndNil(f_Notifiers); FreeAndNil(f_CS); // inherited; //#UC END# *48077504027E_4807838102C9_impl* end;//TatListener.Destroy end.
// the main code formatter engine, combines the parser and formatter do do the work // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterEngine; interface uses {$IFDEF debug} // NOTE: including DbugIntf adds around 300 k to the dll DbugIntf, {$ENDIF} SysUtils, Classes, GX_CollectionLikeLists, GX_CodeFormatterTypes, GX_CodeFormatterTokens, GX_CodeFormatterSettings; (* WISHLIST: - suppress read-only file message - read capitalization from var const type blocks - sorting methods - Is it possible to insert a "user customisable" line or group of lines before each function/procedure, to allow the developer to comment it. Ex : {------------Name of the proc------------------------} (Simple) {*************************** * ...Comment ... * ...Comment ... ***************************/ (A few lines)} *) type TCodeFormatterEngine = class(TObject) private FSettings: TCodeFormatterSettings; FTokens: TOCollection; FText: TStringList; function GetLine(var TokenNo: Integer): string; function GetSourcecode: string; procedure SetSourcecode(const Value: string); public constructor Create; destructor Destroy; override; function Execute: Boolean; property Sourcecode: string read GetSourcecode write SetSourcecode; property Settings: TCodeFormatterSettings read FSettings write FSettings; end; implementation uses StrUtils, GX_CodeFormatterFormatter, GX_CodeFormatterParser; constructor TCodeFormatterEngine.Create; begin inherited; FSettings := TCodeFormatterSettings.Create; FText := TStringList.Create; end; destructor TCodeFormatterEngine.Destroy; begin FreeAndNil(FText); FreeAndNil(FSettings); FreeAndNil(FTokens); inherited; end; function TCodeFormatterEngine.Execute: Boolean; begin try if Assigned(FTokens) then FTokens.Free; FTokens := TCodeFormatterParser.Execute(FText, FSettings); FText.Clear; // we can free some memory since the text is now stored in the tokens TCodeFormatterFormatter.Execute(FTokens, FSettings); Result := True; except on E: Exception do begin Result := False; {ShowMessage('Error occurred, cannot format');} end; end; end; function TCodeFormatterEngine.GetLine(var TokenNo: Integer): string; var Token: TPascalToken; i: Integer; begin Result := ''; if not Assigned(FTokens) then Exit; if (TokenNo >= 0) and (TokenNo < FTokens.Count) then begin Token := FTokens.Items[TokenNo]; repeat Result := Result + Token.GetString; Inc(TokenNo); if TokenNo >= FTokens.Count then break; Token := TPascalToken(FTokens.Items[TokenNo]); until Token.ReservedType = rtLineFeed; end; // remove spaces and tabs at the end i := Length(Result); while (i > 0) and (Result[i] in [' ', Tab]) do begin Dec(i); SetLength(Result, i); end; end; function TCodeFormatterEngine.GetSourcecode: string; var Line: string; TokenNo: Integer; Size: Cardinal; LB: string; begin FText.Clear; LB := sLineBreak; Size := 0; if Assigned(FTokens) then begin TokenNo := 0; while TokenNo < FTokens.Count do begin Line := GetLine(TokenNo); FText.Add(Line); Size := Size + Cardinal(Length(Line)) + Cardinal(Length(LB)); end; end; Result := FText.Text; FText.Clear; end; procedure TCodeFormatterEngine.SetSourcecode(const Value: string); begin FText.Text := Value; end; end.
unit ListFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ToolWin, ComCtrls, StdCtrls, ExtCtrls; type TFrameList = class(TFrame) ListBox: TListBox; Edit: TEdit; btnAdd: TButton; btnRemove: TButton; btnClear: TButton; Bevel: TBevel; procedure btnAddClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure btnClearClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.DFM} procedure TFrameList.btnAddClick(Sender: TObject); begin ListBox.Items.Add (Edit.Text); end; procedure TFrameList.btnRemoveClick(Sender: TObject); begin if ListBox.ItemIndex >= 0 then ListBox.Items.Delete (ListBox.ItemIndex); end; procedure TFrameList.btnClearClick(Sender: TObject); begin ListBox.Clear; end; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SSVolumeController.pas // Creator : Shen Min // Date : 2002-09-28 // Comment : Component to change mixer volume // http://www.sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SSVolumeController; interface uses SysUtils, Classes, MMSystem, Windows, Math; type TssVolumeController = class(TComponent) private m_mixerHandle : Cardinal; m_MuteControl : MixerControl; m_VolControl : MixerControl; m_Mute : Boolean; m_Volume: Integer; m_Balance : Integer; procedure InitMixerControls; procedure UnInitMixerControls; procedure SetVolume(Vol, Balance : Integer); procedure GetVolume(var Vol, Balance : integer); procedure SetMute(Value : Boolean); procedure SetMuteProp(const Value: Boolean); procedure SetVolumeProp(const Value: Integer); procedure SetBalanceProp(const Value: Integer); function GetBalanceProp: Integer; function GetVolumeProp: Integer; public constructor Create(AOwner : TComponent); override; destructor Destroy(); override; published property Mute : Boolean read m_Mute write SetMuteProp; property Volume : Integer read GetVolumeProp write SetVolumeProp; property Balance : Integer read GetBalanceProp write SetBalanceProp; end; procedure Register; implementation procedure Register; begin RegisterComponents('Sunisoft FreeVCL', [TssVolumeController]); end; procedure TssVolumeController.InitMixerControls; var LineControls : MIXERLINECONTROLS; MixerLine : TMIXERLINE; Controls : array [0 .. 30] of TMixerControl; i : integer; begin ZeroMemory(@Controls[0], sizeof(TMixerControl) * 31); mixerOpen(@m_MixerHandle, 0, 0, 0, MIXER_OBJECTF_MIXER); ZeroMemory(@MixerLine, sizeof(TMIXERLINE)); MixerLine.cbStruct := sizeof(TMIXERLINE); MixerLine.dwDestination := 1; MixerLine.dwComponentType := MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; mixerGetLineInfo(m_MixerHandle, @MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE); ZeroMemory(@LineControls, sizeof(MIXERLINECONTROLS)); LineControls.cbStruct := sizeof(MIXERLINECONTROLS); LineControls.dwControlType := MIXERCONTROL_CONTROLTYPE_VOLUME; LineControls.dwLineID := MixerLine.dwLineID; LineControls.cControls := MixerLine.cControls; LineControls.cbmxctrl := sizeof(MIXERCONTROL); LineControls.pamxctrl := @Controls[0]; mixerGetLineControls(m_MixerHandle, @LineControls, MIXER_GETLINECONTROLSF_ALL); for i := 31 downto 0 do begin if Controls[i].dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME then m_VolControl := Controls[i]; if Controls[i].dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE then m_MuteControl := Controls[i]; end; m_VolControl.Metrics.dwReserved[1] := 1; m_VolControl.Metrics.dwReserved[2] := 1; end; procedure TssVolumeController.SetVolume(Vol, Balance : Integer); var V : integer; aDetails : array [0 .. 1] of MIXERCONTROLDETAILS_UNSIGNED; ControlDetails : TMIXERCONTROLDETAILS; begin V := Vol * $FFFF div 100; if Balance < 0 then begin aDetails[0].dwValue := V; aDetails[1].dwValue := V * (100 + Balance) div 100; end else begin aDetails[0].dwValue := V * (100 - Balance) div 100; aDetails[1].dwValue := V; end; ZeroMemory(@ControlDetails, sizeof(TMIXERCONTROLDETAILS)); ControlDetails.cbStruct := sizeof(TMIXERCONTROLDETAILS); ControlDetails.dwControlID := m_VolControl.dwControlID; ControlDetails.cChannels := 2; // 2 sound channels ControlDetails.cMultipleItems := 0; ControlDetails.cbDetails := sizeof(MIXERCONTROLDETAILS_UNSIGNED); ControlDetails.paDetails := @aDetails[0]; mixerSetControlDetails(0, @ControlDetails, MIXER_SETCONTROLDETAILSF_VALUE); end; procedure TssVolumeController.GetVolume(var Vol, Balance:integer); var aDetails : array [0 .. 30] of Integer; ControlDetails : TMIXERCONTROLDETAILS; L, R : Integer; begin ZeroMemory(@ControlDetails, sizeof(TMIXERCONTROLDETAILS)); ControlDetails.cbStruct := sizeof(TMIXERCONTROLDETAILS); ControlDetails.dwControlID := m_VolControl.dwControlID; ControlDetails.cbDetails := sizeof(integer); ControlDetails.hwndOwner := 0; ControlDetails.cChannels := 2; ControlDetails.paDetails := @aDetails; MixerGetControlDetails(m_mixerHandle, @ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE); L := aDetails[0]; R := aDetails[1]; Vol:=Max(L, R) * 100 div $FFFF; if Vol <> 0 then if L>R then Balance := -(L - R) * 100 div L else Balance := (R - L) * 100 div R else Balance := 0; end; procedure TssVolumeController.SetMute(Value : Boolean); var cdetails : TMixerControlDetails; details : array [0 .. 30] of Integer; begin cdetails.cbStruct := sizeof(cdetails); cdetails.dwControlID := m_MuteControl.dwControlID; cdetails.cbDetails := sizeof(integer); cdetails.hwndOwner := 0; cdetails.cChannels := 1; cdetails.paDetails := @details[0]; details[0] := Integer(Value); MixerSetControlDetails(m_mixerhandle, @cdetails, MIXER_GETCONTROLDETAILSF_VALUE); end; constructor TssVolumeController.Create(AOwner: TComponent); begin inherited; InitMixerControls(); Mute := false; GetVolume(m_Volume, m_Balance); end; destructor TssVolumeController.Destroy; begin UnInitMixerControls(); inherited; end; procedure TssVolumeController.UnInitMixerControls; begin // end; procedure TssVolumeController.SetMuteProp(const Value: Boolean); begin m_Mute := Value; SetMute(m_Mute); end; procedure TssVolumeController.SetVolumeProp(const Value: Integer); begin if (Value < 0) or (Value > 100) then Exit; m_Volume := Value; SetVolume(m_Volume, m_Balance); end; procedure TssVolumeController.SetBalanceProp(const Value: Integer); begin if (Value < -100) or (Value > 100) then Exit; m_Balance := Value; SetVolume(m_Volume, m_Balance); end; function TssVolumeController.GetBalanceProp: Integer; begin GetVolume(m_Volume, m_Balance); Result := m_Balance; end; function TssVolumeController.GetVolumeProp: Integer; begin GetVolume(m_Volume, m_Balance); Result := m_Volume; end; end.
unit MarkAddressAsDetectedAsVisitedRequestUnit; interface uses REST.Json.Types, SysUtils, HttpQueryMemberAttributeUnit, GenericParametersUnit; type TMarkAddressAsDetectedAsVisitedRequest = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('route_id')] FRouteId: String; [JSONMarshalled(False)] [HttpQueryMember('route_destination_id')] FRouteDestinationId: Integer; [JSONNameAttribute('is_visited')] FIsVisited: boolean; public constructor Create(RouteId: String; RouteDestinationId: Integer; IsVisited: boolean); reintroduce; end; implementation { TMarkAddressAsDetectedAsVisitedRequest } constructor TMarkAddressAsDetectedAsVisitedRequest.Create(RouteId: String; RouteDestinationId: Integer; IsVisited: boolean); begin Inherited Create; FRouteId := RouteId; FRouteDestinationId := RouteDestinationId; FIsVisited := IsVisited; end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, TeEngine, Series, ExtCtrls, TeeProcs, Chart, ComCtrls, VclTee.TeeGDIPlus; type TRealPoint = record //структура, включающая x и y, x,y:extended; //являющиеся типом числа с плавающей запятой end; TRealPointArray=array of TRealPoint; //массив структур, включающих x и y {Главная форма приложения} TMainFrm = class(TForm) Chart1: TChart; //график Series1: TPointSeries; //градуировочная линия Series2: TPointSeries; //оперативная точка lbl_GradPointPrev: TLabel; lbl_GradPointNext: TLabel; lbl_Power: TLabel; lbl_Current: TLabel; lbl_TrackBetween: TLabel; lbl_ControlPotential: TLabel; lbl_Autor: TLabel; ed_Power: TEdit; ed_Current: TEdit; ed_ControlPotential: TEdit; TrackBar1: TTrackBar; Chart2: TChart; //график для лампы Series3: TFastLineSeries; //характеристика лампы Series4: TPointSeries; //оперативная точка Button2: TButton; //загрузить характеристику лампы Button1: TButton; //загрузить энергетическую характеристику OpenDialog1: TOpenDialog; Chart3: TChart; //график временной характеристики Series5: TLineSeries; //график временной характеристики Button3: TButton; btnStart: TButton; Timer1: TTimer; Series6: TLineSeries; ed_OperativePower: TEdit; Label1: TLabel; Label2: TLabel; //загрузить временную характеристику procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure TrackBar1Change(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private public end; {глобальные функции} {Процедура - реализация метода наименьших квадратов. Входные параметры: динамический массив точек. Выходные параметры: коэффициенты M, B и R для построения прямой, максимально удовлетворяющей множеству точек из входного массива.} procedure LinearLeastSquares(data: TRealPointArray; var M,B, R: extended); {Процедура - получение градуировочных данных (разбор входящей строки на X и Y)} procedure GetXY(Val : string; var X, Y: Double); //Возвращает ближайший номер точки серии при движении с лева на право function FindGradPointX(p_Series: TChartSeries; p_Y: Double): Integer; //Возвращает ближайший номер точки серии при движении с лева на право function FindGradPointY(p_Series: TChartSeries; p_X: Double): Integer; procedure LinearLeastSquaresForSerie(p_Series: TChartSeries; p_GradPointNum: Integer; var M,B,R: extended); procedure LoadGradData(p_Series: TChartSeries; p_FileName: string; var Y0: Double; var MaxY: Double); var MainFrm: TMainFrm; implementation {$R *.dfm} //включение ресурсов формы {Загрузка данных} procedure LoadGradData(p_Series: TChartSeries; p_FileName: string; var Y0: Double; var MaxY: Double); var X, Y: Double; I: Integer; Points: array of TPoint; pt: TPoint; SL : TStringList; begin p_Series.Clear; //Определение объекта списка строк, и указание нашей переменной на него SL := TStringList.Create(); try SL.LoadFromFile(p_FileName); //Загрузка строкового списка из текстового файла Y0 := 0; MaxY := 0; for I := 0 to SL.Count -1 do begin GetXY(Trim(SL.Strings[I]), X, Y);//Разбор входящей строки на X и Y if I = 0 then Y0 := Y; if Y > MaxY then MaxY := Y; p_Series.AddXY(X, Y, '', clTeeColor);//Установка точки на графике end; finally FreeAndNil(SL); {освобождение памяти, используемой объектом, и устанавливление объектной ссылки на ноль.} end; end; procedure TMainFrm.Button1Click(Sender: TObject); var MaxY, MinY : Double; begin if OpenDialog1.Execute then begin LoadGradData(Series1, OpenDialog1.FileName, MinY, MaxY); TrackBar1.Max := Round(MaxY) - 1; //ограничение сверху TrackBar1.Min := Round(MinY) + 1; TrackBar1.Position := 0; //устанвка начального значения {TrdckBar активен только когда оба графика загружены} // TrackBar1.Enabled := (Series1.Count > 0) and (Series3.Count > 0); TrackBar1.Update; end; end; {Нахождение между какими точками на градуировачной кривой лежит входное значение} function FindGradPointX(p_Series: TChartSeries; p_Y: Double): Integer; var I: Integer; begin try Result:= 0; for I := 0 to p_Series.Count -1 do begin if p_Series.YValue[I] >= p_Y then begin Result := I; break; end; end; except on E: Exception do begin ShowMessage(E.Message); //обработка исключительных ситуаций end; end; end; {Нахождение точки на градуировачной кривой, которая лежит слева от входного значения} function FindGradPointY(p_Series: TChartSeries; p_X: Double): Integer; var I: Integer; begin try Result:= 0; for I := 0 to p_Series.Count -1 do begin if p_Series.XValue[I] >= p_X then begin Result := I; break; end; end; except on E: Exception do begin ShowMessage(E.Message); //обработка исключительных ситуаций end; end; end; procedure LinearLeastSquaresForSerie(p_Series: TChartSeries; p_GradPointNum: Integer; var M,B,R: extended); var //массив из 2 точек data: TRealPointArray; X_prev, Y_prev, X_next, Y_next : Double; begin M:= 0; B:= 0; R:= 0; if p_GradPointNum = 0 then exit; if p_GradPointNum >= p_Series.Count then exit; //в массиве перавя точка имеет индех 0 Y_prev := p_Series.YValue[p_GradPointNum-1]; X_prev := p_Series.XValue[p_GradPointNum-1]; Y_next := p_Series.YValue[p_GradPointNum]; X_next := p_Series.XValue[p_GradPointNum]; //при движении по горизонтали Y не меняется if Y_prev = Y_next then begin Exit; end; //установим длину динамического массива в две точки setlength(data, 2); data[0].y := Y_prev; data[0].x := X_prev; data[1].y := Y_next; data[1].x := X_next; //вычисление коэффициентов LinearLeastSquares(data, M, B, R); end; procedure TMainFrm.TrackBar1Change(Sender: TObject); var X_calc, Y_calc : Double; X_Poten_prev, Y_Poten_prev, X_Poten_next, Y_Poten_next, X_Poten_calc, Y_Poten_calc : Double; GradPoint, I : Integer; M,B, R: extended; begin try //FindGradPoint возвращает значения от 1 GradPoint := FindGradPointX(Series1, TrackBar1.Position); if GradPoint = 0 then exit; {показ между какими точками лежит оперативная точка} lbl_GradPointPrev.Caption := IntToStr(GradPoint); //слева lbl_GradPointNext.Caption := IntToStr(GradPoint+1); //справа LinearLeastSquaresForSerie(Series1, GradPoint, M,B,R); if M = 0 then exit; {y = Mx + B, следовательно x =(Y - B)/M } Y_calc := TrackBar1.Position; X_calc := (Y_calc - B)/M; //установка точки на графике (очищение серии и добавка новой точки) Series2.Clear; Series2.AddXY(X_calc, Y_calc, ''); {показ значений в элементах отображения brighteness, current} ed_Power.Text := FloatToStr(Y_calc); ed_Current.Text := FloatToStrF(X_calc, ffFixed, 4, 4); X_Poten_calc := X_calc; GradPoint := FindGradPointY(Series3, X_Poten_calc); if GradPoint < 0 then exit; LinearLeastSquaresForSerie(Series3, GradPoint, M,B,R); //y = Mx + B Y_Poten_calc := M * X_Poten_calc + B; //установка точки на графике (очищение серии и добавка новой точки) Series4.Clear; Series4.AddXY(X_Poten_calc, Y_Poten_calc); {показ control potential в элементе отображения} ed_ControlPotential.Text := FloatToStrF(Y_Poten_calc, ffFixed, 4, 4); except on E: Exception do begin ShowMessage(E.Message); //обработка исключительных ситуаций end; end; end; {Процедура - реализация метода наименьших квадратов.} procedure LinearLeastSquares(data: TRealPointArray; var M,B,R: extended); {Line "Y = mX + b" is linear least squares line for the input array, "data", of TRealPoint} var SumX, SumY, SumX2, SumY2, SumXY: extended; Sx,Sy:extended; n, i: Integer; begin n := Length(data); {количество точек} SumX := 0.0; SumY := 0.0; SumX2 := 0.0; SumY2:=0.0; SumXY := 0.0; for i := 0 to n - 1 do begin //слагаем все X SumX := SumX + data[i].X; //слагаем все Y SumY := SumY + data[i].Y; //слагаем квадраты X SumX2 := SumX2 + data[i].X*data[i].X; //слагаем квадраты Y SumY2 := SumY2 + data[i].Y*data[i].Y; //слагаем произведения X и Y SumXY := SumXY + data[i].X*data[i].Y; end; {Проверка на то, что массив не состоит из точек, у которых одинаковые координаты на всех} if (n*SumX2=SumX*SumX) or (n*SumY2=SumY*SumY) then begin showmessage('LeastSquares() Error - X or Y values cannot all be the same'); M:=0; B:=0; end else{Когда проходим проверку, реализуем алгоритм МНК} begin M:=((n * SumXY) - (SumX * SumY)) / ((n * SumX2) - (SumX * SumX)); {Наклон прямой (M)} B:=(SumY-M*SumX)/n; {Отступ прямой (B)} Sx:=sqrt(SumX2-sqr(SumX)/n); Sy:=Sqrt(SumY2-sqr(SumY)/n); r:=(SumXY-SumX*SumY/n)/(Sx*Sy); //коэффициент корреляции end; end; // разбор входящей строки на X и Y procedure GetXY(Val : string; var X, Y: Double); var temp : string; DelimPos : Integer; begin DelimPos := Pos(';', Val); //поиск позиции разделителя (;) temp := Copy(Val, 0, DelimPos - 1); X := StrToFloat(temp); //X-число до разделителя temp := Copy(Val, DelimPos+1, 999); Y := StrToFloat(temp); //Y-число после разделителя end; procedure TMainFrm.Button2Click(Sender: TObject); var Y0, MaY : Double; begin if OpenDialog1.Execute then begin LoadGradData(Series3, OpenDialog1.FileName, Y0, MaY); end; // TrackBar1.Enabled := (Series1.Count > 0) and (Series3.Count > 0); end; procedure TMainFrm.Button3Click(Sender: TObject); var Y1, MxY : Double; begin if OpenDialog1.Execute then begin LoadGradData(Series5, OpenDialog1.FileName, Y1, MxY); Series6.Clear; Series6.AddXY(0, 0); end; // TrackBar1.Enabled := (Series1.Count > 0) and (Series3.Count > 0); end; procedure TMainFrm.btnStartClick(Sender: TObject); begin Timer1.Enabled := not Timer1.Enabled; if not Timer1.Enabled then btnStart.Caption := 'Start'; end; procedure TMainFrm.Timer1Timer(Sender: TObject); var X, Y, X1, Y1 : Double; Ind : Integer; M,B, R: extended; begin X := Series6.XValue[0]; Y := Series5.MaxYValue; Series6.Clear; X := X + 0.1; Series6.AddXY(X, Y); Series6.AddXY(X, 0); Ind := FindGradPointY(Series5, X); LinearLeastSquaresForSerie(Series5, Ind, M, B, R); if (M = 0) and (B = 0) then Y1 := Series5.YValues[Ind] else // y = Mx + B, Y1 := M * X + B; TrackBar1.Position := Round(Y1); ed_OperativePower.Text := FloatToStrF(Y1, ffFixed, 4, 2); btnStart.Caption := 'Pause'; if X >= Series5.MaxXValue then begin Timer1.Enabled := false; Series6.Clear; Series6.AddXY(0, 0); btnStart.Caption := 'Start'; end; end; end.
unit ddCaseCodeMaker; { Автоматическое создание Номеров дел для Постановлений Федеральных Арбитражных судов } interface Uses l3Base, l3TempMemoryStream, l3Filer, csServerTaskTypes, csProcessTask, dt_Types, l3CustomString, ddProgressObj, CsExport, csMessageManager, ddCaseCodeTaskPrim, ddProcessTaskPrim, SewerPipe ; type TalcuCaseCodeMaker = class(Tl3Base) private f_Filer: Tl3CustomFiler; f_Stream: Tl3TempMemoryStream; f_TopicNo: Integer; f_OutPipe: TSewerPipe; public function Execute(aTask: TddProcessTask; aProgressor: TddProgressObject): Boolean; procedure Abort; end; type TddCaseCodeTask = class(TddCaseCodeTaskPrim) private f_Maker: TalcuCaseCodeMaker; protected procedure DoRun(const aContext: TddRunContext); override; function GetDescription: AnsiString; override; procedure DoAbort; override; public class function CanAsyncRun: Boolean; override; {$If defined(AppServerSide)} procedure SetupServerSideConfigParams; override; {$IfEnd defined(AppServerSide)} end; implementation Uses ddImportPipeKernel, daSchemeConsts, dd_lcCaseCodeGenerator, Document_Const, ddAppConfig, dtIntf, DT_Sab, dt_Doc, DT_Const, DT_Serv, evdWriter, evEvdRd, Classes, DT_IFltr, SysUtils, csTaskTypes, ddServerTask; procedure TalcuCaseCodeMaker.Abort; begin f_OutPipe.Aborted := True; end; function TalcuCaseCodeMaker.Execute(aTask: TddProcessTask; aProgressor: TddProgressObject): Boolean; var l_Maker: TlcCaseCodeGenerator; l_Writer: TevdNativeWriter; l_Sab: ISab; begin // Экспортируем во временный файл f_OutPipe:= TSewerPipe.Create; try f_outPipe.Progressor:= aProgressor; f_OutPipe.ExportDocument:= True; Assert(TddCaseCodeTask(aTask).DiapasonType in [tdSingle, tdNumList]); if TddCaseCodeTask(aTask).DiapasonType = tdNumList then begin DocumentServer.Family:= CurrentFamily; l_Sab:= MakeValueSet(DocumentServer.FileTbl, fID_Fld, TcsExport(aTask).SABStream); l_Sab.Sort; f_OutPipe.DocSab := l_Sab; end else f_OutPipe.MakeSingleDocSab(TcsExport(aTask).DocID, False); l_Maker:= TlcCaseCodeGenerator.Create(nil); try f_OutPipe.Writer:= l_Maker; l_Maker.Generator:= nil; //l_Writer; Result:= f_OutPipe.Execute; finally l3Free(l_Maker); end; finally l3Free(f_OutPipe); end; end; class function TddCaseCodeTask.CanAsyncRun: Boolean; begin Result := True; end; procedure TddCaseCodeTask.DoAbort; begin inherited DoAbort; f_Maker.Abort; end; procedure TddCaseCodeTask.DoRun(const aContext: TddRunContext); begin f_Maker := TalcuCaseCodeMaker.Create; try f_Maker.Execute(Self, aContext.rProgressor) finally FreeAndNil(f_Maker); end; end; function TddCaseCodeTask.GetDescription: AnsiString; begin Result:= 'Расстановка Номеров дел в постановлениях ФАС'; end; {$If defined(AppServerSide)} procedure TddCaseCodeTask.SetupServerSideConfigParams; begin inherited; DiapasonType := tdNumList; ExportEmptyKW := False; ExportDocument := True; ExportRTFBody := False; ExportKW := False; ExportDocImage := False; MultiUser := True; Family := CurrentFamily; InternalFormat := False; OutFileType := outEVD; SeparateFiles := divNone; DocumentFileNameMask := ''; ReferenceFileNameMask := ''; ObjTopicFileName := ''; KWFileName := ''; OutputFileSize := 0; ExportAnnoTopics := False; AnnoTopicFileName := 'Archianno.nsr'; end; {$IfEnd defined(AppServerSide)} initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\dd\ddCaseCodeMaker.pas initialization enter'); {$EndIf} RegisterTaskClass(cs_ttCaseCode, TddCaseCodeTask, 'Создание номеров дел для постановлений ФАС'); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\dd\ddCaseCodeMaker.pas initialization leave'); {$EndIf} end.
unit GX_MenusForEditorExpert; interface uses Menus, ActnList, GX_Experts; type TGxMenusForEditorExperts = class(TGX_Expert) private procedure PopulatePopupMenu(const PopupMenu: TPopupMenu); protected procedure UpdateAction(Action: TCustomAction); override; function SupportsSubmenu: Boolean; public function GetActionCaption: string; override; class function GetName: string; override; function GetDisplayName: string; override; function HasConfigOptions: Boolean; override; function HasSubmenuItems: Boolean; override; procedure CreateSubMenuItems(MenuItem: TMenuItem); override; procedure Execute(Sender: TObject); override; end; implementation uses SysUtils, Windows, Controls, GX_GExperts, GX_OtaUtils, GX_ActionBroker, GX_IdeUtils, GX_EditorExpert, GX_EditorExpertManager, ComCtrls; var InternalPopupMenu: TPopupMenu; function GetInternalPopupMenu: TPopupMenu; const MenuName = 'GxMenusForEditorExpertsInternalPopupMenu'; begin if not Assigned(InternalPopupMenu) then begin InternalPopupMenu := NewPopupMenu(nil, MenuName, paCenter, False, []); InternalPopupMenu.Images := GxOtaGetIdeImageList; end; Result := InternalPopupMenu; end; procedure ReleaseInternalPopupMenu; begin FreeAndNil(InternalPopupMenu); end; { TGxMenusForEditorExperts } procedure TGxMenusForEditorExperts.Execute(Sender: TObject); var MousePosition: TPoint; APopupMenu: TPopupMenu; IsToolButton: Boolean; begin IsToolButton := Assigned(Sender) and (Sender is TCustomAction) and ((Sender as TCustomAction).ActionComponent is TToolButton); if SupportsSubmenu and (not IsToolButton) and Assigned(Sender) then begin // The submenu items perform all actions end else begin MousePosition := Mouse.CursorPos; APopupMenu := GetInternalPopupMenu; Assert(Assigned(APopupMenu)); PopulatePopupMenu(APopupMenu); APopupMenu.Popup(MousePosition.x, MousePosition.y); end; end; // Note: Partially duplicated below procedure TGxMenusForEditorExperts.CreateSubMenuItems(MenuItem: TMenuItem); var i: Integer; AGExpertsInstance: TGExperts; AEditorExpertManager: TGxEditorExpertManager; AEditorExpert: TEditorExpert; ExpertMenuEntry: TMenuItem; begin inherited; Assert(Assigned(MenuItem)); MenuItem.Clear; AGExpertsInstance := GExpertsInst; Assert(Assigned(AGExpertsInstance)); AEditorExpertManager := AGExpertsInstance.EditorExpertManager; // If editor experts are not enabled, then the editor // expert manager is not present; exit if this is the case. if not Assigned(AEditorExpertManager) then Exit; for i := 0 to AEditorExpertManager.EditorExpertCount-1 do begin AEditorExpert := AEditorExpertManager.EditorExpertList[i]; Assert(Assigned(AEditorExpert)); if AEditorExpert.Active then begin ExpertMenuEntry := TMenuItem.Create(MenuItem); ExpertMenuEntry.Action := GxActionBroker.FindAction(AEditorExpert.GetActionName); MenuItem.Add(ExpertMenuEntry); end; end; end; procedure TGxMenusForEditorExperts.PopulatePopupMenu(const PopupMenu: TPopupMenu); procedure ClearMenuItems(AMenu: TMenu); begin Assert(Assigned(AMenu)); AMenu.Items.Clear; end; var i: Integer; AGExpertsInstance: TGExperts; AEditorExpertManager: TGxEditorExpertManager; AEditorExpert: TEditorExpert; ExpertMenuEntry: TMenuItem; begin Assert(Assigned(PopupMenu)); ClearMenuItems(PopupMenu); AGExpertsInstance := GExpertsInst; Assert(Assigned(AGExpertsInstance)); AEditorExpertManager := AGExpertsInstance.EditorExpertManager; // If editor experts are not enabled, then the editor // expert manager is not present; exit if this is the case. if not Assigned(AEditorExpertManager) then Exit; for i := 0 to AEditorExpertManager.EditorExpertCount-1 do begin AEditorExpert := AEditorExpertManager.EditorExpertList[i]; Assert(Assigned(AEditorExpert)); if AEditorExpert.Active then begin ExpertMenuEntry := TMenuItem.Create(PopupMenu); ExpertMenuEntry.Action := GxActionBroker.FindAction(AEditorExpert.GetActionName); PopupMenu.Items.Add(ExpertMenuEntry); end; end; end; function TGxMenusForEditorExperts.GetActionCaption: string; resourcestring SCaption = 'Editor Experts'; begin Result := SCaption; end; function TGxMenusForEditorExperts.GetDisplayName: string; resourcestring SDisplayName = 'Editor Experts'; begin Result := SDisplayName; end; class function TGxMenusForEditorExperts.GetName: string; begin Result := 'EditorExpertsMenu'; end; function TGxMenusForEditorExperts.HasConfigOptions: Boolean; begin Result := False; end; function TGxMenusForEditorExperts.HasSubmenuItems: Boolean; begin Result := SupportsSubmenu; end; function TGxMenusForEditorExperts.SupportsSubmenu: Boolean; begin // The Delphi 7- IDEs seem to clear out the submenu item shortcuts Result := RunningDelphi8OrGreater; end; procedure TGxMenusForEditorExperts.UpdateAction(Action: TCustomAction); begin Action.Enabled := Assigned(GExpertsInst.EditorExpertManager) and (GExpertsInst.EditorExpertManager.EditorExpertCount > 0); Action.Visible := Action.Enabled; end; initialization RegisterGX_Expert(TGxMenusForEditorExperts); finalization ReleaseInternalPopupMenu; end.
{**************************************************************************} { TParamTreeview component } { for Delphi & C++Builder } { } { Copyright © 2001 - 2013 } { TMS Software } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {**************************************************************************} unit paramtreeview; {$I TMSDEFS.INC} {$DEFINE PARAMS} interface uses Windows, Classes, Comctrls, Messages, Controls, Graphics, Menus, StdCtrls, Spin, Forms, ParHTML, PictureContainer, Dialogs; const MAJ_VER = 1; // Major version nr. MIN_VER = 3; // Minor version nr. REL_VER = 3; // Release nr. BLD_VER = 8; // Build nr. // version history // 1.3.0.1 : improved mask editor property handling // 1.3.0.2 : fix for parameter handling on multiline nodes // 1.3.0.3 : fix for context menu selection in inplace editors // : fix for & character editing in EDIT types // 1.3.0.4 : fix for issue with WordWrap = false // 1.3.0.5 : fix issue with inplace editors wider than control width // 1.3.1.0 : improved positioning of directory select dialog on multimonitor machines // 1.3.1.1 : Fixed : issue with hotkey handling for other controls during param edit // 1.3.3.0 : Fixed issue with spinedit // 1.3.3.1 : Fixed painting issue with mousewheel scrolling // 1.3.3.2 : Fixed runtime creation issue // 1.3.3.3 : Improved : repainting of hovered items // 1.3.3.4 : Fixed : Issue with use in combination with TAdvMainMenu // 1.3.3.5 : Improved : Date format compatibility for inplace date picker // 1.3.3.6 : Fixed : Issue with mouse anchor sensitivity // 1.3.3.7 : Fixed : Item background painting on XE3 with theming enabled // 1.3.3.8 : Improved : Editing of very long parameters type {$IFDEF DELPHI_UNICODE} THintInfo = Controls.THintInfo; PHintInfo = Controls.PHintInfo; {$ENDIF} TParamTreeViewClickEvent = procedure(Sender:TObject;ANode: TTreeNode; href: string;var value: string) of object; TParamTreeViewPopupEvent = procedure(Sender:TObject;ANode: TTreeNode; href: string;values:TStringlist;var DoPopup: Boolean) of object; TParamTreeViewSelectEvent = procedure(Sender:TObject;ANode: TTreeNode; href,value: string) of object; TParamTreeViewChangedEvent = procedure(Sender:TObject;ANode: TTreeNode; href,oldvalue, newvalue: string) of object; TParamTreeViewHintEvent = procedure(Sender:TObject; ANode: TTreeNode; href: string; var hintvalue: string; var showhint: Boolean) of object; TParamCustomEditEvent = procedure(Sender: TObject; Node: TTreeNode; href, value, props: string; EditRect: TRect) of object; TParamTreeviewCustomShowEvent = procedure(Sender:TObject; ANode: TTreeNode; href:string; var value:string;ARect:TRect) of object; TParamTreeViewEditEvent = procedure(Sender:TObject;ANode: TTreeNode; href: string;var value: string) of object; TParamTreeview = class; {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TParamTreeview = class(TCustomTreeView) private FVersion : String; { Private declarations } FIndent: Integer; FOldCursor: Integer; FOldScrollPos: Integer; FParamColor: TColor; FSelectionColor: TColor; FSelectionFontColor: TColor; FItemHeight: Integer; FImages: TImageList; FParamPopup: TPopupMenu; FParamList: TPopupListBox; FParamDatePicker: TPopupDatePicker; FParamSpinEdit: TPopupSpinEdit; FParamEdit: TPopupEdit; FParamMaskEdit: TPopupMaskEdit; FOldParam: string; FOnParamChanged: TParamTreeViewChangedEvent; FOnParamClick: TParamTreeViewClickEvent; FOnParamHint: TParamTreeViewHintEvent; FOnParamPopup: TParamTreeViewPopupEvent; FOnParamList: TParamTreeViewPopupEvent; FOnParamSelect: TParamTreeViewSelectEvent; FOnParamEnter: TParamTreeViewSelectEvent; FOnParamExit: TParamTreeViewSelectEvent; FParamListSorted: Boolean; FShowSelection: Boolean; FOnParamPrepare: TParamTreeViewClickEvent; FParamHint: Boolean; FShadowColor: TColor; FShadowOffset: Integer; FUpdateCount: Integer; FWordWrap: Boolean; FMouseDown: Boolean; FContainer: TPictureContainer; FCurrCtrlID: string; FCurrCtrlRect: TRect; FCurrCtrlDown: TRect; FHoverNode: TTreeNode; FHoverHyperLink: Integer; FCurrHoverRect: TRect; FImageCache: THTMLPictureCache; FHover: Boolean; FHoverColor: TColor; FHoverFontColor: TColor; FEditAutoSize: Boolean; FLineSpacing: Integer; FOnParamEditStart: TParamTreeViewEditEvent; FOnParamEditDone: TParamTreeViewEditEvent; FEmptyParam: string; FOldAnchor: string; FOldIndex: Integer; FFocusLink: Integer; FNumHyperLinks: Integer; FEditValue: string; FEditPos: TPoint; FIsEditing: Boolean; FOnParamQuery: TParamTreeViewEditEvent; FOnParamCustomEdit: TParamCustomEditEvent; FAdvanceOnReturn: Boolean; FStopMouseProcessing: Boolean; FShowFocusBorder: Boolean; procedure CMHintShow(Var Msg: TMessage); message CM_HINTSHOW; procedure CMDesignHitTest(var message: TCMDesignHitTest); message CM_DESIGNHITTEST; procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY; procedure CNNotify(var message: TWMNotify); message CN_NOTIFY; procedure WMLButtonDown(var message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonUp(var message: TWMLButtonDown); message WM_LBUTTONUP; procedure WMMouseMove(var message: TWMMouseMove); message WM_MOUSEMOVE; procedure WMHScroll(var message: TMessage); message WM_HSCROLL; procedure WMSize(var message: TMessage); message WM_SIZE; function GetItemHeight: Integer; procedure SetItemHeight(const Value: Integer); procedure SetSelectionColor(const Value: TColor); procedure SetSelectionFontColor(const Value: TColor); procedure SetParamColor(const Value: TColor); procedure SetImages(const Value: TImageList); procedure SetShowSelection(const Value: Boolean); function GetNodeParameter(Node: TTreeNode; HRef: String): string; procedure SetNodeParameter(Node: TTreeNode; HRef: String; const Value: string); function IsParam(x,y:Integer;GetFocusRect: Boolean;var Node: TTreeNode; var hr,cr: TRect; var CID,CT,CV: string): string; function HTMLPrep(s:string):string; function InvHTMLPrep(s:string):string; procedure SetShadowColor(const Value: TColor); procedure SetShadowOffset(const Value: Integer); procedure SetWordWrap(const Value: Boolean); procedure SetLineSpacing(const Value: Integer); function GetParamItemRefCount(Item: Integer): Integer; function GetParamNodeRefCount(Node: TTreeNode): Integer; function GetParamItemRefs(Item, Index: Integer): string; function GetParamRefCount: Integer; function GetParamRefs(Index: Integer): string; procedure StartParamEdit(param:string; Node: TTreeNode; hr: TRect); procedure StartParamDir(Node: TTreeNode; param,curdir:string; hr: TRect); function GetParamRect(href: string): TRect; function GetParamNodeIndex(Node: TTreeNode; href: string): Integer; function GetParamRefNode(href: string): TTreeNode; function GetParameter(href: string): string; procedure SetParameter(href: string; const Value: string); procedure SetHover(const Value: Boolean); function GetParamIndex(href: string): Integer; function GetVersion: string; procedure SetVersion(const Value: string); protected { Protected declarations } function GetVersionNr: Integer; virtual; procedure HandlePopup(Sender:TObject); virtual; procedure Notification(AComponent: TComponent; AOperation: TOperation); override; procedure Loaded; override; procedure CreateWnd; override; procedure WndProc(var Message: TMessage); override; procedure UpdateParam(Param,Value:string); procedure PrepareParam(Param:string; var Value:string); procedure ControlUpdate(Sender: TObject; Param,Text:string); procedure AdvanceEdit(Sender: TObject); procedure KeyPress(var Key: Char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure Change(Node: TTreeNode); override; procedure Expand(Node: TTreeNode); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; property NodeParameter[Node: TTreeNode; HRef: String]:string read GetNodeParameter write SetNodeParameter; property ParamRefCount: Integer read GetParamRefCount; property ParamRefs[Index: Integer]:string read GetParamRefs; property ParamRefNode[href: string]: TTreeNode read GetParamRefNode; property ParamNodeRefCount[Item: Integer]: Integer read GetParamItemRefCount; property ParamNodeRefs[Item,Index: Integer]:string read GetParamItemRefs; property ParamNodeIndex[Node: TTreeNode; href: string]: Integer read GetParamNodeIndex; property ParamIndex[href: string]: Integer read GetParamIndex; property Parameter[href: string]: string read GetParameter write SetParameter; procedure EditParam(href: string); function GetParamInfo(Node: TTreeNode; HRef:string; var AValue, AClass, AProp, AHint: string): Boolean; property DateTimePicker: TPopupDatePicker read FParamDatePicker; property SpinEdit: TPopupSpinEdit read FParamSpinEdit; property Editor: TPopupEdit read FParamEdit; property MaskEditor: TPopupMaskEdit read FParamMaskEdit; property ListBox: TPopupListBox read FParamList; property StopMouseProcessing: Boolean read FStopMouseProcessing write FStopMouseProcessing; published // property Version : string read FVersion write FVersion; { Published declarations } { new introduced properties } property AdvanceOnReturn: Boolean read FAdvanceOnReturn write FAdvanceOnReturn; property EditAutoSize: Boolean read FEditAutoSize write FEditAutoSize; property EmptyParam: string read FEmptyParam write FEmptyParam; property HTMLImages: TImageList read FImages write SetImages; property Hover: Boolean read FHover write SetHover default True; property HoverColor: TColor read FHoverColor write FHoverColor default clGreen; property HoverFontColor: TColor read FHoverFontColor write FHoverFontColor default clWhite; property ItemHeight: Integer read GetItemHeight write SetItemHeight; property LineSpacing: Integer read FLineSpacing write SetLineSpacing default 0; property SelectionColor: TColor read fSelectionColor write SetSelectionColor; property SelectionFontColor: TColor read fSelectionFontColor write SetSelectionFontColor; property ShowSelection: Boolean read FShowSelection write SetShowSelection default False; property ParamColor: TColor read FParamColor write SetParamColor default clGreen; property ParamHint: Boolean read FParamHint write FParamHint; property ShadowColor: TColor read FShadowColor write SetShadowColor; property ShadowOffset: Integer read FShadowOffset write SetShadowOffset; property ShowFocusBorder: Boolean read FShowFocusBorder write FShowFocusBorder default true; property Version: string read GetVersion write SetVersion; property WordWrap: Boolean read FWordWrap write SetWordWrap; { new introduced events } property OnParamPrepare: TParamTreeViewClickEvent read FOnParamPrepare write FOnParamPrepare; property OnParamClick: TParamTreeViewClickEvent read FOnParamClick write FOnParamClick; property OnParamPopup: TParamTreeViewPopupEvent read FOnParamPopup write FOnParamPopup; property OnParamList: TParamTreeViewPopupEvent read FOnParamList write FOnParamList; property OnParamSelect: TParamTreeViewSelectEvent read FOnParamSelect write FOnParamSelect; property OnParamChanged: TParamTreeViewChangedEvent read FOnParamChanged write FOnParamChanged; property OnParamHint: TParamTreeViewHintEvent read FOnParamHint write FOnParamHint; property OnParamEnter: TParamTreeViewSelectEvent read FOnParamEnter write FOnParamEnter; property OnParamExit: TParamTreeViewSelectEvent read FOnParamExit write FOnParamExit; property OnParamEditStart: TParamTreeViewEditEvent read FOnParamEditStart write FOnParamEditStart; property OnParamEditDone: TParamTreeViewEditEvent read FOnParamEditDone write FOnParamEditDone; property OnParamCustomEdit: TParamCustomEditEvent read FOnParamCustomEdit write FOnParamCustomEdit; property OnParamQuery: TParamTreeViewEditEvent read FOnParamQuery write FOnParamQuery; { reintroduced properties } property Align; property Anchors; property AutoExpand; property BiDiMode; property BorderWidth; property ChangeDelay; property Constraints; property DragKind; property HotTrack; property ParentBiDiMode; property RowSelect; property OnCustomDraw; property OnCustomDrawItem; property OnEndDock; property OnStartDock; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property Enabled; property Font; property HideSelection; //property Images; property Indent; property Items; property ParamListSorted: Boolean read FParamListSorted write FParamListSorted; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property RightClickSelect; property ShowButtons; property ShowHint; property ShowLines; property ShowRoot; property SortType; property StateImages; property TabOrder; property TabStop default True; property ToolTips; property Visible; property OnChange; property OnChanging; property OnClick; property OnCollapsing; property OnCollapsed; property OnCompare; property OnDblClick; property OnDeletion; property OnDragDrop; property OnDragOver; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnExpanding; property OnExpanded; property OnGetImageIndex; property OnGetSelectedIndex; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; implementation uses CommCtrl, Shellapi, SysUtils, ShlObj, ActiveX, ImgList, Math {$IFDEF DELPHI6_LVL} , Variants {$ENDIF} ; {$IFDEF VER100} const NM_CUSTOMDRAW = NM_FIRST-12; CDDS_PREPAINT = $00000001; CDDS_POSTPAINT = $00000002; CDDS_PREERASE = $00000003; CDDS_POSTERASE = $00000004; CDDS_ITEM = $00010000; CDDS_ITEMPREPAINT = CDDS_ITEM or CDDS_PREPAINT; CDDS_ITEMPOSTPAINT = CDDS_ITEM or CDDS_POSTPAINT; CDDS_ITEMPREERASE = CDDS_ITEM or CDDS_PREERASE; CDDS_ITEMPOSTERASE = CDDS_ITEM or CDDS_POSTERASE; CDDS_SUBITEM = $00020000; // itemState flags CDIS_SELECTED = $0001; CDIS_GRAYED = $0002; CDIS_DISABLED = $0004; CDIS_CHECKED = $0008; CDIS_FOCUS = $0010; CDIS_DEFAULT = $0020; CDIS_HOT = $0040; CDIS_MARKED = $0080; CDIS_INDETERMINATE = $0100; CDRF_DODEFAULT = $00000000; CDRF_NEWFONT = $00000002; CDRF_SKIPDEFAULT = $00000004; CDRF_NOTIFYPOSTPAINT = $00000010; CDRF_NOTIFYITEMDRAW = $00000020; CDRF_NOTIFYSUBITEMDRAW = $00000020; // flags are the same, we can distinguish by context CDRF_NOTIFYPOSTERASE = $00000040; TVM_GETITEMHEIGHT = TV_FIRST + 28; TVM_SETITEMHEIGHT = TV_FIRST + 27; type tagNMCUSTOMDRAWINFO = packed record hdr: TNMHdr; dwDrawStage: DWORD; hdc: HDC; rc: TRect; dwItemSpec: DWORD; // this is control specific, but it's how to specify an item. valid only with CDDS_ITEM bit set uItemState: UINT; lItemlParam: LPARAM; end; PNMCustomDraw = ^TNMCustomDraw; TNMCustomDraw = tagNMCUSTOMDRAWINFO; tagNMTVCUSTOMDRAW = packed record nmcd: TNMCustomDraw; clrText: COLORREF; clrTextBk: COLORREF; iLevel: Integer; end; PNMTVCustomDraw = ^TNMTVCustomDraw; TNMTVCustomDraw = tagNMTVCUSTOMDRAW; function TreeView_SetItemHeight(hwnd: HWND; iHeight: Integer): Integer; begin Result := SendMessage(hwnd, TVM_SETITEMHEIGHT, iHeight, 0); end; function TreeView_GetItemHeight(hwnd: HWND): Integer; begin Result := SendMessage(hwnd, TVM_GETITEMHEIGHT, 0, 0); end; {$ENDIF} procedure TParamTreeview.CMDesignHitTest(var message: TCMDesignHitTest); begin if htOnItem in GetHitTestInfoAt(message.XPos,message.YPos) then message.Result := 1 else message.Result := 0; end; procedure TParamTreeview.CNNotify(var message: TWMNotify); var TVcd:TNMTVCustomDraw; TVdi:TTVDISPINFO; Canvas: TCanvas; a,s,f: string; xsize,ysize,ml,hl: Integer; tn: TTreenode; r,hr,cr: TRect; urlcol: TColor; Selected: Boolean; CID,CV,CT: string; pt: TPoint; FHyperLink,fl: Integer; FHC, FHFC: TColor; begin if message.NMHdr^.code = TVN_GETDISPINFO then begin TVDi := PTVDispInfo(pointer(message.nmhdr))^; if (tvdi.item.mask and TVIF_TEXT = TVIF_TEXT) then begin tn := Items.GetNode(tvdi.item.hitem); s := HTMLStrip(tn.text); strplcopy(tvdi.item.pszText,s,255); tvdi.item.mask := tvdi.item.mask or TVIF_DI_SETITEM; message.Result := 0; Exit; end; end; if message.NMHdr^.code = NM_CUSTOMDRAW then begin FIndent := TreeView_GetIndent(Handle); TVcd := PNMTVCustomDraw(Pointer(message.NMHdr))^; case TVcd.nmcd.dwDrawStage of CDDS_PREPAINT: begin message.Result := CDRF_NOTIFYITEMDRAW or CDRF_NOTIFYPOSTPAINT; end; CDDS_ITEMPREPAINT: begin //if TVcd.nmcd.uItemState and CDIS_FOCUS = CDIS_FOCUS then // TVcd.nmcd.uItemState := TVcd.nmcd.uItemState and not CDIS_FOCUS; if (TVcd.nmcd.uItemState and CDIS_SELECTED = CDIS_SELECTED) then begin TVcd.nmcd.uItemState := TVcd.nmcd.uItemState and (not CDIS_SELECTED); SetTextColor(TVcd.nmcd.hdc,ColorToRGB(Color)); SetBkColor(TVcd.nmcd.hdc,ColorToRGB(Color)); TVcd.clrTextBk := ColorToRGB(Color); TVcd.clrText := ColorToRGB(Color); end else begin SetTextColor(TVcd.nmcd.hdc,ColorToRGB(Color)); SetBkColor(TVcd.nmcd.hdc,ColorToRGB(Color)); end; message.Result := CDRF_NOTIFYPOSTPAINT; end; CDDS_ITEMPOSTPAINT: begin Canvas := TCanvas.Create; Canvas.Handle := TVcd.nmcd.hdc; Canvas.Font.Assign(Self.Font); tn := Items.GetNode(HTReeItem(TVcd.nmcd.dwitemSpec)); if ShowRoot then TVcd.nmcd.rc.left := TVcd.nmcd.rc.left + FIndent*(tn.level + 1) - GetScrollPos(Handle,SB_HORZ) else TVcd.nmcd.rc.left := TVcd.nmcd.rc.left + FIndent*(tn.level) - GetScrollPos(Handle,SB_HORZ); //Canvas.TextOut(TVcd.nmcd.rc.Left,TVcd.nmcd.rc.Top,tn.Text); Selected := (TVcd.nmcd.uItemState and CDIS_SELECTED = CDIS_SELECTED); HTMLDrawEx(Canvas,tn.Text,TVcd.nmcd.rc,TImageList(HTMLImages),0,0,-1,-1,2, False,True,False,False,Selected and FShowSelection,FHover,Wordwrap,FMouseDown,False,1.0,clGreen, FHoverColor,FHoverFontColor,clGray,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,0); r := TVcd.nmcd.rc; // if (TVcd.nmcd.uItemState and CDIS_FOCUS = CDIS_FOCUS) then begin Canvas.Pen.Color := Color; Canvas.Brush.Color := Color; Canvas.Rectangle(r.Left ,r.Top,r.Right ,r.Bottom); end; if (YSize < r.Bottom - r.Top) then r.Top := r.Top + ((r.Bottom - r.Top - YSize) shr 1); if Selected then begin if FShowSelection then begin Canvas.Brush.Color := FSelectionColor; Canvas.Pen.Color := FSelectionColor; Canvas.Font.Color := FSelectionFontColor; end; with TVcd.nmcd.rc do begin Canvas.Rectangle(Left,Top,self.Width - 4,Bottom); DrawFocusRect(Canvas.Handle,Rect(Left,Top,self.Width - 4,Bottom)); end; if (TVcd.nmcd.uItemState and CDIS_FOCUS = CDIS_FOCUS) then begin Canvas.Pen.Color := clBlack; Canvas.Brush.color := clBlack; //Canvas.DrawFocusRect(TVcd.nmcd.rc); end; TVcd.nmcd.rc := r; TVcd.nmcd.rc.Left := TVcd.nmcd.rc.Left + xsize + 4; end else begin Canvas.Brush.Color := self.Color; Canvas.Pen.Color := self.Color; with TVcd.nmcd.rc do Canvas.Rectangle(Left,Top,Width,Bottom); end; TVcd.nmcd.rc := r; TVcd.nmcd.rc.Left := TVcd.nmcd.rc.Left + 1; urlcol := FParamColor; if (TVcd.nmcd.uItemState and CDIS_SELECTED = CDIS_SELECTED) and FShowSelection then begin Canvas.Brush.Color := FSelectionColor; Canvas.Pen.Color := FSelectionColor; Urlcol := FSelectionFontColor; end; GetCursorPos(pt); pt := ScreenToClient(pt); if (FHoverNode <> tn) then FHyperlink := -1 else FHyperLink := FHoverHyperLink; if (TVcd.nmcd.uItemState and CDIS_FOCUS = CDIS_FOCUS) and ShowFocusBorder then begin fl := FFocusLink; end else fl := -1; if not FHover then begin FHC := clNone; FHFC := clNone; end else begin FHC := FHoverColor; FHFC := FHoverFontColor; end; HTMLDrawEx(Canvas,tn.Text,TVcd.nmcd.rc,TImageList(HTMLImages),pt.X,pt.Y,fl,FHyperLink,ShadowOffset, False,False,False,False,Selected and FShowSelection,FHover,WordWrap,FMouseDown,False,1.0,urlCol, FHC,FHFC,ShadowColor,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,0); Canvas.Free; end; else message.Result := 0; end; end else inherited; end; procedure TParamTreeview.WMLButtonUp(var message: TWMLButtonDown); var hr,cr: TRect; CID,CT,CV,s: string; Node: TTreeNode; begin inherited; FMouseDown := False; Node := GetNodeAt(message.XPos,message.YPos); if Assigned(Node) then begin IsParam(message.XPos,message.YPos,False,Node,hr,cr,CID,CT,CV); if CID <> '' then begin if CT = 'CHECK' then begin BeginUpdate; s := Node.Text; if Uppercase(CV) = 'TRUE' then SetControlValue(s,CID,'FALSE') else SetControlValue(s,CID,'TRUE'); Node.Text := s; EndUpdate; end; if FCurrCtrlDown.Left <> -1 then InvalidateRect(Handle,@FCurrCtrlDown,true); end; FCurrCtrlDown := Rect(-1,-1,-1,-1); end; end; procedure TParamTreeview.WMLButtonDown(var message: TWMLButtonDown); var Node: TTreeNode; a: string; hr,cr: TRect; CID, CV, CT: string; begin Node := GetNodeAt(message.XPos,message.YPos); inherited; if FStopMouseProcessing then begin FStopMouseProcessing := False; Exit; end; if csDesigning in ComponentState then Exit; FMouseDown := True; if Assigned(Node) then begin Selected := Node; a := IsParam(Message.XPos,Message.Ypos,False,Node,hr,cr,CID,CV,CT); if CID <> '' then begin InvalidateRect(Handle,@cr,true); FCurrCtrlDown := cr; end else FCurrCtrlDown := Rect(-1,-1,-1,-1); if (a <> '') then begin hr.Left := hr.Left - GetScrollPos(Handle, SB_HORZ); StartParamEdit(a,Node,hr); end; end; end; procedure TParamTreeView.StartParamEdit(param:string;Node: TTreeNode; hr: TRect); var a, oldvalue,newvalue,v,c,p,h: string; NewValues: TStringList; DoPopup,DoList: Boolean; pt: TPoint; i,lh,rh: Integer; NewMenu: TMenuItem; wndstyle: DWORD; cw: integer; ptleft: TPoint; ptright: TPoint; begin a := param; GetParamInfo(Node,a,v,c,p,h); // FFocusItem := Index; FFocusLink := ParamNodeIndex[Node,param]; {$IFDEF TMSDEBUG} outputdebugstring(pchar('start editing link on '+inttostr(ffocuslink))); {$ENDIF} // if not ShowRoot then // hr.Left := hr.Left - FIndent; FIndent := TreeView_GetIndent(Handle); // hr.Right := hr.Right - FIndent * Node.Level; pt := ClientToScreen(Point(hr.left,hr.top)); ptLeft := ClientToScreen(Point(0,0)); cw := Width; wndStyle := GetWindowLong(self.Handle, GWL_STYLE); if wndStyle and WS_VSCROLL = WS_VSCROLL then cw := cw - GetSystemMetrics(SM_CXVSCROLL); ptright := ClientToScreen(Point(cw,0)); pt.X := Max(ptLeft.X - 2,pt.X + FIndent * (Node.Level + 1)); //lh := Max(0, hr.Left + FIndent * (Node.Level + 1)); rh := hr.Right + FIndent * (Node.Level + 1); lh := hr.Left; //max width allowed cw := ptright.X - pt.X - 4; if Assigned(FOnParamClick) then begin FIsEditing := True; PrepareParam(Param,v); oldvalue := v; FOnParamClick(Self,Node,param,v); if (v <> oldvalue) then ControlUpdate(self,Param,v); FIsEditing := False; end; if (c = 'TOGGLE') then begin NewValues := TStringList.Create; PropToList(InvHTMLPrep(p),NewValues); if NewValues.Count > 1 then begin if v = NewValues[0] then v := NewValues[1] else v := NewValues[0]; ControlUpdate(self,Param,v); FCurrHoverRect := Rect(0,0,0,0); FHoverNode := nil; FHoverHyperLink := -1; Repaint; end; NewValues.Free; end; if (c = 'MENU') then begin FIsEditing := True; GetHRefValue(Node.Text,a,OldValue); newvalue := oldvalue; NewValues := TStringList.Create; NewValues.Sorted := FParamListSorted; DoPopup := True; PropToList(InvHTMLPrep(p),NewValues); if Assigned(FOnParamPopup) then FOnParamPopup(self,Node,a,NewValues,DoPopup); if DoPopup then begin while FParamPopup.Items.Count>0 do FParamPopup.Items[0].Free; FParamPopup.AutoHotkeys := maManual; for i := 1 to NewValues.Count do begin NewMenu := TMenuItem.Create(Self); NewMenu.Caption := NewValues.Strings[i - 1]; NewMenu.OnClick := HandlePopup; FParamPopup.Items.Add(newmenu); end; FOldParam := a; PrepareParam(a,v); FParamPopup.Popup(pt.x,pt.y+2); end; NewValues.Free; FIsEditing := False; end; if c = 'DATE' then begin FIsEditing := True; FParamDatePicker.Top := pt.Y - 2; FParamDatePicker.Left := pt.X + 2; if Max(16,rh - lh) + lh > cw then FParamDatePicker.Width := Min(cw, rh - lh - 4) else FParamDatePicker.Width := Max(64,hr.Right - hr.Left); FParamDatePicker.Kind := dtkDate; FParamDatePicker.Cancelled := False; FParamDatePicker.Parent := Self; FParamDatePicker.Param := a; FParamDatePicker.Visible := True; FParamDatePicker.OnUpdate := ControlUpdate; FParamDatePicker.OnReturn := AdvanceEdit; PrepareParam(a,v); try {$IFDEF DELPHI6_LVL} FParamDatePicker.Date := VarToDateTime(v); {$ENDIF} {$IFNDEF DELPHI6_LVL} FParamDatePicker.Date := StrToDate(v); {$ENDIF} except end; FParamDatePicker.SetFocus; end; if c = 'TIME' then begin FIsEditing := True; FParamDatePicker.Top := pt.Y - 2; FParamDatePicker.Left := pt.X + 2; if Max(16,rh - lh) + lh > cw then FParamDatePicker.Width := Min(cw, rh - lh - 4) else FParamDatePicker.Width := Max(64,hr.Right - hr.Left); FParamDatePicker.ReInit; FParamDatePicker.Cancelled := False; FParamDatePicker.Parent := Self; FParamDatePicker.OnUpdate := ControlUpdate; FParamDatePicker.OnReturn := AdvanceEdit; FParamDatePicker.Kind := dtkTime; FParamDatePicker.Param := a; FParamDatePicker.Visible := True; PrepareParam(a,v); try FParamDatePicker.DateTime := EncodeDate(2005,1,1) + StrToTime(v); except end; FParamDatePicker.SetFocus; end; if c = 'SPIN' then begin FIsEditing := True; FParamSpinEdit.Top := pt.Y - 2; FParamSpinEdit.Left := pt.X + 2; if Max(16,rh - lh) + lh > cw then FParamSpinEdit.Width := Min(cw, rh - lh - 4) else FParamSpinEdit.Width := Max(16,hr.Right - hr.Left) + 16; FParamSpinEdit.Cancelled := False; FParamSpinEdit.Parent := Self; FParamSpinEdit.OnUpdate := ControlUpdate; FParamSpinEdit.OnReturn := AdvanceEdit; FParamSpinEdit.Param := a; FParamSpinEdit.Visible := True; PrepareParam(a,v); try FParamSpinEdit.Value := StrToInt(Trim(v)); except FParamSpinEdit.Value := 0; end; FParamSpinEdit.SetFocus; end; if c = 'EDIT' then begin FIsEditing := True; FParamEdit.Top := pt.Y - 2; FParamEdit.Left := pt.X + 2; if Max(16,rh - lh) + lh > cw then FParamEdit.Width := Min(cw, rh - lh - 4) else FParamEdit.Width := Max(16,hr.Right - hr.Left); FParamEdit.AutoSize := EditAutoSize; FParamEdit.Cancelled := False; FParamEdit.Parent := Self; FParamEdit.OnUpdate := ControlUpdate; FParamEdit.OnReturn := AdvanceEdit; FParamEdit.Param := a; FParamEdit.Visible := True; v := InvHTMLPrep(v); PrepareParam(a,v); FParamEdit.Text := v; FParamEdit.SetFocus; end; if (c = 'MASK') then begin FIsEditing := True; FParamMaskEdit.Top := pt.Y - 2; FParamMaskEdit.Left := pt.X; if Max(16,rh - lh) + lh > cw then FParamMaskEdit.Width := cw - lh - 4 else FParamMaskEdit.Width := Max(16,hr.Right - hr.Left) + 16; FParamMaskEdit.Cancelled := False; FParamMaskEdit.Parent := Self; FParamMaskEdit.OnUpdate := ControlUpdate; FParamMaskEdit.OnReturn := AdvanceEdit; FParamMaskEdit.Param := a; FParamMaskEdit.Visible := True; PrepareParam(a,v); FParamMaskEdit.EditMask := InvHTMLPrep(p); FParamMaskEdit.Text := v; FParamMaskEdit.SetFocus; end; if c = 'DIR' then begin FIsEditing := True; hr.Left := hr.Left + FIndent * (Node.Level + 1) - GetScrollPos(Handle,SB_HORZ); PrepareParam(Param,v); StartParamDir(Node,param,v,hr); FIsEditing := False; end; if (c = 'QUERY') then begin FIsEditing := True; PrepareParam(a,v); if Assigned(OnParamQuery) then OnParamQuery(Self,Node,a,v); ControlUpdate(self,a,v); end; if (c = 'CUSTOM') then begin PrepareParam(Param,v); pt := ClientToScreen(Point(hr.left,hr.top)); pt.X := pt.X + FIndent * (Node.Level + 1) - GetScrollPos(Handle,SB_HORZ); Dec(pt.Y, 2); Inc(pt.X, 2); FIsEditing := True; if Assigned(OnParamCustomEdit) then OnParamCustomEdit(Self,Selected,Param,v,p,Rect(pt.x,pt.Y,pt.X + hr.Right - hr.Left,pt.Y + hr.Bottom - hr.Top)); end; if (c = 'LIST') then begin FIsEditing := True; DoList := True; GetHRefValue(Node.Text,a,OldValue); newvalue := oldvalue; NewValues := TStringList.Create; NewValues.Sorted := FParamListSorted; DoList := True; PropToList(InvHTMLPrep(p),NewValues); if Assigned(FOnParamList) then FOnParamList(self,Node,a,Newvalues,Dolist); if DoList then begin FIndent := TreeView_GetIndent(Handle); pt := Clienttoscreen(Point(hr.left,hr.bottom)); pt.X := pt.X + FIndent * (Node.Level + 1) - GetScrollPos(Handle,SB_HORZ); FParamList.Top := pt.y; FParamList.Left := pt.x; FParamlist.OnUpdate := ControlUpdate; FParamList.OnReturn := AdvanceEdit; FParamlist.Param := a; FParamList.Parent := Self; SetWindowLong( FParamList.Handle, GWL_EXSTYLE, GetWindowLong(FParamList.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW); FParamlist.Visible := True; FParamList.Items.Assign(NewValues); PrepareParam(a,OldValue); FParamList.Ctl3D := False; FParamList.Font.Assign(self.Font); FParamList.SizeDropDownWidth; FParamList.ItemIndex := FParamList.Items.IndexOf(OldValue); FParamList.SetFocus; end; NewValues.Free; FIsEditing := False; end; end; procedure TParamTreeView.WMHScroll(var message:TMessage); begin inherited; if FOldScrollPos <> GetScrollPos(handle,SB_HORZ) then begin Invalidate; FOldScrollPos := GetScrollPos(handle,SB_HORZ); end; // Invalidate; end; function TParamTreeview.IsParam(x, y: Integer;GetFocusRect: Boolean; var Node: TTreeNode; var HR,cr: TRect;var CID,CT,CV: string): string; var r: TRect; s,a,fa: string; xsize,ysize,ml,hl,fl: Integer; wndStyle: Longint; begin Result := ''; if not GetFocusRect then Node := GetNodeAt(x,y); if Assigned(Node) then begin r := Node.DisplayRect(True); wndStyle := GetWindowLong(self.Handle, GWL_STYLE); if wndStyle and WS_VSCROLL = WS_VSCROLL then begin r.Right := Width - GetSystemMetrics(SM_CXVSCROLL); end else r.Right := Width; // r.Right := r.Left + Width; if not WordWrap then r.Right := 4096; r.Left := r.Left - 2; a := ''; Canvas.Font.Assign(Font); HTMLDrawEx(Canvas,Node.Text,r,TImageList(HTMLImages),0,0,-1,-1,2, True,True,False,False,False,False,WordWrap,FMouseDown,False,1.0,clBlue, clNone,clNone,clGray,a,s,fa,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,0); a := ''; // this is for vertically centered alignment if (YSize < r.Bottom - r.Top) then r.Top := r.Top + ((r.Bottom - r.Top - YSize) shr 1); if GetFocusRect then fl := FFocusLink + 1 else fl := -1; if HTMLDrawEx(Canvas,Node.Text,r,TImageList(HTMLImages),x,y,fl,-1,2, True,False,False,False,False,False,WordWrap,FMouseDown,GetFocusRect,1.0,clBlue, clNone,clNone,clGray,a,s,fa,xsize,ysize,FNumHyperLinks,FHoverHyperLink,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,0) then begin Result := a; end; end; end; procedure TParamTreeview.WMMouseMove(var message: TWMMouseMove); var Node : TTreeNode; r,cr,hr: TRect; s,a,f,v: string; xsize,ysize,hl,ml: Integer; CID,CV,CT: string; param:string; begin if csDesigning in ComponentState then begin inherited; Exit; end; if FIsEditing then begin inherited; Exit; end; Node := GetNodeAt(message.XPos,message.YPos); if Assigned(Node) then begin param := IsParam(message.XPos,message.YPos,False,Node,hr,cr,CID,CT,CV); {$IFDEF TMSDEBUG} outputdebugstring(pchar(inttostr(FHOverIdx)+':'+inttostr(FHoverHyperLink)+':'+inttostr(fnumhyperlinks))); {$ENDIF} if param <> FOldAnchor then Application.CancelHint; if (param = '') and (FHoverNode <> Node) and (FHoverNode <> nil) and FHover then begin InvalidateRect(Handle,@FCurrHoverRect,true); FHoverNode := nil; end; if (CID = '') and (FCurrCtrlID <> '') then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('out : '+FCurrCtrlID)); {$ENDIF} InvalidateRect(Handle,@FCurrCtrlRect,True); FCurrCtrlID := CID; end; if (CID <> FCurrCtrlID) and (CID <> '') then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('in : '+cid)); {$ENDIF} InvalidateRect(Handle,@cr,True); FCurrCtrlID := CID; FCurrCtrlRect := cr; end; r := Node.DisplayRect(True); r.Right := r.Left + Width; r.Left := r.Left + 2; a := ''; Canvas.Font.Assign(Font); HTMLDrawEx(Canvas,Node.Text,r,TImageList(HTMLImages),message.xpos,message.ypos,-1,-1,2, True,True,False,False,False,False,WordWrap,FMouseDown,False,1.0,clBlue, clNone,clNone,clGray,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,FLineSpacing); a := ''; if (ysize < r.Bottom - r.Top) then r.top := r.top + ((r.bottom - r.top - ysize) shr 1); HTMLDrawEx(Canvas,Node.Text,r,TImageList(HTMLImages),message.xpos,message.ypos,-1,-1,2, True,True,False,False,False,False,WordWrap,FMouseDown,False,1.0,clBlue, clNone,clNone,clGray,a,s,f,xsize,ysize,hl,ml,hr,cr,CID,CV,CT, FImageCache,FContainer,Handle,FLineSpacing); if (param <> '') then begin {$IFDEF TMSDEBUG} outputdebugstring(pchar('mousemove:'+param)); {$ENDIF} if FHover then begin if (Node <> FHoverNode) or not EqualRect(hr,fCurrHoverRect) then InvalidateRect(self.handle,@fCurrHoverRect,true); end; FHoverNode := Node; if (Cursor <> crHandPoint) then begin FOldCursor := self.Cursor; Cursor := crHandPoint; hr.Left := hr.Left - GetScrollPos(Handle,SB_HORZ); if FHover then InvalidateRect(self.handle,@hr,true); FCurrHoverRect := hr; end; GetHRefValue(Node.Text,a,v); if (FOldAnchor <> a) and (FOldIndex <> Node.AbsoluteIndex) then if Assigned(FOnParamEnter) then FOnParamEnter(Self,Node,a,v); FOldAnchor := param; FOldIndex := Node.AbsoluteIndex; end else begin if (Cursor = crHandPoint) then begin Cursor := FOldCursor; if (FOldAnchor <> '') and (FOldIndex <> -1) then begin if Assigned(FOnParamExit) then FOnParamExit(self,Items[FOldIndex],FOldAnchor, NodeParameter[Items[FOldIndex],FOldAnchor]); FOldAnchor := ''; FOldIndex := -1; FHoverHyperlink := -1; end; if FHover then InvalidateRect(Handle,@FCurrHoverRect,true); end; end; end else begin if (Cursor = crHandPoint) or (FOldAnchor <> '') or (FOldIndex <> -1) then begin if Assigned(FOnParamExit) then FOnParamExit(self,Items[FOldIndex],FOldAnchor, NodeParameter[Items[FOldIndex],FOldAnchor]); Application.CancelHint; Cursor := FOldCursor; FOldAnchor := ''; FOldIndex := -1; FHoverNode := nil; FHoverHyperlink := -1; if FHover then InvalidateRect(Handle,@FCurrHoverRect,true); end; end; inherited; end; constructor TParamTreeview.Create(AOwner: TComponent); begin inherited Create(AOwner); FVersion := '1'; Tooltips:=False; FEmptyParam := '?'; FParamColor := clGreen; FSelectionColor := clHighLight; FSelectionFontColor := clHighLightText; FItemHeight := 16; FOldScrollPos := -1; FParamPopup := TPopupMenu.Create(Self); FParamList := TPopupListBox.Create(Self); FParamDatePicker := TPopupDatePicker.Create(Self); FParamSpinEdit := TPopupSpinEdit.Create(Self); FParamEdit := TPopupEdit.Create(Self); FParamMaskEdit := TPopupMaskEdit.Create(Self); FImageCache := THTMLPictureCache.Create; ReadOnly := True; FShowSelection := False; FShadowOffset := 1; FShadowColor := clGray; FShowFocusBorder := true; FUpdateCount := 0; FWordWrap := True; FHover := True; FHoverColor := clGreen; FHoverFontColor := clWhite; FHoverHyperLink := -1; FNumHyperLinks := -1; end; destructor TParamTreeView.Destroy; begin FParamPopup.Free; FParamList.Free; FParamDatePicker.Free; FParamSpinEdit.Free; FParamEdit.Free; FParamMaskEdit.Free; FImageCache.Free; inherited; end; function TParamTreeview.GetItemHeight: integer; begin Result := TreeView_GetItemHeight(Handle); end; procedure TParamTreeview.SetItemHeight(const Value: integer); begin if (Value <> FItemHeight) then begin FItemHeight := Value; TreeView_SetItemHeight(Handle,FItemHeight); end; end; procedure TParamTreeview.SetSelectionColor(const Value: tcolor); begin FSelectionColor := Value; Invalidate; end; procedure TParamTreeview.SetSelectionFontColor(const Value: tcolor); begin FSelectionFontColor := Value; Invalidate; end; procedure TParamTreeview.SetParamColor(const Value: tcolor); begin FParamColor := Value; Invalidate; end; procedure TParamTreeview.Loaded; begin inherited; FOldCursor := Cursor; end; procedure TParamTreeview.CreateWnd; begin inherited; ItemHeight := FItemHeight; end; procedure TParamTreeview.SetImages(const Value: TImageList); begin FImages := Value; Invalidate; end; procedure TParamTreeView.Notification(AComponent: TComponent; AOperation: TOperation); begin if (AOperation = opRemove) and (AComponent = FImages) then FImages := nil; inherited; end; procedure TParamTreeview.WMSize(var message: TMessage); begin inherited; Invalidate; end; procedure TParamTreeview.WndProc(var Message: TMessage); var sp: integer; begin sp := 0; if HandleAllocated then sp := GetScrollPos(Handle,SB_HORZ); inherited; if (Message.Msg = WM_MOUSEWHEEL) and HandleAllocated then begin if (sp <> GetScrollPos(Handle,SB_HORZ)) then Invalidate; end; end; procedure TParamTreeview.HandlePopup(Sender: TObject); var NewValue,OldValue,NodeText: string; begin with (Sender as TMenuItem) do begin NewValue := Caption; while Pos('&',NewValue) > 0 do System.Delete(NewValue,Pos('&',NewValue),1); NodeText := Selected.Text; GetHRefValue(NodeText,FOldParam,OldValue); if Assigned(FOnParamSelect) then FOnParamSelect(Self,Selected,FOldParam,NewValue); SetHRefValue(NodeText,FOldParam,NewValue); Selected.Text := NodeText; if (OldValue <> NewValue) then if Assigned(FOnParamChanged) then FOnParamChanged(self,Selected,FOldParam,OldValue,NewValue); end; end; procedure TParamTreeview.SetShadowColor(const Value: TColor); begin FShadowColor := Value; Invalidate; end; procedure TParamTreeview.SetShadowOffset(const Value: Integer); begin FShadowOffset := Value; Invalidate; end; procedure TParamTreeview.SetWordWrap(const Value: Boolean); begin FWordWrap := Value; Invalidate; end; procedure TParamTreeview.SetShowSelection(const Value: Boolean); begin FShowSelection := Value; Invalidate; end; function TParamTreeview.GetNodeParameter(Node: TTreeNode; HRef: String): string; var Value: String; begin Result := ''; GetHRefValue(Node.Text,HRef,Value); Value := InvHTMLPrep(Value); Result := Value; end; procedure TParamTreeview.SetNodeParameter(Node: TTreeNode; HRef: String; const Value: string); var NodeText,v: string; begin NodeText := Node.Text; v := HTMLPrep(Value); SetHRefValue(NodeText,HRef,v); Node.Text := NodeText; end; function TParamTreeview.GetParamInfo(Node: TTreeNode; HRef: string; var AValue, AClass, AProp, AHint: string): Boolean; begin if Assigned(Node)then Result := ExtractParamInfo(Node.Text,HRef,AClass,AValue,AProp,AHint) else Result := False; end; procedure TParamTreeview.UpdateParam(Param, Value: string); var NodeText: string; OldValue: string; begin if not Assigned(Selected) then begin Refresh; Exit; end; NodeText := Selected.Text; GetHRefValue(NodeText,Param,OldValue); Value := HTMLPrep(Value); if Assigned(FOnParamSelect) then FOnParamSelect(Self,Selected,Param,Value); SetHRefValue(NodeText,Param,Value); Selected.Text := NodeText; if OldValue <> Value then if Assigned(FOnParamChanged) then FOnParamChanged(Self,Selected,Param,OldValue,Value); end; procedure TParamTreeview.PrepareParam(Param: string; var Value: string); begin if (Value = EmptyParam) and (EmptyParam <> '') then Value := ''; if Assigned(FOnParamPrepare) then FOnParamPrepare(Self,Selected,Param,Value); if Assigned(FOnParamEditStart) then FOnParamEditStart(Self,Selected, Param, Value); end; procedure TParamTreeview.CMHintShow(var Msg: TMessage); var CanShow: Boolean; hi: PHintInfo; Anchor: string; hr,cr: TRect; Node: TTreeNode; CID,CV,CT: string; v,c,p,h:string; Begin CanShow := True; hi := PHintInfo(Msg.LParam); if FParamHint and not FIsEditing then begin Anchor := IsParam(hi^.cursorPos.x,hi^.cursorpos.y,False,Node,hr,cr,CID,CV,CT); GetParamInfo(Node,Anchor,v,c,p,h); if h <> '' then Anchor := h; if (Anchor <> '') then begin hi^.HintPos := clienttoscreen(hi^.CursorPos); hi^.hintpos.y := hi^.hintpos.y-10; hi^.hintpos.x := hi^.hintpos.x+10; if Assigned(FOnParamHint) then FOnParamHint(self,Node,Anchor,Anchor,CanShow); hi^.HintStr := anchor; end; end; Msg.Result := Ord(Not CanShow); end; procedure TParamTreeview.BeginUpdate; begin inc(FUpdateCount); if FUpdateCount = 1 then SendMessage(Handle,WM_SETREDRAW,0,0); end; procedure TParamTreeview.EndUpdate; begin if FUpdateCount > 0 then begin dec(FUpdateCount); if FUpdateCount = 0 then begin SendMessage(Handle,WM_SETREDRAW,1,0); RedrawWindow(Handle,nil,0, RDW_ERASE or RDW_FRAME or RDW_INVALIDATE or RDW_ALLCHILDREN); end; end; end; procedure TParamTreeview.Expand(Node: TTreeNode); begin inherited; Invalidate; end; function TParamTreeView.HTMLPrep(s: string): string; begin s := StringReplace(s,'&','&amp;',[rfReplaceAll]); s := StringReplace(s,'<','&lt;',[rfReplaceAll]); s := StringReplace(s,'>','&gt;',[rfReplaceAll]); s := StringReplace(s,'"','&quot;',[rfReplaceAll]); Result := s; end; function TParamTreeView.InvHTMLPrep(s: string): string; begin s := StringReplace(s,'&lt;','<',[rfReplaceAll]); s := StringReplace(s,'&gt;','>',[rfReplaceAll]); s := StringReplace(s,'&amp;','&',[rfReplaceAll]); s := StringReplace(s,'&quot;','"',[rfReplaceAll]); Result := s; end; procedure TParamTreeView.ControlUpdate(Sender: TObject; Param,Text:string); var s: string; begin s := Text; if (s = '') and (EmptyParam <> '') then s := EmptyParam; if Assigned(FOnParamEditDone) then FOnParamEditDone(Self, Selected, Param, s); UpdateParam(Param, s); FIsEditing := False; //SetFocus; end; procedure TParamTreeview.SetLineSpacing(const Value: Integer); begin FLineSpacing := Value; Invalidate; end; procedure TParamTreeview.CMWantSpecialKey(var Msg: TCMWantSpecialKey); begin inherited; if (Msg.CharCode in [VK_RETURN]) then Msg.Result := 1; end; procedure TParamTreeview.KeyPress(var Key: Char); var r: TRect; s: string; begin inherited; if (Key = #13) and Assigned(Selected) then begin if GetParamItemRefCount(Selected.AbsoluteIndex) > 0 then begin s := ParamNodeRefs[Selected.AbsoluteIndex,FFocusLink]; r := GetParamRect(s); StartParamEdit(s,Selected,r); key := #0; end; end; end; function TParamTreeview.GetParamItemRefCount(Item: Integer): Integer; var s: string; begin Result := 0; s := Uppercase(Items[Item].Text); while (pos('HREF=',s) > 0) do begin Result := Result + 1; system.Delete(s,1, pos('HREF=',s) + 5); end; end; function TParamTreeview.GetParamNodeRefCount(Node: TTreeNode): Integer; var s: string; begin Result := 0; s := Uppercase(Node.Text); while (pos('HREF=',s) > 0) do begin Result := Result + 1 ; system.Delete(s,1, pos('HREF=',s) + 5); end; end; function TParamTreeview.GetParamItemRefs(Item, Index: Integer): string; var j: Integer; s: string; begin j := 0; Result := ''; s := Uppercase(Items[Item].Text); while (pos('HREF="',s) > 0) do begin if (Index = j) then begin system.Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin system.Delete(s,pos('"',s), length(s)); Result := s; end; Exit; end else j := j + 1; system.Delete(s,1, pos('HREF=',s) + 5); end; if Index > j then begin Result := GetParamItemRefs(Item,0); if Result <> '' then FFocusLink := 0; end; end; function TParamTreeview.GetParamRefCount: Integer; var i: Integer; s: string; begin Result := 0; for i := 1 to Items.Count do begin s := Uppercase(Items[i - 1].Text); while (pos('HREF=',s) > 0) do begin Result := Result + 1 ; system.Delete(s,1, pos('HREF=',s) + 5); end; end; end; function TParamTreeview.GetParamRefs(Index: Integer): string; var i,j: Integer; s: string; begin j := 0; Result := ''; for i := 1 to Items.Count do begin s := Uppercase(Items[i - 1].Text); while (pos('HREF="',s) > 0) do begin if (Index = j) then begin system.Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin system.Delete(s,pos('"',s), length(s)); Result := s; end; Exit; end else j := j + 1; system.Delete(s,1, pos('HREF=',s) + 5); end; end; end; function TParamTreeview.GetParamRect(href: string): TRect; var cr: TRect; CID,CV,CT: string; Node: TTreeNode; begin if not Assigned(Selected) then Exit; {$IFDEF TMSDEBUG} outputdebugstring('get rect'); {$ENDIF} // i := FFocusLink + 1; Node := Selected; IsParam(0,0,True,Node,Result,cr,CID,CV,CT); end; function TParamTreeview.GetParamNodeIndex(Node: TTreeNode; href: string): Integer; var j: Integer; s,u: string; begin j := 0; Result := -1; s := Uppercase(Node.Text); while (pos('HREF="',s) > 0) do begin system.Delete(s,1, pos('HREF="',s) + 5); if pos('"',s) > 0 then begin u := s; system.Delete(u,pos('"',u), length(u)); if UpperCase(href) = u then begin Result := j; Exit; end; end; j := j + 1; system.Delete(s,1, pos('"',s)); end; end; procedure TParamTreeview.KeyDown(var Key: Word; Shift: TShiftState); var ir: TRect; cr,hr: TRect; CID,CV,CT: string; Node: TTreeNode; begin if key in [VK_LEFT, VK_RIGHT] then begin if Assigned(Selected) then begin ir := Selected.DisplayRect(True); Node := Selected; IsParam(ir.Left + 2,ir.Top + 2,False,Node,cr,hr,CID,CV,CT); {$IFDEF TMSDEBUG} outputdebugstring(pchar('num:'+inttostr(fnumhyperlinks)+':'+inttostr(ffocuslink))); {$ENDIF} if FNumHyperLinks > 1 then begin if key = VK_LEFT then begin if FFocusLink > 0 then begin Dec(FFocusLink); Key := 0; InvalidateRect(Handle,@ir,True); end; end; if key = VK_RIGHT then begin if FFocusLink < FNumHyperLinks - 1 then begin Inc(FFocusLink); Key := 0; InvalidateRect(Handle,@ir,True); end; end; end; {$IFDEF TMSDEBUG} outputdebugstring(pchar('key focus link to : '+inttostr(ffocuslink))); {$ENDIF} end; end; inherited; end; function EditCallBack (Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer; stdcall; var Temp: String; pt: TPoint; r: TRect; begin if uMsg = BFFM_INITIALIZED then begin with TParamTreeView(lpData) Do begin {$WARNINGS OFF} // avoid platform specific warning if FEditValue = '' then Temp := GetCurrentDir else Temp := ExcludeTrailingBackslash (FEditValue); {WARNINGS ON} SendMessage (Wnd, BFFM_SETSELECTION, 1, Integer(PChar(Temp))); with TParamTreeView(lpData) do begin pt := FEditPos; pt := ClientToScreen(pt); GetWindowRect(Wnd,r); if pt.X + (r.Right - r.Left) > Screen.DesktopWidth then pt.X := pt.X - (r.Right - r.Left); if pt.Y + (r.Bottom - r.Top) < Screen.DesktopHeight then SetWindowPos(wnd,HWND_NOTOPMOST,pt.X,pt.Y,0,0,SWP_NOSIZE or SWP_NOZORDER) else SetWindowPos(wnd,HWND_NOTOPMOST,pt.X,pt.Y-(r.Bottom - r.Top)-Height,0,0,SWP_NOSIZE or SWP_NOZORDER) end; end; end; Result := 0; end; procedure TParamTreeView.StartParamDir(Node: TTreeNode; param, curdir: string; hr: TRect); var bi: TBrowseInfo; iIdList: PItemIDList; ResStr: array[0..MAX_PATH] of char; MAlloc: IMalloc; s: string; // BIF_NONEWFOLDERBUTTON begin FillChar(bi, sizeof(bi), #0); with bi do begin if curdir <> '' then StrPCopy(ResStr,curdir) else StrPCopy(ResStr,GetCurrentDir); FEditValue := resstr; FEditPos := Point(hr.Left,hr.Bottom); hwndOwner := Application.Handle; pszDisplayName := ResStr; lpszTitle := PChar('Select directory'); ulFlags := BIF_RETURNONLYFSDIRS; lpfn := EditCallBack; lParam := Integer(Self); end; iIdList := Nil; try iIdList := SHBrowseForFolder(bi); except end; if iIdList <> Nil then begin try FillChar(ResStr,sizeof(ResStr),#0); if SHGetPathFromIDList (iIdList, ResStr) then begin s := resstr; if Assigned(OnParamChanged) then OnParamChanged(Self, Node, param, curdir, s); UpdateParam(Param,ResStr); end; finally SHGetMalloc(MAlloc); Malloc.Free(iIdList); end; end; end; procedure TParamTreeview.EditParam(href: string); var tn: TTreeNode; begin tn := GetParamRefNode(href); if Assigned(tn) then begin Selected := tn; Selected.Expanded :=true; StartParamEdit(href, tn, GetParamRect(href)); end; end; function TParamTreeview.GetParamRefNode(href: string): TTreeNode; var i: Integer; tn: TTreeNode; begin Result := nil; for i := 1 to Items.Count do begin tn := Items[i - 1]; if ParamNodeIndex[tn, href] <> -1 then begin Result := tn; Break; end; end; end; function TParamTreeview.GetParameter(href: string): string; var tn: TTreeNode; begin Result := ''; tn := ParamRefNode[href]; if Assigned(tn) then Result := NodeParameter[tn,href]; end; procedure TParamTreeview.SetParameter(href: string; const Value: string); var tn: TTreeNode; begin tn := ParamRefNode[href]; if Assigned(tn) then NodeParameter[tn,href] := Value; end; procedure TParamTreeview.SetHover(const Value: Boolean); begin FHover := Value; Invalidate; end; procedure TParamTreeView.AdvanceEdit(Sender: TObject); var idx: Integer; s,v,c,p,h: string; Node: TTreeNode; begin if not FAdvanceOnReturn then Exit; if FFocusLink = -1 then Exit; idx := FFocusLink; s := ParamNodeRefs[Selected.AbsoluteIndex,idx]; idx := ParamIndex[s]; if idx < ParamRefCount - 1 then inc(idx) else idx := 0; s := ParamRefs[idx]; if (s <> '') then begin Node := ParamRefNode[s]; Selected := Node; FFocusLink := ParamNodeIndex[Node, s]; GetParamInfo(Node, s, v, c, p, h); if c <> '' then StartParamEdit(s,Node,GetParamRect(s)); end; end; function TParamTreeview.GetParamIndex(href: string): Integer; var i: Integer; begin Result := -1; for i := 1 to ParamRefCount do begin if StrIComp(pchar(ParamRefs[i - 1]),pchar(href))=0 then begin Result := i - 1; Break; end; end; end; procedure TParamTreeview.Change(Node: TTreeNode); begin inherited; if FFocusLink >= GetParamNodeRefCount(Node) then FFocusLink := 0; end; function TParamTreeview.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TParamTreeview.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TParamTreeview.SetVersion(const Value: string); begin end; end.
unit MMO.Client; interface uses IdTcpClient, MMO.Packet, Classes, SysUtils, MMO.ClientReadThread, MMO.PacketReader, MMO.Types, IdComponent; type TClient = class abstract private var m_client: TIdTcpClient; var m_clientReadThread: TClientReadThread; procedure OnClientConnected(sender: TObject); procedure OnClientDisconnected(sender: TObject); procedure OnClientRead(const sender: TObject; const packetReader: TPacketReader); procedure OnClientStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); protected constructor Create(host: string; port: UInt16); destructor Destroy; override; procedure Connect; procedure Disconnect; procedure Send(packet: TPacket); procedure OnConnected; virtual; procedure OnDisconnected; virtual; procedure OnReceivePacket(const packetReader: TPacketReader); virtual; procedure Sleep(ms: Integer); end; implementation uses Rtti; constructor TClient.Create(host: string; port: UInt16); begin inherited Create; m_client := TIdTcpClient.Create(nil); m_client.Port := port; m_client.Host := host; // m_client.OnBeforeBind // m_client.OnAfterBind // m_client.OnSocketAllocated m_client.OnConnected := OnClientConnected; m_client.OnDisconnected := OnClientDisconnected; // m_client.OnWork // m_client.OnWorkBegin // m_client.OnWorkEnd m_client.OnStatus := OnClientStatus; m_clientReadThread := TClientReadThread.Create('Client', m_client); m_clientReadThread.OnRead := OnClientRead; end; destructor TClient.Destroy; begin m_client.Free; m_clientReadThread.Free; inherited; end; procedure TClient.Connect; begin m_client.Connect; m_clientReadThread.Start; end; procedure TClient.Disconnect; begin m_clientReadThread.Terminate; m_client.Disconnect; end; procedure TClient.Send(packet: TPacket); var memoryStream: TMemoryStream; dataSize: UInt32; memory: Pointer; packetHeader: TPacketHeader; begin dataSize := packet.GetSize; if dataSize = 0 then begin Exit; end; memory := packet.Memory; packetHeader.Size := dataSize; memoryStream := TMemoryStream.Create; memoryStream.Write(packetHeader, SizeOfTpacketHeader); memoryStream.Write(memory^, dataSize); m_client.IOHandler.Write(memoryStream); memoryStream.Free; end; procedure TClient.OnClientConnected(sender: TObject); begin OnConnected; end; procedure TClient.OnClientDisconnected(sender: TObject); begin OnDisconnected; end; procedure TClient.OnClientStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin //WriteLn(String.Format('TClient.OnClientStatus %s', [TRttiEnumerationType.GetName(AStatus)])); case AStatus of hsResolving: ; hsConnecting: ; hsConnected: ; hsDisconnecting: ; hsDisconnected: begin OnDisconnected; end; hsStatusText: ; ftpTransfer: ; ftpReady: ; ftpAborted: ; end; end; procedure TClient.OnClientRead(const sender: TObject; const packetReader: TPacketReader); begin OnReceivePacket(packetReader); end; procedure TClient.OnConnected; begin end; procedure TClient.OnDisconnected; begin end; procedure TClient.OnReceivePacket(const packetReader: TPacketReader); begin end; procedure TClient.Sleep(ms: Integer); begin m_clientReadThread.Sleep(ms); end; end.
unit evDecorStyleEliminator; {$Include ..\Everest\evDefine.inc} interface uses evdLeafParaFilter, k2Base, l3Variant, k2Interfaces ; type TevDecorStyleEliminator = class(TevdLeafParaFilter) public DocID : Integer; NeedCorrect : Boolean; protected procedure LogDocID(aStyle : Integer); procedure DoAddAtomEx(AtomIndex: Integer; const Value: Tk2Variant); override; protected // overridden protected methods function ParaTypeForFiltering: Tk2Type; override; {* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация } procedure DoWritePara(aLeaf: Tl3Variant); override; {* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца } end;//TevDecorStyleEliminator implementation uses TextPara_Const, k2Tags, Formula_Const, evdTypes, l3_String {$If defined(k2ForEditor)} , evParaTools {$IfEnd} //k2ForEditor , l3Base, Segment_Const, StrUtils, SysUtils, l3String, evdStyles, Document_Const, ObjectSegment_Const, Hyperlink_Const, vtDebug ; // start class TevDecorStyleEliminator procedure TevDecorStyleEliminator.LogDocID(aStyle : Integer); begin dbgAppendToLogLn(ChangeFileExt(ParamStr(0), '.num'), ClassName + ' ' + IntToStr(DocID) + ' : ' + IntToStr(aStyle)); NeedCorrect := true; end; procedure TevDecorStyleEliminator.DoAddAtomEx(AtomIndex: Integer; const Value: Tk2Variant); begin if CurrentType.IsKindOf(k2_typDocument) then begin case AtomIndex of k2_tiInternalHandle: if (Value.AsInteger > 0) then DocID := Value.AsInteger; end;//case AtomIndex end;//CurrentType.IsKindOf(k2_typDocument) inherited; end; function TevDecorStyleEliminator.ParaTypeForFiltering: Tk2Type; begin Result := k2_typTextPara; end;//TevDecorStyleEliminator.ParaTypeForFiltering procedure TevDecorStyleEliminator.DoWritePara(aLeaf: Tl3Variant); var l_Objects : Tl3Variant; l_Index : Integer; l_O : Tl3Variant; l_Style : Integer; begin ///if evHasText(aLeaf) then begin l_Objects := aLeaf.rAtomEx([k2_tiSegments, k2_tiChildren, k2_tiHandle, Ord(ev_slView)]); if l_Objects.IsValid AND (l_Objects.ChildrenCount > 0) then begin l_Index := 0; while (l_Index < l_Objects.ChildrenCount) do begin l_O := l_Objects.Child[l_Index]; if not l_O.IsKindOf(k2_typObjectSegment) then if not l_O.IsKindOf(k2_typHyperlink) then if l_O.HasSubAtom(k2_tiStyle) then begin l_Style := l_O.IntA[k2_tiStyle]; if (l_Style > 0) OR (l_Style = ev_saNormalTable) OR (l_Style = ev_saNormalSBSLeft) OR (l_Style = ev_saNormalSBSRight) OR (l_Style = ev_saCenteredTable) OR (l_Style = ev_saNormalTableList) OR (l_Style = ev_saUserComment) OR (l_Style = ev_saContents) OR (l_Style = ev_saToLeft) OR (l_Style = ev_saAddedText) OR (l_Style = ev_saDeletedText) OR (l_Style = ev_saChatHeaderSender) OR (l_Style = ev_saChatHeaderRecipient) OR (l_Style = ev_saColorSelectionForBaseSearch) OR (l_Style = ev_saTechComment) OR (l_Style = ev_saTxtNormalANSI) OR (l_Style = ev_saTxtNormalOEM) OR (l_Style = ev_saANSIDOS) OR (l_Style = ev_saNormalNote) OR (l_Style = ev_saNormalAnno) OR (l_Style = ev_saChangesInfo) OR (l_Style = ev_saTxtHeader1) OR (l_Style = ev_saTxtHeader2) OR (l_Style = ev_saTxtHeader3) OR (l_Style = ev_saTxtHeader4) OR (l_Style = ev_saArticleHeader) OR (l_Style = ev_saInterface) OR (l_Style = ev_saDialogs) OR (l_Style = ev_saActiveHyperlink) OR (l_Style = ev_saSnippet) OR (l_Style = ev_saAbolishedDocumentLink) OR (l_Style = ev_saVisitedDocumentInList) OR (l_Style = ev_saVisitedSnippetInList) OR (l_Style = ev_saExpandedText) OR (l_Style = ev_saObject) OR (l_Style = ev_saMistake) OR (l_Style = ev_saMainMenuConstPath) OR (l_Style = ev_saMainMenuChangePath) OR (l_Style = ev_saMainMenuHeader) OR (l_Style = ev_saMainMenuInteractiveHeader) OR (l_Style = ev_saMainMenu) then begin LogDocID(l_Style); l_O.AttrW[k2_tiStyle, nil] := nil; end; end;//l_O.HasSubAtom(k2_tiStyle) Inc(l_Index); end;//while l_Index end;//l_Objects.IsValid end;//evHasText(aLeaf) inherited; end;//TevDecorStyleEliminator.DoWritePara end.
{ This is a personal project that I give to community under this licence: Copyright 2016 Eric Buso (Alias Caine_dvp) 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 UCommons; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface Uses SysUtils, Variants, Classes,StrUtils; type TLogsInfo = record IpAddress , Domain , DateTime , FileRequest:String; FileSize , Code : Integer; case IsBot: boolean of True : (BotName : String[255]); False : (Referrer: String[255]; Country : String[15]; Browser : String[15]; OS : String[15]; UserAgentInfos:String[255]; ); end; { TLogParser } { TLogStats } TLogStats = Class(Tobject) private FUniqueIP: array[1..10000] of string; FLastIP : integer; public function UniqueIPCounter(const LogsInfo: TLogsInfo) : integer; end; TLogParser = class(Tobject) private FLogsInfo : TLogsInfo; FSplitted , FRobotsIp,FUserAgentSplit : TStringList; function GetIsBot: Boolean; function TrimFileRequest (const Request : String) : String; function TrimBotName(const UserAgentInfos : String):String; Procedure TrimUserAgentInfos(const UserAgentInfos : String); Procedure TrimCountry(Const CountryInfos : String); Procedure Clear; public constructor Create; destructor Destroy; override; property IsBot : Boolean Read GetIsBot; property LogInfos : TLogsInfo Read FLogsInfo; function ParseLine (const Line : String): Boolean; function SqlTimeStamp(const TimeStamp : String) : String; end; implementation Uses Math; { TLogStats } function TLogStats.UniqueIPCounter(const LogsInfo: TLogsInfo): integer; begin {Accumuler le nombre d'adresses IP uniques} //if Self.FUniqueIP[FLastIP] end; { TLogParser } procedure TLogParser.Clear; begin With Self.FLogsInfo Do Begin IpAddress := EmptyStr; Domain := EmptyStr; DateTime := EmptyStr; FileRequest := EmptyStr; FileSize :=0; Code :=0; BotName := EmptyStr; Referrer:= EmptyStr; Country := EmptyStr; Browser := EmptyStr; OS := EmptyStr; End; end; constructor TLogParser.Create; begin inherited; FSplitted := TStringlist.Create; FRobotsIP := TStringlist.Create; FUserAgentSplit := TStringlist.Create; end; destructor TLogParser.Destroy; begin FreeAndNil(FSplitted); FreeAndNil(FRobotsIP); FreeAndNil(FUserAgentSplit); inherited; end; function TLogParser.GetIsBot: Boolean; begin result := FLogsInfo.IsBot; end; function TLogParser.ParseLine(const Line: String): Boolean; Var IsABot : Boolean; Str : String; begin Result := False; IsABot := False; FSplitted.Clear ; FSplitted.Delimiter := ' '; FSplitted.DelimitedText := Line; // Seules les informations sur les fichiers html ou robots.txt nous intéressent. // Note : lorsque le fichier demandé est '/', il correspond à index.html // Les fichier images, CSS, javascipt, etc ne sont pas parser. If (Pos('.html',FSplitted[5]) >0) or (Pos('.txt',FSplitted[5])>0) or (Pos(' / ',FSplitted[5])>0)Then //DROP If (Pos('?',FSplitted[5])=0) or (Pos('.css',FSplitted[5])=0) or (Pos('.jpg',FSplitted[5])=0) or (Pos('.js',FSplitted[5]) =0) or (Pos('.gif',FSplitted[5]) =0) Then Begin //Reset des anciennes informations. Self.Clear; //Indiquer à l'appelant que le fichier est parsé. Result:=True; With Self.FLogsInfo Do Begin //Addresse IP IpAddress := Trim(FSplitted[0]); //Nom de domaine recherché Domain := Trim(FSplitted[1]); //Extraire la date et l'heure Str := Trim(FSplitted[3]); Str := Copy(Str,2,Length(Str)-1);//Sauter le '[' résiduel. //TODO SqlTimeStamp renvoit 03 pour May!!! DateTime := SqlTimeStamp(Str); //Page demandée par le navigateur FileRequest:= TrimFileRequest(FSplitted[5]); //Code envoyé par le serveur Appache -200=OK, 404= non trouvée, 503=En maitenance, 301=Redirection Code := StrToInt(Trim(FSplitted[6])); //Extraction et convertion de la taille en octet de la page. FileSize := -1; try If (Code = 200) Then FileSize := StrToInt(Trim(FSplitted[7])); Except FileSize := -1; end; //L'adresse IP est déjà connu comme robot pour ce log. IsABot := FRobotsIp.IndexOf(IpAddress) >= 0; // Rechercher si le fichier robot.txt a été demandé pour cette adresse IP If (Pos('/robots.txt',FSplitted[5]) >0) or (IsABot) Then Begin IsBot := True; //Stoquer l'adresse IP correspondant au robot. If FRobotsIp.IndexOf(IpAddress) =-1 Then FRobotsIp.Add(IpAddress); //Extraire le nom du robot //OLD BotName := TrimBotName(FSplitted[9]); BotName := FSplitted[9]; End Else Begin // Attention, cas d'un robot qui ne demande pas 'robots.txt'; // Dans ce use case, il est certain que l'IP n'est pas celle d'un robot. // 2ème cas du test : Match robot sur User agent info vide (égal à "-"). if (Pos('Bot',FSplitted[9])>0) or (Pos('crawl',FSplitted[9])>0) or (Pos('Bot',FSplitted[9])>0) or (Pos('bot',FSplitted[9])>0) or (Pos('spider',FSplitted[9])>0) or ( CompareStr('-',FSplitted[9]) = 0) then Begin IsBot := True; FRobotsIp.Add(IpAddress); //OLD BotName := TrimBotName(FSplitted[9]); BotName := FSplitted[9]; Exit; End; IsBot := False; Referrer := Trim(FSplitted[8]); Str := Referrer; //OLD TrimUserAgentInfos(FSplitted[9]); UserAgentInfos := FSplitted[9]; Str := UserAgentInfos; End; End; End; end; //Transformer une date DD/MMM/YYYY:HH:MM:SS (format windows, // MMM est une string (DEC par exemple)) // en format Sql Timestamp : YYYY-MM-DD HH:MM:SS function TLogParser.SqlTimeStamp(const TimeStamp: String): String; var Day,Month,Year : String; begin Result := EmptyStr; SetLength(Result,20); Day := Copy(TimeStamp,1,2); Month := Copy(TimeStamp,4,3); // Transformer Month en chiffres. //'Jan'->1,'Feb'->2,'Mar'->3,'Apr'->4,'May'->5,'Jun'->6,'Jul'->7,'Aug'->8 //'Sep'->9,'Oct'->10,'Nov'->11,'Dec'->12 Case Month[1] of 'J': If Month[2]='a' then Month := '01' Else if Month[3]='n' then Month := '06' Else Month := '07'; 'F': Month := '02'; 'M': If Month[3]='y' then Month := '05' Else Month := '03'; 'A': If Month[2]='p' Then Month := '04' Else Month := '08'; 'S': Month := '09'; 'O': Month := '10'; 'N': Month := '11'; 'D': Month := '12'; End; Year := Copy(TimeStamp,8,4); Result := Year+'-'+Month+'-'+Day+' ' + Copy(TimeStamp,13,9); end; procedure TLogParser.TrimCountry(const CountryInfos: String); Var I,L:Integer; CountryInfosTrim:String; begin L:=Length(CountryInfos); // Cas où le pay est remplacé par une chaîne d'info, souvent avec au moins un chiffre. For I:= 1 To L Do If CountryInfos[I] in ['0'..'9'] Then Begin Self.FLogsInfo.Country := '-'; Exit; End; //Unification des chaînes de pays. CountryInfosTrim := Trim(LowerCase(CountryInfos)); If CompareStr(CountryInfosTrim,'fr-fr')=0 then Begin Self.FLogsInfo.Country := 'fr'; Exit; End; If CompareStr(CountryInfosTrim,'eng-us')=0 then Begin Self.FLogsInfo.Country := 'usa'; Exit;End; Self.FLogsInfo.Country := CountryInfosTrim; end; function TLogParser.TrimFileRequest(const Request: String): String; var start,L,P : Integer; begin If Pos(' / ',request) > 0 Then Begin result := 'index.html'; Exit;End; start := Pos(' /',request); L := Length(request); P := start+2; Repeat If Request[P] = ' ' Then Break; Inc(P); Until P = L; Result := Copy(request,start+2,p-start-2); end; function TLogParser.TrimBotName(const UserAgentInfos: String):String; var start,Cnt,Ex : Integer; begin { start := Pos('Bot', UserAgentInfos ); If start = 0 Then Begin start := Pos('bot', UserAgentInfos ); End; If start >0 Then Begin Ex := PosEx(' ',UserAgentInfos,start); Cnt:=start; Repeat Dec(Cnt); until (UserAgentInfos[Cnt] =' ') Or (Cnt >0); End ; If (Ex = 0) And (Cnt = 0) Then Begin Result:= UserAgentInfos; Exit; End; end; } FUserAgentSplit.Clear; FUserAgentSplit.Delimiter := ';'; FUserAgentSplit.DelimitedText := UserAgentInfos; //Result := Copy( UserAgentInfos,Cnt,Ex); Result := FUserAgentSplit[2]; end; //Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions] procedure TLogParser.TrimUserAgentInfos(const UserAgentInfos: String); var start,Cnt{,L},Ex : Integer; begin start := Pos('(compatible; ', UserAgentInfos ); // L := Length( UserAgentInfos ); If start > 0 Then Begin //Rechercher le navigateur Cnt := Length('(compatible; '); Inc(start,Cnt); Ex := PosEx('; ',UserAgentInfos,start); If Ex = -1 Then Exit; Self.FLogsInfo.Browser := Copy(UserAgentInfos, start, Ex-Start); //Rechercher l'OS start := Ex+1; Ex := PosEx('; ',UserAgentInfos,start); Self.FLogsInfo.Os := Copy(UserAgentInfos, start, Ex-Start+1); //Rechercher le pays start := PosEx('; ',UserAgentInfos,Ex+1)+2; Ex := PosEx('; ',UserAgentInfos,start); TrimCountry(Trim(Copy(UserAgentInfos, start, Ex-Start))); End Else Begin //Rechercher l'OS start := Pos(' (', UserAgentInfos); Inc(start,Length(' (')); Ex := PosEx('; ',UserAgentInfos,start); start := Ex+1; Ex := PosEx('; ',UserAgentInfos,start); start := Ex+1; Ex := PosEx('; ',UserAgentInfos,start); Self.FLogsInfo.Os := Copy(UserAgentInfos, start, Ex-Start+1); //Rechercher le pays start := Ex+1; // Cas '( ; ;Pays; )' Ex := PosEx(';',UserAgentInfos,start); // Cas '( ; ;Pays )' If Ex = 0 Then Ex := PosEx(')',UserAgentInfos,start); TrimCountry(Trim(Copy(UserAgentInfos, start, Ex-Start))); End; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.13 27.08.2004 22:04:00 Andreas Hausladen speed optimization ("const" for string parameters) Rev 1.12 2004.05.20 1:39:16 PM czhower Last of the IdStream updates Rev 1.11 2004.05.20 11:36:58 AM czhower IdStreamVCL Rev 1.10 2004.05.20 11:13:02 AM czhower More IdStream conversions Rev 1.9 2004.05.19 3:06:42 PM czhower IdStream / .NET fix Rev 1.8 2004.02.03 5:44:04 PM czhower Name changes Rev 1.7 2004.01.22 5:56:54 PM czhower TextIsSame Rev 1.6 1/21/2004 2:20:24 PM JPMugaas InitComponent Rev 1.5 1/21/2004 1:30:10 PM JPMugaas InitComponent Rev 1.4 10/17/2003 12:41:16 AM DSiders Added localization comments. Rev 1.3 26/09/2003 01:06:18 CCostelloe CodingType property added so caller can find out if it was UUE or XXE encoded Rev 1.2 6/14/2003 03:07:20 PM JPMugaas Fixed MessageDecoder so that DecodeBegin is called right after creation and DecodeEnd is called just before destruction. I also fixed where the code was always assuming that LDecode was always being created. Rev 1.1 6/13/2003 07:58:44 AM JPMugaas Should now compile with new decoder design. Rev 1.0 11/13/2002 07:57:14 AM JPMugaas 2003-Sep-20 Ciaran Costelloe CodingType property added so caller can find out if it was UUE or XXE encoded } unit IdMessageCoderUUE; interface {$i IdCompilerDefines.inc} uses Classes, IdCoder3to4, IdMessageCoder, IdMessage, IdGlobal; type TIdMessageDecoderUUE = class(TIdMessageDecoder) protected FCodingType: string; public function ReadBody(ADestStream: TStream; var AMsgEnd: Boolean): TIdMessageDecoder; override; property CodingType: string read FCodingType; end; TIdMessageDecoderInfoUUE = class(TIdMessageDecoderInfo) public function CheckForStart(ASender: TIdMessage; const ALine: string): TIdMessageDecoder; override; end; TIdMessageEncoderUUEBase = class(TIdMessageEncoder) protected FEncoderClass: TIdEncoder3to4Class; public procedure Encode(ASrc: TStream; ADest: TStream); override; end; TIdMessageEncoderUUE = class(TIdMessageEncoderUUEBase) protected procedure InitComponent; override; end; TIdMessageEncoderInfoUUE = class(TIdMessageEncoderInfo) public constructor Create; override; end; implementation uses IdCoderUUE, IdCoderXXE, IdException, IdGlobalProtocols, IdResourceStringsProtocols, SysUtils; { TIdMessageDecoderInfoUUE } function TIdMessageDecoderInfoUUE.CheckForStart(ASender: TIdMessage; const ALine: string): TIdMessageDecoder; var LPermissionCode: integer; begin Result := nil; if TextStartsWith(ALine, 'begin ') and CharEquals(ALine, 10, ' ') then begin {Do not Localize} LPermissionCode := IndyStrToInt(Copy(ALine, 7, 3), 0); if LPermissionCode > 0 then begin Result := TIdMessageDecoderUUE.Create(ASender); with TIdMessageDecoderUUE(Result) do begin FFilename := Copy(ALine, 11, MaxInt); FPartType := mcptAttachment; end; end; end; end; { TIdMessageDecoderUUE } function TIdMessageDecoderUUE.ReadBody(ADestStream: TStream; var AMsgEnd: Boolean): TIdMessageDecoder; var LDecoder: TIdDecoder4to3; LLine: string; LMsgEnd: Boolean; begin AMsgEnd := False; Result := nil; LLine := ReadLnRFC(LMsgEnd, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); if LMsgEnd then begin Exit; end; LDecoder := nil; if Length(LLine) > 0 then begin case LLine[1] of #32..#85: begin {Do not Localize} // line length may be from 2 (first char + newline) to 65, // this is 0 useable to 63 usable bytes, + #32 gives this as a range. // (yes, the line length is encoded in the first bytes of each line!) LDecoder := TIdDecoderUUE.Create(nil); LDecoder.DecodeBegin(ADestStream); FCodingType := 'UUE'; {do not localize} end; 'h': begin {do not localize} LDecoder := TIdDecoderXXE.Create(nil); LDecoder.DecodeBegin(ADestStream); FCodingType := 'XXE'; {do not localize} end; else begin raise EIdException.Create(RSUnrecognizedUUEEncodingScheme); end; end; end; try if Assigned(LDecoder) then begin repeat if (Length(Trim(LLine)) = 0) or (LLine = String(LDecoder.FillChar)) then begin // UUE: Comes on the line before end. Supposed to be `, but some put a // blank line instead end else begin LDecoder.Decode(LLine); end; LLine := ReadLnRFC(LMsgEnd, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); until TextIsSame(Trim(LLine), 'end') or LMsgEnd; {Do not Localize} LDecoder.DecodeEnd; end; finally FreeAndNil(LDecoder); end; end; { TIdMessageEncoderInfoUUE } constructor TIdMessageEncoderInfoUUE.Create; begin inherited; FMessageEncoderClass := TIdMessageEncoderUUE; end; { TIdMessageEncoderUUEBase } procedure TIdMessageEncoderUUEBase.Encode(ASrc: TStream; ADest: TStream); var LEncoder: TIdEncoder3to4; begin ASrc.Position := 0; WriteStringToStream(ADest, 'begin ' + IntToStr(PermissionCode) + ' ' + Filename + EOL); {Do not Localize} LEncoder := FEncoderClass.Create(nil); try while ASrc.Position < ASrc.Size do begin LEncoder.Encode(ASrc, ADest, 45); WriteStringToStream(ADest, EOL); end; WriteStringToStream(ADest, LEncoder.FillChar + EOL + 'end' + EOL); {Do not Localize} finally FreeAndNil(LEncoder); end; end; { TIdMessageEncoderUUE } procedure TIdMessageEncoderUUE.InitComponent; begin inherited; FEncoderClass := TIdEncoderUUE; end; initialization TIdMessageDecoderList.RegisterDecoder('UUE', TIdMessageDecoderInfoUUE.Create); {Do not Localize} TIdMessageEncoderList.RegisterEncoder('UUE', TIdMessageEncoderInfoUUE.Create); {Do not Localize} end.
unit uDmPai; interface uses System.SysUtils, System.Classes, Datasnap.DBClient, Data.DB; type TCampo = record Nome: string; Descricao: string; Tipo: TFieldType; Tamanho: Integer; procedure Limpa; end; TCamposArray = array of TCampo; TdmPai = class(TDataModule) private { Private declarations } protected procedure criarCDS(cds: TClientDataSet; campos :array of TCampo); public { Public declarations } end; var dmPai: TdmPai; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmPai } procedure TdmPai.criarCDS(cds: TClientDataSet; campos :array of TCampo); var index, minimo, maximo: Integer; begin cds.Close; minimo := Low(Campos); maximo := High(Campos); for index := minimo to maximo do begin with cds.FieldDefs.AddFieldDef do begin Name := Campos[index].Nome; DataType := Campos[index].Tipo; Size := Campos[index].Tamanho; DisplayName := Campos[index].Descricao; end; end; cds.IndexFieldNames := 'CODIGO'; cds.CreateDataSet; end; { TCampo } procedure TCampo.Limpa; begin Nome := ''; Descricao := ''; Tipo := ftUnknown; Tamanho := 0; end; end.
unit VisualClassesData; interface function GetVisualRootPath : string; procedure SetVisualRootPath(const aPath : string); implementation uses Windows, Registry; var VisualRoot : string = ''; const tidVisualRoot = '\Software\Oceanus\Five\VisualClasses'; function ReadVisualClassRoot : string; var Reg : TRegistry; begin Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; try if Reg.OpenKey(tidVisualRoot, false) then result := Reg.ReadString('RootPath') else result := ''; finally Reg.Free; end; end; procedure WriteVisualClassRoot(aRootPath : string); var Reg : TRegistry; begin Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; try if Reg.OpenKey(tidVisualRoot, true) then Reg.WriteString('RootPath', aRootPath) finally Reg.Free; end; end; function GetVisualRootPath : string; begin if VisualRoot = '' then VisualRoot := ReadVisualClassRoot; result := VisualRoot; end; procedure SetVisualRootPath(const aPath : string); begin if aPath[length(aPath)] = '\' then VisualRoot := aPath else VisualRoot := aPath + '\'; WriteVisualClassRoot(VisualRoot); end; end.
unit uFunctions; interface uses System.SysUtils, System.Classes, IPPeerClient, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, REST.Types, System.JSON, System.Generics.Collections, FMX.Maps, System.UITypes, uMapa, uDM; type TDestino = class private FDestino: string; public property Destino: string read FDestino write FDestino; end; TListaDestinos = TObjectList<TDestino>; TAtributosRotas = class private FKeyMaps: string; FListaDestinos: TListaDestinos; public property ListaDestinos: TListaDestinos read FListaDestinos write FListaDestinos; procedure AddCircle(pLatitude, pLongitude: Double); procedure AddMarca(pLatitude, pLongitude: Double; pDescricao: string); procedure AddPolyline(pPontosline: System.TArray<FMX.Maps.TMapCoordinate>); procedure BuscarCoordenadasMarcas(pEndereco, pDescricao: string); function GetParadas(pOrdem: Integer): string; end; TRota = class private class var FRota: TAtributosRotas; class function GetRota: TAtributosRotas; static; public class destructor Destroy; class property Rota: TAtributosRotas read GetRota; end; implementation uses FMX.Graphics; { TAtributosRotas } procedure TAtributosRotas.AddCircle(pLatitude, pLongitude: Double); var lCircleDescritor: TMapCircleDescriptor; lMapCoordinate: TMapCoordinate; begin lMapCoordinate := TMapCoordinate.Create(pLatitude, pLongitude); lCircleDescritor := TMapCircleDescriptor.Create(lMapCoordinate, 2); lCircleDescritor.Center := lMapCoordinate; lCircleDescritor.FillColor := TAlphaColorRec.Lightpink; lCircleDescritor.StrokeColor := TAlphaColorRec.Hotpink; lCircleDescritor.StrokeWidth := 2; if Assigned(F_GMaps.MapView1) then F_GMaps.MapView1.AddCircle(lCircleDescritor); end; procedure TAtributosRotas.AddMarca(pLatitude, pLongitude: Double; pDescricao: string); var lMarca: TMapMarkerDescriptor; begin lMarca := TMapMarkerDescriptor.Create(TMapCoordinate.Create(pLatitude, pLongitude), pDescricao); lMarca.Rotation := 0; lMarca.Snippet := 'Detalhes '+pDescricao; lMarca.Appearance := TMarkerAppearance.Billboard; if Assigned(F_GMaps.MapView1) then F_GMaps.MapView1.AddMarker(lMarca); end; procedure TAtributosRotas.AddPolyline(pPontosline: System.TArray<FMX.Maps.TMapCoordinate>); var lPolyline: TMapPolylineDescriptor; begin lPolyline := TMapPolylineDescriptor.Create(pPontosline); lPolyline.Points.Points := pPontosline; lPolyline.StrokeColor := TAlphaColorRec.steelblue; lPolyline.StrokeWidth := 10; lPolyline.Geodesic := true; F_GMaps.MapView1.AddPolyline(lPolyline); end; function TAtributosRotas.GetParadas(pOrdem: Integer): string; var lParadas: string; begin if ListaDestinos.Count > 1 then begin lParadas := ListaDestinos[0].Destino; for var cont := 1 to ListaDestinos.Count-2 do lParadas := lParadas +'|'+ ListaDestinos[cont].Destino; end; Result := lParadas; end; procedure TAtributosRotas.BuscarCoordenadasMarcas(pEndereco, pDescricao: string); begin DM.ConfigMarcas(pEndereco); if DM.GetStatusRetorno('marca') then begin AddMarca(DM.GetLatitude, DM.GetLongitude, pDescricao); end; end; { TRotas } class destructor TRota.Destroy; begin FRota.Free; end; class function TRota.GetRota: TAtributosRotas; begin if FRota = nil then FRota := TAtributosRotas.Create; Result := FRota; end; end.
unit Model.Bancos; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, System.SysUtils, Control.Sistema, System.Variants; type TBancos = class private FCodigo: String; FNome: String; FConexao: TConexao; FAcao: TAcao; FQuery: TFDQuery; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public Constructor Create(); property Codigo: String read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Acao: TAcao read FAcao write FAcao; property Query: TFDQuery read FQuery write FQuery; function GetField(sField: String; sKey: String; sKeyValue: String): String; function SetupModel(FDBanco: TFDQuery): Boolean; function Localizar(aParam: array of variant): TFDQuery; function LocalizarExt(aParam: array of variant): Boolean; function Gravar(): Boolean; end; const TABLENAME = 'tbbancos'; SQLINSERT = 'insert into ' + TABLENAME + ' (cod_banco, nom_banco) values (:cod_banco, :nom_banco);'; SQLUPDATE = 'update ' + TABLENAME + ' set nom_banco = nom_banco where cod_banco = :cod_banco'; implementation { TBancos } function TBancos.Alterar: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE, [Nome, Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TBancos.Create; begin FConexao := TConexao.Create; end; function TBancos.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_banco = :pcod_banco', [Codigo]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end;end; function TBancos.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try Result := ''; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FDQuery.Open(); if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString; finally FDQuery.Free; end; end; function TBancos.Gravar: Boolean; begin Result := False; case FAcao of tacAlterar: Result := Alterar(); tacIncluir: Result := Inserir(); tacExcluir: Result := Excluir(); end; end; function TBancos.Inserir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLINSERT, [Codigo, Nome]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBancos.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_banco = :pcod_banco'); FDQuery.ParamByName('pcod_banco').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('where nom_banco = :pnom_banco'); FDQuery.ParamByName('pnom_banco').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TBancos.LocalizarExt(aParam: array of variant): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_banco = :pcod_banco'); FDQuery.ParamByName('pcod_banco').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('where nom_banco = :pnom_banco'); FDQuery.ParamByName('pnom_banco').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); if FDQuery.IsEmpty then begin Exit; end; FQuery := FDQuery; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBancos.SetupModel(FDBanco: TFDQuery): Boolean; begin try Codigo := FDBanco.FieldByName('cod_banco').AsString; Nome := FDBanco.FieldByName('nom_banco').AsString; finally Result := True; end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; edt_m: TEdit; edt_n: TEdit; M: TLabel; N: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure GetGCD(m:integer;n:integer); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var m,n,temp: integer; begin m := strtoint(trim(edt_m.Text)); n := strtoint(trim(edt_n.Text)); if n>m then begin temp := m; m := n; n := temp; end; GetGCD(m,n); end; procedure TForm1.GetGCD(m:integer;n:integer); var r: integer; begin if (m Mod n)=0 then Memo1.Lines.Add(trim(edt_m.Text)+' 与 '+trim(edt_n.Text)+' 的最大公约数为 '+inttostr(n)) else begin r := m Mod n; Memo1.Lines.Add('被除数m: '+inttostr(m)+'; 除数n:'+inttostr(n)+'; 余数r: '+inttostr(r)); m := n; n := r; GetGCD(m,n); end; end; end.
unit iOSXIBResource; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LCLMemManager, forms, dom, XMLRead,XMLWrite, ProjectIntf, UnitResources; type { TXIBResourcefileFormat } TXIBResourcefileFormat = class(TUnitResourcefileFormat) public class function FindResourceDirective(Source: TObject): boolean; override; class function ResourceDirectiveFilename: string; override; class function GetUnitResourceFilename(AUnitFilename: string; Loading: boolean): string; override; class procedure TextStreamToBinStream(ATxtStream, ABinStream: TExtMemoryStream); override; class procedure BinStreamToTextStream(ABinStream, ATextStream: TExtMemoryStream); override; class function GetClassNameFromStream(s: TStream; out IsInherited: Boolean): shortstring; override; class function CreateReader(s: TStream; var DestroyDriver: boolean): TReader; override; class function CreateWriter(s: TStream; var DestroyDriver: boolean): TWriter; override; class function QuickCheckResourceBuffer(PascalBuffer, LFMBuffer: TObject; out LFMType, LFMComponentName, LFMClassName: string; out LCLVersion: string; out MissingClasses: TStrings): TModalResult; override; end; implementation uses CodeCache, CodeToolManager, BasicCodeTools, ios_views; { TXIBResourcefileFormat } class function TXIBResourcefileFormat.FindResourceDirective(Source: TObject): boolean; var cb: TCodeBuffer; nx,ny,nt: integer; r,p: integer; begin r := FindNextCompilerDirectiveWithName((source as TCodeBuffer).Source, -1, 'FakeResource', False, p); result := (r > -1) end; class function TXIBResourcefileFormat.ResourceDirectiveFilename: string; begin result := '*.xib'; end; class function TXIBResourcefileFormat.GetUnitResourceFilename( AUnitFilename: string; Loading: boolean): string; begin result := ChangeFileExt(AUnitFilename,'.xib'); end; class procedure TXIBResourcefileFormat.TextStreamToBinStream(ATxtStream, ABinStream: TExtMemoryStream); begin ABinStream.LoadFromStream(ATxtStream); end; class procedure TXIBResourcefileFormat.BinStreamToTextStream(ABinStream, ATextStream: TExtMemoryStream); begin ATextStream.LoadFromStream(ABinStream); end; class function TXIBResourcefileFormat.GetClassNameFromStream(s: TStream; out IsInherited: Boolean): shortstring; begin result := 'TAppDelegate_iPhone'; end; class function TXIBResourcefileFormat.CreateReader(s: TStream; var DestroyDriver: boolean): TReader; begin result := TXIBReader.Create(S, 4096); end; class function TXIBResourcefileFormat.CreateWriter(s: TStream; var DestroyDriver: boolean): TWriter; begin result := TWriter.Create(TNIBObjectWriter.Create(s)); end; class function TXIBResourcefileFormat.QuickCheckResourceBuffer(PascalBuffer, LFMBuffer: TObject; out LFMType, LFMComponentName, LFMClassName: string; out LCLVersion: string; out MissingClasses: TStrings): TModalResult; var ms: TStream; XMLDocument: TXMLDocument; RO, CR, OO, MO : TDOMElement; i: int64; b: boolean; AnElement: TDOMElement; begin ms := TStringStream.Create((LFMBuffer as TCodeBuffer).Source); try ObtainBaseObjectInfoFromXIB(ms, XMLDocument, RO, CR, OO, MO,i, b); try AnElement := FindKeyNode(MO,'string','objectName'); if assigned(AnElement) then LFMComponentName:=AnElement.TextContent; finally XMLDocument.Free; end; finally ms.Free; end; LCLVersion:='1.1'; LFMType:='unknown'; LFMClassName:='TAppDelegate_iPhone'; end; end.
unit WinSockRDOConnectionsServer; interface uses Windows, Classes, SyncObjs, SmartThreads, SocketComp, RDOInterfaces; type TWinSockRDOConnectionsServer = class( TInterfacedObject, IRDOServerConnection, IRDOConnectionsServer ) private fQueryServer : IRDOQueryServer; fSocketComponent : TServerSocket; fMsgLoopThread : TSmartThread; fEventSink : IRDOConnectionServerEvents; fQueryQueue : TList; fQueryWaiting : THandle; fQueryQueueLock : TCriticalSection; fMaxQueryThreads : integer; fQueryThreads : TList; fTerminateEvent : THandle; // these variables are only for debug fReceivedQueries : integer; // public constructor Create( Prt : integer ); destructor Destroy; override; protected procedure SetQueryServer( const QueryServer : IRDOQueryServer ); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads( MaxQueryThreads : integer ); protected procedure StartListening; procedure StopListening; function GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection; procedure InitEvents( const EventSink : IRDOConnectionServerEvents ); private procedure ClientConnected( Sender : TObject; Socket : TCustomWinSocket ); procedure ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket ); procedure DoClientRead( Sender : TObject; Socket : TCustomWinSocket ); procedure HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); end; implementation uses SysUtils, WinSock, RDOProtocol, RDOUtils, {$IFDEF Logs} LogFile, {$ENDIF} ErrorCodes, RDOQueryServer, WinSockRDOServerClientConnection; type TSocketData = record RDOConnection : IRDOConnection; Buffer : string; end; PSocketData = ^TSocketData; type TQueryToService = record Text : string; Socket : TCustomWinSocket; end; PQueryToService = ^TQueryToService; type TServicingQueryThread = class( TSmartThread ) private fConnectionsServer : TWinSockRDOConnectionsServer; public constructor Create( theConnServer : TWinSockRDOConnectionsServer ); procedure Execute; override; end; type TMsgLoopThread = class( TSmartThread ) private fRDOConnServ : TWinSockRDOConnectionsServer; public constructor Create( RDOConnServ : TWinSockRDOConnectionsServer ); procedure Execute; override; end; // TServicingQueryThread constructor TServicingQueryThread.Create( theConnServer : TWinSockRDOConnectionsServer ); begin fConnectionsServer := theConnServer; inherited Create( false ) end; procedure TServicingQueryThread.Execute; var QueryResult : string; QueryToService : PQueryToService; QueryThreadEvents : array [ 1 .. 2 ] of THandle; begin with fConnectionsServer do begin QueryThreadEvents[ 1 ] := fQueryWaiting; QueryThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin WaitForMultipleObjects( 2, @QueryThreadEvents[ 1 ], false, INFINITE ); fQueryQueueLock.Acquire; try if fQueryQueue.Count <> 0 then begin QueryToService := fQueryQueue[ 0 ]; fQueryQueue.Delete( 0 ) end else begin QueryToService := nil; ResetEvent( fQueryWaiting ) end finally fQueryQueueLock.Release end; if QueryToService <> nil then try // fQueryServer.Lock; QueryResult := fQueryServer.ExecQuery( QueryToService.Text ); // fQueryServer.Unlock; if QueryResult <> '' then try QueryToService.Socket.SendText( AnswerId + QueryResult ); {$IFDEF Logs} LogThis( 'Result : ' + QueryResult ); {$ENDIF} except {$IFDEF Logs} LogThis( 'Error sending query result' ) {$ENDIF} end else begin {$IFDEF Logs} LogThis( 'No result' ) {$ENDIF} end finally Dispose( QueryToService ) end end end end; // TMsgLoopThread constructor TMsgLoopThread.Create( RDOConnServ : TWinSockRDOConnectionsServer ); begin fRDOConnServ := RDOConnServ; // FreeOnTerminate := true; // Priority := tpHighest; inherited Create( false ) end; procedure TMsgLoopThread.Execute; var Msg : TMsg; begin with fRDOConnServ do begin try with fSocketComponent do if not Active then Active := true except {$IFDEF Logs} LogThis( 'Error establishing connection' ) {$ENDIF} end; while not Terminated do if PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) then DispatchMessage( Msg ) else MsgWaitForMultipleObjects( 1, fTerminateEvent, false, INFINITE, QS_ALLINPUT ); with fSocketComponent do Active := false end end; // TWinSockRDOConnectionsServer constructor TWinSockRDOConnectionsServer.Create( Prt : integer ); begin inherited Create; fSocketComponent := TServerSocket.Create( nil ); with fSocketComponent do begin Active := false; ServerType := stNonBlocking; Port := Prt; OnClientConnect := ClientConnected; OnClientDisconnect := ClientDisconnected; OnClientRead := DoClientRead; OnClientError := HandleError end; fQueryQueue := TList.Create; fQueryThreads := TList.Create; fQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueueLock := TCriticalSection.Create; fTerminateEvent := CreateEvent( nil, true, false, nil ) end; destructor TWinSockRDOConnectionsServer.Destroy; procedure FreeQueryQueue; var QueryIdx : integer; begin for QueryIdx := 0 to fQueryQueue.Count - 1 do Dispose( PQueryToService( fQueryQueue[ QueryIdx ] ) ); fQueryQueue.Free end; begin StopListening; fSocketComponent.Free; FreeQueryQueue; CloseHandle( fQueryWaiting ); CloseHandle( fTerminateEvent ); fQueryQueueLock.Free; {$IFDEF Logs} LogThis( 'Received queries : ' + IntToStr( fReceivedQueries ) ); {$ENDIF} inherited Destroy end; procedure TWinSockRDOConnectionsServer.SetQueryServer( const QueryServer : IRDOQueryServer ); begin fQueryServer := QueryServer end; function TWinSockRDOConnectionsServer.GetMaxQueryThreads : integer; begin Result := fMaxQueryThreads end; procedure TWinSockRDOConnectionsServer.SetMaxQueryThreads( MaxQueryThreads : integer ); begin fMaxQueryThreads := MaxQueryThreads end; procedure TWinSockRDOConnectionsServer.StartListening; var ThreadIdx : integer; begin ResetEvent( fTerminateEvent ); fMsgLoopThread := TMsgLoopThread.Create( Self ); for ThreadIdx := 1 to fMaxQueryThreads do fQueryThreads.Add( TServicingQueryThread.Create( Self ) ) end; procedure TWinSockRDOConnectionsServer.StopListening; procedure FreeQueryThreads; var ThreadIdx : integer; aQueryThread : TSmartThread; begin for ThreadIdx := 0 to fQueryThreads.Count - 1 do begin aQueryThread := TSmartThread( fQueryThreads[ ThreadIdx ] ); aQueryThread.Free end; fQueryThreads.Free end; begin SetEvent( fTerminateEvent ); // fMsgLoopThread.Terminate; fMsgLoopThread.Free; fMsgLoopThread := nil; FreeQueryThreads end; function TWinSockRDOConnectionsServer.GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection; var ConnIdx : integer; ConnCount : integer; FoundConn : IRDOConnection; UseIPAddr : boolean; CurrConn : TCustomWinSocket; CurConnRmtAddr : string; begin ConnIdx := 0; with fSocketComponent do begin ConnCount := Socket.ActiveConnections; FoundConn := nil; if inet_addr( PChar( ClientAddress ) ) = INADDR_NONE then UseIPAddr := false else UseIPAddr := true; while ( ConnIdx < ConnCount ) and ( FoundConn = nil ) do begin CurrConn := Socket.Connections[ ConnIdx ]; if UseIPAddr then CurConnRmtAddr := CurrConn.RemoteAddress else CurConnRmtAddr := CurrConn.RemoteHost; if ( CurConnRmtAddr = ClientAddress ) and ( CurrConn.RemotePort = ClientPort ) then FoundConn := PSocketData( CurrConn.Data ).RDOConnection; inc( ConnIdx ) end end; Result := FoundConn end; procedure TWinSockRDOConnectionsServer.InitEvents( const EventSink : IRDOConnectionServerEvents ); begin fEventSink := EventSink end; procedure TWinSockRDOConnectionsServer.ClientConnected( Sender : TObject; Socket : TCustomWinSocket ); var SocketData : PSocketData; begin New( SocketData ); SocketData.RDOConnection := TWinSockRDOServerClientConnection.Create( Socket ); Socket.Data := SocketData; if fEventSink <> nil then fEventSink.OnClientConnect( SocketData.RDOConnection ) end; procedure TWinSockRDOConnectionsServer.ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket ); var SocketData : PSocketData; begin SocketData := PSocketData( Socket.Data ); if fEventSink <> nil then fEventSink.OnClientDisconnect( SocketData.RDOConnection ); Dispose( SocketData ) end; procedure TWinSockRDOConnectionsServer.DoClientRead( Sender : TObject; Socket : TCustomWinSocket ); var NonWSPCharIdx : integer; QueryToService : PQueryToService; QueryText : string; ReadError : boolean; ReceivedText : string; SocketData : PSocketData; ServClienConn : IRDOServerClientConnection; begin ReadError := false; try ReceivedText := Socket.ReceiveText; {$IFDEF Logs} if ReceivedText <> '' then LogThis( 'Read : ' + ReceivedText ) {$ENDIF} except ReadError := true end; if not ReadError and ( fQueryServer <> nil ) then begin SocketData := PSocketData( Socket.Data ); SocketData.Buffer := SocketData.Buffer + ReceivedText; QueryText := GetQueryText( SocketData.Buffer ); while QueryText <> '' do begin NonWSPCharIdx := 1; SkipSpaces( QueryText, NonWSPCharIdx ); if QueryText[ NonWSPCharIdx ] = CallId then begin Delete( QueryText, NonWSPCharIdx, 1 ); inc( fReceivedQueries ); {$IFDEF Logs} LogThis( 'Query : ' + QueryText ); {$ENDIF} New( QueryToService ); QueryToService.Text := QueryText; QueryToService.Socket := Socket; fQueryQueueLock.Acquire; try fQueryQueue.Add( QueryToService ); if fQueryQueue.Count = 1 then SetEvent( fQueryWaiting ) finally fQueryQueueLock.Release end end else if QueryText[ NonWSPCharIdx ] = AnswerId then begin try Delete( QueryText, NonWSPCharIdx, 1 ); ServClienConn := SocketData.RDOConnection as IRDOServerClientConnection; ServClienConn.OnQueryResultArrival( QueryText ) except end end; QueryText := GetQueryText( SocketData.Buffer ) end end else {$IFDEF Logs} LogThis( 'Error while reading from socket' ) {$ENDIF} end; procedure TWinSockRDOConnectionsServer.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : Integer ); begin ErrorCode := 0; {$IFDEF Logs} case ErrorEvent of eeGeneral: LogThis( 'General socket error' ); eeSend: LogThis( 'Error writing to socket' ); eeReceive: LogThis( 'Error reading from socket' ); eeConnect: LogThis( 'Error establishing connection' ); eeDisconnect: LogThis( 'Error closing connection' ); eeAccept: LogThis( 'Error accepting connection' ) end {$ENDIF} end; end.
unit uTipoDesp_Rec; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils; type TTipoDecRec = class private ConexaoDB:TZConnection; FCodigo: Integer; FTipo: string; FDesc: string; public constructor Create(aConexao: TZConnection); destructor Destroy; override; function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published property Codigo: Integer read FCodigo write FCodigo; property Tipo: string read FTipo write FTipo; property Desc: string read FDesc write FDesc; end; implementation { TTipoDecRec } function TTipoDecRec.Apagar: Boolean; var Qry:TZQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Código: '+IntToStr(FCodigo)+#13+ 'Descrição: '+Fdesc,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin Result:=false; abort; end; try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM TIPO_DESPESA_RECEITA '+ ' WHERE TIPODR_COD=:TIPODR_COD '); Qry.ParamByName('TIPODR_COD').AsInteger :=FCodigo; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TTipoDecRec.Atualizar: Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE TIPO_DESPESA_RECEITA '+ ' SET TipoDR_Ti =:Tipo '+ ' ,TipoDR_Desc =:descricao '+ ' WHERE TipoDR_Cod =:TipoDR_Cod '); Qry.ParamByName('TipoDR_Ti').AsString :=Self.FTipo; Qry.ParamByName('TipoDR_Desc').AsString :=Self.FDesc; Qry.ParamByName('TipoDR_Cod').AsInteger :=Self.FCodigo; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; constructor TTipoDecRec.Create(aConexao: TZConnection); begin ConexaoDB:=aConexao; end; destructor TTipoDecRec.Destroy; begin inherited; end; function TTipoDecRec.Inserir: Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO TIPO_DESPESA_RECEITA'+ '(TipoDR_Tipo, '+ ' TipoDR_Desc)'+ ' VALUES(:Tipo, '+ ':Desc) '); Qry.ParamByName('Tipo').AsString :=Self.FTipo; Qry.ParamByName('Desc').AsString :=Self.FDesc; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TTipoDecRec.Selecionar(id: Integer): Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT TipoDR_Tipo, '+ ' TipoDR_Desc, '+ ' TipoDR_Cod'+ ' FROM TIPO_DESPESA_RECEITA '+ ' WHERE TIPODR_Cod =:TIPODR_Cod'); Qry.ParamByName('TIPODR_Cod').AsInteger:=id; Try Qry.Open; Self.FCodigo := Qry.FieldByName('TIPODR_Cod').AsInteger; Self.FTipo := Qry.FieldByName('TipoDR_Tipo').AsString; Self.FDesc := Qry.FieldByName('TipoDR_Desc').AsString; Except Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; end.
{$IfNDef nsNodeNotifierImplementation_imp} // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsNodeNotifierImplementation.imp.pas" // Стереотип: "Impurity" // Элемент модели: "nsNodeNotifierImplementation" MUID: (48FDA9D500E4) // Имя типа: "_nsNodeNotifierImplementation_" {$Define nsNodeNotifierImplementation_imp} _nsNodeNotifierBase_Parent_ = _nsNodeNotifierImplementation_Parent_; {$Include w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsNodeNotifierBase.imp.pas} _nsNodeNotifierImplementation_ = class(_nsNodeNotifierBase_, INodeNotifier) protected procedure OldChanging; procedure OldChanged; procedure ChangeChildrenCount(node_index: TVisibleIndex; delta: Integer; const index_path: INodeIndexPath; child_index: TIndexInParent); stdcall; {* нотификация об изменении кол-ва видимых детей на ноде с указвнным индексом. В случае если изменение нод внутри рута не последовательное и не от начала, индекс должен быть задан как -1. parent_path - путь к УЗЛУ в котором произашли изменения (если delta < 0 - удаление, если delta > 0 - вставка) left_child_index - индекс ребенка в узле: если удаление, то начиная с которого (включительно) мы удаляем delta элементорв; если вставка, то сразу после которого вы вставляем delta элементов. left_child_index, может принять "специальное" значение IIP_BEFORE_LEFT_CHILD (-1) - означающее элемент "до первого" - например для вставки в начало детей. } procedure ResetChildrenCount; stdcall; {* устанавливает кол-во детей = 0 } function IsRootVisible: ByteBool; stdcall; {* признак аутлайнера что он с видимым рутом } function IsOneLevel: ByteBool; stdcall; {* признак аутлайнера что он одноуровневый } procedure Invalidate(const index_path: INodeIndexPath); stdcall; {* нотификация о необходимости перерисовки. Должна вызываться после change_children_count (которые можно группирвать) или самостоятельно при изменении дерева не связанном с кол-вом детей. parent_path - путь к НОДЕ в которой произашли изменения } procedure Changing; stdcall; {* Начало итерации изменения дерева } procedure Changed; stdcall; {* Конец итерации изменения дерева } function GetId: TNotifierID; stdcall; {* Возвращает уникальный идентификатор объекта } end;//_nsNodeNotifierImplementation_ {$Else nsNodeNotifierImplementation_imp} {$IfNDef nsNodeNotifierImplementation_imp_impl} {$Define nsNodeNotifierImplementation_imp_impl} {$Include w:\garant6x\implementation\Garant\GbaNemesis\Data\Tree\nsNodeNotifierBase.imp.pas} procedure _nsNodeNotifierImplementation_.OldChanging; //#UC START# *48FDAA2000B3_48FDA9D500E4_var* //#UC END# *48FDAA2000B3_48FDA9D500E4_var* begin //#UC START# *48FDAA2000B3_48FDA9D500E4_impl* inherited Changing; //#UC END# *48FDAA2000B3_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.OldChanging procedure _nsNodeNotifierImplementation_.OldChanged; //#UC START# *48FDAA330353_48FDA9D500E4_var* //#UC END# *48FDAA330353_48FDA9D500E4_var* begin //#UC START# *48FDAA330353_48FDA9D500E4_impl* inherited Changed; //#UC END# *48FDAA330353_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.OldChanged procedure _nsNodeNotifierImplementation_.ChangeChildrenCount(node_index: TVisibleIndex; delta: Integer; const index_path: INodeIndexPath; child_index: TIndexInParent); {* нотификация об изменении кол-ва видимых детей на ноде с указвнным индексом. В случае если изменение нод внутри рута не последовательное и не от начала, индекс должен быть задан как -1. parent_path - путь к УЗЛУ в котором произашли изменения (если delta < 0 - удаление, если delta > 0 - вставка) left_child_index - индекс ребенка в узле: если удаление, то начиная с которого (включительно) мы удаляем delta элементорв; если вставка, то сразу после которого вы вставляем delta элементов. left_child_index, может принять "специальное" значение IIP_BEFORE_LEFT_CHILD (-1) - означающее элемент "до первого" - например для вставки в начало детей. } //#UC START# *45EEC8E102FE_48FDA9D500E4_var* var l_Data: TnsThreadCallParamsRec; //#UC END# *45EEC8E102FE_48FDA9D500E4_var* begin //#UC START# *45EEC8E102FE_48FDA9D500E4_impl* if IsInGetByVisibleIndex then // Дерево разворачивалось в процессе получения узла f_CountViewChanged := True; if (GetCurrentThreadID = MainThreadID) then ChangeChildrenCountPrim(Node_Index, Delta, Index_Path, Child_Index) else begin with l_Data do begin rNodeIndex := Node_Index; rDelta := Delta; rIndexPath := Index_Path; rChildIndex := Child_Index; end;//with l_Data Synchronize(ChangeChildrenCountThread, @l_Data, SizeOf(l_Data), [l_Data.rIndexPath]); end;//GetCurrentThreadID = MainThreadID //#UC END# *45EEC8E102FE_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.ChangeChildrenCount procedure _nsNodeNotifierImplementation_.ResetChildrenCount; {* устанавливает кол-во детей = 0 } //#UC START# *45EEC8E10303_48FDA9D500E4_var* //#UC END# *45EEC8E10303_48FDA9D500E4_var* begin //#UC START# *45EEC8E10303_48FDA9D500E4_impl* ResetChildrenCountPrim; //#UC END# *45EEC8E10303_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.ResetChildrenCount function _nsNodeNotifierImplementation_.IsRootVisible: ByteBool; {* признак аутлайнера что он с видимым рутом } //#UC START# *45EEC8E10304_48FDA9D500E4_var* //#UC END# *45EEC8E10304_48FDA9D500E4_var* begin //#UC START# *45EEC8E10304_48FDA9D500E4_impl* Result := GetShowRoot; //#UC END# *45EEC8E10304_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.IsRootVisible function _nsNodeNotifierImplementation_.IsOneLevel: ByteBool; {* признак аутлайнера что он одноуровневый } //#UC START# *45EEC8E10305_48FDA9D500E4_var* //#UC END# *45EEC8E10305_48FDA9D500E4_var* begin //#UC START# *45EEC8E10305_48FDA9D500E4_impl* Result := IsOneLevelPrim; //#UC END# *45EEC8E10305_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.IsOneLevel procedure _nsNodeNotifierImplementation_.Invalidate(const index_path: INodeIndexPath); {* нотификация о необходимости перерисовки. Должна вызываться после change_children_count (которые можно группирвать) или самостоятельно при изменении дерева не связанном с кол-вом детей. parent_path - путь к НОДЕ в которой произашли изменения } //#UC START# *45EEC8E10306_48FDA9D500E4_var* var l_Data: TnsThreadCallParamsRec; //#UC END# *45EEC8E10306_48FDA9D500E4_var* begin //#UC START# *45EEC8E10306_48FDA9D500E4_impl* if (GetCurrentThreadID = MainThreadID) then InvalidatePrim else begin with l_Data do begin rNodeIndex := 0; rDelta := 0; rIndexPath := nil; rChildIndex := 0; end;//with l_Data Synchronize(InvalidateThread, @l_Data, SizeOf(l_Data)); end; //#UC END# *45EEC8E10306_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.Invalidate procedure _nsNodeNotifierImplementation_.Changing; {* Начало итерации изменения дерева } //#UC START# *45EEC8E10308_48FDA9D500E4_var* //#UC END# *45EEC8E10308_48FDA9D500E4_var* begin //#UC START# *45EEC8E10308_48FDA9D500E4_impl* // Эта операция целенаправлено не синхронизируется с основной триадой, а выполняется сразу // т.к. в ней идет запоминание текущих нод, которые влидну только непосредственно в момент этого вызова // // Причем в ходе обработки НЕ РЕКОМЕНДУЕТСЯ создавать/убивать кэшируемые объекты на классах // которые общаются с адаптером - это может приводить к следующему дедлоку // майн - убивает объект подписанный на адаптерную нотификацию // входит в добавление в кэш с захватом критической секции // этот поток - Адаптер перед каждой нотификацией захватывает адаптерный мьютекс // создает/убивает кэшируемый объект при этом встает на критической секции // майн - выполняет Cleanup и пытается отписаться от адаптерной нотификации и встает на // адаптерном мьютексе ChangingPrim; //#UC END# *45EEC8E10308_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.Changing procedure _nsNodeNotifierImplementation_.Changed; {* Конец итерации изменения дерева } //#UC START# *45EEC8E10309_48FDA9D500E4_var* var l_Data: TnsThreadCallParamsRec; //#UC END# *45EEC8E10309_48FDA9D500E4_var* begin //#UC START# *45EEC8E10309_48FDA9D500E4_impl* if (GetCurrentThreadID = MainThreadID) then ChangedPrim else begin with l_Data do begin rNodeIndex := 0; rDelta := 0; rIndexPath := nil; rChildIndex := 0; end;//with l_Data Synchronize(ChangedThread, @l_Data, SizeOf(l_Data)); end; //#UC END# *45EEC8E10309_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.Changed function _nsNodeNotifierImplementation_.GetId: TNotifierID; {* Возвращает уникальный идентификатор объекта } //#UC START# *475E4B020072_48FDA9D500E4_var* //#UC END# *475E4B020072_48FDA9D500E4_var* begin //#UC START# *475E4B020072_48FDA9D500E4_impl* Result := TNotifierID(Self); //#UC END# *475E4B020072_48FDA9D500E4_impl* end;//_nsNodeNotifierImplementation_.GetId {$EndIf nsNodeNotifierImplementation_imp_impl} {$EndIf nsNodeNotifierImplementation_imp}
unit nevDocumentProvider; // Модуль: "w:\common\components\gui\Garant\Everest\nevDocumentProvider.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevDocumentProvider" MUID: (4CB57E560195) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , nevTools , l3Variant , afwInterfaces , nevBase , evdInterfaces ; type TnevDocumentProvider = class(Tl3ProtoObject, InevDocumentProvider) private f_Storable: InevStorable; protected function pm_GetCanProvideOriginalDocument: Boolean; virtual; function pm_GetOriginalDocument: Tl3Variant; virtual; function pm_GetPageSetup: IafwPageSetup; virtual; procedure Store(const aView: InevView; const G: InevTagGenerator; aFlags: TevdStoreFlags = evDefaultStoreFlags); overload; {* сохраняет выделение в G. } function Get_CanProvideOriginalDocument: Boolean; function Get_PageSetup: IafwPageSetup; function Get_OriginalDocument: Tl3Variant; procedure ClearFields; override; public constructor Create(const aStorable: InevStorable); reintroduce; class function Make(const aStorable: InevStorable): InevDocumentProvider; reintroduce; protected property CanProvideOriginalDocument: Boolean read pm_GetCanProvideOriginalDocument; property OriginalDocument: Tl3Variant read pm_GetOriginalDocument; property PageSetup: IafwPageSetup read pm_GetPageSetup; end;//TnevDocumentProvider implementation uses l3ImplUses , afwFacade , evPreviewForTestsTuning //#UC START# *4CB57E560195impl_uses* //#UC END# *4CB57E560195impl_uses* ; function TnevDocumentProvider.pm_GetCanProvideOriginalDocument: Boolean; //#UC START# *4CB589C80045_4CB57E560195get_var* //#UC END# *4CB589C80045_4CB57E560195get_var* begin //#UC START# *4CB589C80045_4CB57E560195get_impl* Result := false; //#UC END# *4CB589C80045_4CB57E560195get_impl* end;//TnevDocumentProvider.pm_GetCanProvideOriginalDocument function TnevDocumentProvider.pm_GetOriginalDocument: Tl3Variant; //#UC START# *4CB589F902EA_4CB57E560195get_var* //#UC END# *4CB589F902EA_4CB57E560195get_var* begin //#UC START# *4CB589F902EA_4CB57E560195get_impl* Result := nil; //#UC END# *4CB589F902EA_4CB57E560195get_impl* end;//TnevDocumentProvider.pm_GetOriginalDocument function TnevDocumentProvider.pm_GetPageSetup: IafwPageSetup; //#UC START# *4D18832500B4_4CB57E560195get_var* //#UC END# *4D18832500B4_4CB57E560195get_var* begin //#UC START# *4D18832500B4_4CB57E560195get_impl* Result := nil; //#UC END# *4D18832500B4_4CB57E560195get_impl* end;//TnevDocumentProvider.pm_GetPageSetup constructor TnevDocumentProvider.Create(const aStorable: InevStorable); //#UC START# *4CB57EB40216_4CB57E560195_var* //#UC END# *4CB57EB40216_4CB57E560195_var* begin //#UC START# *4CB57EB40216_4CB57E560195_impl* Assert(aStorable <> nil); inherited Create; f_Storable := aStorable; //#UC END# *4CB57EB40216_4CB57E560195_impl* end;//TnevDocumentProvider.Create class function TnevDocumentProvider.Make(const aStorable: InevStorable): InevDocumentProvider; var l_Inst : TnevDocumentProvider; begin l_Inst := Create(aStorable); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnevDocumentProvider.Make procedure TnevDocumentProvider.Store(const aView: InevView; const G: InevTagGenerator; aFlags: TevdStoreFlags = evDefaultStoreFlags); {* сохраняет выделение в G. } //#UC START# *47C68BFD011C_4CB57E560195_var* //#UC END# *47C68BFD011C_4CB57E560195_var* begin //#UC START# *47C68BFD011C_4CB57E560195_impl* f_Storable.Store(aView, G, aFlags); //#UC END# *47C68BFD011C_4CB57E560195_impl* end;//TnevDocumentProvider.Store function TnevDocumentProvider.Get_CanProvideOriginalDocument: Boolean; //#UC START# *4CB5897501F9_4CB57E560195get_var* //#UC END# *4CB5897501F9_4CB57E560195get_var* begin //#UC START# *4CB5897501F9_4CB57E560195get_impl* Result := Self.CanProvideOriginalDocument; //#UC END# *4CB5897501F9_4CB57E560195get_impl* end;//TnevDocumentProvider.Get_CanProvideOriginalDocument function TnevDocumentProvider.Get_PageSetup: IafwPageSetup; //#UC START# *4D1882B00158_4CB57E560195get_var* //#UC END# *4D1882B00158_4CB57E560195get_var* begin //#UC START# *4D1882B00158_4CB57E560195get_impl* Result := Self.PageSetup; if (Result = nil) then if (afw.Application <> nil) AND (afw.Application.PrintManager <> nil) then Result := afw.Application.PrintManager.PageSetup; //#UC END# *4D1882B00158_4CB57E560195get_impl* end;//TnevDocumentProvider.Get_PageSetup function TnevDocumentProvider.Get_OriginalDocument: Tl3Variant; //#UC START# *5343C5D2028A_4CB57E560195get_var* //#UC END# *5343C5D2028A_4CB57E560195get_var* begin //#UC START# *5343C5D2028A_4CB57E560195get_impl* Result := Self.OriginalDocument; //#UC END# *5343C5D2028A_4CB57E560195get_impl* end;//TnevDocumentProvider.Get_OriginalDocument procedure TnevDocumentProvider.ClearFields; begin f_Storable := nil; inherited; end;//TnevDocumentProvider.ClearFields end.
unit K200087275; {* [Requestlink:200087275] } // Модуль: "w:\archi\source\projects\Archi\Tests\K200087275.pas" // Стереотип: "TestCase" // Элемент модели: "K200087275" MUID: (4F30CBE30015) // Имя типа: "TK200087275" {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3IntfUses {$If NOT Defined(NoScripts)} , ArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ; type TK200087275 = class({$If NOT Defined(NoScripts)} TArchiInsiderTest {$IfEnd} // NOT Defined(NoScripts) ) {* [Requestlink:200087275] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK200087275 {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) implementation {$If Defined(nsTest) AND Defined(InsiderTest)} uses l3ImplUses , TestFrameWork //#UC START# *4F30CBE30015impl_uses* //#UC END# *4F30CBE30015impl_uses* ; {$If NOT Defined(NoScripts)} function TK200087275.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'TableBoundariesAlignment'; end;//TK200087275.GetFolder function TK200087275.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4F30CBE30015'; end;//TK200087275.GetModelElementGUID initialization TestFramework.RegisterTest(TK200087275.Suite); {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) end.
{ Subroutine SST_W_C_EXP_EXPLICIT (EXP, DTYPE, SYM_P) * * Create a variable that will have the value of the expression EXP. * The variable will be declared and set to the expression value. * DTYPE is the descriptor for the data type the variable is to have. * SYM_P is returned pointing to the variable's symbol descriptor. } module sst_w_c_EXP_EXPLICIT; define sst_w_c_exp_explicit; %include 'sst_w_c.ins.pas'; procedure sst_w_c_exp_explicit ( {always create variable for expression value} in exp: sst_exp_t; {descriptor for expression} in dtype: sst_dtype_t; {data type descriptor for variable} out sym_p: sst_symbol_p_t); {will point to variable's symbol descriptor} var v: sst_var_t; {descriptor for implicit var reference} begin if exp.val_fnd { * The expression has a known constant value. The implicit variable will * be declared STATIC, with the expression as its initial value. If a * static variable was previously declared with the same data type and value, * then the existing static variable will be reused. } then begin sst_w_c_implicit_const ( {create/reuse static constant variable} dtype, {data type of variable} exp.val, {value of variable} sym_p); {returned pointer to new/created variable} end { * The expression does not have a known constant value. The expression value * will be assigned to the implicit value at run time right before the current * statement. } else begin sst_w_c_implicit_var ( {create and declare implicit variable} dtype, {data type for new variable} v); {filled in variable reference descriptor} sst_w_c_pos_push (sment_type_exec_k); {position for write before curr statement} sst_w_c_assign (v, exp); {assign expression value to new variable} sst_w_c_pos_pop; {restore original writing position} sym_p := v.mod1.top_sym_p; {return pointer to new symbol descriptor} end ; end;
unit uPageParse; interface uses Winapi.Windows, System.SysUtils, System.Classes, SuperObject; type TPageItem = class private FID: Integer; FDesc: string; public property ID: Integer read FID write FID; property Desc: string read FDesc write FDesc; end; TAppConfig = class private FLastPages: TArray<TPageItem>; public property LastPages: TArray<TPageItem> read FLastPages write FLastPages; end; TSerizalizes = class public class function AsJSON<T>(AObject: T; Indent: Boolean = False): string; class function AsType<T>(AJsonText: string; var tRet: T): Boolean; end; procedure LoadConfig(); implementation uses uGlobal; { TSerizalizes } class function TSerizalizes.AsJSON<T>(AObject: T; Indent: Boolean): string; var Ctx: TSuperRttiContext; begin Ctx := TSuperRttiContext.Create; try try Result := Ctx.AsJson<T>(AObject).AsJSon(Indent, False); except on E: Exception do OutputDebugString(PWideChar(Format('MS - AsJson fail, Err: %s', [E.Message]))); end; finally Ctx.Free; end; end; class function TSerizalizes.AsType<T>(AJsonText: string; var tRet: T): Boolean; var Ctx: TSuperRttiContext; begin Result := False; Ctx := TSuperRttiContext.Create; try try tRet := Ctx.AsType<T>(SO(AJsonText)); Result := True; except on E: Exception do begin OutputDebugString(PWideChar(Format('MS - AsType fail, Err: %s', [E.Message]))); end; end; finally Ctx.Free; end; end; procedure LoadConfig(); var vLst: TStrings; begin if not FileExists(uGlobal.GConfigFile) then begin OutputDebugString('MS - 配置不存在'); Exit; end; vLst := TStringList.Create; try vLst.LoadFromFile(uGlobal.GConfigFile); if vLst.Count <= 0 then begin OutputDebugString('MS - 配置内容为空'); Exit; end; if not TSerizalizes.AsType<TAppConfig>(vLst.Text, GAppConfig) then begin OutputDebugString('MS - 序列化配置内容出错'); Exit; end; finally FreeAndNil(vLst); end; end; initialization LoadConfig(); end.
{***************************************************************************} { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } {***************************************************************************} { } { 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 storeware.IdZeroConf; interface uses System.Classes, System.SysUtils, IdUDPServer, IdGlobal, IdSocketHandle, System.Json; Type TIdZeroConfType = (zctClient, zctServer); TIdZeroConfEvent = procedure(sender: TObject; AData: string) of object; TIdZeroConfBase = class(TComponent) private FDefaultPort:Word; FUDPServer: TIdUDPServer; FzeroConfType: TIdZeroConfType; FAppDefaultPort: word; FServiceName: String; FOnResponse: TIdZeroConfEvent; FLocalHost, FAppDefaultHost: string; FAppDefaultPath: string; procedure SetAppDefaultPort(const Value: word); procedure SetDefaultPort(const Value: word); procedure SetzeroConfType(const Value: TIdZeroConfType); function GetDefaultPort: word; procedure SetServiceName(const Value: String); procedure SetOnResponse(const Value: TIdZeroConfEvent); function GetActive: boolean; procedure SetActive(const Value: boolean); procedure SetAppDefaultHost(const Value: string); function GetzeroConfType: TIdZeroConfType; function GetOnResponse: TIdZeroConfEvent; function GetAppDefaultHost: string; function GetAppDefaultPort: word; procedure SetAppDefaultPath(const Value: string); function getAppDefaultPath: string; function GetLocalHost: string; protected FClientPort: word; procedure DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); procedure Broadcast(AData: string; APort: word); function CreatePayload(ACommand: string; AMessage: String): TJsonObject; public constructor create(AOwner: TComponent); virtual; destructor destroy; override; property LocalHost: string read GetLocalHost; published property ServiceName: String read FServiceName write SetServiceName; property Active: boolean read GetActive write SetActive; end; TIdZeroConfServer = class(TIdZeroConfBase) public constructor create(AOwner: TComponent); override; published property ServerPort: word read GetDefaultPort write SetDefaultPort; property AppDefaultHost: string read GetAppDefaultHost write SetAppDefaultHost; property AppDefaultPort: word read GetAppDefaultPort write SetAppDefaultPort; property AppDefaultPath: string read getAppDefaultPath write SetAppDefaultPath; property OnRequestEvent: TIdZeroConfEvent read GetOnResponse write SetOnResponse; end; TIdZeroConfClient = class(TIdZeroConfBase) private FServerPort: word; FBroadcastIP: string; procedure SetServerPort(const Value: word); procedure SetBroadcastIP(const Value: string); public // envia para o servidor perguntando onde ele esta. procedure Send; constructor create(AOwner: TComponent); override; published // porta do servidor para onde ira enviar a mensagem de broadcast property ServerPort: word read FServerPort write SetServerPort; property BroadcastIP:string read FBroadcastIP write SetBroadcastIP; // porta para onde o cliente esta escutando para pegar a resposta do servidor property ClientPort: word read GetDefaultPort write SetDefaultPort; property OnResponseEvent: TIdZeroConfEvent read GetOnResponse write SetOnResponse; end; procedure Register; implementation { TIdZeroConf } uses IdStack; const ID_ZeroConf_Port = 53330; procedure TIdZeroConfBase.Broadcast(AData: string; APort: word); begin FUDPServer.Broadcast(AData, APort); end; constructor TIdZeroConfBase.create(AOwner: TComponent); begin inherited create(AOwner); FUDPServer := TIdUDPServer.create(self); FUDPServer.OnUDPRead := DoUDPRead; FUDPServer.BroadcastEnabled := true; FUDPServer.ThreadedEvent := true; FServiceName := 'ZeroConf'; end; function TIdZeroConfBase.CreatePayload(ACommand, AMessage: String): TJsonObject; begin FLocalHost := GStack.LocalAddress; result := TJsonObject.create; result.AddPair('service', FServiceName); result.AddPair('command', ACommand); result.AddPair('payload', AMessage); result.AddPair('source', FLocalHost); end; destructor TIdZeroConfBase.destroy; begin FUDPServer.Free; inherited; end; function BytesToString(arr: TIdBytes): string; var i: Integer; begin result := ''; for i := low(arr) to high(arr) do result := result + chr(arr[i]); end; // system.ujson procedure TIdZeroConfBase.DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var resp, ASource, AMessage: string; AComand: string; ABase: string; AJson: TJsonObject; ACmd: TJsonObject; begin AMessage := BytesToString(AData); AJson := TJsonObject.ParseJSONValue(AMessage) as TJsonObject; if AJson.Values['service'].Value <> FServiceName then exit; // nao é o servico esperado AComand := AJson.Values['command'].Value; AJson.TryGetValue<string>('source', ASource); if sameText('ping', AComand) then begin AJson.TryGetValue<word>('client', FClientPort); ACmd := CreatePayload('response', formatDateTime('yyyy-mm-dd hh:mm:ss', now)); try if FAppDefaultHost = '' then FAppDefaultHost := FLocalHost; ACmd.AddPair('host', FAppDefaultHost); ACmd.AddPair('port', TJSONNumber.create(FAppDefaultPort)); ACmd.AddPair('path', FAppDefaultPath); FUDPServer.Broadcast(ACmd.ToString, FClientPort, ASource); finally ACmd.Free; end; end; if assigned(FOnResponse) then FOnResponse(self, AMessage); end; function TIdZeroConfBase.GetActive: boolean; begin result := FUDPServer.Active; end; function TIdZeroConfBase.GetAppDefaultHost: string; begin result := FAppDefaultHost; end; function TIdZeroConfBase.getAppDefaultPath: string; begin result := FAppDefaultPath; end; function TIdZeroConfBase.GetAppDefaultPort: word; begin result := FAppDefaultPort; end; function TIdZeroConfBase.GetDefaultPort: word; begin result := FDefaultPort; end; function TIdZeroConfBase.GetLocalHost: string; begin if FLocalHost = '' then FLocalHost := GStack.LocalAddress; result := FLocalHost; end; function TIdZeroConfBase.GetOnResponse: TIdZeroConfEvent; begin result := FOnResponse; end; function TIdZeroConfBase.GetzeroConfType: TIdZeroConfType; begin result := FzeroConfType; end; procedure TIdZeroConfBase.SetActive(const Value: boolean); begin if FUDPServer.Active <> Value then begin if value then FUDPServer.DefaultPort := FDefaultPort; FUDPServer.Active := Value; end; end; procedure TIdZeroConfBase.SetAppDefaultHost(const Value: string); begin FAppDefaultHost := Value; end; procedure TIdZeroConfBase.SetAppDefaultPath(const Value: string); begin FAppDefaultPath := Value; end; procedure TIdZeroConfBase.SetAppDefaultPort(const Value: word); begin FAppDefaultPort := Value; end; procedure TIdZeroConfBase.SetDefaultPort(const Value: word); begin FDefaultPort := Value; end; procedure TIdZeroConfBase.SetOnResponse(const Value: TIdZeroConfEvent); begin FOnResponse := Value; end; procedure TIdZeroConfBase.SetServiceName(const Value: String); begin FServiceName := Value; end; procedure TIdZeroConfBase.SetzeroConfType(const Value: TIdZeroConfType); begin FzeroConfType := Value; end; constructor TIdZeroConfClient.create(AOwner: TComponent); begin inherited; if (ServerPort = 0) then begin ServerPort := ID_ZeroConf_Port; ClientPort := ID_ZeroConf_Port + 1; end; SetzeroConfType(zctClient); end; { function FormatBroadcastIP(AIP:string):String; var i,n:integer; begin result := ''; if AIP='' then exit; n := 0; for I := low(AIP) to High(AIP) do begin if AIP[I]='.' then begin inc(n); if n=3 then begin result := result+'.0'; exit; end; end else result := result + AIP[i]; end; end; } procedure TIdZeroConfClient.Send; var AJson: TJsonObject; AIP:string; begin AIP:= FBroadcastIP; // prepara ip para broadcast //AIP := formatBroadcastIP(FBroadcastIP); // nao funcionou GetLocalHost; AJson := CreatePayload('ping', ''); try AJson.AddPair('client', TJSONNumber.create(ClientPort)); if not active then active := true; // passa para o servidor onde o cliente esta escutando FUDPServer.Broadcast(AJson.ToString, FServerPort,AIP); // envia os dados para o servidor finally AJson.Free; end; end; procedure TIdZeroConfClient.SetBroadcastIP(const Value: string); begin FBroadcastIP := Value; end; procedure TIdZeroConfClient.SetServerPort(const Value: word); begin FServerPort := Value; end; { TIdZeroConfServer } constructor TIdZeroConfServer.create(AOwner: TComponent); begin inherited create(AOwner); if (ServerPort = 0) then begin ServerPort := ID_ZeroConf_Port; FAppDefaultHost := FLocalHost; AppDefaultPort := 8080; AppDefaultPath := '/rest/datasnap/'; end; SetzeroConfType(zctServer); end; procedure Register; begin RegisterComponents('Storeware',[TIdZeroConfServer,TIdZeroConfClient]); end; end.
unit uProjectData; interface uses uUpdateListObserverInterface, Classes, uLoadDataInterface, xmldom, XMLIntf, msxmldom, XMLDoc, IdGlobal, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, SysUtils; type TProjectData = class(TComponent, ISubject, ILoadXMLData) private FDoc: IXMLDocument; FIdHTTP: TIdHTTP; FObserverList: TList; FProjectList: TStringList; FHTTPURL: String; procedure SaveDataToInputXML; protected function GetXMLText : String; public FCheckLBItems: TStrings; constructor Create(AOwner: TComponent);override; destructor Destroy; override; procedure SetProjectInformation; procedure RegisterObserver(aObserver: IUpdateListObserver); procedure RemoveObserver(aObserver: IUpdateListObserver); procedure NotifyObservers; procedure LoadDataFromInputXML; virtual; function LoadDataViaHTTP: String; virtual; procedure DoAfterXMLDataScan; property ProjectList : TStringList read FProjectList write FProjectList; property Doc: IXMLDocument read FDoc; property HTTPURL : String read FHTTPURL write FHTTPURL; end; implementation uses uProjectConstants, uBehaviorInterfaces; { TProjectData } constructor TProjectData.Create(AOwner: TComponent); begin inherited Create(AOwner); FObserverList := TList.Create; FProjectList := TStringList.Create; FDoc := LoadXMLDocument(rsXMLPath); FIdHTTP := TIdHTTP.Create(AOwner); end; destructor TProjectData.Destroy; begin FreeAndNil(FProjectList); FreeAndNil(FObserverList); FreeAndNil(FIdHTTP); inherited; end; function TProjectData.GetXMLText : String; begin Result := FDoc.XML.Text; end; procedure TProjectData.LoadDataFromInputXML; begin FDoc.LoadFromXML(GetXMLText); end; procedure TProjectData.NotifyObservers; var Observer: IUpdateListObserver; i : Integer; begin for i := 0 to (FObserverList.Count - 1) do begin Observer := IUpdateListObserver(FObserverList.Items[i]); if Assigned(Observer) then Observer.UpdateCheckListBox(FProjectList); end; end; procedure TProjectData.RegisterObserver(aObserver: IUpdateListObserver); begin FObserverList.Add(Pointer(aObserver)); end; procedure TProjectData.RemoveObserver(aObserver: IUpdateListObserver); begin FObserverList.Remove(Pointer(aObserver)); end; procedure TProjectData.SetProjectInformation; var Node: IXMlNode; begin Node := FDoc.DocumentElement.ChildNodes.First; while Assigned(node) do begin FProjectList.Add(Node.Attributes[LIST_OF_XML_FIELD_NAMES[xfnName]]); Node := Node.NextSibling; end; DoAfterXMLDataScan; end; procedure TProjectData.DoAfterXMLDataScan; begin NotifyObservers; end; function TProjectData.LoadDataViaHTTP: String; begin Result := FIdHTTP.Get(FHTTPURL); if Result <> EmptyStr then begin FDoc.XML.Text := Result; SaveDataToInputXML; end; end; procedure TProjectData.SaveDataToInputXML; begin if not FDoc.Active then FDoc.Active := True; FDoc.SaveToFile(rsXMLPath); end; end.
unit UHeartRateForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Ani, FMX.StdCtrls, System.Bluetooth, FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.Edit, FMX.Objects, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Bluetooth.Components, FMX.ListBox, System.Tether.AppProfile, System.SyncObjs; type TSensorContactStatus = (NonSupported, NonDetected, Detected); THRMFlags = record HRValue16bits: boolean; SensorContactStatus: TSensorContactStatus; EnergyExpended: boolean; RRInterval: boolean; end; TfrmHeartMonitor = class(TForm) BluetoothLE1: TBluetoothLE; pnlLog: TPanel; LogList: TListBox; ListBoxGroupHeader1: TListBoxGroupHeader; ListBoxItem1: TListBoxItem; Memo1: TMemo; pnlMain: TPanel; MainList: TListBox; DeviceScan: TListBoxItem; lblDevice: TLabel; btnScan: TButton; BPM: TListBoxItem; lblBPM: TLabel; Image: TListBoxItem; imgHeart: TImage; Location: TListBoxItem; lblBodyLocation: TLabel; Status: TListBoxItem; lblContactStatus: TLabel; Monitoring: TListBoxItem; btnMonitorize: TButton; ToolBar1: TToolBar; Label1: TLabel; pnlAT: TPanel; ATList: TListBox; ListBoxGroupHeader2: TListBoxGroupHeader; ListBoxItem2: TListBoxItem; Memo2: TMemo; TetheringManager1: TTetheringManager; TetherProfile: TTetheringAppProfile; lbBPM: TListBox; btnSendBPM: TButton; tmSendBPM: TTimer; lblUsername: TLabel; edtUsername: TEdit; procedure btnScanClick(Sender: TObject); procedure btnMonitorizeClick(Sender: TObject); procedure btConnectClick(Sender: TObject); procedure BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure BluetoothLE1DescriptorRead(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); procedure BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); procedure FormCreate(Sender: TObject); procedure TetheringManager1RequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetheringManager1PairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringManager1PairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringManager1EndManagersDiscovery(const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); procedure TetheringManager1EndProfilesDiscovery(const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); procedure TetheringManager1NewManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringManager1UnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure TetheringManager1RemoteManagerShutdown(const Sender: TObject; const AManagerIdentifier: string); procedure TetherProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); procedure TetherProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure FormDestroy(Sender: TObject); procedure TetherProfileDisconnect(const Sender: TObject; const AProfileInfo: TTetheringProfileInfo); procedure RefreshBPMList; procedure btnSendBPMClick(Sender: TObject); procedure tmSendBPMTimer(Sender: TObject); private { Private declarations } FBLEDevice: TBluetoothLEDevice; FHRGattService: TBluetoothGattService; FHRMeasurementGattCharact: TBluetoothGattCharacteristic; FBodySensorLocationGattCharact: TBluetoothGattCharacteristic; // App Tethering Shared Resource FMyBPM: String; FLock: TCriticalSection; FRemoteProfiles: TTetheringProfileInfoList; procedure Lock; procedure Unlock; procedure GetServiceAndCharacteristics; procedure ManageCharacteristicData(const ACharacteristic : TBluetoothGattCharacteristic); procedure DisplayHeartRateMeasurementData(Data: TBytes); procedure DisplayBodySensorLocationData(Index: Byte); function GetFlags(Data: Byte): THRMFlags; procedure EnableHRMMonitorize(Enabled: boolean); procedure ReadBodySensorLocation; procedure ClearData; procedure DoScan; public { Public declarations } end; const HRDeviceName = 'Cardiosport HRM'; ServiceUUID = ''; CharactUUID = ''; HRSERVICE: TBluetoothUUID = '{0000180D-0000-1000-8000-00805F9B34FB}'; HRMEASUREMENT_CHARACTERISTIC : TBluetoothUUID = '{00002A37-0000-1000-8000-00805F9B34FB}'; BODY_SENSOR_LOCATION_CHARACTERISTIC : TBluetoothUUID = '{00002A38-0000-1000-8000-00805F9B34FB}'; BodySensorLocations: array [0 .. 6] of string = ('Other', 'Chest', 'Wrist', 'Finger', 'Hand', 'Ear Lobe', 'Foot'); HR_VALUE_FORMAT_MASK = $1; SENSOR_CONTACT_STATUS_MASK = $6; ENERGY_EXPANDED_STATUS_MASK = $8; RR_INTERVAL_MASK = $10; var frmHeartMonitor: TfrmHeartMonitor; implementation {$R *.fmx} procedure TfrmHeartMonitor.Lock; begin FLock.Acquire; end; procedure TfrmHeartMonitor.Unlock; begin FLock.Release; end; function BytesToString(const B: TBytes): string; var I: Integer; begin if Length(B) > 0 then begin Result := Format('%0.2X', [B[0]]); for I := 1 to High(B) do Result := Result + Format(' %0.2X', [B[I]]); end else Result := ''; end; function TfrmHeartMonitor.GetFlags(Data: Byte): THRMFlags; var LValue: Byte; begin Result.HRValue16bits := (Data and HR_VALUE_FORMAT_MASK) = 1; LValue := (Data and SENSOR_CONTACT_STATUS_MASK) shr 1; case LValue of 2: Result.SensorContactStatus := NonDetected; 3: Result.SensorContactStatus := Detected; else Result.SensorContactStatus := NonSupported; end; Result.EnergyExpended := ((Data and ENERGY_EXPANDED_STATUS_MASK) shr 3) = 1; Result.RRInterval := ((Data and RR_INTERVAL_MASK) shr 4) = 1; end; procedure TfrmHeartMonitor.EnableHRMMonitorize(Enabled: boolean); begin if FHRMeasurementGattCharact <> nil then begin if Enabled then begin BluetoothLE1.SubscribeToCharacteristic(FBLEDevice, FHRMeasurementGattCharact); btnMonitorize.Text := 'Stop monitoring' end else begin BluetoothLE1.UnSubscribeToCharacteristic(FBLEDevice, FHRMeasurementGattCharact); btnMonitorize.Text := 'Start monitoring'; ClearData; end; btnMonitorize.Enabled := True; end else begin Memo1.Lines.Add('HRM Characteristic not found'); lblBPM.Font.Size := 13; lblBPM.Text := 'HRM Characteristic not found'; btnMonitorize.Enabled := False; end; end; procedure TfrmHeartMonitor.FormCreate(Sender: TObject); begin // Assign a default value to the "MyBPM" Resource TetherProfile.Resources.FindByName('MyBPM').Value := 'Waiting for BPM...'; // Create the Remote Profile Lock FLock := TCriticalSection.Create; // Create the Remote Profiles List FRemoteProfiles := TTetheringProfileInfoList.Create; // Log the unique LOCAL identifier so we can distinguish between instances // This is a unique GUID generated when our application is executed Memo2.Lines.Add('Local Identifier: ' + TetheringManager1.Identifier); // Now let's look for Remote Mangers with which to pair... Memo2.Lines.Add('Scanning for Remote Managers with which to pair...'); TetheringManager1.DiscoverManagers; end; procedure TfrmHeartMonitor.FormDestroy(Sender: TObject); begin // Destroy the Remote Profiles List and Lock FRemoteProfiles.Free; FLock.Free; end; procedure TfrmHeartMonitor.GetServiceAndCharacteristics; var I, J, K: Integer; begin for I := 0 to FBLEDevice.Services.Count - 1 do begin Memo1.Lines.Add(FBLEDevice.Services[I].UUIDName + ' : ' + FBLEDevice.Services[I].UUID.ToString); for J := 0 to FBLEDevice.Services[I].Characteristics.Count - 1 do begin Memo1.Lines.Add('--> ' + FBLEDevice.Services[I].Characteristics[J] .UUIDName + ' : ' + FBLEDevice.Services[I].Characteristics[J] .UUID.ToString); for K := 0 to FBLEDevice.Services[I].Characteristics[J] .Descriptors.Count - 1 do begin Memo1.Lines.Add('----> ' + FBLEDevice.Services[I].Characteristics[J] .Descriptors[K].UUIDName + ' : ' + FBLEDevice.Services[I] .Characteristics[J].Descriptors[K].UUID.ToString); end; end; end; FHRGattService := nil; FHRMeasurementGattCharact := nil; FBodySensorLocationGattCharact := nil; FHRGattService := BluetoothLE1.GetService(FBLEDevice, HRSERVICE); if FHRGattService <> nil then begin Memo1.Lines.Add('Service found'); FHRMeasurementGattCharact := BluetoothLE1.GetCharacteristic(FHRGattService, HRMEASUREMENT_CHARACTERISTIC); FBodySensorLocationGattCharact := BluetoothLE1.GetCharacteristic (FHRGattService, BODY_SENSOR_LOCATION_CHARACTERISTIC); end else begin Memo1.Lines.Add('Service not found'); lblBPM.Font.Size := 26; lblBPM.Text := 'Service not found'; end; EnableHRMMonitorize(True); ReadBodySensorLocation; end; procedure TfrmHeartMonitor.ManageCharacteristicData(const ACharacteristic : TBluetoothGattCharacteristic); begin if ACharacteristic.UUID = HRMEASUREMENT_CHARACTERISTIC then begin DisplayHeartRateMeasurementData(ACharacteristic.Value); end; if ACharacteristic.UUID = BODY_SENSOR_LOCATION_CHARACTERISTIC then begin DisplayBodySensorLocationData(ACharacteristic.Value[0]); end; end; procedure TfrmHeartMonitor.ReadBodySensorLocation; begin if FBodySensorLocationGattCharact <> nil then BluetoothLE1.ReadCharacteristic(FBLEDevice, FBodySensorLocationGattCharact) else begin Memo1.Lines.Add('FBodySensorLocationGattCharact not found!!!'); lblBodyLocation.Text := 'Sensor location charact not found'; end; end; procedure TfrmHeartMonitor.TetheringManager1EndManagersDiscovery (const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); var I: Integer; begin // Output the number of Remote Managers into the Memo. // Handle pairing with Remote Managers Memo2.Lines.Add(Format('Manager Discovery Complete, found %d Remote Managers', [ARemoteManagers.Count])); // Iterate through all of the discovered Remote Managers, // Check if the Text property matches that of the HRM Manager App. // If it matches, then we can pair with it; for I := 0 to ARemoteManagers.Count - 1 do begin // Log information about the Remote Manager Memo2.Lines.Add(Format('Discovered Remote Manager %d - %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [I, ARemoteManagers[I].ManagerIdentifier, ARemoteManagers[I].ManagerName, ARemoteManagers[I].ManagerText, ARemoteManagers[I].ConnectionString])); // Check if the Remote Manager's "Text" matches the Local Manager's if (ARemoteManagers[I].ManagerText = TetheringManager1.Text) then begin // Log that we're attempting to pair with this Remote Manager Memo2.Lines.Add ('Remote Manager matches Local Manger, attempting to pair...'); // Pair with the Remote Manager TetheringManager1.PairManager(ARemoteManagers[I]); end else begin // Log that this Remote Manager is of no interest Memo2.Lines.Add ('Remote Manager does not match Local Manager, ignoring it...'); end; end; // Once the Local Manager pairs with a Remote Manager, // the Profile Discovery process automatically takes place on both sides. end; procedure TfrmHeartMonitor.TetheringManager1EndProfilesDiscovery (const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); var LRemoteProfile: TTetheringProfileInfo; begin Memo2.Lines.Add(Format('Profile Discovery Complete, Found %d Remote Profiles', [ARemoteProfiles.Count])); // Lock the container Lock; try // Iterate all discovered profiles for LRemoteProfile in ARemoteProfiles do begin // If the profile isn't already in the list... if (not FRemoteProfiles.Contains(LRemoteProfile)) then begin // If we can connect to the Remote Profile if TetherProfile.Connect(LRemoteProfile) then begin // We need to Subscribe to each Remote Profile‘s BPM resource. // This will enable the OnResourceUpdated event to update the BPM list. // Each time a Remote Profile changes the value of its BPM resource, // our Local Profile‘s OnResourceUpdated event is automatically fired, // thus refreshing our BPM list. TetherProfile.SubscribeToRemoteItem(LRemoteProfile, TetherProfile.GetRemoteResourceValue(LRemoteProfile, 'MyBPM')); // Add it into our lockable container FRemoteProfiles.Add(LRemoteProfile); // Log the Remote Profile Memo2.Lines.Add(Format('Added Remote Profile %s to the Lockable List', [LRemoteProfile.ProfileIdentifier])); end; end; end; // Re-sort the lockable container FRemoteProfiles.Sort; finally // Unlock the container Unlock; end; end; procedure TfrmHeartMonitor.TetheringManager1NewManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log that we've paired to a Remote Manager and provide details Memo2.Lines.Add(Format('New Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHeartMonitor.TetheringManager1PairedFromLocal (const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log that we've paired to a Remote Manager and provide details Memo2.Lines.Add(Format('A Remote Manager %s has paired with us' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHeartMonitor.TetheringManager1PairedToRemote (const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Log that we've paired to a Remote Manager and provide details Memo2.Lines.Add(Format('We have paired with a Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHeartMonitor.TetheringManager1RemoteManagerShutdown (const Sender: TObject; const AManagerIdentifier: string); begin // Logs the identity of a Remote Manager that has shut down. Memo2.Lines.Add(Format('Remote Manager %s Shutdown', [AManagerIdentifier])); end; procedure TfrmHeartMonitor.TetheringManager1RequestManagerPassword (const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin // Log the request // Set Password = “1234” TThread.Synchronize(TThread.CurrentThread, procedure begin Memo1.Lines.Add(Format('Remote Manager %s requested for a password...', [ARemoteIdentifier])); end); Password := '1234'; end; procedure TfrmHeartMonitor.TetheringManager1UnPairManager(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin // Logs information about a Remote Manager from which we have UnPaired. Memo2.Lines.Add(Format('UnPaired with Remote Manager %s' + #13#10 + #9 + 'Manager Name: %s' + #13#10 + #9 + 'Manager Text: %s' + #13#10 + #9 + 'Connection String: %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName, AManagerInfo.ManagerText, AManagerInfo.ConnectionString])); end; procedure TfrmHeartMonitor.TetherProfileDisconnect(const Sender: TObject; const AProfileInfo: TTetheringProfileInfo); var LIndex: Integer; LProfileInfo: TTetheringProfileInfo; begin // Engage the Lock Lock; try // If the Profile is in the list... if FRemoteProfiles.BinarySearch(AProfileInfo, LIndex) then begin // ...remove it FRemoteProfiles.Delete(LIndex); // Log that we've removed it LProfileInfo := AProfileInfo; TThread.Synchronize(TThread.CurrentThread, procedure begin Memo2.Lines.Add (Format('Removed Remote Profile %s from the lockable container', [LProfileInfo.ProfileIdentifier])); end); end; finally // Disengage the Lock Unlock; end; end; procedure TfrmHeartMonitor.TetherProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); // Use this Event to send our HR BPM (Temporary Resources) // to the App Tethered Paired Apps begin Memo2.Lines.Add(Format('Temporary Resource Received: %s', [AResource.Hint])); // if it's a String resource... if (AResource.Hint = 'BPM') and (AResource.Value.DataType = TResourceType.String) then begin // Add the message to the display Memo1.Lines.Add(AResource.Value.AsString); end; end; procedure TfrmHeartMonitor.TetherProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); // Fires when the Resource (MyBPM) gets updated in the Remote Profile. // Use this event to send the HR BPM as Persistent Resources // to the App Tethered Paired apps. begin // Log that a Remote Resource has been updated Memo2.Lines.Add(Format('Remote Resource Updated: %s', [AResource.Name])); // if this is the MyBPM resource... if AResource.Name = 'MyBPM' then // Refresh the BPM list RefreshBPMList; end; procedure TfrmHeartMonitor.tmSendBPMTimer(Sender: TObject); var LRemoteProfile: TTetheringProfileInfo; LBPM: String; RecordedTime: string; begin // Format the Message String RecordedTime := FormatDateTime(' mm/dd/yyyy hh:nn:ss', Now); LBPM := edtUsername.Text + ' ' + lblBPM.Text + RecordedTime; // Add the message to our own UI. Memo1.Lines.Add(LBPM); // Lock the Container Lock; try // Iterate all Remote Profiles for LRemoteProfile in FRemoteProfiles do begin // Send the updated BPM Resource to all the connected Tethered Apps. TetherProfile.SendString(LRemoteProfile, 'BPM', LBPM); end; finally // Unlock the Container Unlock; end; end; procedure TfrmHeartMonitor.BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var LSValue: string; begin if AGattStatus <> TBluetoothGattStatus.Success then Memo1.Lines.Add('Error reading Characteristic ' + ACharacteristic.UUIDName + ': ' + Ord(AGattStatus).ToString) else begin LSValue := BytesToString(ACharacteristic.Value); Memo1.Lines.Add(ACharacteristic.UUIDName + ' Value: ' + LSValue); ManageCharacteristicData(ACharacteristic); end; end; procedure TfrmHeartMonitor.BluetoothLE1DescriptorRead(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); var LSValue: string; begin if AGattStatus <> TBluetoothGattStatus.Success then Memo1.Lines.Add('Error reading Characteristic ' + ADescriptor.UUIDName + ': ' + Ord(AGattStatus).ToString) else begin LSValue := BytesToString(ADescriptor.GetValue); Memo1.Lines.Add(ADescriptor.UUIDName + ' Value: ' + LSValue); end; end; procedure TfrmHeartMonitor.BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); var I: Integer; begin // log Memo1.Lines.Add(ADeviceList.Count.ToString + ' devices discovered:'); for I := 0 to ADeviceList.Count - 1 do Memo1.Lines.Add(ADeviceList[I].DeviceName); if BluetoothLE1.DiscoveredDevices.Count > 0 then begin FBLEDevice := BluetoothLE1.DiscoveredDevices.First; lblDevice.Text := HRDeviceName; if BluetoothLE1.GetServices(FBLEDevice).Count = 0 then begin Memo1.Lines.Add('No services found!'); lblBPM.Font.Size := 26; lblBPM.Text := 'No services found!'; end else GetServiceAndCharacteristics; end else lblDevice.Text := 'Device not found'; end; procedure TfrmHeartMonitor.btConnectClick(Sender: TObject); begin GetServiceAndCharacteristics; end; procedure TfrmHeartMonitor.btnMonitorizeClick(Sender: TObject); begin if btnMonitorize.Text.StartsWith('Stop') then begin tmSendBPM.Enabled := False; EnableHRMMonitorize(False) end else EnableHRMMonitorize(True) end; procedure TfrmHeartMonitor.btnScanClick(Sender: TObject); begin DoScan; end; procedure TfrmHeartMonitor.btnSendBPMClick(Sender: TObject); var LRemoteProfile: TTetheringProfileInfo; LBPM: String; RecordedTime: string; begin // Format the Message String LBPM := Format('%s - %s', ['Alfonso', '88']); RecordedTime := FormatDateTime(' mm/dd/yyyy hh:nn:ss', Now); LBPM := edtUsername.Text + ' ' + lblBPM.Text + RecordedTime; // Add the message to our OWN display Memo1.Lines.Add(LBPM); // Lock the Container Lock; try // Iterate all Remote Profiles for LRemoteProfile in FRemoteProfiles do begin // Send the Message TetherProfile.SendString(LRemoteProfile, 'BPM', LBPM); end; finally // Unlock the Container Unlock; end; end; procedure TfrmHeartMonitor.ClearData; begin lblBPM.Font.Size := 26; lblBPM.Text := '? bpm'; imgHeart.Visible := False; end; procedure TfrmHeartMonitor.DisplayBodySensorLocationData(Index: Byte); begin if Index > 6 then lblBodyLocation.Text := '' else lblBodyLocation.Text := 'Sensor location: ' + BodySensorLocations[Index]; end; procedure TfrmHeartMonitor.DisplayHeartRateMeasurementData(Data: TBytes); var Flags: THRMFlags; LBPM: Integer; RecordedTime: string; begin Flags := GetFlags(Data[0]); if Flags.HRValue16bits then LBPM := Data[1] + (Data[2] * 16) else LBPM := Data[1]; case Flags.SensorContactStatus of NonSupported: lblContactStatus.Text := ''; NonDetected: lblContactStatus.Text := 'Sensor contact non detected'; Detected: lblContactStatus.Text := 'Sensor contact detected'; end; if Flags.SensorContactStatus = NonDetected then ClearData else begin RecordedTime := FormatDateTime(' mm/dd/yyyy hh:nn:ss', Now); lblBPM.Font.Size := 26; lblBPM.Text := LBPM.ToString + ' bpm'; imgHeart.Visible := not imgHeart.Visible; Memo1.Lines.Add(edtUsername.Text + ' ' + lblBPM.Text + RecordedTime); end; end; procedure TfrmHeartMonitor.DoScan; begin ClearData; lblDevice.Text := ''; lblBodyLocation.Text := ''; lblContactStatus.Text := ''; tmSendBPM.Enabled := True; BluetoothLE1.DiscoverDevices(2500, [HRSERVICE]); end; procedure TfrmHeartMonitor.RefreshBPMList; var LRemoteProfile: TTetheringProfileInfo; LRemoteBPM: String; begin // Clear the list lbBPM.Clear; // Lock the container Lock; try // Iterate all Connected Remote Profiles for LRemoteProfile in FRemoteProfiles do begin // Retreive the BPM LRemoteBPM := TetherProfile.GetRemoteResourceValue(LRemoteProfile, 'MyBPM').Value.AsString; // If the BPM has been specified if LRemoteBPM <> 'Waiting for BPM...' then begin // Add the BPM to the list lbBPM.Items.Add(LRemoteBPM); end; end; // Unlock the container finally Unlock; end; end; end.
program UnionFindQuickFind(input, output); const N = 9; type vector = array [0 .. N] of integer; var id : vector; a, b : integer; procedure init(); var i : integer; begin for i := 0 to N do id[i] := i end; function connected(p, q : integer) : boolean; begin connected := id[p] = id[q]; end; procedure union(p, q : integer); var pid, qid, i : integer; begin pid := id[p]; qid := id[q]; for i := 0 to N do if id[i] = pid then id[i] := qid; end; procedure printId(); var i : integer; begin for i := 0 to N do write(id[i], ' '); writeln(); end; begin init(); a := N; b := N + 1; while(a <> b) do begin read(a); read(b); if a > N then a := N; if b > N then b := N; if not connected(a, b) then union(a, b); end; printId(); end.
unit NewWordDefinitorPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\NewWordDefinitorPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "NewWordDefinitorPack" MUID: (55895EA203B9) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwScriptingInterfaces , kwCompiledVar , kwCompiledWordPrim , tfwTypeInfo ; type TkwGlobalVar = class(TkwCompiledVar) public function CanClearInRecursiveCalls: Boolean; override; function IsForHelp: Boolean; override; function IsGlobalVar: Boolean; override; end;//TkwGlobalVar _kwCompiledVar_Parent_ = TkwCompiledWordPrim; {$Include w:\common\components\rtl\Garant\ScriptEngine\kwCompiledVar.imp.pas} TkwRefcountVar = class(_kwCompiledVar_) protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; function AcceptMedianBracket(aBracket: TtfwWord; var aCtx: TtfwContext): Boolean; override; procedure SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwRefcountVar TkwRefcountGlobalVar = class(TkwRefcountVar) public function CanClearInRecursiveCalls: Boolean; override; function IsForHelp: Boolean; override; function IsGlobalVar: Boolean; override; end;//TkwRefcountGlobalVar {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwClassLike , l3Interfaces , TypInfo , tfwPropertyLike , l3Base , l3String , tfwThreadVar , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *55895EA203B9impl_uses* //#UC END# *55895EA203B9impl_uses* ; type TkwPopNewWordDefinitorCheckWord = {final} class(TtfwClassLike) {* Слово скрипта pop:NewWordDefinitor:CheckWord } private function CheckWord(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; const aName: Il3CString): TtfwKeyWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckWord } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopNewWordDefinitorCheckWord TkwPopNewWordDefinitorCheckVar = {final} class(TtfwClassLike) {* Слово скрипта pop:NewWordDefinitor:CheckVar } private function CheckVar(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckVar } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopNewWordDefinitorCheckVar TkwPopNewWordDefinitorDefineInParameter = {final} class(TtfwClassLike) {* Слово скрипта pop:NewWordDefinitor:DefineInParameter } private function DefineInParameter(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; const aParamName: Il3CString; aStereo: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:DefineInParameter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopNewWordDefinitorDefineInParameter TkwPopNewWordDefinitorCheckRefcountVar = {final} class(TtfwClassLike) {* Слово скрипта pop:NewWordDefinitor:CheckRefcountVar } private function CheckRefcountVar(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckRefcountVar } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopNewWordDefinitorCheckRefcountVar TkwPopNewWordDefinitorCheckVarForce = {final} class(TtfwClassLike) {* Слово скрипта pop:NewWordDefinitor:CheckVarForce } private function CheckVarForce(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckVarForce } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopNewWordDefinitorCheckVarForce TkwPopNewWordDefinitorKeywordFinder = {final} class(TtfwPropertyLike) {* Слово скрипта pop:NewWordDefinitor:KeywordFinder } private function KeywordFinder(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor): TtfwKeywordFinder; {* Реализация слова скрипта pop:NewWordDefinitor:KeywordFinder } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopNewWordDefinitorKeywordFinder function TkwGlobalVar.CanClearInRecursiveCalls: Boolean; //#UC START# *559A470F0288_559A4C070092_var* //#UC END# *559A470F0288_559A4C070092_var* begin //#UC START# *559A470F0288_559A4C070092_impl* Result := false; //#UC END# *559A470F0288_559A4C070092_impl* end;//TkwGlobalVar.CanClearInRecursiveCalls function TkwGlobalVar.IsForHelp: Boolean; //#UC START# *55C399C9009B_559A4C070092_var* //#UC END# *55C399C9009B_559A4C070092_var* begin //#UC START# *55C399C9009B_559A4C070092_impl* Result := false; //#UC END# *55C399C9009B_559A4C070092_impl* end;//TkwGlobalVar.IsForHelp function TkwGlobalVar.IsGlobalVar: Boolean; //#UC START# *56456DDD037D_559A4C070092_var* //#UC END# *56456DDD037D_559A4C070092_var* begin //#UC START# *56456DDD037D_559A4C070092_impl* Result := true; //#UC END# *56456DDD037D_559A4C070092_impl* end;//TkwGlobalVar.IsGlobalVar {$Include w:\common\components\rtl\Garant\ScriptEngine\kwCompiledVar.imp.pas} procedure TkwRefcountVar.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5673DCB101B4_var* //#UC END# *479731C50290_5673DCB101B4_var* begin //#UC START# *479731C50290_5673DCB101B4_impl* if (f_Value.rType = tfw_vtObj) then begin f_Value.AsObject.Free; f_Value.rInteger := 0; end;//f_Value.rType = tfw_vtObj inherited; //#UC END# *479731C50290_5673DCB101B4_impl* end;//TkwRefcountVar.Cleanup procedure TkwRefcountVar.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *52D00B00031A_5673DCB101B4_var* //#UC END# *52D00B00031A_5673DCB101B4_var* begin //#UC START# *52D00B00031A_5673DCB101B4_impl* if (f_Value.rType = tfw_vtObj) then begin if (aValue.rType = tfw_vtObj) AND (f_Value.AsObject = aValue.AsObject) then Exit; f_Value.AsObject.Free; end;//f_Value.rType = tfw_vtObj f_Value := aValue; if (aValue.rType = tfw_vtObj) then begin l3Use(aValue.AsObject); end;//aValue.rType = tfw_vtObj //#UC END# *52D00B00031A_5673DCB101B4_impl* end;//TkwRefcountVar.SetValuePrim function TkwRefcountVar.AcceptMedianBracket(aBracket: TtfwWord; var aCtx: TtfwContext): Boolean; //#UC START# *52D7DC84019E_5673DCB101B4_var* //#UC END# *52D7DC84019E_5673DCB101B4_var* begin //#UC START# *52D7DC84019E_5673DCB101B4_impl* Result := false; //#UC END# *52D7DC84019E_5673DCB101B4_impl* end;//TkwRefcountVar.AcceptMedianBracket procedure TkwRefcountVar.SetValue(const aValue: TtfwStackValue; const aCtx: TtfwContext); //#UC START# *56096688024A_5673DCB101B4_var* //#UC END# *56096688024A_5673DCB101B4_var* begin //#UC START# *56096688024A_5673DCB101B4_impl* inherited; //#UC END# *56096688024A_5673DCB101B4_impl* end;//TkwRefcountVar.SetValue function TkwRefcountGlobalVar.CanClearInRecursiveCalls: Boolean; //#UC START# *559A470F0288_5673DD44029E_var* //#UC END# *559A470F0288_5673DD44029E_var* begin //#UC START# *559A470F0288_5673DD44029E_impl* Result := false; //#UC END# *559A470F0288_5673DD44029E_impl* end;//TkwRefcountGlobalVar.CanClearInRecursiveCalls function TkwRefcountGlobalVar.IsForHelp: Boolean; //#UC START# *55C399C9009B_5673DD44029E_var* //#UC END# *55C399C9009B_5673DD44029E_var* begin //#UC START# *55C399C9009B_5673DD44029E_impl* Result := false; //#UC END# *55C399C9009B_5673DD44029E_impl* end;//TkwRefcountGlobalVar.IsForHelp function TkwRefcountGlobalVar.IsGlobalVar: Boolean; //#UC START# *56456DDD037D_5673DD44029E_var* //#UC END# *56456DDD037D_5673DD44029E_var* begin //#UC START# *56456DDD037D_5673DD44029E_impl* Result := true; //#UC END# *56456DDD037D_5673DD44029E_impl* end;//TkwRefcountGlobalVar.IsGlobalVar function TkwPopNewWordDefinitorCheckWord.CheckWord(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; const aName: Il3CString): TtfwKeyWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckWord } begin Result := aNewWordDefinitor.CheckWord(aName); end;//TkwPopNewWordDefinitorCheckWord.CheckWord class function TkwPopNewWordDefinitorCheckWord.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:CheckWord'; end;//TkwPopNewWordDefinitorCheckWord.GetWordNameForRegister function TkwPopNewWordDefinitorCheckWord.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwKeyWord); end;//TkwPopNewWordDefinitorCheckWord.GetResultTypeInfo function TkwPopNewWordDefinitorCheckWord.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopNewWordDefinitorCheckWord.GetAllParamsCount function TkwPopNewWordDefinitorCheckWord.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor), @tfw_tiString]); end;//TkwPopNewWordDefinitorCheckWord.ParamsTypes procedure TkwPopNewWordDefinitorCheckWord.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; var l_aName: Il3CString; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CheckWord(aCtx, l_aNewWordDefinitor, l_aName)); end;//TkwPopNewWordDefinitorCheckWord.DoDoIt function TkwPopNewWordDefinitorCheckVar.CheckVar(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckVar } //#UC START# *5589A2F10199_5589A2F10199_4DC95E96023B_Word_var* var l_KW : TtfwKeyWord; l_W : TtfwWord; //#UC END# *5589A2F10199_5589A2F10199_4DC95E96023B_Word_var* begin //#UC START# *5589A2F10199_5589A2F10199_4DC95E96023B_Word_impl* l_KW := aNewWordDefinitor.CheckWord(aName); l_W := l_KW.Word; if (l_W = nil) then begin if aLocal then l_W := TkwCompiledVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW) else l_W := TkwGlobalVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW); try l_KW.SetWord(aCtx, l_W); Result := l_W; finally FreeAndNil(l_W); end;//try..finally end//l_W = nil else Result := l_W; //#UC END# *5589A2F10199_5589A2F10199_4DC95E96023B_Word_impl* end;//TkwPopNewWordDefinitorCheckVar.CheckVar class function TkwPopNewWordDefinitorCheckVar.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:CheckVar'; end;//TkwPopNewWordDefinitorCheckVar.GetWordNameForRegister function TkwPopNewWordDefinitorCheckVar.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopNewWordDefinitorCheckVar.GetResultTypeInfo function TkwPopNewWordDefinitorCheckVar.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopNewWordDefinitorCheckVar.GetAllParamsCount function TkwPopNewWordDefinitorCheckVar.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor), TypeInfo(Boolean), @tfw_tiString]); end;//TkwPopNewWordDefinitorCheckVar.ParamsTypes procedure TkwPopNewWordDefinitorCheckVar.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; var l_aLocal: Boolean; var l_aName: Il3CString; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aLocal := aCtx.rEngine.PopBool; except on E: Exception do begin RunnerError('Ошибка при получении параметра aLocal: Boolean : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CheckVar(aCtx, l_aNewWordDefinitor, l_aLocal, l_aName)); end;//TkwPopNewWordDefinitorCheckVar.DoDoIt function TkwPopNewWordDefinitorDefineInParameter.DefineInParameter(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; const aParamName: Il3CString; aStereo: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:DefineInParameter } //#UC START# *559D266D0010_559D266D0010_4DC95E96023B_Word_var* //#UC END# *559D266D0010_559D266D0010_4DC95E96023B_Word_var* begin //#UC START# *559D266D0010_559D266D0010_4DC95E96023B_Word_impl* Result := aNewWordDefinitor.DefineInParameter(aCtx, aParamName, aStereo, aCtx.rTypeInfo); //#UC END# *559D266D0010_559D266D0010_4DC95E96023B_Word_impl* end;//TkwPopNewWordDefinitorDefineInParameter.DefineInParameter class function TkwPopNewWordDefinitorDefineInParameter.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:DefineInParameter'; end;//TkwPopNewWordDefinitorDefineInParameter.GetWordNameForRegister function TkwPopNewWordDefinitorDefineInParameter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopNewWordDefinitorDefineInParameter.GetResultTypeInfo function TkwPopNewWordDefinitorDefineInParameter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopNewWordDefinitorDefineInParameter.GetAllParamsCount function TkwPopNewWordDefinitorDefineInParameter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor), @tfw_tiString, TypeInfo(TtfwWord)]); end;//TkwPopNewWordDefinitorDefineInParameter.ParamsTypes procedure TkwPopNewWordDefinitorDefineInParameter.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; var l_aParamName: Il3CString; var l_aStereo: TtfwWord; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aParamName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aParamName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aStereo := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aStereo: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(DefineInParameter(aCtx, l_aNewWordDefinitor, l_aParamName, l_aStereo)); end;//TkwPopNewWordDefinitorDefineInParameter.DoDoIt function TkwPopNewWordDefinitorCheckRefcountVar.CheckRefcountVar(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckRefcountVar } //#UC START# *5673DD6F001B_5673DD6F001B_4DC95E96023B_Word_var* var l_KW : TtfwKeyWord; l_W : TtfwWord; //#UC END# *5673DD6F001B_5673DD6F001B_4DC95E96023B_Word_var* begin //#UC START# *5673DD6F001B_5673DD6F001B_4DC95E96023B_Word_impl* l_KW := aNewWordDefinitor.CheckWord(aName); l_W := l_KW.Word; if (l_W = nil) then begin if aLocal then l_W := TkwRefcountVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW) else l_W := TkwRefcountGlobalVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW); try l_KW.SetWord(aCtx, l_W); Result := l_W; finally FreeAndNil(l_W); end;//try..finally end//l_W = nil else Result := l_W; //#UC END# *5673DD6F001B_5673DD6F001B_4DC95E96023B_Word_impl* end;//TkwPopNewWordDefinitorCheckRefcountVar.CheckRefcountVar class function TkwPopNewWordDefinitorCheckRefcountVar.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:CheckRefcountVar'; end;//TkwPopNewWordDefinitorCheckRefcountVar.GetWordNameForRegister function TkwPopNewWordDefinitorCheckRefcountVar.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopNewWordDefinitorCheckRefcountVar.GetResultTypeInfo function TkwPopNewWordDefinitorCheckRefcountVar.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopNewWordDefinitorCheckRefcountVar.GetAllParamsCount function TkwPopNewWordDefinitorCheckRefcountVar.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor), TypeInfo(Boolean), @tfw_tiString]); end;//TkwPopNewWordDefinitorCheckRefcountVar.ParamsTypes procedure TkwPopNewWordDefinitorCheckRefcountVar.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; var l_aLocal: Boolean; var l_aName: Il3CString; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aLocal := aCtx.rEngine.PopBool; except on E: Exception do begin RunnerError('Ошибка при получении параметра aLocal: Boolean : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CheckRefcountVar(aCtx, l_aNewWordDefinitor, l_aLocal, l_aName)); end;//TkwPopNewWordDefinitorCheckRefcountVar.DoDoIt function TkwPopNewWordDefinitorCheckVarForce.CheckVarForce(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor; aLocal: Boolean; const aName: Il3CString): TtfwWord; {* Реализация слова скрипта pop:NewWordDefinitor:CheckVarForce } //#UC START# *57B55A630344_57B55A630344_4DC95E96023B_Word_var* var l_KW : TtfwKeyWord; l_W : TtfwWord; //#UC END# *57B55A630344_57B55A630344_4DC95E96023B_Word_var* begin //#UC START# *57B55A630344_57B55A630344_4DC95E96023B_Word_impl* l_KW := aNewWordDefinitor.CheckWord(aName); if (l_KW.Word <> nil) then if l_KW.Word.IsForwardDeclaration then Assert(false, 'Пытаются создать переменную вместо предварительного описания слова' + l3Str(Self.Key.AsWStr) + ' : ' + l3Str(aName)); if aLocal then l_W := TkwCompiledVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW) else l_W := TkwGlobalVar.Create(Self, aNewWordDefinitor.KeywordFinder(aCtx){PrevFinder}, aCtx.rTypeInfo, aCtx, l_KW); try l_KW.SetWord(aCtx, l_W); Result := l_W; finally FreeAndNil(l_W); end;//try..finally //#UC END# *57B55A630344_57B55A630344_4DC95E96023B_Word_impl* end;//TkwPopNewWordDefinitorCheckVarForce.CheckVarForce class function TkwPopNewWordDefinitorCheckVarForce.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:CheckVarForce'; end;//TkwPopNewWordDefinitorCheckVarForce.GetWordNameForRegister function TkwPopNewWordDefinitorCheckVarForce.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopNewWordDefinitorCheckVarForce.GetResultTypeInfo function TkwPopNewWordDefinitorCheckVarForce.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 3; end;//TkwPopNewWordDefinitorCheckVarForce.GetAllParamsCount function TkwPopNewWordDefinitorCheckVarForce.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor), TypeInfo(Boolean), @tfw_tiString]); end;//TkwPopNewWordDefinitorCheckVarForce.ParamsTypes procedure TkwPopNewWordDefinitorCheckVarForce.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; var l_aLocal: Boolean; var l_aName: Il3CString; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aLocal := aCtx.rEngine.PopBool; except on E: Exception do begin RunnerError('Ошибка при получении параметра aLocal: Boolean : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CheckVarForce(aCtx, l_aNewWordDefinitor, l_aLocal, l_aName)); end;//TkwPopNewWordDefinitorCheckVarForce.DoDoIt function TkwPopNewWordDefinitorKeywordFinder.KeywordFinder(const aCtx: TtfwContext; aNewWordDefinitor: TtfwNewWordDefinitor): TtfwKeywordFinder; {* Реализация слова скрипта pop:NewWordDefinitor:KeywordFinder } //#UC START# *559BE01B0219_559BE01B0219_4DC95E96023B_Word_var* //#UC END# *559BE01B0219_559BE01B0219_4DC95E96023B_Word_var* begin //#UC START# *559BE01B0219_559BE01B0219_4DC95E96023B_Word_impl* Result := aNewWordDefinitor.KeywordFinder(aCtx); //#UC END# *559BE01B0219_559BE01B0219_4DC95E96023B_Word_impl* end;//TkwPopNewWordDefinitorKeywordFinder.KeywordFinder class function TkwPopNewWordDefinitorKeywordFinder.GetWordNameForRegister: AnsiString; begin Result := 'pop:NewWordDefinitor:KeywordFinder'; end;//TkwPopNewWordDefinitorKeywordFinder.GetWordNameForRegister function TkwPopNewWordDefinitorKeywordFinder.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwKeywordFinder); end;//TkwPopNewWordDefinitorKeywordFinder.GetResultTypeInfo function TkwPopNewWordDefinitorKeywordFinder.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopNewWordDefinitorKeywordFinder.GetAllParamsCount function TkwPopNewWordDefinitorKeywordFinder.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwNewWordDefinitor)]); end;//TkwPopNewWordDefinitorKeywordFinder.ParamsTypes procedure TkwPopNewWordDefinitorKeywordFinder.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству KeywordFinder', aCtx); end;//TkwPopNewWordDefinitorKeywordFinder.SetValuePrim procedure TkwPopNewWordDefinitorKeywordFinder.DoDoIt(const aCtx: TtfwContext); var l_aNewWordDefinitor: TtfwNewWordDefinitor; begin try l_aNewWordDefinitor := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aNewWordDefinitor: TtfwNewWordDefinitor : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(KeywordFinder(aCtx, l_aNewWordDefinitor)); end;//TkwPopNewWordDefinitorKeywordFinder.DoDoIt initialization TkwGlobalVar.RegisterClass; {* Регистрация TkwGlobalVar } TkwRefcountVar.RegisterClass; {* Регистрация TkwRefcountVar } TkwRefcountGlobalVar.RegisterClass; {* Регистрация TkwRefcountGlobalVar } TkwPopNewWordDefinitorCheckWord.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_CheckWord } TkwPopNewWordDefinitorCheckVar.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_CheckVar } TkwPopNewWordDefinitorDefineInParameter.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_DefineInParameter } TkwPopNewWordDefinitorCheckRefcountVar.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_CheckRefcountVar } TkwPopNewWordDefinitorCheckVarForce.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_CheckVarForce } TkwPopNewWordDefinitorKeywordFinder.RegisterInEngine; {* Регистрация pop_NewWordDefinitor_KeywordFinder } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwNewWordDefinitor)); {* Регистрация типа TtfwNewWordDefinitor } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeyWord)); {* Регистрация типа TtfwKeyWord } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwWord)); {* Регистрация типа TtfwWord } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeywordFinder)); {* Регистрация типа TtfwKeywordFinder } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа Il3CString } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // NOT Defined(NoScripts) end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIStandardDsaEncoding; {$I ..\Include\CryptoLib.inc} interface uses ClpBigInteger, ClpIAsn1Sequence, ClpIDerInteger, ClpIDsaEncoding, ClpCryptoLibTypes; type IStandardDsaEncoding = interface(IDsaEncoding) ['{A8662374-922B-4D72-B956-FE0ED3505C68}'] function CheckValue(const n, x: TBigInteger): TBigInteger; function DecodeValue(const n: TBigInteger; const s: IAsn1Sequence; pos: Int32): TBigInteger; function EncodeValue(const n, x: TBigInteger): IDerInteger; function Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray) : TCryptoLibGenericArray<TBigInteger>; function Encode(const n, r, s: TBigInteger): TCryptoLibByteArray; end; implementation end.
unit db.lua.api; interface uses System.Classes, Winapi.Windows, System.SysUtils, System.IOUtils; const LUA_IDSIZE = 60; LUAI_FIRSTPSEUDOIDX = -1001000; LUA_VERSION_MAJOR = '5'; LUA_VERSION_MINOR = '3'; LUA_VERSION_NUM = 503; LUA_VERSION_RELEASE = '0'; LUA_VERSION_ = 'Lua ' + LUA_VERSION_MAJOR + '.' + LUA_VERSION_MINOR; LUA_RELEASE = LUA_VERSION_ + '.' + LUA_VERSION_RELEASE; LUA_COPYRIGHT = LUA_RELEASE + ' Copyright (C) 1994-2015 Lua.org, PUC-Rio'; LUA_AUTHORS = 'R. Ierusalimschy, L. H. de Figueiredo, W. Celes'; LUA_SIGNATURE = #$1b'Lua'; LUA_MULTRET = -1; LUA_REGISTRYINDEX = LUAI_FIRSTPSEUDOIDX; LUA_OK = 0; LUA_YIELD_ = 1; LUA_ERRRUN = 2; LUA_ERRSYNTAX = 3; LUA_ERRMEM = 4; LUA_ERRGCMM = 5; LUA_ERRERR = 6; LUA_TNONE = (-1); LUA_TNIL = 0; LUA_TBOOLEAN = 1; LUA_TLIGHTUSERDATA = 2; LUA_TNUMBER = 3; LUA_TSTRING = 4; LUA_TTABLE = 5; LUA_TFUNCTION = 6; LUA_TUSERDATA = 7; LUA_TTHREAD = 8; LUA_NUMTAGS = 9; LUA_MINSTACK = 20; LUA_RIDX_MAINTHREAD = 1; LUA_RIDX_GLOBALS = 2; LUA_RIDX_LAST = LUA_RIDX_GLOBALS; LUA_OPADD = 0; LUA_OPSUB = 1; LUA_OPMUL = 2; LUA_OPMOD = 3; LUA_OPPOW = 4; LUA_OPDIV = 5; LUA_OPIDIV = 6; LUA_OPBAND = 7; LUA_OPBOR = 8; LUA_OPBXOR = 9; LUA_OPSHL = 10; LUA_OPSHR = 11; LUA_OPUNM = 12; LUA_OPBNOT = 13; LUA_OPEQ = 0; LUA_OPLT = 1; LUA_OPLE = 2; LUA_GCSTOP = 0; LUA_GCRESTART = 1; LUA_GCCOLLECT = 2; LUA_GCCOUNT = 3; LUA_GCCOUNTB = 4; LUA_GCSTEP = 5; LUA_GCSETPAUSE = 6; LUA_GCSETSTEPMUL = 7; LUA_GCISRUNNING = 9; LUA_HOOKCALL = 0; LUA_HOOKRET = 1; LUA_HOOKLINE = 2; LUA_HOOKCOUNT = 3; LUA_HOOKTAILCALL = 4; LUA_MASKCALL = (1 SHL LUA_HOOKCALL); LUA_MASKRET = (1 SHL LUA_HOOKRET); LUA_MASKLINE = (1 SHL LUA_HOOKLINE); LUA_MASKCOUNT = (1 SHL LUA_HOOKCOUNT); LUA_COLIBNAME = 'coroutine'; LUA_TABLIBNAME = 'table'; LUA_IOLIBNAME = 'io'; LUA_OSLIBNAME = 'os'; LUA_STRLIBNAME = 'string'; LUA_UTF8LIBNAME = 'utf8'; LUA_BITLIBNAME = 'bit32'; LUA_MATHLIBNAME = 'math'; LUA_DBLIBNAME = 'debug'; LUA_LOADLIBNAME = 'package'; LUAL_NUMSIZES = sizeof(NativeInt) * 16 + sizeof(Double); LUA_NOREF = -2; LUA_REFNIL = -1; LUAL_BUFFERSIZE = Integer($80 * sizeof(Pointer) * sizeof(NativeInt)); LUA_FILEHANDLE = 'FILE*'; type lua_State = Pointer; ptrdiff_t = NativeInt; lua_Number = Double; lua_Integer = Int64; lua_Unsigned = Uint64; lua_KContext = ptrdiff_t; lua_CFunction = function(L: lua_State) : Integer; cdecl; lua_KFunction = function(L: lua_State; status: Integer; ctx: lua_KContext) : Integer; cdecl; lua_Reader = function(L: lua_State; ud: Pointer; sz: Psize_t) : Pointer; cdecl; lua_Writer = function(L: lua_State; p: Pointer; sz: size_t; ud: Pointer) : Integer; cdecl; lua_Alloc = function(ud: Pointer; ptr: Pointer; osize: size_t; nsize: size_t): Pointer; cdecl; lua_Debug = record event: Integer; name: MarshaledAString; namewhat: MarshaledAString; what: MarshaledAString; source: MarshaledAString; currentline: Integer; linedefined: Integer; lastlinedefined: Integer; nups: Byte; nparams: Byte; isvararg: ByteBool; istailcall: ByteBool; short_src: array [0 .. LUA_IDSIZE - 1] of Char; i_ci: Pointer; end; Plua_Debug = ^lua_Debug; lua_Hook = procedure(L: lua_State; ar: Plua_Debug); cdecl; luaL_Reg = record name: MarshaledAString; func: lua_CFunction; end; PluaL_Reg = ^luaL_Reg; luaL_Buffer = record b: MarshaledAString; size: size_t; n: size_t; L: lua_State; initb: array [0 .. LUAL_BUFFERSIZE - 1] of Byte; end; Plual_Buffer = ^luaL_Buffer; luaL_Stream = record f: Pointer; closef: lua_CFunction; end; var lua_newstate : function(f: lua_Alloc; ud: Pointer): lua_State; cdecl; lua_close : procedure(L: lua_State); cdecl; lua_newthread : function(L: lua_State): lua_State; cdecl; lua_atpanic : function(L: lua_State; panicf: lua_CFunction): lua_CFunction; cdecl; lua_version : function(L: lua_State): lua_Number; cdecl; lua_absindex : function(L: lua_State; idx: Integer): Integer; cdecl; lua_gettop : function(L: lua_State): Integer; cdecl; lua_settop : procedure(L: lua_State; idx: Integer); cdecl; lua_pushvalue : procedure(L: lua_State; idx: Integer); cdecl; lua_rotate : procedure(L: lua_State; idx: Integer; n: Integer); cdecl; lua_copy : procedure(L: lua_State; fromidx: Integer; toidx: Integer); cdecl; lua_checkstack : function(L: lua_State; n: Integer): Integer; cdecl; lua_xmove : procedure(from: lua_State; to_: lua_State; n: Integer); cdecl; lua_isnumber : function(L: lua_State; idx: Integer): Integer; cdecl; lua_isstring : function(L: lua_State; idx: Integer): Integer; cdecl; lua_iscfunction : function(L: lua_State; idx: Integer): Integer; cdecl; lua_isinteger : function(L: lua_State; idx: Integer): Integer; cdecl; lua_isuserdata : function(L: lua_State; idx: Integer): Integer; cdecl; lua_type : function(L: lua_State; idx: Integer): Integer; cdecl; lua_typename : function(L: lua_State; tp: Integer): MarshaledAString; cdecl; lua_tonumberx : function(L: lua_State; idx: Integer; isnum: PLongBool): lua_Number; cdecl; lua_tointegerx : function(L: lua_State; idx: Integer; isnum: PLongBool): lua_Integer; cdecl; lua_toboolean : function(L: lua_State; idx: Integer): Integer; cdecl; lua_tolstring : function(L: lua_State; idx: Integer; len: Psize_t): MarshaledAString; cdecl; lua_rawlen : function(L: lua_State; idx: Integer): size_t; cdecl; lua_tocfunction : function(L: lua_State; idx: Integer): lua_CFunction; cdecl; lua_touserdata : function(L: lua_State; idx: Integer): Pointer; cdecl; lua_tothread : function(L: lua_State; idx: Integer): lua_State; cdecl; lua_topointer : function(L: lua_State; idx: Integer): Pointer; cdecl; lua_arith : procedure(L: lua_State; op: Integer); cdecl; lua_rawequal : function(L: lua_State; idx1: Integer; idx2: Integer): Integer; cdecl; lua_compare : function(L: lua_State; idx1: Integer; idx2: Integer; op: Integer): Integer; cdecl; lua_pushnil : procedure(L: lua_State); cdecl; lua_pushnumber : procedure(L: lua_State; n: lua_Number); cdecl; lua_pushinteger : procedure(L: lua_State; n: lua_Integer); cdecl; lua_pushlstring : function(L: lua_State; s: MarshaledAString; len: size_t): MarshaledAString; cdecl; lua_pushstring : function(L: lua_State; s: MarshaledAString): MarshaledAString; cdecl; lua_pushvfstring : function(L: lua_State; fmt: MarshaledAString; argp: Pointer): MarshaledAString; cdecl; lua_pushfstring : function(L: lua_State; fmt: MarshaledAString; args: array of const): MarshaledAString; cdecl; lua_pushcclosure : procedure(L: lua_State; fn: lua_CFunction; n: Integer); cdecl; lua_pushboolean : procedure(L: lua_State; b: Integer); cdecl; lua_pushlightuserdata: procedure(L: lua_State; p: Pointer); cdecl; lua_pushthread : function(L: lua_State): Integer; cdecl; lua_getglobal : function(L: lua_State; const name: MarshaledAString): Integer; cdecl; lua_gettable : function(L: lua_State; idx: Integer): Integer; cdecl; lua_getfield : function(L: lua_State; idx: Integer; k: MarshaledAString): Integer; cdecl; lua_geti : function(L: lua_State; idx: Integer; n: lua_Integer): Integer; cdecl; lua_rawget : function(L: lua_State; idx: Integer): Integer; cdecl; lua_rawgeti : function(L: lua_State; idx: Integer; n: lua_Integer): Integer; cdecl; lua_rawgetp : function(L: lua_State; idx: Integer; p: Pointer): Integer; cdecl; lua_createtable : procedure(L: lua_State; narr: Integer; nrec: Integer); cdecl; lua_newuserdata : function(L: lua_State; sz: size_t): Pointer; cdecl; lua_getmetatable : function(L: lua_State; objindex: Integer): Integer; cdecl; lua_getuservalue : function(L: lua_State; idx: Integer): Integer; cdecl; lua_setglobal : procedure(L: lua_State; name: MarshaledAString); cdecl; lua_settable : procedure(L: lua_State; idx: Integer); cdecl; lua_setfield : procedure(L: lua_State; idx: Integer; k: MarshaledAString); cdecl; lua_seti : procedure(L: lua_State; idx: Integer; n: lua_Integer); cdecl; lua_rawset : procedure(L: lua_State; idx: Integer); cdecl; lua_rawseti : procedure(L: lua_State; idx: Integer; n: lua_Integer); cdecl; lua_rawsetp : procedure(L: lua_State; idx: Integer; p: Pointer); cdecl; lua_setmetatable : function(L: lua_State; objindex: Integer): Integer; cdecl; lua_setuservalue : procedure(L: lua_State; idx: Integer); cdecl; lua_callk : procedure(L: lua_State; nargs: Integer; nresults: Integer; ctx: lua_KContext; k: lua_KFunction); cdecl; lua_pcallk : function(L: lua_State; nargs: Integer; nresults: Integer; errfunc: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; lua_load : function(L: lua_State; reader: lua_Reader; dt: Pointer; const chunkname: MarshaledAString; const mode: MarshaledAString): Integer; cdecl; lua_dump : function(L: lua_State; writer: lua_Writer; data: Pointer; strip: Integer): Integer; cdecl; lua_yieldk : function(L: lua_State; nresults: Integer; ctx: lua_KContext; k: lua_KFunction): Integer; cdecl; lua_resume : function(L: lua_State; from: lua_State; narg: Integer): Integer; cdecl; lua_status : function(L: lua_State): Integer; cdecl; lua_isyieldable : function(L: lua_State): Integer; cdecl; lua_gc : function(L: lua_State; what: Integer; data: Integer): Integer; cdecl; lua_error : function(L: lua_State): Integer; cdecl; lua_next : function(L: lua_State; idx: Integer): Integer; cdecl; lua_concat : procedure(L: lua_State; n: Integer); cdecl; lua_len : procedure(L: lua_State; idx: Integer); cdecl; lua_stringtonumber : function(L: lua_State; const s: MarshaledAString): size_t; cdecl; lua_getallocf : function(L: lua_State; ud: PPointer): lua_Alloc; cdecl; lua_setallocf : procedure(L: lua_State; f: lua_Alloc; ud: Pointer); cdecl; lua_getstack : function(L: lua_State; level: Integer; ar: Plua_Debug): Integer; cdecl; lua_getinfo : function(L: lua_State; const what: MarshaledAString; ar: Plua_Debug): Integer; cdecl; lua_getlocal : function(L: lua_State; const ar: Plua_Debug; n: Integer): MarshaledAString; cdecl; lua_setlocal : function(L: lua_State; const ar: Plua_Debug; n: Integer): MarshaledAString; cdecl; lua_getupvalue : function(L: lua_State; funcindex, n: Integer): MarshaledAString; cdecl; lua_setupvalue : function(L: lua_State; funcindex, n: Integer): MarshaledAString; cdecl; lua_upvalueid : function(L: lua_State; fidx, n: Integer): Pointer; cdecl; lua_upvaluejoin : procedure(L: lua_State; fix1, n1, fidx2, n2: Integer); cdecl; lua_sethook : procedure(L: lua_State; func: lua_Hook; mask: Integer; count: Integer); cdecl; lua_gethook : function(L: lua_State): lua_Hook; cdecl; lua_gethookmask : function(L: lua_State): Integer; cdecl; lua_gethookcount : function(L: lua_State): Integer; cdecl; luaopen_base : function(L: lua_State): Integer; cdecl; luaopen_coroutine : function(L: lua_State): Integer; cdecl; luaopen_table : function(L: lua_State): Integer; cdecl; luaopen_io : function(L: lua_State): Integer; cdecl; luaopen_os : function(L: lua_State): Integer; cdecl; luaopen_string : function(L: lua_State): Integer; cdecl; luaopen_utf8 : function(L: lua_State): Integer; cdecl; luaopen_bit32 : function(L: lua_State): Integer; cdecl; luaopen_math : function(L: lua_State): Integer; cdecl; luaopen_debug : function(L: lua_State): Integer; cdecl; luaopen_package : function(L: lua_State): Integer; cdecl; luaL_openlibs : procedure(L: lua_State); cdecl; luaL_checkversion_ : procedure(L: lua_State; ver: lua_Number; sz: size_t); cdecl; luaL_getmetafield : function(L: lua_State; obj: Integer; e: MarshaledAString): Integer; cdecl; luaL_callmeta : function(L: lua_State; obj: Integer; e: MarshaledAString): Integer; cdecl; luaL_tolstring : function(L: lua_State; idx: Integer; len: Psize_t): MarshaledAString; cdecl; luaL_argerror : function(L: lua_State; arg: Integer; extramsg: MarshaledAString): Integer; cdecl; luaL_checklstring : function(L: lua_State; arg: Integer; l_: Psize_t): MarshaledAString; cdecl; luaL_optlstring : function(L: lua_State; arg: Integer; const def: MarshaledAString; l_: Psize_t): MarshaledAString; cdecl; luaL_checknumber : function(L: lua_State; arg: Integer): lua_Number; cdecl; luaL_optnumber : function(L: lua_State; arg: Integer; def: lua_Number): lua_Number; cdecl; luaL_checkinteger : function(L: lua_State; arg: Integer): lua_Integer; cdecl; luaL_optinteger : function(L: lua_State; arg: Integer; def: lua_Integer): lua_Integer; cdecl; luaL_checkstack : procedure(L: lua_State; sz: Integer; const msg: MarshaledAString); cdecl; luaL_checktype : procedure(L: lua_State; arg: Integer; t: Integer); cdecl; luaL_checkany : procedure(L: lua_State; arg: Integer); cdecl; luaL_newmetatable : function(L: lua_State; const tname: MarshaledAString): Integer; cdecl; luaL_setmetatable : procedure(L: lua_State; const tname: MarshaledAString); cdecl; luaL_testudata : procedure(L: lua_State; ud: Integer; const tname: MarshaledAString); cdecl; luaL_checkudata : function(L: lua_State; ud: Integer; const tname: MarshaledAString): Pointer; cdecl; luaL_where : procedure(L: lua_State; lvl: Integer); cdecl; luaL_error : function(L: lua_State; fmt: MarshaledAString; args: array of const): Integer; cdecl; luaL_checkoption : function(L: lua_State; arg: Integer; const def: MarshaledAString; const lst: PMarshaledAString): Integer; cdecl; luaL_fileresult : function(L: lua_State; stat: Integer; fname: MarshaledAString): Integer; cdecl; luaL_execresult : function(L: lua_State; stat: Integer): Integer; cdecl; luaL_ref : function(L: lua_State; t: Integer): Integer; cdecl; luaL_unref : procedure(L: lua_State; t: Integer; ref: Integer); cdecl; luaL_loadfilex : function(L: lua_State; const filename: MarshaledAString; const mode: MarshaledAString): Integer; cdecl; luaL_loadbufferx : function(L: lua_State; const buff: MarshaledAString; sz: size_t; const name: MarshaledAString; const mode: MarshaledAString): Integer; cdecl; luaL_loadstring : function(L: lua_State; const s: MarshaledAString): Integer; cdecl; luaL_newstate : function(): lua_State; cdecl; luaL_len : function(L: lua_State; idx: Integer): lua_Integer; cdecl; luaL_gsub : function(L: lua_State; const s: MarshaledAString; const p: MarshaledAString; const r: MarshaledAString): MarshaledAString; cdecl; luaL_setfuncs : procedure(L: lua_State; const l_: PluaL_Reg; nup: Integer); cdecl; luaL_getsubtable : function(L: lua_State; idx: Integer; const fname: MarshaledAString): Integer; cdecl; luaL_traceback : procedure(L: lua_State; L1: lua_State; const msg: MarshaledAString; level: Integer); cdecl; luaL_requiref : procedure(L: lua_State; const modname: MarshaledAString; openf: lua_CFunction; glb: Integer); cdecl; luaL_buffinit : procedure(L: lua_State; b: Plual_Buffer); cdecl; luaL_prepbuffsize : function(b: Plual_Buffer; sz: size_t): Pointer; cdecl; luaL_addlstring : procedure(b: Plual_Buffer; const s: MarshaledAString; L: size_t); cdecl; luaL_addstring : procedure(b: Plual_Buffer; const s: MarshaledAString); cdecl; luaL_addvalue : procedure(b: Plual_Buffer); cdecl; luaL_pushresult : procedure(b: Plual_Buffer); cdecl; luaL_pushresultsize : procedure(b: Plual_Buffer; sz: size_t); cdecl; luaL_buffinitsize : function(L: lua_State; b: Plual_Buffer; sz: size_t): Pointer; cdecl; function lua_tonumber(L: lua_State; idx: Integer): lua_Number; inline; function lua_tointeger(L: lua_State; idx: Integer): lua_Integer; inline; procedure lua_pop(L: lua_State; n: Integer); inline; procedure lua_newtable(L: lua_State); inline; procedure lua_register(L: lua_State; const n: MarshaledAString; f: lua_CFunction); inline; procedure lua_pushcfunction(L: lua_State; f: lua_CFunction); inline; function lua_isfunction(L: lua_State; n: Integer): Boolean; inline; function lua_istable(L: lua_State; n: Integer): Boolean; inline; function lua_islightuserdata(L: lua_State; n: Integer): Boolean; inline; function lua_isnil(L: lua_State; n: Integer): Boolean; inline; function lua_isboolean(L: lua_State; n: Integer): Boolean; inline; function lua_isthread(L: lua_State; n: Integer): Boolean; inline; function lua_isnone(L: lua_State; n: Integer): Boolean; inline; function lua_isnoneornil(L: lua_State; n: Integer): Boolean; inline; procedure lua_pushliteral(L: lua_State; s: MarshaledAString); inline; procedure lua_pushglobaltable(L: lua_State); inline; function lua_tostring(L: lua_State; i: Integer): MarshaledAString; procedure lua_insert(L: lua_State; idx: Integer); inline; procedure lua_remove(L: lua_State; idx: Integer); inline; procedure lua_replace(L: lua_State; idx: Integer); inline; procedure luaL_newlibtable(L: lua_State; lr: array of luaL_Reg); overload; procedure luaL_newlibtable(L: lua_State; lr: PluaL_Reg); overload; procedure luaL_newlib(L: lua_State; lr: array of luaL_Reg); overload; procedure luaL_newlib(L: lua_State; lr: PluaL_Reg); overload; procedure luaL_argcheck(L: lua_State; cond: Boolean; arg: Integer; extramsg: MarshaledAString); function luaL_checkstring(L: lua_State; n: Integer): MarshaledAString; function luaL_optstring(L: lua_State; n: Integer; d: MarshaledAString): MarshaledAString; function luaL_typename(L: lua_State; i: Integer): MarshaledAString; function luaL_dofile(L: lua_State; const fn: MarshaledAString): Integer; function luaL_dostring(L: lua_State; const s: MarshaledAString): Integer; procedure luaL_getmetatable(L: lua_State; n: MarshaledAString); function luaL_loadbuffer(L: lua_State; const s: MarshaledAString; sz: size_t; const n: MarshaledAString): Integer; procedure lua_call(L: lua_State; nargs: Integer; nresults: Integer); inline; function lua_pcall(L: lua_State; nargs: Integer; nresults: Integer; errfunc: Integer): Integer; inline; function lua_yield(L: lua_State; nresults: Integer): Integer; inline; function lua_upvalueindex(i: Integer): Integer; inline; procedure luaL_checkversion(L: lua_State); inline; function lual_loadfile(L: lua_State; const filename: MarshaledAString): Integer; inline; function luaL_prepbuffer(b: Plual_Buffer): MarshaledAString; inline; implementation function lua_tonumber(L: lua_State; idx: Integer): lua_Number; inline; begin Result := lua_tonumberx(L, idx, NIL); end; function lua_tointeger(L: lua_State; idx: Integer): lua_Integer; inline; begin Result := lua_tointegerx(L, idx, NIL); end; procedure lua_pop(L: lua_State; n: Integer); inline; begin lua_settop(L, -(n) - 1); end; procedure lua_newtable(L: lua_State); inline; begin lua_createtable(L, 0, 0); end; procedure lua_register(L: lua_State; const n: MarshaledAString; f: lua_CFunction); begin lua_pushcfunction(L, f); lua_setglobal(L, n); end; procedure lua_pushcfunction(L: lua_State; f: lua_CFunction); begin lua_pushcclosure(L, f, 0); end; function lua_isfunction(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TFUNCTION); end; function lua_istable(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TTABLE); end; function lua_islightuserdata(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TLIGHTUSERDATA); end; function lua_isnil(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TNIL); end; function lua_isboolean(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TBOOLEAN); end; function lua_isthread(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TTHREAD); end; function lua_isnone(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) = LUA_TNONE); end; function lua_isnoneornil(L: lua_State; n: Integer): Boolean; begin Result := (lua_type(L, n) <= 0); end; procedure lua_pushliteral(L: lua_State; s: MarshaledAString); begin lua_pushlstring(L, s, Length(s)); end; procedure lua_pushglobaltable(L: lua_State); begin lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); end; function lua_tostring(L: lua_State; i: Integer): MarshaledAString; begin Result := lua_tolstring(L, i, NIL); end; procedure lua_insert(L: lua_State; idx: Integer); begin lua_rotate(L, idx, 1); end; procedure lua_remove(L: lua_State; idx: Integer); begin lua_rotate(L, idx, -1); lua_pop(L, 1); end; procedure lua_replace(L: lua_State; idx: Integer); begin lua_copy(L, -1, idx); lua_pop(L, 1); end; procedure lua_call(L: lua_State; nargs: Integer; nresults: Integer); inline; begin lua_callk(L, nargs, nresults, 0, NIL); end; function lua_pcall(L: lua_State; nargs: Integer; nresults: Integer; errfunc: Integer): Integer; inline; begin Result := lua_pcallk(L, nargs, nresults, errfunc, 0, NIL); end; function lua_yield(L: lua_State; nresults: Integer): Integer; inline; begin Result := lua_yieldk(L, nresults, 0, NIL); end; function lua_upvalueindex(i: Integer): Integer; inline; begin Result := LUA_REGISTRYINDEX - i; end; procedure luaL_newlibtable(L: lua_State; lr: array of luaL_Reg); overload; begin lua_createtable(L, 0, High(lr)); end; procedure luaL_newlibtable(L: lua_State; lr: PluaL_Reg); overload; var n: Integer; begin n := 0; while lr^.name <> nil do begin inc(n); inc(lr); end; lua_createtable(L, 0, n); end; procedure luaL_newlib(L: lua_State; lr: array of luaL_Reg); overload; begin luaL_newlibtable(L, lr); luaL_setfuncs(L, @lr, 0); end; procedure luaL_newlib(L: lua_State; lr: PluaL_Reg); overload; begin luaL_newlibtable(L, lr); luaL_setfuncs(L, lr, 0); end; procedure luaL_argcheck(L: lua_State; cond: Boolean; arg: Integer; extramsg: MarshaledAString); begin if not cond then luaL_argerror(L, arg, extramsg); end; function luaL_checkstring(L: lua_State; n: Integer): MarshaledAString; begin Result := luaL_checklstring(L, n, nil); end; function luaL_optstring(L: lua_State; n: Integer; d: MarshaledAString): MarshaledAString; begin Result := luaL_optlstring(L, n, d, nil); end; function luaL_typename(L: lua_State; i: Integer): MarshaledAString; begin Result := lua_typename(L, lua_type(L, i)); end; function luaL_dofile(L: lua_State; const fn: MarshaledAString): Integer; begin Result := lual_loadfile(L, fn); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; function luaL_dostring(L: lua_State; const s: MarshaledAString): Integer; begin Result := luaL_loadstring(L, s); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; procedure luaL_getmetatable(L: lua_State; n: MarshaledAString); begin lua_getfield(L, LUA_REGISTRYINDEX, n); end; function luaL_loadbuffer(L: lua_State; const s: MarshaledAString; sz: size_t; const n: MarshaledAString): Integer; begin Result := luaL_loadbufferx(L, s, sz, n, NIL); end; procedure luaL_checkversion(L: lua_State); inline; begin luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES); end; function lual_loadfile(L: lua_State; const filename: MarshaledAString): Integer; inline; begin Result := luaL_loadfilex(L, filename, NIL); end; function luaL_prepbuffer(b: Plual_Buffer): MarshaledAString; inline; begin Result := luaL_prepbuffsize(b, LUAL_BUFFERSIZE); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.6 12/5/2004 5:06:30 PM JPMugaas Tightened the detection for NCSA Telnet FTP Server for DOS. The parser was causing problems with SuperTCP because the formats are similar. By preventing SuperTCP from being detected, LongFilenames were not parsed in SuperTCP running on Windows 2000. Rev 1.5 10/26/2004 9:51:14 PM JPMugaas Updated refs. Rev 1.4 6/5/2004 4:45:22 PM JPMugaas Reports SizeAvail=False for directories in a list. As per the dir format. Rev 1.3 4/19/2004 5:05:58 PM JPMugaas Class rework Kudzu wanted. Rev 1.2 2004.02.03 5:45:32 PM czhower Name changes Rev 1.1 10/19/2003 3:36:04 PM DSiders Added localization comments. Rev 1.0 2/19/2003 10:13:38 PM JPMugaas Moved parsers to their own classes. } unit IdFTPListParseNCSAForDOS; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase; type TIdNCSAforDOSFTPListItem = class(TIdFTPListItem); TIdFTPLPNCSAforDOS = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function IsFooter(const AData : String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function GetIdent : String; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseNCSAForDOS"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPNCSAforDOS } class function TIdFTPLPNCSAforDOS.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var s : TStrings; LData : String; i : Integer; begin Result := False; if AListing.Count > 0 then begin //we have to loop through because there is a similar format //in SuperTCP but that one has an additional field with spaces //for long filenames. for i := 0 to AListing.Count-2 do begin LData := AListing[i]; s := TStringList.Create; try SplitColumns(LData, s); if s.Count = 4 then begin Result := ((s[1] = '<DIR>') or IsNumeric(s[1])) and {do not localize} IsMMDDYY(s[2], '-') and IsHHMMSS(s[3], ':') and {do not localize} ExcludeQVNET(LData); end; finally FreeAndNil(s); end; if not Result then begin Break; end; end; Result := IsFooter(AListing[AListing.Count-1]); end; end; class function TIdFTPLPNCSAforDOS.GetIdent: String; begin Result := 'NCSA for MS-DOS (CU/TCP)'; {do not localize} end; class function TIdFTPLPNCSAforDOS.IsFooter(const AData: String): Boolean; var LWords : TStrings; begin Result := False; LWords := TStringList.Create; try SplitColumns(Trim(StringReplace(AData, '-', ' ', [rfReplaceAll])), LWords); while LWords.Count > 2 do begin LWords.Delete(0); end; if LWords.Count = 2 then begin Result := (LWords[0] = 'Bytes') and (LWords[1] = 'Available'); {do not localize} end; finally FreeAndNil(LWords); end; end; class function TIdFTPLPNCSAforDOS.IsHeader(const AData: String): Boolean; begin Result := False; end; class function TIdFTPLPNCSAforDOS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdNCSAforDOSFTPListItem.Create(AOwner); end; class function TIdFTPLPNCSAforDOS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf, LPt : String; begin LBuf := AItem.Data; {filename - note that a space is illegal in MS-DOS so this should be safe} AItem.FileName := Fetch(LBuf); {type or size} LBuf := Trim(LBuf); LPt := Fetch(LBuf); if LPt = '<DIR>' then {do not localize} begin AItem.ItemType := ditDirectory; AItem.SizeAvail := False; end else begin AItem.ItemType := ditFile; AItem.Size := IndyStrToInt64(LPt, 0); end; //time stamp if LBuf <> '' then begin LBuf := Trim(LBuf); LPt := Fetch(LBuf); if LPt <> '' then begin //Date AItem.ModifiedDate := DateMMDDYY(LPt); LBuf := Trim(LBuf); LPt := Fetch(LBuf); if LPt <> '' then begin AItem.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LPt); end; end; end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPNCSAforDOS); finalization UnRegisterFTPListParser(TIdFTPLPNCSAforDOS); end.
//Exercicio 86: Faça um algoritmo que leia uma matriz A NxM de valores inteiros, determine //a sua matriz transposta e exiba. { Solução em Portugol Algoritmo Exercicio 86; Var matriz: vetor[1..1000,1..1000] de inteiro; N,M,i,j: inteiro; Inicio exiba("Programa que exibe a transposta de uma matriz de números inteiros."); // Leitura das dimensões da matriz. exiba("Digite a dimensão N da matriz:"); leia(N); enquanto(N <= 0)faça exiba("Digite uma dimensão maior que 0:"); leia(N); fimenquanto; exiba("Digite a dimensão M da matriz:"); leia(M); enquanto(M <= 0)faça exiba("Digite uma dimensão maior que 0:"); leia(M); fimenquanto; para i <- 1 até N faça // Leitura dos elementos da matriz. para j <-1 até M faça exiba("Digite o elemento matriz[",i,",",j,"]); leia(matriz[i,j]); fimpara; fimpara; exiba("A matriz é:"); para i <- 1 até N faça // Exibindo a matriz para j <- 1 até M faça exiba(matriz[i,j]," "); fimpara; exiba(''); // Pula linha. fimpara; exiba("A matriz transposta é:"); para j <- 1 até M faça // Exibe a transposta. para i <-1 até N faça exiba(matriz[j,i]," "); fimpara; exiba(""); // Pula linha. fimpara; Fim. } // Solução em Pascal Program Exercicio86; uses crt; Var matriz: array[1..1000,1..1000] of integer; N,M,i,j: integer; Begin ClrScr; writeln('Programa que exibe a transposta de uma matriz de números inteiros.'); // Leitura das dimensões da matriz. writeln('Digite a dimensão N da matriz:'); readln(N); while(N <= 0)do Begin writeln('Digite uma dimensão maior que 0:'); readln(N); End; writeln('Digite a dimensão M da matriz:'); readln(M); while(M <= 0)do Begin writeln('Digite uma dimensão maior que 0:'); readln(M); End; for i := 1 to N do // Leitura dos elementos da matriz. for j :=1 to M do Begin writeln('Digite o elemento matriz[',i,',',j,']'); readln(matriz[i,j]); End; writeln('A matriz é:'); for i := 1 to N do // Exibindo a matriz Begin for j := 1 to M do write(matriz[i,j],' '); writeln(''); // Pula linha. End; writeln('A matriz transposta é:'); for i := 1 to M do // Exibindo a transposta Begin for j := 1 to N do write(matriz[j,i],' '); writeln(''); // Pula linha. End; repeat until keypressed; end.
unit infosistemas.view.messages; interface uses WinAPI.Windows; type //Mensagens exibidas na aplicação. TMessagesConst = class const ClientNotFound = 'Não foi encontrado um cliente com este CPF!'; InvalidHostMail = 'A caixa de destino da mensagem não pode ser vazia!'; InvalidMailData = 'Os dados do cliente não foram recebido para serem enviados ' + 'na mensagem de email!'; InvalidMail = 'O email informado não é válido!'; InvalidCEP = 'O cep informado não é válido e não pode ter seus dados obtidos.'; end; implementation end.
unit MdCollect; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type ECanError = class (Exception); TMyItem = class (TCollectionItem) private FCode: Integer; FText: string; procedure SetCode(const Value: Integer); procedure SetText(const Value: string); published property Text: string read FText write SetText; property Code: Integer read FCode write SetCode; end; TMyCollection = class (TCollection) private fComp: TComponent; fCollString: string; public constructor Create (CollOwner: TComponent); function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; end; TMdCollection = class(TComponent) private fColl: TMyCollection; procedure SetMoreData(const Value: TMyCollection); function GetCollString: string; protected public constructor Create (aOwner: TComponent); override; destructor Destroy; override; published property MoreData: TMyCollection read FColl write SetMoreData; property CollString: string read GetCollString; end; procedure Register; implementation procedure Register; begin RegisterComponents ('Md', [TMdCollection]); end; { TMdCollection } constructor TMdCollection.Create(aOwner: TComponent); begin inherited; fColl := TMyCollection.Create (self); end; destructor TMdCollection.Destroy; begin inherited; fColl.Free; end; function TMdCollection.GetCollString: string; begin Result := fColl.fCollString; end; procedure TMdCollection.SetMoreData(const Value: TMyCollection); begin FColl.Assign (Value); end; { TMyItem } procedure TMyItem.SetCode(const Value: Integer); begin FCode := Value; Changed (False); end; procedure TMyItem.SetText(const Value: string); begin FText := Value; Changed (False); end; { TMyCollection } constructor TMyCollection.Create (CollOwner: TComponent); begin inherited Create (TMyItem); fComp := CollOwner; end; function TMyCollection.GetOwner: TPersistent; begin Result := fComp; end; procedure TMyCollection.Update(Item: TCollectionItem); var str: string; i: integer; begin inherited; // udpate all in any case str := ''; for i := 0 to Count - 1 do begin str := str + (Items [i] as TMyItem).Text; if i < Count - 1 then str := str + '-'; end; fCollString := str; end; end.
unit IdTransactedFileStream; interface {$I IdCompilerDefines.inc} { Original author: Grahame Grieve His notes are: If you want transactional file handling, with commit and rollback, then this is the unit for you. It provides transactional safety on Vista, win7, and windows server 2008, and just falls through to normal file handling on earlier versions of windows. There's a couple of issues with the wrapper classes TKernelTransaction and TIdTransactedFileStream: - you can specify how you want file reading to work with a transactional isolation. I don't surface this. - you can elevate the transactions to coordinate with DTC. They don't do this (for instance, you could put your file handling in the same transaction as an SQLServer transaction). I haven't done this - but if you do this, I'd love a copy ;-) you use it like this: procedure StringToFile(const AStr, AFilename: String); var oFileStream: TIdTransactedFileStream; oTransaction : TKernelTransaction; begin oTransaction := TIdKernelTransaction.Create('Save Content to file '+aFilename, false); Try Try oFileStream := TIdTransactedFileStream.Create(AFilename, fmCreate); try if Length(AStr) > 0 then LFileStream.Write(AStr[1], Length(AStr)); finally LFileStream.Free; end; oTransaction.Commit; Except oTransaction.Rollback; raise; End; Finally oTransaction.Free; End; end; anyway - maybe useful in temporary file handling with file and email? I've been burnt with temporary files and server crashes before. } uses {$IFDEF WIN32_OR_WIN64} Windows, Consts, {$ENDIF} Classes, SysUtils, IdGlobal; {$IFDEF WIN32_OR_WIN64} const TRANSACTION_DO_NOT_PROMOTE = 1; TXFS_MINIVERSION_COMMITTED_VIEW : Word = $0000; // The view of the file as of its last commit. TXFS_MINIVERSION_DIRTY_VIEW : Word = $FFFE; // The view of the file as it is being modified by the transaction. TXFS_MINIVERSION_DEFAULT_VIEW : Word = $FFFF; // Either the committed or dirty view of the file, depending on the context. // A transaction that is modifying the file gets the dirty view, while a transaction // that is not modifying the file gets the committed view. // remember to close the transaction handle. Use the CloseTransaction function here to avoid problems if the transactions are not available type TktmCreateTransaction = function (lpSecurityAttributes: PSecurityAttributes; pUow : Pointer; CreateOptions, IsolationLevel, IsolationFlags, Timeout : DWORD; Description : PWideChar) : THandle; stdcall; TktmCreateFileTransacted = function (lpFileName: PChar; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle; hTransaction : THandle; MiniVersion : Word; pExtendedParameter : Pointer): THandle; stdcall; TktmCommitTransaction = function (hTransaction : THandle) : Boolean; stdcall; TktmRollbackTransaction = function (hTransaction : THandle) : Boolean; stdcall; TktmCloseTransaction = function (hTransaction : THandle) : Boolean; stdcall; var CreateTransaction : TktmCreateTransaction; CreateFileTransacted : TktmCreateFileTransacted; CommitTransaction : TktmCommitTransaction; RollbackTransaction : TktmRollbackTransaction; CloseTransaction : TktmCloseTransaction; {$ENDIF} Function IsTransactionsWorking : Boolean; type TIdKernelTransaction = class (TObject) protected FHandle : THandle; public constructor Create(Const sDescription : String; bCanPromote : Boolean = false); destructor Destroy; override; function IsTransactional : Boolean; procedure Commit; procedure RollBack; end; TIdTransactedFileStream = class(THandleStream) {$IFNDEF WIN32_OR_WIN64} protected FFileStream : TFileStream; {$ENDIF} public constructor Create(const FileName: string; Mode: Word; oTransaction : TIdKernelTransaction); destructor Destroy; override; end; implementation uses RTLConsts; {$IFDEF WIN32_OR_WIN64} var GHandleKtm : HModule; GHandleKernel : HModule; function DummyCreateTransaction(lpSecurityAttributes: PSecurityAttributes; pUow : Pointer; CreateOptions, IsolationLevel, IsolationFlags, Timeout : DWORD; Description : PWideChar) : THandle; stdcall; begin result := 1; end; function DummyCreateFileTransacted(lpFileName: PChar; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle; hTransaction : THandle; MiniVersion : Word; pExtendedParameter : Pointer): THandle; stdcall; begin result := CreateFile(lpFilename, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); end; function DummyCommitTransaction(hTransaction : THandle) : Boolean; stdcall; begin assert(hTransaction = 1); result := true; end; function DummyRollbackTransaction(hTransaction : THandle) : Boolean; stdcall; begin assert(hTransaction = 1); result := true; end; function DummyCloseTransaction(hTransaction : THandle) : Boolean; stdcall; begin assert(hTransaction = 1); result := true; end; procedure LoadDll; begin GHandleKtm := LoadLibrary('ktmw32.dll'); if GHandleKtm <> 0 Then begin GHandleKernel := GetModuleHandle('Kernel32.dll'); //LoadLibrary('kernel32.dll'); @CreateTransaction := GetProcAddress(GHandleKtm, 'CreateTransaction'); @CommitTransaction := GetProcAddress(GHandleKtm, 'CommitTransaction'); @RollbackTransaction := GetProcAddress(GHandleKtm, 'RollbackTransaction'); @CloseTransaction := GetProcAddress(GHandleKernel, 'CloseHandle'); {$IFDEF UNICODE} @CreateFileTransacted := GetProcAddress(GHandleKernel, 'CreateFileTransactedW'); {$ELSE} @CreateFileTransacted := GetProcAddress(GHandleKernel, 'CreateFileTransactedA'); {$ENDIF} end else begin @CreateTransaction := @DummyCreateTransaction; @CommitTransaction := @DummyCommitTransaction; @RollbackTransaction := @DummyRollbackTransaction; @CloseTransaction := @DummyCloseTransaction; @CreateFileTransacted := @DummyCreateFileTransacted; end; end; procedure UnloadDll; begin if GHandleKtm <> 0 then begin freelibrary(GHandleKtm); // freelibrary(GHandleKernel); end end; function IsTransactionsWorking : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} begin result := GHandleKtm <> 0; end; {$ELSE} function IsTransactionsWorking : Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} begin result := False; end; {$ENDIF} { TIdKernelTransaction } constructor TIdKernelTransaction.Create(const sDescription: String; bCanPromote : Boolean); var pDesc : PWideChar; begin inherited Create; {$IFDEF UNICODE} GetMem(pDesc, length(sDescription) + 2); try StringToWideChar(sDescription, pDesc, length(sDescription) + 2); {$ELSE} GetMem(pDesc, length(sDescription) * 2 + 4); try StringToWideChar(sDescription, pDesc, length(sDescription) * 2 + 4); {$ENDIF} {$IFDEF WIN32_OR_WIN64} if bCanPromote Then begin FHandle := CreateTransaction(nil, nil, 0, 0, 0, 0, pDesc); end else begin FHandle := CreateTransaction(nil, nil, TRANSACTION_DO_NOT_PROMOTE, 0, 0, 0, pDesc); end; {$ENDIF} finally FreeMem(pDesc); end; end; destructor TIdKernelTransaction.Destroy; begin {$IFDEF WIN32_OR_WIN64} CloseTransaction(FHandle); {$ENDIF} inherited Destroy; end; procedure TIdKernelTransaction.Commit; begin {$IFDEF WIN32_OR_WIN64} if not CommitTransaction(FHandle) then begin IndyRaiseLastError; end; {$ENDIF} end; function TIdKernelTransaction.IsTransactional: Boolean; begin result := IsTransactionsWorking; end; procedure TIdKernelTransaction.RollBack; begin {$IFDEF WIN32_OR_WIN64} if not RollbackTransaction(FHandle) then begin IndyRaiseLastError; end; {$ENDIF} end; {$IFDEF WIN32_OR_WIN64} function FileCreateTransacted(const FileName: string; hTransaction : THandle): THandle; begin Result := THandle(CreateFileTransacted(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0, hTransaction, 0, nil)); if result = INVALID_HANDLE_VALUE Then begin IndyRaiseLastError; end; end; function FileOpenTransacted(const FileName: string; Mode: LongWord; hTransaction : THandle): THandle; 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 Result := THandle(CreateFileTransacted(PChar(FileName),AccessMode[Mode and 3], ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0, hTransaction,TXFS_MINIVERSION_DEFAULT_VIEW, nil)); end; {$ENDIF} { TIdTransactedFileStream } {$IFDEF WIN32_OR_WIN64} constructor TIdTransactedFileStream.Create(const FileName: string; Mode: Word; oTransaction: TIdKernelTransaction); var aHandle : THandle; begin if Mode = fmCreate then begin aHandle := FileCreateTransacted(FileName, oTransaction.FHandle); if aHandle = INVALID_HANDLE_VALUE then begin raise EFCreateError.CreateResFmt(@SFCreateError, [FileName]); end; end else begin aHandle := FileOpenTransacted(FileName, Mode, oTransaction.FHandle); if aHandle = INVALID_HANDLE_VALUE then begin raise EFOpenError.CreateResFmt(@SFOpenError, [FileName]); end; end; inherited Create(ahandle); end; {$ELSE} constructor TIdTransactedFileStream.Create(const FileName: string; Mode: Word; oTransaction: TIdKernelTransaction); var LStream : TFileStream; begin LStream := FFileStream.Create(FileName,Mode); inherited Create ( LStream.Handle); FFileStream := LStream; end; {$ENDIF} destructor TIdTransactedFileStream.Destroy ; begin {$IFDEF WIN32_OR_WIN64} if Handle = INVALID_HANDLE_VALUE then begin FileClose(Handle); end; inherited Destroy; {$ELSE} //we have to deference our copy of the THandle so we don't free it twice. FHandle := INVALID_HANDLE_VALUE; FreeAndNil( FFileStream ); inherited Destroy; {$ENDIF} end; {$IFDEF WIN32_OR_WIN64} initialization LoadDLL; finalization UnloadDLL; {$ENDIF} End.
unit dr_script; {$mode objfpc}{$H+} interface uses Classes, SysUtils , winpeimagereader {need this for reading exe info} , elfreader {needed for reading ELF executables} , machoreader {needed for reading MACH-O executables} , uPSCompiler, uPSRuntime, uPSComponent, uPSDisassembly, uPSR_std, uPSC_std, uPSR_classes, uPSC_classes, (*uPSC_controls, uPSR_controls, uPSC_forms, uPSR_forms,*) uPSR_dateutils, uPSC_dateutils, uPSR_dll, uPSC_dll ; type TPascalScriptHelper = class (TObject) protected _compiler : TPSPascalCompiler; procedure SaveCompiled(var Data: string; outName : string = 'out'); procedure SaveDisassembly(var Data: string; outName : string = 'dis'); procedure ExtendRuntime(runtime: TPSExec; classImporter: TPSRuntimeClassImporter); (* procedure OnCompile(Sender: TPSPascalCompiler); procedure OnExecImport(Sender: TObject; se: TPSExec; x: TPSRuntimeClassImporter); *) public constructor Create; destructor Destroy; override; function CompileScript(script: string; out bytecode, messages: string): boolean; function RunCompiledScript(bytecode: string; out runtimeErrors: string): boolean; (*function Compile(const FileName: string): Boolean; function Execute: Boolean;*) end; function ExtendCompiler(compiler: TPSPascalCompiler; const name: string): boolean; implementation procedure MWritedt(d : TDateTime); var s: String; begin s:= DateToStr(d) + ' ' + TimeToStr(d); Write(s); end; procedure MWrites(const s: string); begin Write(s); end; procedure MWritei(const i: Integer); begin Write(i); end; procedure MWrited(const d: Double); begin Write(d:0:1); end; procedure MWriteln; begin Writeln; end; procedure MVal(const s: string; var n, z: Integer); begin Val(s, n, z); end; function ExtendCompiler(compiler: TPSPascalCompiler; const name: string): boolean; var customClass: TPSCompileTimeClass; begin try //compiler.AddDelphiFunction('procedure print(const AText: AnsiString);'); RegisterDateTimeLibrary_C(compiler); compiler.AddDelphiFunction('procedure Writes(const s: string)'); compiler.AddDelphiFunction('procedure WriteDT(d : TDateTime)'); compiler.AddDelphiFunction('procedure Writei(const i: Integer)'); compiler.AddDelphiFunction('procedure Writed(const f: Double)'); compiler.AddDelphiFunction('procedure Writeln'); compiler.AddDelphiFunction('procedure Val(const s: string; var n, z: Integer)'); compiler.AddDelphiFunction('function FileCreate(const FileName: string): integer)'); compiler.AddDelphiFunction('function FileWrite(Handle: Integer; const Buffer: pChar; Count: LongWord): Integer)'); compiler.AddDelphiFunction('procedure FileClose(handle: integer)'); //Sender.AddRegisteredVariable('Application', 'TApplication'); SIRegister_Std(compiler); SIRegister_Classes(compiler,true); //SIRegister_Controls(compiler); //SIRegister_Forms(compiler); SIRegisterTObject(compiler); // Add compile-time definition for TObject //customClass := compiler.AddClass(compiler.FindClass('TObject'), TAccumulator); //customclass.RegisterMethod('procedure Add(AValue: Integer)'); //customClass.RegisterMethod('function GetTotal: Integer'); Result := True; except Result := False; // will halt compilation end; end; //============================================================================== // TPascalScriptHelper //============================================================================== constructor TPascalScriptHelper.Create; begin _compiler := TPSPascalCompiler.Create; end; destructor TPascalScriptHelper.Destroy; begin _compiler.Free; end; procedure TPascalScriptHelper.SaveCompiled(var data : String; outName : string); var outFile: string; fx: Longint; begin OutFile:= ExtractFilePath(ParamStr(0)) + ChangeFileExt(outName,'.out'); Fx:= FileCreate(outFile); FileWrite(fx,data[1],Length(data)); FileClose(fx); end; procedure TPascalScriptHelper.SaveDisassembly(var data: string; outName : string); var outFile: string; fx: Longint; begin OutFile:= ExtractFilePath(ParamStr(0)) + ChangeFileExt(outName,'.dis'); fx:= FileCreate(outFile); FileWrite(fx, data[1], Length(data)); FileClose(fx); end; function TPascalScriptHelper.CompileScript(script: string; out bytecode, messages: string): boolean; var i: Integer; begin bytecode := ''; messages := ''; _compiler.OnUses := @ExtendCompiler; try Result := _compiler.Compile(script) and _compiler.GetOutput(bytecode); for i := 0 to _compiler.MsgCount - 1 do if Length(messages) = 0 then messages := _compiler.Msg[i].MessageToString else messages := messages + #13#10 + _compiler.Msg[i].MessageToString; finally _compiler.Free; end; end; function TPascalScriptHelper.RunCompiledScript(bytecode: string; out runtimeErrors: string): boolean; var runtime: TPSExec; classImporter: TPSRuntimeClassImporter; begin runtime := TPSExec.Create; classImporter := TPSRuntimeClassImporter.CreateAndRegister(runtime, false); try ExtendRuntime(runtime, classImporter); Result := runtime.LoadData(Bytecode) and runtime.RunScript and (runtime.ExceptionCode = erNoError); if not Result then runtimeErrors := PSErrorToString(runtime.LastEx, ''); finally classImporter.Free; runtime.Free; end; end; procedure TPascalScriptHelper.ExtendRuntime(runtime: TPSExec; classImporter: TPSRuntimeClassImporter); var runtimeClass: TPSRuntimeClass; begin //runtime.RegisterDelphiMethod(Self, @TForm1.MyPrint, 'print', cdRegister); runtime.RegisterDelphiFunction(@MWrites, 'procedure Writes(const s: string)', cdRegister); runtime.RegisterDelphiFunction(@MWriteDT, 'procedure WriteDT(d : TDateTime)', cdRegister); runtime.RegisterDelphiFunction(@MWritei, 'procedure Writei(const i: Integer)', cdRegister); runtime.RegisterDelphiFunction(@MWrited, 'procedure Writed(const f: Double)', cdRegister); runtime.RegisterDelphiFunction(@MWriteln, 'procedure Writeln', cdRegister); runtime.RegisterDelphiFunction(@MVal, 'procedure Val(const s: string; var n, z: Integer)', cdRegister); runtime.RegisterDelphiFunction(@FileCreate, 'function FileCreate(const FileName: string): integer)', cdRegister); runtime.RegisterDelphiFunction(@FileWrite, 'function FileWrite(Handle: Integer; const Buffer: pChar; Count: LongWord): Integer)', cdRegister); runtime.RegisterDelphiFunction(@FileClose, 'procedure FileClose(handle: integer)', cdRegister); RIRegister_Std(classImporter); RIRegister_Classes(classImporter,true); //RIRegister_Controls(classImporter); //RIRegister_Forms(classImporter); RegisterDateTimeLibrary_R(runtime); RegisterDLLRuntime(runtime); RIRegisterTObject(classImporter); //RuntimeClass := ClassImporter.Add(TAccumulator); //RuntimeClass.RegisterMethod(@TAccumulator.Add, 'Add'); //RuntimeClass.RegisterMethod(@TAccumulator.GetTotal, 'GetTotal'); end; (* procedure TPascalScriptHelper.OnExecImport(Sender: TObject; se: TPSExec; x: TPSRuntimeClassImporter); begin RIRegister_Std(x); RIRegister_Classes(x,true); RIRegister_Controls(x); RIRegister_Forms(x); RegisterDateTimeLibrary_R(se); RegisterDLLRuntime(se); end; procedure TPascalScriptHelper.OnCompile(Sender: TPSScript); begin RegisterDateTimeLibrary_C(Sender.Comp); Sender.AddFunction(@MWrites, 'procedure Writes(const s: string)'); Sender.AddFunction(@MWritedt,'procedure WriteDT(d : TDateTime)'); Sender.AddFunction(@MWritei, 'procedure Writei(const i: Integer)'); Sender.AddFunction(@MWrited, 'procedure Writed(const f: Double)'); Sender.AddFunction(@MWriteln, 'procedure Writeln'); Sender.AddFunction(@MyVal, 'procedure Val(const s: string; var n, z: Integer)'); Sender.AddFunction(@FileCreate, 'Function FileCreate(const FileName: string): integer)'); Sender.AddFunction(@FileWrite, 'function FileWrite(Handle: Integer; const Buffer: pChar; Count: LongWord): Integer)'); Sender.AddFunction(@FileClose, 'Procedure FileClose(handle: integer)'); //Sender.AddRegisteredVariable('Application', 'TApplication'); SIRegister_Std(Sender.Comp); SIRegister_Classes(Sender.Comp,true); SIRegister_Controls(Sender.Comp); SIRegister_Forms(Sender.Comp); end; function TPascalScriptHelper.Compile(const FileName: string): Boolean; var S: TStringList; i: Integer; begin Result:= False; if FileExists(FileName) then begin S:= TStringList.Create; S.LoadFromFile(FileName); _script.Script:= S; Result:= _script.Compile; for i:= 0 to _script.CompilerMessageCount - 1 do writeln(_script.CompilerMessages[i].MessageToString); S.Free; if not Result then if _script.CompilerMessageCount > 0 then for i:= 0 to _script.CompilerMessageCount-1 do Writeln(_script.CompilerErrorToStr(i)); end else Writeln('Script File not found: ', FileName); end; function TPascalScriptHelper.Execute: Boolean; begin //_script.SetVarToInstance('APPLICATION', Application); //_script.SetVarToInstance('SELF', Self); Result:= _script.Execute; //writeln(_script.About); if not Result then Writeln('Run-time error:' + _script.ExecErrorToString); end; *) end.
{*************************************************************************} { TImagePicker component } { for Delphi & C++Builder } { } { Copyright © 2000-2012 } { TMS Software } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {*************************************************************************} unit ImagePicker; {$I TMSDEFS.INC} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, StdCtrls, AdvCombo, Forms, Dialogs {$IFDEF DELPHIXE3_LVL} , System.UITypes {$ENDIF} ; const COLUMN_DELIMITER = '|'; MAJ_VER = 1; // Major version nr. MIN_VER = 1; // Minor version nr. REL_VER = 2; // Release nr. BLD_VER = 1; // Build nr. // version history // 1.1.0.0 : Added property ShowCaption to show caption always in the edit part of the dropdown // 1.1.0.1 : Fixed : issue with EditHeight // 1.1.1.0 : Added new method SelectByTag // 1.1.2.0 : Improved : ImageIndex not reset after calling EndUpdate // 1.1.2.1 : Fixed : Handling SelectByTag in sorted list type TImagePicker = class; TImagePickerItem = class(TCollectionItem) private FImageIndex: Integer; FCaption: string; FTag: Integer; procedure SetImageIndex(const Value: Integer); procedure SetCaption(const Value: string); protected function GetDisplayName: string; override; public constructor Create(Collection:TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property ImageIndex: Integer read FImageIndex write SetImageIndex; property Caption: string read FCaption write SetCaption; property Tag: Integer read FTag write FTag; end; TImagePickerItemCollection = class(TCollection) private FOwner:TImagePicker; function GetItem(Index: Integer): TImagePickerItem; procedure SetItem(Index: Integer; const Value: TImagePickerItem); protected procedure Update(Item: TCollectionItem); override; public function Add:TImagePickerItem; function Insert(index: Integer): TImagePickerItem; property Items[Index: Integer]: TImagePickerItem read GetItem write SetItem; default; constructor Create(AOwner:TImagePicker); function GetOwner: tPersistent; override; function IndexOf(s:string): Integer; end; {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TImagePicker = class(TAdvCustomCombo) private FImages:TImageList; FDropHeight: Integer; FEditHeight: Integer; FImagePickerItems:TImagePickerItemCollection; FEditColumn: Integer; FItemIndex: Integer; FUpdateCount: Integer; FLookup: string; FLookupIncr: Boolean; FSortedEx: Boolean; FDropped: Boolean; FShowCaption: Boolean; procedure SetEditHeight(Value: Integer); function GetEditHeight: Integer; procedure SetImages(const Value: TImageList); procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure WMLButtonUp(var Msg:TWMLButtonDown); message WM_LBUTTONUP; procedure WMChar(var Msg:TWMChar); message WM_CHAR; procedure WMSize(var Msg:TWMSize); message WM_SIZE; procedure SetItemIndexEx(const Value : Integer); function GetItemIndexEx: Integer; procedure BuildItems; function GetSortedEx: boolean; procedure SetSortedEx(const Value: boolean); procedure Sort; function GetDelimiter: Char; procedure SetDelimiter(const Value: Char); function GetComboItems: TStrings; procedure SetComboItems(const Value: TStrings); function GetSelection: TImagePickerItem; function GetCaption(Value: string):string; procedure SetShowCaption(const Value: Boolean); protected function GetVersionNr: Integer; override; procedure SetStyle(Value: TComboBoxStyle); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MeasureItem(Index: Integer; var Height: Integer); override; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override; procedure Notification(AComponent: TComponent; AOperation: TOperation); override; property ComboItems: TStrings read GetComboItems write SetComboItems; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure CreateWnd; override; property Text; procedure BeginUpdate; procedure EndUpdate; procedure SelectByCaption(const Value: string); procedure SelectByImageIdx(const Value: Integer); procedure SelectByTag(const Value: Integer); property Delimiter: Char read GetDelimiter write SetDelimiter; property Selection: TImagePickerItem read GetSelection; published property Anchors; property Constraints; property DragKind; property Color; property Ctl3D; property Items: TImagePickerItemCollection read FImagePickerItems write FImagePickerItems; property DragMode; property DragCursor; property EditHeight: Integer read GetEditheight write SetEditHeight; property DropHeight: Integer read fDropHeight write fDropHeight; property DropWidth; property Images: TImageList read FImages write SetImages; property Enabled; property Etched; property Flat; property FlatLineColor; property FocusBorder; property Font; // property ItemHeight; property ItemIndex: Integer read GetItemIndexEx write SetItemIndexEx; property ItemHeight; property LookupIncr: Boolean read FLookupIncr write FLookupIncr default False; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property ShowCaption: Boolean read FShowCaption write SetShowCaption default False; property Sorted: Boolean read GetSortedEx write SetSortedEx; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnStartDrag; property OnStartDock; property OnEndDock; property OnContextPopup; end; implementation uses ExtCtrls,ShellApi,CommCtrl ,ImgList ; const FDelimiter : Char = COLUMN_DELIMITER; var SortCol: Integer; procedure TImagePicker.SetStyle(Value: TComboBoxStyle); begin inherited SetStyle(csOwnerDrawFixed); end; function GetColumnString(var s:string):string; begin if (Pos(FDelimiter,s) > 0) then begin Result := Copy(s,1,Pos(FDelimiter,s)-1); Delete(s,1,Pos(FDelimiter,s)); end else begin Result := s; s := ''; end; end; function GetColumn(i: Integer; s:string): String; var k: Integer; begin k := 0; repeat Result := GetColumnString(s); inc(k); until (k > i); end; procedure TImagePicker.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var r,dr:TRect; s,su:string; ImgIdx,Err: Integer; isEdit:boolean; begin isEdit := odComboBoxEdit in State; r := Rect; if odSelected in State then Canvas.rectangle(r.left,r.top,r.right,r.bottom); if odSelected in State then begin Canvas.Brush.Color := clHighLight; Canvas.Pen.Color := clHighLight; Canvas.Font.Color := clHighLightText; end else begin Canvas.Brush.Color := Color; Canvas.Pen.color := Canvas.Brush.Color; end; dr := r; Canvas.Rectangle(dr.Left,dr.Top,dr.Right,dr.Bottom); if index < 0 then Exit; dr.Left := dr.Left + 2; s := ComboItems[Index]; su := Copy(s,1,Pos(FDelimiter,s)-1); Val(su,ImgIdx,Err); Delete(s,1,Pos(FDelimiter,s)); su := Copy(s,1,Pos(FDelimiter,s)-1); if Assigned(FImages) then FImages.Draw(Canvas,dr.left,dr.top,imgidx); if not isEdit or ShowCaption then begin if Assigned(FImages) then dr.left := dr.left + FImages.Width + 4; DrawTextEx(Canvas.handle,pchar(su),length(su),dr,DT_LEFT or DT_END_ELLIPSIS or DT_VCENTER or DT_SINGLELINE,nil); end; Canvas.Brush.color := Color; Canvas.Pen.color := Color; end; procedure TImagePicker.CreateWnd; begin inherited CreateWnd; if EditHeight = 0 then EditHeight := 18; end; constructor TImagePicker.Create(AOwner: TComponent); begin inherited Create(AOwner); FDropheight := 200; FEditColumn := -1; FImagePickerItems := TImagePickerItemCollection.Create(self); Flat := false; FDelimiter := COLUMN_DELIMITER; Width := 48; Style := csOwnerDrawFixed; end; destructor TImagePicker.Destroy; begin FImagePickerItems.Free; inherited Destroy; end; procedure TImagePicker.MeasureItem(Index: Integer; var Height: Integer); var Res: Integer; Canvas: TCanvas; begin Height := 40; if (index >= 0) then begin Canvas := TCanvas.Create; Canvas.Handle := GetDC(self.Handle); res := Canvas.TextHeight('gh') + 4; {avoid overlap on fonts} ReleaseDC(handle,Canvas.handle); Canvas.Free; Sendmessage(self.Handle,CB_SETITEMHEIGHT,index,res); end else begin res := EditHeight; end; Height := res; end; function TImagePicker.GetEditHeight: Integer; begin // if (csLoading in ComponentState) then Result := FEditHeight // else // Result := SendMessage(Handle,CB_GETITEMHEIGHT,-1,0) end; procedure TImagePicker.SetEditHeight(Value: Integer); begin FEditHeight := Value; SendMessage(Handle,CB_SETITEMHEIGHT,-1,Value); SendMessage(Handle,CB_SETITEMHEIGHT,0,Value); end; procedure TImagePicker.SetImages(const Value: TImageList); begin FImages := Value; Invalidate; end; procedure TImagePicker.CNCommand(var Message: TWMCommand); begin inherited; case message.NotifyCode of CBN_DROPDOWN: begin MoveWindow(self.Handle,self.Left,self.Top,width,EditHeight + FDropheight,True); DropDown; FDropped := True; ItemIndex := SendMessage(self.Handle,CB_GETCURSEL,0,0); message.Result := 0; if Assigned(OnClick) then OnClick(Self); end; CBN_SELCHANGE: begin FDropped := False; FItemIndex := SendMessage(self.Handle,CB_GETCURSEL,0,0); if Assigned(OnChange) then OnChange(Self); end; else inherited; end; end; function TImagePicker.GetItemIndexEx: Integer; begin Result := SendMessage(Handle,CB_GETCURSEL,0,0); end; procedure TImagePicker.SetItemIndexEx(const Value: Integer); begin if FDropped then FItemIndex := Value; SendMessage(Handle,CB_SETCURSEL,Value,0); end; procedure TImagePicker.Notification(AComponent: TComponent; AOperation: TOperation); begin if (aOperation = opRemove) and (AComponent = FImages) then FImages := nil; inherited; end; procedure TImagePicker.BuildItems; var i: Integer; s: string; begin if (csLoading in ComponentState) then Exit; while ComboItems.Count > FImagePickerItems.Count do ComboItems.Delete(ComboItems.Count - 1); for i := 1 to FImagePickerItems.Count do begin with FImagePickerItems.Items[i - 1] do s := Inttostr(FImageIndex) + FDelimiter + FCaption + FDelimiter + IntToStr(i-1); if ComboItems.Count >= i then begin ComboItems[i-1] := s; ComboItems.Objects[i - 1] := FImagePickerItems.Items[i-1]; end else begin ComboItems.AddObject(s, FImagePickerItems.Items[i-1]); end; end; end; procedure TImagePicker.Loaded; var eh: integer; begin inherited; eh := FEditHeight; BuildItems; ItemIndex := FItemIndex; if FSortedEx then Sort; EditHeight := eh; end; procedure TImagePicker.BeginUpdate; begin Inc(FUpdateCount); end; procedure TImagePicker.EndUpdate; var idx: integer; begin if FUpdateCount > 0 then begin Dec(FUpdateCount); if FUpdateCount = 0 then begin idx := ItemIndex; BuildItems; ItemIndex := idx; end; end; end; procedure TImagePicker.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if key in [vk_up,vk_down,vk_left,vk_right,vk_next,vk_prior,vk_home,vk_end,vk_escape] then begin FLookup := ''; Exit; end; if (Key = vk_back) and (Length(FLookup)>0) then Delete(FLookup,Length(FLookup),1); end; function TImagePicker.GetSortedEx: boolean; begin Result := FSortedEx; end; function ColumnCompare(List: TStringList; Index1, Index2: Integer): Integer; begin Result := AnsiStrComp(pchar(GetColumn(SortCol, List.Strings[Index1] )),pchar(GetColumn(SortCol, List.Strings[Index2]))); end; procedure TImagePicker.Sort; var sl: TStringList; begin sl := TStringList.Create; sl.Assign(ComboItems); SortCol := 1; sl.CustomSort(ColumnCompare); ComboItems.Assign(sl); sl.Free; end; procedure TImagePicker.SetSortedEx(const Value: boolean); begin fSortedEx := Value; if Value then if not (csLoading in ComponentState) then Sort; end; procedure TImagePicker.WMLButtonUp(var Msg:TWMLButtonDown); begin inherited; if FDropped then begin ItemIndex := fItemIndex; if SendMessage(self.Handle,CB_GETDROPPEDSTATE,0,0)=0 then FDropped := false; end; end; function TImagePicker.GetDelimiter: Char; begin Result := FDelimiter; end; procedure TImagePicker.SetDelimiter(const Value: Char); begin FDelimiter := Value; end; procedure TImagePicker.WMChar(var Msg: TWMChar); var i: Integer; s: string; Key: Char; function Max(a,b: Integer): Integer; begin if (a > b) then Result := a else Result := b; end; begin inherited; Key := Chr(Msg.CharCode); if not FLookupIncr then FLookup := Key else FLookup := FLookup + Key; if (ItemIndex >= 0) or (FLookupIncr) then begin for i := Max(1,ItemIndex+1) to Items.Count do begin s := GetCaption(ComboItems[i-1]); if s <> '' then if (Pos(AnsiUpperCase(FLookup),AnsiUpperCase(s)) = 1) then begin ItemIndex := i-1; Exit; end; end; end; for i := 1 to Items.Count do begin s := GetCaption(ComboItems[i-1]); if s <> '' then if (Pos(Uppercase(FLookup),Uppercase(s))=1) then begin ItemIndex := i-1; Exit; end; end; if FLookupIncr then begin FLookup := Key; for i := 1 to Items.Count do begin s := GetCaption(ComboItems[i-1]); if s <> '' then if (pos(AnsiUpperCase(FLookup),AnsiUpperCase(s))=1) then begin ItemIndex := i-1; Exit; end; end; end; end; function TImagePicker.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; { TImagePickerItemCollection } function TImagePickerItemCollection.Add: TImagePickerItem; begin Result := TImagePickerItem(inherited Add); end; constructor TImagePickerItemCollection.Create(AOwner: TImagePicker); begin inherited Create(TImagePickerItem); FOwner := AOwner; end; function TImagePickerItemCollection.GetItem(Index: Integer): TImagePickerItem; begin Result := TImagePickerItem(inherited Items[index]); end; function TImagePickerItemCollection.GetOwner: tPersistent; begin Result := FOwner; end; function TImagePickerItemCollection.IndexOf(s: string): Integer; var i: Integer; begin Result := -1; for i := 1 to Count do begin if Items[i - 1].Caption = s then begin Result := i - 1; Break; end; end; end; function TImagePickerItemCollection.Insert(Index: Integer): TImagePickerItem; begin Result := TImagePickerItem(inherited Insert(Index)); End; procedure TImagePickerItemCollection.SetItem(Index: Integer; const Value: TImagePickerItem); begin inherited SetItem(Index, Value); end; procedure TImagePickerItemCollection.Update(Item: TCollectionItem); begin inherited; end; { TImagePickerItem } procedure TImagePickerItem.Assign(Source: TPersistent); begin if Source is TImagePickerItem then begin ImageIndex := TImagePickerItem(Source).ImageIndex; Caption := TImagePickerItem(Source).Caption; Tag := TImagePickerItem(Source).Tag; TImagePickerItemCollection(collection).FOwner.BuildItems; end; end; constructor TImagePickerItem.Create(Collection: TCollection); begin inherited; FCaption := ''; FImageIndex := -1; end; destructor TImagePickerItem.Destroy; var AOwner: TImagePicker; begin AOwner := TImagePickerItemCollection(Collection).FOwner; inherited; if AOwner.HandleAllocated then AOwner.BuildItems; end; function TImagePickerItem.GetDisplayName: string; begin Result := 'Item'+inttostr(index); end; procedure TImagePickerItem.SetImageIndex(const Value: Integer); begin FImageIndex := Value; TImagePickerItemCollection(collection).FOwner.Invalidate; end; procedure TImagePickerItem.SetCaption(const Value: string); begin if FCaption <> Value then begin FCaption := Value; TImagePickerItemCollection(Collection).FOwner.Invalidate; end; end; function TImagePicker.GetComboItems: TStrings; begin Result := inherited Items; end; procedure TImagePicker.SetComboItems(const Value: TStrings); begin with inherited Items do Assign(Value); end; function TImagePicker.GetSelection: TImagePickerItem; var Idx,Err: Integer; s: string; begin Result := nil; if ItemIndex > -1 then begin s := ComboItems[ItemIndex]; Delete(s,1,Pos(FDelimiter,s)); Delete(s,1,Pos(FDelimiter,s)); val(s,Idx,Err); if (Err = 0) and (Idx < Items.Count) then Result := Items.Items[Idx]; end; end; procedure TImagePicker.SelectByCaption(const Value: string); var i: Integer; s: string; begin for i := 1 to Items.Count do begin s := GetCaption(ComboItems[i - 1]); if s = Value then begin ItemIndex := i - 1; Break; end; end; end; procedure TImagePicker.SelectByImageIdx(const Value: Integer); var i: Integer; s: string; begin for i := 1 to Items.Count do begin s := ComboItems[i - 1]; s := Copy(s,1,Pos(FDelimiter,s) - 1); if s = IntToStr(Value) then begin ItemIndex := i - 1; Break; end; end; end; procedure TImagePicker.SelectByTag(const Value: Integer); var i: integer; begin for i := 0 to ComboItems.Count - 1 do begin if TImagePickerItem(ComboItems.Objects[i]).Tag = Value then begin ItemIndex := i; Break; end; end; end; function TImagePicker.GetCaption(Value: string): string; begin Delete(Value,1,Pos(FDelimiter,Value)); Result := Copy(Value,1,Pos(FDelimiter,Value) - 1); end; procedure TImagePicker.WMSize(var Msg: TWMSize); begin inherited; if (csDesigning in ComponentState) and not (csLoading in ComponentState) then EditHeight := FEditHeight; end; procedure TImagePicker.SetShowCaption(const Value: Boolean); begin FShowCaption := Value; Invalidate; end; end.
{ Subroutine SST_R_SYN_EXPRESSION (JTARG) * * Process EXPRESSION syntax. } module sst_r_syn_expression; define sst_r_syn_expression; %include 'sst_r_syn.ins.pas'; procedure sst_r_syn_expression ( {process EXPRESSION syntax} in out jtarg: jump_targets_t); {execution block jump targets info} val_param; var tag: sys_int_machine_t; {tag from syntax tree} jt: jump_targets_t; {jump targets for nested routines} label trerr; begin if not syn_trav_next_down (syn_p^) {down into EXPRESSION syntax} then goto trerr; { * Process the item that always starts the expression. } sst_r_syn_jtarg_sub ( {make subordinate jump targets for ITEM} jtarg, {parent jump targets} jt, {new subordinate targets} lab_fall_k, {fall thru on YES} lab_fall_k); {fall thru on NO} sst_r_syn_item (jt); {process ITEM, set MATCH accordingly} sst_r_syn_jtarg_here (jt); {define jump target labels here} { * Get the next tag, and handle the remainder of this syntax according to which * form of expression it is. } tag := syn_trav_next_tag(syn_p^); {get tag identifying overall expression form} case tag of {what is the format of this expression ?} { **************************************** * * Expression form is: * ITEM EXPRESSION } 1: begin sst_r_syn_jtarg_sub ( {make subordinate jump targets for ITEM} jtarg, {parent jump targets} jt, {new subordinate targets} lab_fall_k, {fall thru on YES} lab_same_k); {same as parent on NO} sst_r_syn_jtarg_goto (jt, [jtarg_no_k]); {abort on ITEM failed} sst_r_syn_jtarg_here (jt); {define local jump target labels here} sst_r_syn_expression (jtarg); {process subordinate EXPRESSION syntax} sst_r_syn_jtarg_goto (jtarg, [jtarg_yes_k, jtarg_no_k]); end; { **************************************** * * Expression form is: * ITEM .or EXPRESSION } 2: begin sst_r_syn_jtarg_sub ( {make subordinate jump targets for ITEM} jtarg, {parent jump targets} jt, {new subordinate targets} lab_same_k, {to parent on YES} lab_fall_k); {continue here on NO} sst_r_syn_jtarg_goto ( {all done if ITEM matched} jt, [jtarg_yes_k, jtarg_no_k]); sst_r_syn_jtarg_here (jt); {define jump target labels here} sst_r_syn_expression (jtarg); {process subordinate EXPRESSION syntax} sst_r_syn_jtarg_goto (jtarg, [jtarg_yes_k, jtarg_no_k]); end; { **************************************** * * Expression form is: * ITEM } 3: begin sst_r_syn_jtarg_goto ( {ITEM was whole expression} jtarg, [jtarg_yes_k, jtarg_no_k]); end; { ************************************** * * Unexpected expression format tag value. } otherwise discard( syn_trav_next(syn_p^) ); {go to tree entry tag came from} syn_msg_tag_bomb (syn_p^, 'sst_syn_read', 'syerr_expression', nil, 0); end; {end of expression format cases} if not syn_trav_up(syn_p^) {back up from EXPRESSION syntax} then goto trerr; return; { * The syntax tree is not as expected. We assume this is due to a syntax * error. } trerr: sys_message ('sst_syn_read', 'syerr_expression'); syn_parse_err_show (syn_p^); sys_bomb; end;
{ rxceEditLookupFields unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit rxceEditLookupFields; {$mode objfpc}{$H+} interface uses Classes, SysUtils, PropEdits; type { TLookupFieldProperty } TLookupFieldProperty = class(TStringPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; procedure FillValues(const Values: TStrings); virtual; end; { TLookupDisplayProperty } TLookupDisplayProperty = class(TLookupFieldProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; procedure RegisterCEEditLookupFields; implementation uses // db, duallist, Forms, rxstrutils, TypInfo, //unit for edits rxlookup; procedure RegisterCEEditLookupFields; begin RegisterPropertyEditor(TypeInfo(string), TRxDBLookupCombo, 'LookupField', TLookupFieldProperty); RegisterPropertyEditor(TypeInfo(string), TRxDBLookupCombo, 'LookupDisplay', TLookupDisplayProperty); RegisterPropertyEditor(TypeInfo(string), TRxLookupEdit, 'LookupField', TLookupFieldProperty); RegisterPropertyEditor(TypeInfo(string), TRxLookupEdit, 'LookupDisplay', TLookupDisplayProperty); end; { TLookupFieldProperty } function TLookupFieldProperty.GetAttributes: TPropertyAttributes; begin Result:= [paValueList, paSortList, paMultiSelect]; end; procedure TLookupFieldProperty.GetValues(Proc: TGetStrProc); var I: Integer; Values: TStringList; begin Values := TStringList.Create; try FillValues(Values); for I := 0 to Values.Count - 1 do Proc(Values[I]); finally Values.Free; end; end; procedure TLookupFieldProperty.FillValues(const Values: TStrings); var DataSource: TDataSource; begin DataSource := GetObjectProp(GetComponent(0), 'LookupSource') as TDataSource; // DataSource := TRxDBLookupCombo(GetComponent(0)).LookupSource; if (DataSource is TDataSource) and Assigned(DataSource.DataSet) then DataSource.DataSet.GetFieldNames(Values); end; { TLookupDisplayProperty } function TLookupDisplayProperty.GetAttributes: TPropertyAttributes; begin Result:=inherited GetAttributes + [paDialog] end; procedure TLookupDisplayProperty.Edit; var DualListDialog1: TDualListDialog; Cmp1:TRxDBLookupCombo; Cmp2:TRxLookupEdit; procedure DoInitFill; var i,j:integer; LookupDisplay:string; begin if Assigned(Cmp1) then LookupDisplay:=Cmp1.LookupDisplay else LookupDisplay:=Cmp2.LookupDisplay; if LookupDisplay<>'' then begin StrToStrings(LookupDisplay, DualListDialog1.List2, ';'); for i:=DualListDialog1.List1.Count-1 downto 0 do begin j:=DualListDialog1.List2.IndexOf(DualListDialog1.List1[i]); if j>=0 then DualListDialog1.List1.Delete(i); end; end; end; function DoFillDone:string; var i:integer; begin for i:=0 to DualListDialog1.List2.Count-1 do Result:=Result + DualListDialog1.List2[i]+';'; if Result<>'' then Result:=Copy(Result, 1, Length(Result)-1); end; procedure DoSetCaptions; begin DualListDialog1.Label1Caption:='All fields'; DualListDialog1.Label2Caption:='Fields is LookupDisplay'; DualListDialog1.Title:='Fill fields in LookupDisplay property'; end; begin Cmp1:=nil; Cmp2:=nil; if GetComponent(0) is TRxDBLookupCombo then Cmp1:=TRxDBLookupCombo(GetComponent(0)) else Cmp2:=TRxLookupEdit(GetComponent(0)); DualListDialog1:=TDualListDialog.Create(Application); try DoSetCaptions; FillValues(DualListDialog1.List1); DoInitFill; if DualListDialog1.Execute then begin if Assigned(Cmp1) then Cmp1.LookupDisplay:=DoFillDone else Cmp2.LookupDisplay:=DoFillDone; end; finally FreeAndNil(DualListDialog1); end; end; end.