text
stringlengths
14
6.51M
unit rtfListTable; { Таблица списков для чтения из RTF } interface uses l3Base, l3Memory, l3LongintList, l3ProtoObject, l3ProtoObjectRefList, ddCharacterProperty; type TrtfListLevel = class(Tl3ProtoObject) private f_CHP: TddCharacterProperty; f_CurNumber: Integer; f_Follow: Integer; f_Justify: Integer; f_LevelJC: Integer; f_LevelJCN: Integer; f_LevelNFC: Integer; f_LevelNFCN: Integer; f_Numbers: AnsiString; f_NumberType: Integer; f_StartAt: Integer; f_Text: AnsiString; f_UnicodeText : Tl3String; private function pm_GetCurNumber: Integer; function pm_GetNextNumber: Integer; protected procedure Cleanup; override; public constructor Create; procedure Restart; property CHP: TddCharacterProperty read f_CHP; property CurNumber: Integer read pm_GetCurNumber; property Follow: Integer read f_Follow write f_Follow; property Justify: Integer read f_Justify write f_Justify; property LevelJC: Integer read f_LevelJC write f_LevelJC; property LevelJCN: Integer read f_LevelJCN write f_LevelJCN; property LevelNFC: Integer read f_LevelNFC write f_LevelNFC; property LevelNFCN: Integer read f_LevelNFCN write f_LevelNFCN; property NextNumber: Integer read pm_GetNextNumber; property Numbers: AnsiString read f_Numbers write f_Numbers; property NumberType: Integer read f_NumberType write f_NumberType; property StartAt: Integer read f_StartAt write f_StartAt; property Text: AnsiString read f_Text write f_Text; property UnicodeText: Tl3String read f_UnicodeText write f_UnicodeText; end; TrtfList = class(Tl3ProtoObjectRefList) private f_ID: Integer; f_ListName: AnsiString; f_TemplateID: Integer; private function pm_GetLevels(Index: Integer): TrtfListLevel; public procedure RestartAt(const aStartList: Tl3LongintList); procedure GetNumberAndNFC(anIndex, aLevel: Integer; out aNumber, aLevelNFC: Integer); procedure AddLevel(aLevel: TrtfListLevel); property ID: Integer read f_ID write f_ID; property Levels[Index: Integer]: TrtfListLevel read pm_GetLevels; default; property ListName: AnsiString read f_ListName write f_ListName; property TemplateID: Integer read f_TemplateID write f_TemplateID; end; TrtfListTable = class(Tl3ProtoObjectRefList) private function pm_GetLists(Index: Integer): TrtfList; public procedure AddList(aList: TrtfList); property Lists[Index: Integer]: TrtfList read pm_GetLists; default; end; TrtfListOverride = class(Tl3ProtoObject) private f_ListID: Integer; f_ListOverrideCount: Integer; f_LS: Integer; f_StartAt: Tl3LongintList; private function GetStartAt(anIndex: Integer): Integer; protected procedure Cleanup; override; public procedure Assign(anList: TrtfListOverride); procedure Clear; constructor Create; property ListID: Integer read f_ListID write f_ListID; property ListOverrideCount: Integer read f_ListOverrideCount write f_ListOverrideCount; property LS: Integer read f_LS write f_LS; function GetStartAtCount: Integer; property StartAtList: Tl3LongintList read f_StartAt; procedure AddStartAt(aValue: Integer); end; TrtfListOverrideTable = class(Tl3ProtoObjectRefList) end; implementation uses SysUtils; procedure TrtfList.AddLevel(aLevel: TrtfListLevel); var l_Level: TrtfListLevel; begin l_Level := TrtfListLevel.Create; try l_Level.CHP.AssignFrom(aLevel.CHP); l_Level.Follow := aLevel.Follow; l_Level.Justify := aLevel.Justify; l_Level.LevelJC := aLevel.LevelJC; l_Level.LevelJCN := aLevel.LevelJCN; l_Level.LevelNFC := aLevel.LevelNFC; l_Level.LevelNFCN := aLevel.LevelNFCN; l_Level.Numbers := aLevel.Numbers; l_Level.NumberType := aLevel.NumberType; l_Level.StartAt := aLevel.StartAt; l_Level.Text := aLevel.Text; l_Level.UnicodeText.AssignString(aLevel.UnicodeText); Add(l_Level); finally FreeAndNil(l_Level); end; end; procedure TrtfList.GetNumberAndNFC(anIndex, aLevel: Integer; out aNumber, aLevelNFC: Integer); const cnErrorValue = 256; // Игнорируем значение - какая-то фигня: http://mdp.garant.ru/pages/viewpage.action?pageId=605147298 var i : Integer; l_CurrentLevel: Integer; begin l_CurrentLevel := Ord(Levels[aLevel].Numbers[anIndex]); if l_CurrentLevel >= Count then begin aLevelNFC := cnErrorValue; aNumber := 0; Exit; end // if l_CurrentLevel >= Count then else if l_CurrentLevel <> aLevel then aNumber := Levels[l_CurrentLevel].CurNumber else begin aNumber := Levels[l_CurrentLevel].NextNumber; for i := l_CurrentLevel + 1 to Count - 1 do Levels[i].Restart; end; aLevelNFC := Levels[l_CurrentLevel].LevelNFC; end; function TrtfList.pm_GetLevels(Index: Integer): TrtfListLevel; begin Result := Items[Index] as TrtfListLevel; end; procedure TrtfListTable.AddList(aList: TrtfList); var l_List: TrtfList; i: Integer; begin l_List := TrtfList.Make; try l_List.ID := aList.ID; l_List.ListName := aList.ListName; l_List.TemplateID := aList.TemplateID; for i := 0 to aList.Hi do l_List.AddLevel(aList.Levels[i]); Add(l_List); finally FreeAndNil(l_List); end; end; function TrtfListTable.pm_GetLists(Index: Integer): TrtfList; begin Result := Items[Index] as TrtfList; end; constructor TrtfListLevel.Create; begin inherited Create; f_CHP := TddCharacterProperty.Create; f_CurNumber := 0; f_StartAt := 1; f_UnicodeText := Tl3String.Create; end; procedure TrtfListLevel.Cleanup; begin inherited; FreeAndNil(f_UnicodeText); FreeAndNil(f_CHP); end; function TrtfListLevel.pm_GetCurNumber: Integer; begin if f_CurNumber = 0 then Result := StartAt else Result := f_CurNumber; end; function TrtfListLevel.pm_GetNextNumber: Integer; begin if f_CurNumber = 0 then f_CurNumber := StartAt else Inc(f_CurNumber); Result := f_CurNumber; end; procedure TrtfListLevel.Restart; begin f_CurNumber := 0; end; { TrtfListOverride } procedure TrtfListOverride.AddStartAt(aValue: Integer); begin f_StartAt.Add(aValue); end; procedure TrtfListOverride.Assign(anList: TrtfListOverride); var i: Integer; begin ListID := anList.ListID; ListOverrideCount := anList.ListOverrideCount; LS := anList.LS; f_StartAt.Assign(anList.f_StartAt); end; procedure TrtfListOverride.Cleanup; begin Clear; FreeAndNil(f_StartAt); inherited; end; procedure TrtfListOverride.Clear; begin f_ListID := -1; f_ListOverrideCount := 0; f_LS := -1; f_StartAt.Clear; end; constructor TrtfListOverride.Create; begin inherited Create; f_StartAt := Tl3LongintList.Create; Clear; end; procedure TrtfList.RestartAt(const aStartList: Tl3LongintList); var i : Integer; l_Level: TrtfListLevel; begin for i := 0 to Count - 1 do begin l_Level := Levels[i]; if i < aStartList.Count then begin l_Level.StartAt := aStartList[i]; l_Level.Restart; end // if i < aStartList.Count then else Break; end; // for i := 0 to Count - 1 do end; function TrtfListOverride.GetStartAt(anIndex: Integer): Integer; begin Result := f_StartAt[anIndex]; end; function TrtfListOverride.GetStartAtCount: Integer; begin Result := f_StartAt.Count; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011-2013 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Platform; interface uses System.Classes, System.SysUtils, System.Types, System.Rtti, System.UITypes, System.Generics.Collections, FMX.Types, FMX.Forms, FMX.Dialogs, FMX.Text; type EInvalidFmxHandle = class(Exception); EUnsupportedPlatformService = class(Exception) constructor Create(const Msg: string); end; TPlatformServices = class private FServicesList: TDictionary<TGUID, IInterface>; FGlobalFlags: TDictionary<string, Boolean>; class var FCurrentPlatform: TPlatformServices; class function GetCurrent: TPlatformServices; static; public constructor Create; destructor Destroy; override; class procedure UnInitialize; procedure AddPlatformService(const AServiceGUID: TGUID; const AService: IInterface); procedure RemovePlatformService(const AServiceGUID: TGUID); function GetPlatformService(const AServiceGUID: TGUID): IInterface; function SupportsPlatformService(const AServiceGUID: TGUID): Boolean; overload; function SupportsPlatformService(const AServiceGUID: TGUID; out AService: IInterface): Boolean; overload; property GlobalFlags: TDictionary<string, Boolean> read FGlobalFlags; class property Current: TPlatformServices read GetCurrent; end; IFMXApplicationService = interface(IInterface) ['{EFBE3310-D103-4E9E-A8E1-4E45AB46D0D8}'] procedure Run; procedure Terminate; function HandleMessage: Boolean; procedure WaitMessage; function GetTitle: string; function Terminating: Boolean; end; TApplicationEvent = (aeFinishedLaunching, aeBecameActive, aeWillBecomeInactive, aeEnteredBackground, aeWillBecomeForeground, aeWillTerminate, aeLowMemory, aeTimeChange, aeOpenURL); TApplicationEventHandler = function(AAppEvent: TApplicationEvent; AContext: TObject): Boolean of object; IFMXApplicationEventService = interface(IInterface) ['{F3AAF11A-1678-4CC6-A5BF-721A24A676FD}'] procedure SetApplicationEventHandler(AEventHandler: TApplicationEventHandler); end; IFMXHideAppService = interface(IInterface) ['{D9E49FCB-6A8B-454C-B11A-CEB3CEFAD357}'] function GetHidden: boolean; procedure SetHidden(const Value: boolean); procedure HideOthers; property Hidden: boolean read GetHidden write SetHidden; end; IFMXDeviceService = interface(IInterface) ['{9419B3C0-379A-4556-B5CA-36C975462326}'] function GetModel: string; end; IFMXStyleService = interface(IInterface) ['{9EA04045-26A5-4210-870B-56F9CBB7146B}'] function GetSystemStyle: TFmxObject; end; IFMXStyleHiResService = interface(IInterface) ['{265F896D-B5A9-480A-895E-EEEB813B49AD}'] function GetSystemStyleHiRes: TFmxObject; end; IFMXSystemFontService = interface(IInterface) ['{62017F22-ADF1-44D9-A21D-796D8C7F3CF0}'] function GetDefaultFontFamilyName: string; end; IFMXDragDropService = interface(IInterface) ['{73133536-5868-44B6-B02D-7364F75FAD0E}'] procedure BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap); end; IFMXClipboardService = interface(IInterface) ['{CC9F70B3-E5AE-4E01-A6FB-E3FC54F5C54E}'] procedure SetClipboard(Value: TValue); function GetClipboard: TValue; end; IFMXScreenService = interface(IInterface) ['{BBA246B6-8DEF-4490-9D9C-D2CBE6251A24}'] function GetScreenSize: TPointF; function GetScreenScale: Single; function GetScreenOrientation: TScreenOrientation; end; IFMXLocaleService = interface(IInterface) ['{311A40D4-3D5B-40CC-A201-78465760B25E}'] function GetCurrentLangID: string; function GetLocaleFirstDayOfWeek: string; end; IFMXDialogService = interface(IInterface) ['{CF7DCC1C-B5D6-4B24-92E7-1D09768E2D6B}'] function DialogOpenFiles(var FileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; function DialogPrint(var ACollate, APrintToFile: Boolean; var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange; AOptions: TPrintDialogOptions): Boolean; function PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; function DialogPageSetup(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; function DialogSaveFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; function DialogPrinterSetup: Boolean; function MessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn; X, Y: Integer; HelpCtx: Longint; const HelpFileName: string): Integer; function InputQuery(const ACaption: string; const APrompts: array of string; var AValues: array of string; CloseQueryFunc: TInputCloseQueryFunc = nil): Boolean; end; IFMXLoggingService = interface(IInterface) ['{01BFC200-0493-4b3b-9D7E-E3CDB1242795}'] procedure Log(Format: String; Params: array of const); end; IFMXTextService = interface(IInterface) ['{A5FECE29-9A9C-4E8A-8794-89271EC71F1A}'] function GetTextServiceClass: TTextServiceClass; end; IFMXCanvasService = interface(IInterface) ['{476E5E53-A77A-4ADA-93E3-CA66A8956059}'] procedure RegisterCanvasClasses; procedure UnregisterCanvasClasses; end; IFMXContextService = interface(IInterface) ['{EB6C9074-48B9-4A99-ABF4-BFB6FCF9C385}'] procedure RegisterContextClasses; procedure UnregisterContextClasses; end; { System Information service } TScrollingBehaviour = (sbBoundsAnimation, sbAnimation, sbTouchTracking, sbAutoShowing); TScrollingBehaviours = set of TScrollingBehaviour; IFMXSystemInformationService = interface(IInterface) ['{2E01A60B-E297-4AC0-AA24-C5F52289EC1E}'] { Scrolling information } function GetScrollingBehaviour: TScrollingBehaviours; function GetMinScrollThumbSize: Single; { Caret information } function GetCaretWidth: Integer; end; TComponentKind = (ckButton, ckLabel, ckEdit, ckScrollBar, ckListBoxItem); { Default metrics } IFMXDefaultMetricsService = interface(IInterface) ['{216841F5-C089-45F1-B350-E9B018B73441}'] function SupportsDefaultSize(const AComponent: TComponentKind): Boolean; function GetDefaultSize(const AComponent: TComponentKind): TSize; end; { Generation tools } IFMXImageGeneratorService = interface(IInterface) ['{D8D50379-2ABE-4959-8FE7-3EF97BC68689}'] function GenerateTabIcon(const ASource, ADest: TBitmap; const IsSelected, HiRes: Boolean): Boolean; end; { Platform-specific property defaults } IFMXDefaultPropertyValueService = interface(IInterface) ['{7E8A25A0-5FCF-49fa-990C-CEDE6ABEAE50}'] function GetDefaultPropertyValue(const AClassName: string; const PropertyName: string): TValue; end; implementation uses {$IFDEF IOS} FMX.Platform.iOS, {$ELSE} {$IFDEF MACOS} FMX.Platform.Mac, {$ENDIF MACOS} {$ENDIF IOS} {$IFDEF MSWINDOWS} FMX.Platform.Win, {$ENDIF} FMX.Consts; { TPlatformServices } procedure TPlatformServices.AddPlatformService(const AServiceGUID: TGUID; const AService: IInterface); begin if not FServicesList.ContainsKey(AServiceGUID) then FServicesList.Add(AServiceGUID, AService); end; constructor TPlatformServices.Create; begin inherited; FServicesList := TDictionary<TGUID, IInterface>.Create; FGlobalFlags := TDictionary<string, Boolean>.Create; end; class procedure TPlatformServices.UnInitialize; begin FreeAndNil(FCurrentPlatform); inherited; end; class function TPlatformServices.GetCurrent: TPlatformServices; begin if FCurrentPlatform = nil then FCurrentPlatform := TPlatformServices.Create; Result := FCurrentPlatform; end; destructor TPlatformServices.Destroy; begin FServicesList.Free; FGlobalFlags.Free; inherited; end; function TPlatformServices.GetPlatformService(const AServiceGUID: TGUID): IInterface; begin Supports(FServicesList.Items[AServiceGUID], AServiceGUID, Result); end; procedure TPlatformServices.RemovePlatformService(const AServiceGUID: TGUID); begin FServicesList.Remove(AServiceGUID); end; function TPlatformServices.SupportsPlatformService(const AServiceGUID: TGUID; out AService: IInterface): Boolean; begin if FServicesList.ContainsKey(AServiceGUID) then Result := Supports(FServicesList.Items[AServiceGUID], AServiceGUID, AService) else begin AService := nil; Result := False; end; end; function TPlatformServices.SupportsPlatformService(const AServiceGUID: TGUID): Boolean; begin Result := FServicesList.ContainsKey(AServiceGUID); end; { EUnsupportedPlatformService } constructor EUnsupportedPlatformService.Create(const Msg: string); begin inherited CreateResFmt(@SUnsupportedPlatformService, [Msg]); end; initialization RegisterCorePlatformServices; end.
unit MFichas.Model.Produto; interface uses System.SysUtils, MFichas.Model.Produto.Interfaces, MFichas.Model.Produto.Metodos.Buscar, MFichas.Model.Produto.Metodos.Buscar.Model, MFichas.Model.Produto.Metodos.Cadastrar, MFichas.Model.Produto.Metodos.Editar, MFichas.Model.Entidade.PRODUTO, MFichas.Model.Conexao.Factory, MFichas.Model.Conexao.Interfaces, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.FDMemTable, ORMBR.Container.DataSet.interfaces, FireDAC.Comp.Client; type TModelProduto = class(TInterfacedObject, iModelProduto, iModelProdutoMetodos) private FEntidade : TPRODUTO; FConn : iModelConexaoSQL; FDAOObjectSet: IContainerObjectSet<TPRODUTO>; FDAODataSet : IContainerDataSet<TPRODUTO>; FFDMemTable : TFDMemTable; constructor Create; public destructor Destroy; override; class function New: iModelProduto; function Metodos : iModelProdutoMetodos; function Entidade : TPRODUTO; overload; function Entidade(AEntidade: TPRODUTO): iModelProduto; overload; function DAO : iContainerObjectSet<TPRODUTO>; function DAODataSet : iContainerDataSet<TPRODUTO>; //METODOS function CadastrarView: iModelProdutoMetodosCadastrar; function EditarView : iModelProdutoMetodosEditar; function BuscarView : iModelProdutoMetodosBuscar; function BuscarModel : iModelProdutoMetodosBuscarModel; function &End : iModelProduto; end; implementation { TModelProduto } function TModelProduto.BuscarModel: iModelProdutoMetodosBuscarModel; begin Result := TModelProdutoMetodosBuscarModel.New(Self); end; function TModelProduto.BuscarView: iModelProdutoMetodosBuscar; begin Result := TModelProdutoMetodosBuscar.New(Self); end; function TModelProduto.CadastrarView: iModelProdutoMetodosCadastrar; begin Result := TModelProdutoMetodosCadastrar.New(Self); end; function TModelProduto.EditarView: iModelProdutoMetodosEditar; begin Result := TModelProdutoMetodosEditar.New(Self); end; function TModelProduto.&End: iModelProduto; begin Result := Self; end; function TModelProduto.Entidade: TPRODUTO; begin Result := FEntidade; end; function TModelProduto.Entidade(AEntidade: TPRODUTO): iModelProduto; begin Result := Self; FEntidade := AEntidade; end; constructor TModelProduto.Create; begin FEntidade := TPRODUTO.Create; FConn := TModelConexaoFactory.New.ConexaoSQL; FDAOObjectSet := TContainerObjectSet<TPRODUTO>.Create(FConn.Conn, 10); FFDMemTable := TFDMemTable.Create(nil); FDAODataSet := TContainerFDMemTable<TPRODUTO>.Create(FConn.Conn, FFDMemTable); end; function TModelProduto.DAODataSet: iContainerDataSet<TPRODUTO>; begin Result := FDAODataSet; end; function TModelProduto.DAO: iContainerObjectSet<TPRODUTO>; begin Result := FDAOObjectSet; end; destructor TModelProduto.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); FreeAndNil(FFDMemTable); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; FFDMemTable.Free; FFDMemTable.DisposeOf; {$ENDIF} inherited; end; function TModelProduto.Metodos: iModelProdutoMetodos; begin Result := Self; end; class function TModelProduto.New: iModelProduto; begin Result := Self.Create; end; end.
unit DSoundOut; interface uses Windows, DirectSound, ExtTimer; type TDataProc = function(var Data; Size : integer) : integer of object; TDsoundOut = class public constructor Create; destructor Destroy; override; public procedure Play; procedure Stop; public procedure Pause; procedure Resume; private fSamplingRate : integer; fChannels : integer; fBitsPerSample : integer; fBufferSize : integer; private function MsToSamples(aMs : integer) : integer; function GetBlockAlign : integer; private fDSound : IDirectSound; fBuffer : IDirectSoundBuffer; fTimer : TExtTimer; fNextWrite : dword; fPlayBufferSize : dword; procedure CreateBuffer; procedure CheckBuffer; procedure Feed(aSize : integer); function GetPlayedSize : integer; procedure TimerProc; procedure ReadData(var Data; Size : integer); private fOnData : TDataProc; public property OnData : TDataProc read fOnData write fOnData; public property SamplingRate : integer read fSamplingRate write fSamplingRate; property Channels : integer read fChannels write fChannels; property BitsPerSample : integer read fBitsPerSample write fBitsPerSample; property BlockAlign : integer read GetBlockAlign; property BufferSize : integer read fBufferSize write fBufferSize; private fVolume : integer; procedure SetVolume(aVolume : integer); procedure UpdateBufferVolume; public property DirectSound : IDirectSound read fDSound write fDSound; property Volume : integer read fVolume write SetVolume; // in percent, from 0 to 100 end; implementation uses mmSystem, SysUtils, DSoundUtils; const DefaultSamplingRate = 8000; DefaultChannels = 1; DefaultBitsPerSample = 16; DefaultBufferSize = 250; // 250 ms DefaultEmulBufferSize = 1000; // 1000 ms BufferSpans = 6; constructor TDsoundOut.Create; begin inherited Create; SamplingRate := DefaultSamplingRate; Channels := DefaultChannels; BitsPerSample := DefaultBitsPerSample; BufferSize := DefaultBufferSize; Volume := 100; fTimer := TExtTimer.Create(40); fTimer.OnTimer := TimerProc; end; destructor TDsoundOut.Destroy; begin Stop; fBuffer := nil; fDSound := nil; fTimer.Free; inherited; end; procedure TDsoundOut.Play; begin Stop; CreateBuffer; fBuffer.SetCurrentPosition(0); Resume; fTimer.Interval := BufferSize div BufferSpans; fTimer.Enabled := true; end; procedure TDsoundOut.Stop; begin if fBuffer <> nil then begin fTimer.Enabled := false; fBuffer.Stop; fBuffer := nil; end; end; procedure TDsoundOut.Pause; begin if fBuffer <> nil then fBuffer.Stop; end; procedure TDsoundOut.Resume; begin if fBuffer <> nil then DSoundCheck(fBuffer.Play(0, 0, DSBPLAY_LOOPING)); end; function TDsoundOut.MsToSamples(aMs : integer) : integer; begin Result := MulDiv(aMs, fSamplingRate, 1000); end; function TDsoundOut.GetBlockAlign : integer; begin Result := (fBitsPerSample div 8) * fChannels; end; procedure TDsoundOut.CreateBuffer; var Desc : TDSBUFFERDESC; DSCaps : TDSCAPS; Format : TWaveFormatEx; begin fBuffer := nil; // Destroy previous buffer if fDSound = nil then fDSound := CreateHelperDSound; fillchar(DSCaps, sizeof(DSCaps), 0); DSCaps.dwSize := sizeof(DSCaps); DSoundCheck(fDSound.GetCaps(DSCaps)); if DSCaps.dwFlags and DSCAPS_EMULDRIVER <> 0 then BufferSize := DefaultEmulBufferSize else BufferSize := DefaultBufferSize; FillPCMFormat(fSamplingRate, fBitsPerSample, fChannels, Format); fPlayBufferSize := MsToSamples(fBufferSize) * GetBlockAlign; fillchar(Desc, sizeof(Desc), 0); Desc.dwSize := sizeof(Desc); Desc.dwFlags := DSBCAPS_GLOBALFOCUS or DSBCAPS_GETCURRENTPOSITION2 or DSBCAPS_CTRLVOLUME; Desc.dwBufferBytes := fPlayBufferSize; Desc.lpwfxFormat := @Format; DSoundCheck(fDSound.CreateSoundBuffer(Desc, fBuffer, nil)); UpdateBufferVolume; fNextWrite := 0; Feed(fPlayBufferSize); end; procedure TDsoundOut.CheckBuffer; var Status : dword; hr : hResult; begin if fBuffer <> nil then begin Status := 0; hr := fBuffer.GetStatus(Status); if Succeeded(hr) and (Status = DSBSTATUS_BUFFERLOST) then fBuffer.Restore; end; end; procedure TDsoundOut.Feed(aSize : integer); var FirstData : pointer; SecondData : pointer; FirstSize : dword; SecondSize : dword; begin if (aSize > 0) and (fBuffer <> nil) then begin if Succeeded(fBuffer.Lock(fNextWrite, aSize, FirstData, FirstSize, SecondData, SecondSize, 0)) then try if FirstData <> nil then ReadData(FirstData^, FirstSize); if SecondData <> nil then ReadData(SecondData^, SecondSize); inc(fNextWrite, aSize); if fNextWrite >= fPlayBufferSize then dec(fNextWrite, fPlayBufferSize); finally fBuffer.Unlock(FirstData, FirstSize, SecondData, SecondSize); end; end; end; function TDsoundOut.GetPlayedSize : integer; var WriteCursor : dword; PlayCursor : dword; begin if fBuffer <> nil then begin fBuffer.GetCurrentPosition(@PlayCursor, @WriteCursor); if PlayCursor < fNextWrite then Result := PlayCursor + fPlayBufferSize - fNextWrite else Result := PlayCursor - fNextWrite; end else Result := 0; end; procedure TDsoundOut.TimerProc; begin CheckBuffer; Feed(GetPlayedSize); end; procedure TDsoundOut.ReadData(var Data; Size : integer); var DataBytes : TByteArray absolute Data; Written : integer; begin if assigned(fOnData) then Written := fOnData(Data, Size) else Written := 0; fillchar(DataBytes[Written], Size - Written, 0); end; procedure TDsoundOut.SetVolume(aVolume : integer); begin fVolume := aVolume; UpdateBufferVolume; end; procedure TDsoundOut.UpdateBufferVolume; begin if fBuffer <> nil then fBuffer.SetVolume(PercentToBufferVolume(fVolume)); end; end.
unit DW.PushKit.iOS; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // macOS Macapi.ObjectiveC, // DW DW.iOSapi.PushKit, DW.PushKit; type TPlatformPushKit = class; TPushRegistryDelegate = class(TOCLocal, PKPushRegistryDelegate) private FPushKit: TPlatformPushKit; FRegistry: PKPushRegistry; protected procedure RegisterTypes(const APushTypes: array of PKPushType); public { PKPushRegistryDelegate } procedure pushRegistry(registry: PKPushRegistry; didInvalidatePushTokenForType: PKPushType); overload; cdecl; procedure pushRegistry(registry: PKPushRegistry; didReceiveIncomingPushWithPayload: PKPushPayload; forType: PKPushType; withCompletionHandler: Pointer); overload; cdecl; procedure pushRegistry(registry: PKPushRegistry; didUpdatePushCredentials: PKPushCredentials; forType: PKPushType); overload; cdecl; public constructor Create(const APushKit: TPlatformPushKit); destructor Destroy; override; end; TPlatformPushKit = class(TCustomPlatformPushKit) private FDelegate: TPushRegistryDelegate; protected function GetStoredToken: string; override; procedure MessageReceived(const APayload: PKPushPayload); procedure TokenReceived(const AToken: string; const AIsNew: Boolean); procedure Start; override; public constructor Create(const APushKit: TPushKit); override; destructor Destroy; override; end; implementation uses // RTL System.SysUtils, System.Classes, // macOS Macapi.Helpers, Macapi.ObjCRuntime, // iOS iOSapi.Foundation, iOSapi.CocoaTypes, // DW DW.OSLog, DW.iOSapi.CallKit, DW.UserDefaults.iOS, DW.iOSapi.Helpers; function NSDataToHexString(const AData: NSData): string; var LData, LHex: TBytes; begin SetLength(LData, AData.length); Move(AData.bytes^, LData[0], AData.length); SetLength(LHex, AData.length * 2); BinToHex(LData, 0, LHex, 0, AData.length); Result := StringOf(LHex).ToLower; end; { TPushRegistryDelegate } constructor TPushRegistryDelegate.Create(const APushKit: TPlatformPushKit); begin inherited Create; FPushKit := APushKit; FRegistry := TPKPushRegistry.Wrap(TPKPushRegistry.Wrap(TPKPushRegistry.OCClass.alloc).initWithQueue(0)); FRegistry.setDelegate(GetObjectID); end; destructor TPushRegistryDelegate.Destroy; begin // inherited; end; procedure TPushRegistryDelegate.RegisterTypes(const APushTypes: array of PKPushType); var LArray: NSMutableArray; LPushType: PKPushType; LSet: NSSet; begin LArray := TNSMutableArray.Create; for LPushType in APushTypes do LArray.addObject(NSObjectToID(LPushType)); // LSet := TNSSet.Wrap(TNSSet.OCClass.setWithArray(LArray)); LSet := TNSSet.Wrap(TNSSet.OCClass.setWithObject(NSObjectToID(PKPushTypeVoIP))); FRegistry.setDesiredPushTypes(LSet); end; procedure TPushRegistryDelegate.pushRegistry(registry: PKPushRegistry; didInvalidatePushTokenForType: PKPushType); begin // TOSLog.d('TPushRegistryDelegate.pushRegistry didInvalidatePushTokenForType'); end; procedure TPushRegistryDelegate.pushRegistry(registry: PKPushRegistry; didUpdatePushCredentials: PKPushCredentials; forType: PKPushType); var LHex: string; LToken: NSString; LStoredToken: NSString; LIsNew: Boolean; begin TOSLog.d('TPushRegistryDelegate.pushRegistry didUpdatePushCredentials'); LHex := NSDataToHexString(didUpdatePushCredentials.token); LToken := StrToNSStr(LHex); LStoredToken := TUserDefaults.GetValue(didUpdatePushCredentials.&type); LIsNew := (LStoredToken = nil) or not LStoredToken.isEqualToString(LToken); TUserDefaults.SetValue(didUpdatePushCredentials.&type, LToken); FPushKit.TokenReceived(LHex, LIsNew); end; procedure TPushRegistryDelegate.pushRegistry(registry: PKPushRegistry; didReceiveIncomingPushWithPayload: PKPushPayload; forType: PKPushType; withCompletionHandler: Pointer); var LCompletionHandlerImp: procedure; cdecl; begin TOSLog.d('TPushRegistryDelegate.pushRegistry didReceiveIncomingPushWithPayload'); FPushKit.MessageReceived(didReceiveIncomingPushWithPayload); @LCompletionHandlerImp := imp_implementationWithBlock(withCompletionHandler); LCompletionHandlerImp; imp_removeBlock(@LCompletionHandlerImp); end; { TPlatformPushKit } constructor TPlatformPushKit.Create(const APushKit: TPushKit); begin inherited; FDelegate := TPushRegistryDelegate.Create(Self); end; destructor TPlatformPushKit.Destroy; begin FDelegate.Free; inherited; end; function TPlatformPushKit.GetStoredToken: string; var LStoredToken: NSString; begin LStoredToken := TUserDefaults.GetValue(PKPushTypeVoIP); if LStoredToken <> nil then Result := NSStrToStr(LStoredToken) else Result := ''; end; procedure TPlatformPushKit.MessageReceived(const APayload: PKPushPayload); begin DoMessageReceived(TiOSHelperEx.NSDictionaryToJSON(APayload.dictionaryPayload)); end; procedure TPlatformPushKit.Start; begin TOSLog.d('TPlatformPushKit.Start'); FDelegate.RegisterTypes([PKPushTypeVoIP]); end; procedure TPlatformPushKit.TokenReceived(const AToken: string; const AIsNew: Boolean); begin DoTokenReceived(AToken, AIsNew); end; end.
{Version 9.45} {$i HtmlCons.inc} unit HtmlGif1; {***************************************************************} {* htmlgif1.pas *} {* *} {* Thanks to Ron Collins for the Gif code in this module. *} {* His copyright notice is below. *} {* *} {* This is only a portion of his code modified slightly *} {* in a few places to accomodate my own needs. Ron's *} {* full package may be found at www.Torry.net/gif.htm. *} {* The zip file is rctgif.zip. *} {* *} {***************************************************************} { ============================================================================ TGif.pas copyright (C) 2000 R. Collins rlcollins@ksaits.com LEGAL STUFF: This software is provided "as-is". This software comes without warranty or garantee, explicit or implied. Use this software at your own risk. The author will not be liable for any damage to equipment, data, or information that may result while using this software. By using this software, you agree to the conditions stated above. This software may be used freely, provided the author's name and copyright statement remain a part of the source code. NOTE: CompuServe, Inc. holds the patent to the compression algorithym used in creating a GIF file. Before you save a GIF file (using LZW compression) that may be distributed for profit, make sure you understand the full implications and legal ramifications of using the LZW compression. ============================================================================ } interface uses {$ifdef UseCLX} SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls; {$else} SysUtils, Classes, {$IFNDEF LCL} Windows, Messages, WinTypes, WinProcs, {$ELSE} LclIntf, LMessages, Types, LclType, HtmlMisc, {$ENDIF} Graphics, Controls, StdCtrls, ExtCtrls, Forms; {$endif} // LZW encode table sizes const kGifCodeTableSize = 4096; // the parts of a GIF file // yes, yes, I know ... I don't have to put in "type" // before each record definition. I just think it makes it // easier to read, especially when the definitions may be broken // across the printed page. if you don't like it, take them out. type {LDB} TRGBQUAD = packed record rgbBlue: Byte; rgbGreen: Byte; rgbRed: Byte; rgbReserved: Byte; end; type PGifDataBlock = ^TGifDataBlock; TGifDataBlock = record // generic data clump rSize: integer; // NOTE: array starts at "1" rData: packed array[1..255] of byte; end; type PGifSignature = ^TgifSignature; TGifSignature = record // GIF87A or GIF89A rSignature: packed array[1..6] of char; end; type PGifExtensionGraphic = ^TgifExtensionGraphic; TGifExtensionGraphic = record // graphic control extension rBlockSize: integer; // must always be 4 rDisposal: integer; // disposal method when drawing rUserInputValid: boolean; // wait for user input? rTransparentValid: boolean; // transparent color given? rDelayTime: integer; // delay between display images rTransparentIndex: integer; // into color table end; type PGifExtensionComment = ^TgifExtensionComment; TGifExtensionComment = record // comment extension rDataBlockList: TList; // data blocks end; type PGifExtensionText = ^TGifExtensionText; TGifExtensionText = record // plain text extension rBlockSize: integer; // must always be 12 rGridLeft: integer; // text grid position rGridTop: integer; rGridWidth: integer; // text grid size rGridHeight: integer; rCellWidth: integer; // size of a character cell rCellHeight: integer; rForegroundIndex: integer; // text foreground color rBackgroundIndex: integer; // text background color rDataBlockList: TList; // data blocks end; type PGifExtensionApplication = ^TgifExtensionApplication; TGifExtensionApplication = record // application extension rBlockSize: integer; // must always be 11 rIdentifier: packed array[1..8] of char; rAuthentication: packed array[1..3] of char; rDataBlockList: TList; // data blocks end; type PGifExtension = ^TGifExtension; TGifExtension = record // for any extension type case rLabel: byte of // cannot use CONST names $f9: (rGraphic: TGifExtensionGraphic); $fe: (rComment: TGifExtensionComment); $01: (rText: TGifExtensionText); $ff: (rApp: TGifExtensionApplication); $00: (rDummy: longint); end; type PGifScreenDescriptor = ^TGifScreenDescriptor; TGifScreenDescriptor = record rWidth: integer; // size of logical screen rHeight: integer; // size of logical screen rGlobalColorValid: boolean; // global color table found in file? rColorResolution: integer; // bits per color rSorted: boolean; // global colors are sorted? rGlobalColorSize: integer; // size of global color table rBackgroundIndex: integer; // background color index rAspectRatio: integer; // pixel aspect ratio rGlobalColorTable: integer; // default color table for all images end; type PGifColorTable = ^TGifColorTable; // pointer to a color table TGifColorTable = record rSize: integer; // number of valid entries rColors: array[0..255] of TColor; // the colors end; type PGifImageDescriptor = ^TGifImageDescriptor; TGifImageDescriptor = record rIndex: integer; // which image is this? rLeft: integer; // position of image rTop: integer; // position of image rWidth: integer; // size of image rHeight: integer; // size of image rLocalColorValid: boolean; // color table used? rInterlaced: boolean; // interlaced lines? rSorted: boolean; // color table sorted? rLocalColorSize: integer; // number entries in local color table rLocalColorTable: integer; // index into master list rLZWSize: integer; // LZW minimum code size rExtensionList: TList; // extensions read before this image rPixelList: PChar; // decoded pixel indices rPixelCount: longint; // number of pixels rBitmap: TBitmap; // the actual image end; type PGifZip = ^TGifZip; TGifZip = record rID: PGifImageDescriptor; // image parameters to decode rCT: PGifColorTable; // color table for this image rPrefix: array[0..kGifCodeTableSize-1] of integer; // string prefixes rSuffix: array[0..kGifCodeTableSize-1] of integer; // string suffixes rCodeStack: array[0..kGifCodeTableSize-1] of byte; // decode/encoded pixels rSP: integer; // pointer into CodeStack rClearCode: integer; // reset decode params rEndCode: integer; // last code in input stream rHighCode: integer; // highest LZW code possible rCurSize: integer; // current code size rBitString: integer; // steady stream of bits to be decoded rBits: integer; // number of valid bits in BitString rCurSlot: integer; // next stack index to store a code rTopSlot: integer; // highest slot used so far rMaxVal: boolean; // max code value found? rCurX: integer; // position of next pixel rCurY: integer; // position of next pixel rCurPass: integer; // pixel line pass 1..4 rFirstSlot: integer; // for encoding an image rNextSlot: integer; // for encoding rCount: integer; // number of bytes read/written rLast: integer; // last byte read in rUnget: boolean; // read a new byte, or use zLast? end; { ---------------------------------------------------------------------------- } // define a GIF type TGif = class(TObject) private fIOStream: TMemoryStream; // read or write the image fDataStream: TMemoryStream; // temp storage for LZW fExtension: TList; // latest extensions read/written fSignature: PGifSignature; // version of GIF fScreenDescriptor: PGifScreenDescriptor; // logical screen descriptor fImageDescriptorList: TList; // list of all images fColorTableList: TList; // list of all color tables fPaletteList: TList; // list of palettes from color tables fZipData: PGifZip; // for encode/decode image FLoopCount: integer; // number of animated iterations // functions that override TGraphic items protected function GetHeight: integer; function GetWidth: integer; function GetTransparent: boolean; // procedures to read a bitmap private procedure ReadSignature; procedure ReadScreenDescriptor; procedure ReadColorTable(Size: integer; var Table: integer); procedure ReadImageDescriptor; procedure ReadDataBlockList(List: TList); procedure ReadExtension(var Done: boolean); procedure ReadSourceInteger(size: integer; var value: integer); // LZW encode and decode procedure LZWDecode(pID: PGifImageDescriptor); procedure LZWInit(pID: PGifImageDescriptor); procedure LZWFinit; procedure LZWReset; function LZWGetCode: integer; procedure LZWSaveCode(Code: integer); procedure LZWDecodeCode(var Code: integer); procedure LZWSaveSlot(Prefix, Suffix: integer); procedure LZWIncrPosition; procedure LZWCheckSlot; procedure LZWWriteBitmap; function LZWReadBitmap: integer; // procedures used to implement the PROPERTIES function GetSignature: string; function GetScreenDescriptor: PGifScreenDescriptor; function GetImageCount: integer; function GetImageDescriptor(image: integer): PGifImageDescriptor; function GetBitmap(image: integer): TBitmap; function GetColorTableCount: integer; function GetColorTable(table: integer): PGifColorTable; function GetImageDelay(Image: integer): integer; {LDB} function GetImageDisposal(Image: integer): integer; {LDB} function GetColorIndex(image, x, y: integer): integer; function GetTransparentIndex(image: integer): integer; function GetTransparentColor: TColor; function GetImageLeft(image: integer): integer; function GetImageTop(image: integer): integer; function GetImageWidth(image: integer): integer; function GetImageHeight(image: integer): integer; function GetImageDepth(image: integer): integer; // generally usefull routines procedure FreeDataBlockList(var list: TList); procedure FreeExtensionList(var list: TList); procedure MakeBitmaps; function FindGraphicExtension(image: integer): PGifExtensionGraphic; function FindColorIndex(c: TColor; ct: PGifColorTable): integer; procedure ExtractLoopCount(List: TList); public constructor Create; destructor Destroy; override; procedure FreeImage; procedure LoadFromStream(Source: TStream); function GetStripBitmap(var Mask: TBitmap): TBitmap; {LDB} property Signature: string read GetSignature; property ScreenDescriptor: PGifScreenDescriptor read GetScreenDescriptor; property ImageCount: integer read GetImageCount; property ImageDescriptor[Image: integer]: PGifImageDescriptor read GetImageDescriptor; property Bitmap[Image: integer]: TBitmap read GetBitmap; property ColorTableCount: integer read GetColorTableCount; property ColorTable[Table: integer]: PGifColorTable read GetColorTable; property Height: integer read GetHeight; property Width: integer read GetWidth ; property ImageDelay[Image: integer]: integer read GetImageDelay; property ImageDisposal[Image: integer]: integer read GetImageDisposal; property Transparent: boolean read GetTransparent; property TransparentIndex[Image: integer]: integer read GetTransparentIndex; property TransparentColor: TColor read GetTransparentColor; property ImageLeft[Image: integer]: integer read GetImageLeft; property ImageTop[Image: integer]: integer read GetImageTop; property ImageWidth[Image: integer]: integer read GetImageWidth; property ImageHeight[Image: integer]: integer read GetImageHeight; property ImageDepth[Image: integer]: integer read GetImageDepth; property LoopCount: integer read FLoopCount; end; implementation uses HtmlUn2; const TransColor = $170725; // GIF record separators const kGifImageSeparator: byte = $2c; kGifExtensionSeparator: byte = $21; kGifTerminator: byte = $3b; kGifLabelGraphic: byte = $f9; kGifLabelComment: byte = $fe; kGifLabelText: byte = $01; kGifLabelApplication: byte = $ff; // define a set of error messages const kGifErrorMessages: array[0..27] of string = ( 'no error', // 0 'Invalid GIF Signature Code', // 1 'No Local or Global Color Table for Image', // 2 'Unknown Graphics Extension Type', // 3 'Unknown Graphics Operation Code', // 4 'Invalid Extension Block Size', // 5 '[special message]', // 6 'Invalid Extension Block Terminator', // 7 'Invalid Integer Size', // 8 'No GIF Terminator Found', // 9 'Extension Block Out-Of-Order With Image Data', // 10 'Invalid Image Descriptor Index', // 11 'Invalid LZW Code Size', // 12 'Invalid LZW Data Format', // 13 'LZW Code Overflow', // 14 'Value Out Of Range', // 15 'NIL Pointer assigned', // 16 'Invalid Color Table Size', // 17 'No Image Description', // 18 'Invalid Bitmap Image', // 19 'Invalid Color Table Index', // 20 'Invalid Interlace Pass', // 21 'Invalid Bitmap', // 22 'Too Many Colors In Bitmap', // 23 'Unexpected end of file', // 24 {LDB} 'Animated GIF too large', // 25 {LDB} 'Zero width or height', // 26 {LDB} 'next message' // ); var GIF_ErrorCode: integer; // last error GIF_ErrorString: string; // last error procedure GIF_Error(n: integer); forward; procedure GIF_ErrorMessage(m: string); forward; constructor TGif.Create; begin inherited Create; // nothing defined yet fIOStream := nil; fDataStream := nil; fExtension := nil; fSignature := nil; fScreenDescriptor := nil; fImageDescriptorList := nil; fColorTableList := nil; fPaletteList := nil; fZipData := nil; FLoopCount := -1; // -1 is no loop count entered // some things, though, will always be needed new(fSignature); if (fSignature = nil) then OutOfMemoryError; fSignature^.rSignature := '------'; new(fScreenDescriptor); if (fScreenDescriptor = nil) then OutOfMemoryError; fillchar(fScreenDescriptor^, sizeof(TGifScreenDescriptor), 0); fImageDescriptorList := TList.Create; fColorTableList := TList.Create; fPaletteList := TList.Create; end; destructor TGif.Destroy; begin // clean up most of the data FreeImage; // and then the left-overs dispose(fSignature); dispose(fScreenDescriptor); fImageDescriptorList.Free; fColorTableList.Free; fPaletteList.Free; // and the ancestor inherited; end; { ---------------------------------------------------------------------------- } { release all memory used to store image data } procedure TGif.FreeImage; var i: integer; id: PGifImageDescriptor; ct: PGifColorTable; begin // temp input/output stream if (fIOStream <> nil) then fIOStream.Free; fIOStream := nil; // temp encoded data if (fDataStream <> nil) then fDataStream.Free; fDataStream:= nil; // temp list of image extensions if (fExtension <> nil) then FreeExtensionList(fExtension); fExtension := nil; // signature record stays, but is cleared if (fSignature = nil) then new(fSignature); fSignature^.rSignature := '------'; // ditto the screen descriptor if (fScreenDescriptor = nil) then new(fScreenDescriptor); fillchar(fScreenDescriptor^, sizeof(TGifScreenDescriptor), 0); // delete all items from image list, but leave the list if (fImageDescriptorList = nil) then fImageDescriptorList := TList.Create; for i := 0 to (fImageDescriptorList.Count - 1) do begin id := fImageDescriptorList.Items[i]; if (id <> nil) then begin if (id^.rExtensionList <> nil) then FreeExtensionList(id^.rExtensionList); if (id^.rPixelList <> nil) then freemem(id^.rPixelList); if (id^.rBitmap <> nil) then id^.rBitmap.Free; dispose(id); end; end; fImageDescriptorList.Clear; // release color tables, but keep the list if (fColorTableList = nil) then fColorTableList := TList.Create; for i := 0 to (fColorTableList.Count - 1) do begin ct := fColorTableList.Items[i]; if (ct <> nil) then dispose(ct); end; fColorTableList.Clear; // once again, keep the palette list object, but not the data if (fPaletteList = nil) then fPaletteList := TList.Create; fPaletteList.Clear; // don't need the zip/unzip data block if (fZipData <> nil) then dispose(fZipData); fZipData := nil; end; { ---------------------------------------------------------------------------- } { READ and WRITE A GIF ------------------------------------------------------- } { ---------------------------------------------------------------------------- } { read a GIF definition from a stream } procedure TGif.LoadFromStream(Source: TStream); var done: boolean; b: byte; begin // release old image that may be here ... FreeImage; // no error yet GIF_ErrorCode := 0; GIF_ErrorString := ''; // make a local copy of the source data // memory streams are faster and easier to manipulate than file streams fIOStream := TMemoryStream.Create; Source.Position := 0; fIOStream.LoadFromStream(Source); // local temp vars fDataStream := TMemoryStream.Create; // data to be un-zipped fExtension := nil; // extensions to an image // read the signature GIF87A or GIF89A ReadSignature; // read the logical screen descriptor ReadScreenDescriptor; // read extensions and image data until end of file done := false; while (not done) do try {LDB} if (fIOStream.Position >= fIOStream.Size) then //GIF_Error(9); {LDB} b := 0 {LDB} else fIOStream.Read(b, 1); {LDB} // image separator if (b = 0) then // just skip this? begin b := 0; Done := True; {LDB} end else if (b = kGifTerminator) then // got it all begin done := true; end else if (b = kGifImageSeparator) then // next bitmap begin ReadImageDescriptor; end else if (b = kGifExtensionSeparator) then // special operations begin ReadExtension(Done); end else // unknown begin GIF_Error(4); end; except {LDB} if GetImageCount > 0 then Done := True {use what images we have} else Raise; end; // must have an image if (fImageDescriptorList.Count = 0) then GIF_Error(18); // no longer need the source data in memory fIOStream.Free; fDataStream.Free; FreeExtensionList(fExtension); fIOStream := nil; fDataStream := nil; fExtension := nil; end; function TGif.GetHeight: integer; begin GetHeight := fScreenDescriptor^.rHeight; end; function TGif.GetWidth: integer; begin GetWidth := fScreenDescriptor^.rWidth; end; { ---------------------------------------------------------------------------- } { TRANSPARENT is assument to be the same for all images; i.e., if the first } { image is transparent, they they are all transparent } { if SetTransparent(TRUE) then set default color index for transparent color } { this can be changed with TransparentColor after this call } {LDB changed so that if any images are transparent, Transparent returns True} function TGif.GetTransparent: boolean; var b: boolean; gx: PGifExtensionGraphic; i: integer; begin b := false; for I := 0 to (fImageDescriptorList.Count - 1) do begin gx := FindGraphicExtension(I); if (gx <> nil) then b := gx^.rTransparentValid or b; end; GetTransparent := b; end; { ---------------------------------------------------------------------------- } { PROCEDURES TO READ A GIF FILE ---------------------------------------------- } { ---------------------------------------------------------------------------- } { read the GIF signature from the source stream } { this assumes the memory stream position is correct } { the signature is always 6 bytes, and must be either GIF87A or GIF89A } procedure TGif.ReadSignature; var s: string; begin with fSignature^ do begin fIOStream.Read(rSignature, 6); s := rSignature; s := UpperCase(s); if ((s <> 'GIF87A') and (s <> 'GIF89A')) then GIF_Error(1); end; end; { ---------------------------------------------------------------------------- } { read the GIF logical screen descriptor from the source stream } { this assumes the memory stream position is correct } { this always follows the GIF signature } procedure TGif.ReadScreenDescriptor; var i,n: integer; begin with fScreenDescriptor^ do begin ReadSourceInteger(2, rWidth); // logical screen width ReadSourceInteger(2, rHeight); // logical screen height ReadSourceInteger(1, n); // packed bit fields rGlobalColorValid := ((n and $80) <> 0); rColorResolution := ((n shr 4) and $07) + 1; rSorted := ((n and $08) <> 0); i := (n and $07); if (i = 0) then rGlobalColorSize := 2 else if (i = 1) then rGlobalColorSize := 4 else if (i = 2) then rGlobalColorSize := 8 else if (i = 3) then rGlobalColorSize := 16 else if (i = 4) then rGlobalColorSize := 32 else if (i = 5) then rGlobalColorSize := 64 else if (i = 6) then rGlobalColorSize := 128 else if (i = 7) then rGlobalColorSize := 256 else rGlobalColorSize := 256; ReadSourceInteger(1, rBackgroundIndex); // background color ReadSourceInteger(1, rAspectRatio); // pixel aspect ratio // read the global color table from the source stream // this assumes the memory stream position is correct // the global color table is only valid if a flag is set in the logical // screen descriptor. if the flag is set, the global color table will // immediately follow the logical screen descriptor rGlobalColorTable := -1; if (rGlobalColorValid) then // a global color table? ReadColorTable(rGlobalColorSize, rGlobalColorTable) end; end; { ---------------------------------------------------------------------------- } { read in any type of color table } { number of RGB entries is given by SIZE, and save the index into the } { master color table list in TABLE } { if SIZE is <= 0, then there is no table, and the TABLE becomes -1 } procedure TGif.ReadColorTable(Size: integer; var Table: integer); var i,n: integer; r,g,b: byte; ct: PGifColorTable; begin Table := -1; // assume no table if (Size > 0) then // OK, a table does exist begin new(ct); // make a anew color table if (ct = nil) then OutOfMemoryError; n := fColorTableList.Add(ct); // save it in master list Table := n; // save index for a valid table ct^.rSize := Size; for i := 0 to (ct^.rSize-1) do // read a triplet for each TColor begin fIOStream.Read(r, 1); // red fIOStream.Read(g, 1); // green fIOStream.Read(b, 1); // blue ct^.rColors[i] := r or (g shl 8) or (b shl 16); end; // make sure we store palette handle in same index slot as the color table while (fPaletteList.Count < fColorTableList.Count) do fPaletteList.Add(nil); fPaletteList.Items[Table] := Nil; end; end; { ---------------------------------------------------------------------------- } { read the next image descriptor } { the source stream position should be immediately following the } { special code image separator } { note: this routine only reads in the raw data; the LZW de-compression } { occurs later, after all the data has been read } { this probably makes for a bigger data chunk, but it doesn't much effect } { the speed, and it is certainly a more modular approach and is much easier } { to understand the mechanics later } procedure TGif.ReadImageDescriptor; var i,n: integer; ix: integer; id: PGifImageDescriptor; db: TGifDataBlock; begin // make a new image desctiptor record and add this record to main list new(id); if (id = nil) then OutOfMemoryError; if (fImageDescriptorList = nil) then fImageDescriptorList := TList.Create; ix := fImageDescriptorList.Add(id); id^.rIndex := ix; // initialize data fillchar(id^, sizeof(TGifImageDescriptor), 0); // init the sotrage for compressed data fDataStream.Clear; // if extensions were read in earlier, save that list // for this image descriptor // if no extensions were read in, then we don't need this list at all if (fExtension <> nil) then begin id^.rExtensionList := fExtension; fExtension := nil; end; // shortcut to the record fields with id^ do begin // read the basic descriptor record ReadSourceInteger(2, rLeft); // left position ReadSourceInteger(2, rTop); // top position ReadSourceInteger(2, rWidth); // size of image ReadSourceInteger(2, rHeight); // size of image if rHeight > Height then {LDB make sure bad values don't overflow elsewhere} rHeight := Height; ReadSourceInteger(1, n); // packed bit field rLocalColorValid := ((n and $80) <> 0); rInterlaced := ((n and $40) <> 0); rSorted := ((n and $20) <> 0); i := (n and $07); if (i = 0) then rLocalColorSize := 2 else if (i = 1) then rLocalColorSize := 4 else if (i = 2) then rLocalColorSize := 8 else if (i = 3) then rLocalColorSize := 16 else if (i = 4) then rLocalColorSize := 32 else if (i = 5) then rLocalColorSize := 64 else if (i = 6) then rLocalColorSize := 128 else if (i = 7) then rLocalColorSize := 256 else rLocalColorSize := 256; // if a local color table is defined, read it // otherwise, use the global color table if (rLocalColorValid) then ReadColorTable(rLocalColorSize, rLocalColorTable) else rLocalColorTable := fScreenDescriptor^.rGlobalColorTable; // _something_ must have defined by now ... if (rLocalColorTable < 0) then GIF_Error(2); // the LZW minimum code size ReadSourceInteger(1, rLZWSize); // read data blocks until the end of the list ReadSourceInteger(1, db.rSize); while (db.rSize > 0) do begin if fIOStream.Read(db.rData, db.rSize) < db.rSize then Gif_Error(24); {LDB} fDataStream.Write(db.rData, db.rSize); ReadSourceInteger(1, db.rSize); end; // save the pixel list rPixelCount := rWidth * rHeight; if rPixelCount = 0 then {LDB} Gif_Error(26); rPixelList := allocmem(rPixelCount); if (rPixelList = nil) then OutOfMemoryError; // uncompress the data and write the bitmap LZWDecode(id); end; // with id^ end; { ---------------------------------------------------------------------------- } { read in a group of data blocks until a zero-length block is found } { store the data on the give TList } procedure TGif.ReadDataBlockList(List: TList); var b: byte; db: PGifDataBlock; BytesRead: integer; begin // read data blocks until the end of the list fIOStream.Read(b, 1); // size of next block while (b > 0) do // more blocks to get? begin new(db); // new data block record db^.rSize := b; BytesRead := fIOStream.Read(db^.rData, db^.rSize); // read the data List.Add(db); // save in given list if BytesRead < db^.rSize then Gif_Error(24); {LDB} fIOStream.Read(b, 1); // size of next block end; end; { ---------------------------------------------------------------------------- } { read in any type of extension record } { assume that the source position is AFTER the extension separator, } { but BEFORE the specific extension label } { the extension record we read in is stored in the master extension } { list; however, the indexes for these exrtensions is stored in a } { temporary list which will be assigned to the next image descriptor } { record read in. this is because all extension blocks preceed the } { image descriptor to which they belong } procedure TGif.ReadExtension(var Done: boolean); var n: integer; b: byte; eb: PGifExtension; begin // make a list exists if (fExtension = nil) then fExtension := TList.Create; // make a new extension record and add it to temp holding list new(eb); if (eb = nil) then OutOfMemoryError; fillchar(eb^, sizeof(TGifExtension), 0); fExtension.Add(eb); // get the type of extension fIOStream.Read(b, 1); eb^.rLabel := b; // "with eb^" gives us access to rGraphic, rText, rComment, and rApp with eb^ do begin // a graphic extension if (rLabel = kGifLabelGraphic) then begin ReadSourceInteger(1, rGraphic.rBlockSize); // block size if (rGraphic.rBlockSize <> 4) then GIF_Error(5); ReadSourceInteger(1, n); // packed bit field rGraphic.rDisposal := ((n shr 2) and $07); rGraphic.rUserInputValid := ((n and $02) <> 0); rGraphic.rTransparentValid := ((n and $01) <> 0); ReadSourceInteger(2, rGraphic.rDelayTime); // delay time ReadSourceInteger(1, rGraphic.rTransparentIndex); // transparent color ReadSourceInteger(1, n); // block terminator if (n <> 0) then GIF_Error(7); end // a comment extension else if (rLabel = kGifLabelComment) then begin rComment.rDataBlockList := TList.Create; ReadDataBlockList(rComment.rDataBlockList); end // a plain text extension else if (rLabel = kGifLabelText) then begin ReadSourceInteger(1, rText.rBlockSize); // block size if (rText.rBlockSize <> 12) then GIF_Error(5); ReadSourceInteger(2, rText.rGridLeft); // grid position ReadSourceInteger(2, rText.rGridTop); // grid position ReadSourceInteger(2, rText.rGridWidth); // grid size ReadSourceInteger(2, rText.rGridHeight); // grid size ReadSourceInteger(1, rText.rCellWidth); // character cell size {LDB}{was 2 bytes} ReadSourceInteger(1, rText.rCellHeight); // character cell size ReadSourceInteger(1, rText.rForegroundIndex); // foreground color ReadSourceInteger(1, rText.rBackgroundIndex); // background color rText.rDataBlockList := TList.Create; // list of text data blocks ReadDataBlockList(rText.rDataBlockList); end // an application extension else if (rLabel = kGifLabelApplication) then begin ReadSourceInteger(1, rApp.rBlockSize); // block size if (rApp.rBlockSize <> 11) then //GIF_Error(5); {LDB} allow other blocksizes begin fIOStream.Position := fIOStream.Position+rApp.rBlockSize; rApp.rDataBlockList := TList.Create; ReadDataBlockList(rApp.rDataBlockList); end else begin fIOStream.Read(rApp.rIdentifier, 8); // application identifier fIOStream.Read(rApp.rAuthentication, 3); // authentication code rApp.rDataBlockList := TList.Create; ReadDataBlockList(rApp.rDataBlockList); if rApp.rIdentifier = 'NETSCAPE' then ExtractLoopCount(rApp.rDataBlockList); end; end // unknown type else begin GIF_ErrorMessage('unknown extension: ' + IntToHex(rLabel, 4)); end; end; // with eb^ end; { ---------------------------------------------------------------------------- } { read a 1 or 2-byte integer from the source stream } procedure TGif.ReadSourceInteger(size: integer; var value: integer); var b: byte; w: word; begin if (size = 1) then begin fIOStream.Read(b, 1); value := b; end else if (size = 2) then begin fIOStream.Read(w, 2); value := w; end else begin GIF_Error(8); end; end; { ---------------------------------------------------------------------------- } { decode the compressed data blocks into a bitmap } procedure TGif.LZWDecode(pID: PGifImageDescriptor); var pc: integer; // next compressed code parsed from input cc: integer; // current code to translate oc: integer; // old code translated tt: integer; // temp storage for OldCode Done: boolean; begin // init local data LZWInit(pID); LZWReset; // do everything within the ZIP record with fZipData^ do begin // parse next code from BitString pc := LZWGetCode; oc := pc; Done := False; while (pc <> rEndCode) and not Done do begin // reset decode parameters and save first code if (pc = rClearCode) then begin rCurSize := rID^.rLZWSize + 1; rCurSlot := rEndCode + 1; rTopSlot := (1 shl rCurSize); while (pc = rClearCode) do pc := LZWGetCode; if (pc = rEndCode) then GIF_Error(13); if (pc >= rCurSlot) then pc := 0; oc := pc; LZWSaveCode(pc); end // find a code in the table and write out translation else begin cc := pc; if (cc < rCurSlot) then begin LZWDecodeCode(cc); if (rCurSlot <= rTopSlot) then begin LZWSaveSlot(oc, cc); oc := pc; end; LZWCheckSlot; end // add a new code to the decode table else begin if (cc <> rCurSlot) then GIF_Error(13); tt := oc; while (oc > rHighCode) do oc := rPrefix[oc]; if (rCurSlot <= rTopSlot) then LZWSaveSlot(tt, oc); LZWCheckSlot; LZWDecodeCode(cc); oc := pc; end; end; // write out translated bytes to the image storage LZWWriteBitmap; if fDataStream.Position < fDataStream.Size then pc := LZWGetCode else Done := True; rMaxVal := false; end; // while not EOI end; // with // done with stack space LZWFinit; end; { ---------------------------------------------------------------------------- } procedure TGif.LZWInit(pID: PGifImageDescriptor); begin // get a valid record? if (pID = nil) then GIF_Error(11); // make sure we can actually decode this turkey // if ((pID^.rLZWSize < 2) or (pID^.rLZWSize > 9)) then GIF_Error(12); // allocate stack space new(fZipData); if (fZipData = nil) then OutOfMemoryError; // init data block fillchar(fZipData^, sizeof(TGifZip), 0); fZipData^.rID := pID; fZipData^.rCT := fColorTableList.Items[pID^.rLocalColorTable]; // reset data stream fDataStream.Position := 0; end; { ---------------------------------------------------------------------------- } procedure TGif.LZWFinit; begin if (fZipData <> nil) then dispose(fZipData); fZipData := nil; end; { ---------------------------------------------------------------------------- } procedure TGif.LZWReset; var i: integer; begin with fZipData^ do begin for i := 0 to (kGifCodeTableSize - 1) do begin rPrefix[i] := 0; rSuffix[i] := 0; end; rCurSize := rID^.rLZWSize + 1; rClearCode := (1 shl rID^.rLZWSize); rEndCode := rClearCode + 1; rHighCode := rClearCode - 1; rFirstSlot := (1 shl (rCurSize - 1)) + 2; rNextSlot := rFirstSlot; rMaxVal := false; end; // with end; { ---------------------------------------------------------------------------- } { get the next code from the BitString } { CurrentSize specifies the number of bits to get } function TGif.LZWGetCode: integer; var n: integer; cc: integer; mask: integer; b: byte; begin with fZipData^ do begin // make sure we have enough bits while (rCurSize > rBits) do begin if (fDataStream.Position >= fDataStream.Size) then b := 0 else fDataStream.Read(b, 1); n := b; n := (n shl rBits); // scoot bits over to avoid previous data rBitString := (rBitString or n); // put bits in the BitString rBits := rBits + 8; // number of bits in a byte end; // get the code, then dump the bits we used from the BitString case rCurSize of 0: mask := 0; 1: mask := $0001; 2: mask := $0003; 3: mask := $0007; 4: mask := $000f; 5: mask := $001f; 6: mask := $003f; 7: mask := $007f; 8: mask := $00ff; 9: mask := $01ff; 10: mask := $03ff; 11: mask := $07ff; 12: mask := $0fff; else begin GIF_Error(12); Mask := 0; //stop warning end; end; cc := (rBitString and mask); // mask off bits wanted rBitString := (rBitString shr rCurSize); // delete bits we just took rBits := rBits - rCurSize; // number of bits left in BitString end; // with // done LZWGetCode := cc; end; { ---------------------------------------------------------------------------- } { save a code value on the code stack } procedure TGif.LZWSaveCode(Code: integer); begin with fZipData^ do begin rCodeStack[rSP] := Code; rSP := rSP + 1; end; end; { ---------------------------------------------------------------------------- } { decode the CurrentCode into the clear-text pixel value } { mainly, just save the CurrentCode on the output stack, along with } { whatever prefixes go with it } procedure TGif.LZWDecodeCode(var Code: integer); begin with fZipData^ do begin while (Code > rHighCode) do begin LZWSaveCode(rSuffix[Code]); Code := rPrefix[Code]; end; LZWSaveCode(Code); end; end; { ---------------------------------------------------------------------------- } { save a new prefix/suffix pair } procedure TGif.LZWSaveSlot(Prefix, Suffix: integer); begin with fZipData^ do begin rPrefix[rCurSlot] := Prefix; rSuffix[rCurSlot] := Suffix; rCurSlot := rCurSlot + 1; end; end; { ---------------------------------------------------------------------------- } { given current line number, compute the next line to be filled } { this gets a little tricky if an interlaced image } { what is the purpose of this interlace, anyway? it doesn't save space, } { and I can't imagine it makes for any faster image disply or loading } procedure TGif.LZWIncrPosition; var n: integer; begin with fZipData^ do begin // if first pass, make sure CurPass was initialized if (rCurPass = 0) then rCurPass := 1; // incr X position rCurX := rCurX + 1; // bumping Y ? if (rCurX >= rID^.rWidth) then begin rCurX := 0; // if not interlaced image, then just move down the page if (not rID^.rInterlaced) then begin rCurY := rCurY + 1; end // interlaced images select the next line by some archane black-magical sheme else begin case rCurPass of // delta to next row on this pass 1: n := 8; 2: n := 8; 3: n := 4; 4: n := 2; else begin GIF_Error(21); n := 0; //prevent warning end; end; rCurY := rCurY + n; // if past the end of the bitmap, start next pass if (rCurY >= rID^.rHeight) then begin rCurPass := rCurPass + 1; if (rCurPass = 5) then rCurPass := 1; case rCurPass of // first line for given pass 1: n := 0; 2: n := 4; 3: n := 2; 4: n := 1; else GIF_Error(21); end; rCurY := n; end; end; end; end; // with end; { ---------------------------------------------------------------------------- } { see if it is time to add a new slot to the decoder tables } procedure TGif.LZWCheckSlot; begin with fZipData^ do begin if (rCurSlot >= rTopSlot) then begin if (rCurSize < 12) then begin rTopSlot := (rTopSlot shl 1); rCurSize := rCurSize + 1; end else begin rMaxVal := true; end; end; end; end; { ---------------------------------------------------------------------------- } { empty the Codes stack and write to the Bitmap } procedure TGif.LZWWriteBitmap; var i,n: integer; j: longint; p: PChar; begin with fZipData^ do begin for n := (rSP - 1) downto 0 do begin rCount := rCount + 1; // get next code from the stack, and index into PixelList i := rCodeStack[n]; j := (rCurY * rID^.rWidth) + rCurX; if ((0 <= j) and (j < rID^.rPixelCount)) then begin // store the pixel index into PixelList p := rID^.rPixelList + j; p^ := chr(i); end; LZWIncrPosition; end; rSP := 0; end; // with end; { ---------------------------------------------------------------------------- } { get the next pixel from the bitmap, and return it as an index into } { the colormap } function TGif.LZWReadBitmap: integer; var n: integer; j: longint; p: PChar; begin with fZipData^ do begin if (rUnget) then begin n := rLast; rUnget := false; end else begin rCount := rCount + 1; j := (rCurY * rID^.rWidth) + rCurX; if ((0 <= j) and (j < rID^.rPixelCount)) then begin p := rID^.rPixelList + j; n := ord(p^); end else begin n := 0; end; LZWIncrPosition; end; rLast := n; end; // with LZWReadBitmap := n; end; { ---------------------------------------------------------------------------- } { PROCEDURES TO IMPLEMENT PROPERTIES ----------------------------------------- } { ---------------------------------------------------------------------------- } function TGif.GetSignature: string; var s: string; begin s := fSignature^.rSignature; GetSignature := s; end; { ---------------------------------------------------------------------------- } { return screen descriptor data pointer, or set a new record block } function TGif.GetScreenDescriptor: PGifScreenDescriptor; begin GetScreenDescriptor := fScreenDescriptor; end; { ---------------------------------------------------------------------------- } function TGif.GetImageCount: integer; begin GetImageCount := fImageDescriptorList.Count; end; function TGif.GetImageDescriptor(image: integer): PGifImageDescriptor; begin if ((image < 0) or (image >= fImageDescriptorList.Count)) then GIF_Error(15); GetImageDescriptor := fImageDescriptorList.Items[image]; end; { ---------------------------------------------------------------------------- } function TGif.GetBitmap(image: integer): TBitmap; var p: PGifImageDescriptor; b: TBitmap; begin p := GetImageDescriptor(image); if (p^.rBitmap = nil) then MakeBitmaps; b := p^.rBitmap; GetBitmap := b; end; { ---------------------------------------------------------------------------- } function TGif.GetColorTableCount: integer; begin GetColorTableCount := fColorTableList.Count; end; function TGif.GetColorTable(table: integer): PGifColorTable; begin if ((table < 0) or (table >= fColorTableList.Count)) then GIF_Error(15); GetColorTable := fColorTableList.Items[table]; end; function TGif.GetImageDelay(Image: integer): integer; var gx: PGifExtensionGraphic; begin gx := FindGraphicExtension(Image); if (gx <> nil) then begin Result := gx^.rDelayTime; if Result < 1 then Result := 1; end else Result := 1; end; function TGif.GetImageDisposal(Image: integer): integer; var gx: PGifExtensionGraphic; begin gx := FindGraphicExtension(Image); if (gx <> nil) then Result := gx^.rDisposal and 3 else Result := 0; end; { ---------------------------------------------------------------------------- } function TGif.GetColorIndex(image, x, y: integer): integer; var i,n: integer; id: PGifImageDescriptor; p: PChar; begin if ((image < 0) or (image >= fImageDescriptorList.Count)) then GIF_Error(15); id := fImageDescriptorList.Items[image]; if ((x < 0) or (x >= id^.rWidth)) then GIF_Error(15); if ((y < 0) or (y >= id^.rHeight)) then GIF_Error(15); n := (y * id^.rWidth) + x; p := id^.rPixelList + n; i := ord(p^); GetColorIndex := i; end; { ---------------------------------------------------------------------------- } { transparent color for each individual image. returns -1 if none. } function TGif.GetTransparentIndex(image: integer): integer; var i: integer; gx: PGifExtensionGraphic; begin i := -1; gx := FindGraphicExtension(image); if (gx <> nil) and (gx^.rTransparentValid) then {LDB} i := gx^.rTransparentIndex; GetTransparentIndex := i; end; { ---------------------------------------------------------------------------- } { transparent color for all images } {LDB Changed to always return the standard used for the transparent color} function TGif.GetTransparentColor: TColor; begin GetTransparentColor := TransColor; end; procedure TGif.ExtractLoopCount(List: TList); begin if List.Count > 0 then with PGifDataBlock(List[0])^ do if rSize = 3 then FLoopCount := rData[2] + rData[3]*256; end; { ---------------------------------------------------------------------------- } function TGif.GetImageLeft(image: integer): integer; var id: PGifImageDescriptor; begin id := GetImageDescriptor(image); GetImageLeft := id^.rLeft; end; function TGif.GetImageTop(image: integer): integer; var id: PGifImageDescriptor; begin id := GetImageDescriptor(image); GetImageTop := id^.rTop; end; function TGif.GetImageWidth(image: integer): integer; var id: PGifImageDescriptor; begin id := GetImageDescriptor(image); GetImageWidth := id^.rWidth; end; function TGif.GetImageHeight(image: integer): integer; var id: PGifImageDescriptor; begin id := GetImageDescriptor(image); GetImageHeight := id^.rHeight; end; function TGif.GetImageDepth(image: integer): integer; var id: PGifImageDescriptor; ct: PGifColorTable; begin id := GetImageDescriptor(image); ct := fColorTableList.Items[id^.rLocalColorTable]; GetImageDepth := ct^.rSize; end; { ---------------------------------------------------------------------------- } { GENERAL INTERNAL ROUTINES -------------------------------------------------- } { ---------------------------------------------------------------------------- } procedure TGif.FreeDataBlockList(var list: TList); var i: integer; db: PGifDataBlock; begin if (list <> nil) then begin for i := 0 to (list.Count - 1) do begin db := list.Items[i]; if (db <> nil) then dispose(db); end; list.Free; end; list := nil; end; { ---------------------------------------------------------------------------- } procedure TGif.FreeExtensionList(var list: TList); var i: integer; ex: PGifExtension; begin if (list <> nil) then begin for i := 0 to (list.Count - 1) do begin ex := list.Items[i]; if (ex <> nil) then begin if (ex^.rLabel = kGifLabelComment) then FreeDataBlockList(ex^.rComment.rDataBlockList) else if (ex^.rLabel = kGifLabelText) then FreeDataBlockList(ex^.rText.rDataBlockList) else if (ex^.rLabel = kGifLabelApplication) then FreeDataBlockList(ex^.rApp.rDataBlockList); dispose(ex); end; end; list.Free; end; list := nil; end; { ---------------------------------------------------------------------------- } { after an image has been LZW decoded, write a bitmap from the string of pixels } {----------------TGif.MakeBitmaps} procedure TGif.MakeBitmaps; type LayoutType = Packed Record BFH: TBitmapFileHeader; BIH: TBitmapInfoHeader; end; PLayoutType = ^LayoutType; var id: PGifImageDescriptor; ct: PGifColorTable; FullWidth, PixelSize, FileSize: integer; Stream: TMemoryStream; PL: PLayoutType; Color: TColor; Index: integer; Pix, P: PChar; I, X, Y, N: integer; TrIndex: integer; begin for i := 0 to (fImageDescriptorList.Count - 1) do begin id := fImageDescriptorList.Items[i]; if ((id <> nil) and (id^.rBitmap = nil)) then // don't do it again with id^ do begin FullWidth := rWidth * 3; if FullWidth and $3 <> 0 then FullWidth := (FullWidth and $FFFFFFFC) + $4; PixelSize := FullWidth * rHeight; FileSize := Sizeof(LayoutType)+PixelSize; Stream := TMemoryStream.Create; try Stream.Size := FileSize; PL := Stream.Memory; FillChar(PL^, FileSize, 0); with PL^.BFH do begin bfType := 19778; bfSize := FileSize; bfReserved1 := 0; bfReserved2 := 0; bfOffBits := Sizeof(LayoutType); end; with PL^.BIH do begin biSize := Sizeof(TBitmapInfoHeader); biWidth := rWidth; biHeight := rHeight; biPlanes := 1; biBitCount := 24; biCompression := 0; biSizeImage := 0; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; end; ct := fColorTableList.Items[rLocalColorTable]; TrIndex := GetTransparentIndex(i); if (TrIndex >= 0) and (TrIndex < ct^.rSize) then {change transparent color to something that won't likely match any other color} ct^.rColors[TrIndex] := TransColor; N := 0; Pix := PChar(PL) + Sizeof(LayoutType); for Y := rHeight-1 downto 0 do begin P := Pix + (Y * FullWidth); for X := 0 to rWidth-1 do begin Index := Integer((rPixelList + N)^); Color := ct^.rColors[Index]; P^ := Char((Color shr 16) and $FF); Inc(P); P^ := Char((Color shr 8) and $FF); Inc(P); P^ := Char(Color and $FF); Inc(P); Inc(N); end; end; rBitmap := TBitmap.Create; {$ifndef UseCLX} rBitmap.HandleType := bmDIB; {$endif} rBitmap.LoadFromStream(Stream); finally Stream.Free; end; // is bitmap transparent? if ((0 <= TrIndex) and (TrIndex < ct^.rSize)) then begin rBitmap.Transparent := true; rBitmap.TransparentMode := tmFixed; rBitmap.TransparentColor := ct^.rColors[TrIndex]; end; end; end; end; {----------------TGif.GetStripBitmap} function TGif.GetStripBitmap(var Mask: TBitmap): TBitmap; {LDB} {This is a single bitmap containing all the frames. A mask is also provided if the GIF is transparent. Each Frame is set up so that it can be transparently blted to a background.} type LayoutType = Packed Record BFH: TBitmapFileHeader; BIH: TBitmapInfoHeader; end; PLayoutType = ^LayoutType; var id: PGifImageDescriptor; ct: PGifColorTable; FullWidth, PixelSize, FileSize: integer; Stream, MStream: TMemoryStream; PL, MPL: PLayoutType; Color: TColor; Index: integer; Pix, P, MPix, MP, PRight: PChar; I, X, Y, N: integer; TrIndex: integer; C: char; IsTransparent: boolean; begin MStream := Nil; Result := Nil; Mask := Nil; MP := Nil; MPix := Nil; {find size needed for strip bitmap} FullWidth := Width * 3 * ImageCount; {3 bytes per pixel} if FullWidth and $3 <> 0 then {make sure it is DWord boundary} FullWidth := (FullWidth and $FFFFFFFC) + $4; PixelSize := FullWidth * Height; FileSize := Sizeof(LayoutType)+PixelSize; if (FileSize > 200000000) or Transparent and (FileSize > 100000000) then GIF_Error(25); Stream := TMemoryStream.Create; try Stream.Size := FileSize; PL := Stream.Memory; FillChar(PL^, FileSize, 0); with PL^.BFH do begin {set up the bitmap file header} bfType := 19778; bfSize := FileSize; bfReserved1 := 0; bfReserved2 := 0; bfOffBits := Sizeof(LayoutType); end; with PL^.BIH do begin {and the bitmap info header} biSize := Sizeof(TBitmapInfoHeader); biWidth := Width * ImageCount; biHeight := Height; biPlanes := 1; biBitCount := 24; {will use 24 bit pixel} biCompression := 0; biSizeImage := 0; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; end; Pix := PChar(PL) + Sizeof(LayoutType); {where pixels start} IsTransparent := Transparent; if IsTransparent then begin {set up a mask similarly} MStream := TMemoryStream.Create; MStream.Size := FileSize; MPL := MStream.Memory; Move(PL^, MPL^, FileSize); {for now, this is a direct copy} MPix := PChar(MPL) + Sizeof(LayoutType); {where mask pixels start} FillChar(MPix^, PixelSize, $FF); {Need to make first frame totally transparent} end; for i := 0 to (fImageDescriptorList.Count - 1) do {for all the frames} begin id := fImageDescriptorList.Items[i]; if (id <> nil) then with id^ do begin ct := fColorTableList.Items[rLocalColorTable]; TrIndex := GetTransparentIndex(i); N := 0; {pixel index in rPixelList, the frame source pixels} for Y := Height-1 downto IntMax(Height-rHeight, ImageTop[I]) do begin {find the start of each frame row in destination. Note that the source frame may be smaller than the destination and positioned according to imagetop and imageleft} P := Pix + ((Y-ImageTop[i]) * FullWidth) + i*Width*3 +ImageLeft[i]*3; PRight := P + Width*3; if IsTransparent then {same for mask} MP := MPix + ((Y-ImageTop[i]) * FullWidth) + i*Width*3 +ImageLeft[i]*3; for X := 0 to rWidth-1 do begin if P < PRight then {prevent write beyond proper right side in case rwidth to wide} begin Index := Integer((rPixelList + N)^); {Source pixel index in colortable} Color := ct^.rColors[Index]; {its color} {for frames after the 0th, only the non transparent pixels are written as writing transparent ones might cover results copied from the previous frame} if (Index <> trIndex) then begin P^ := Char((Color shr 16) and $FF); Inc(P); P^ := Char((Color shr 8) and $FF); Inc(P); P^ := Char(Color and $FF); Inc(P); end else if i = 0 then begin {transparent pixel, first frame, write black} P^ := #0; Inc(P); P^ := #0; Inc(P); P^ := #0; Inc(P); end else Inc(P, 3); {ignore transparent pixel} if IsTransparent then {also do the mask} begin if Index = trIndex then C := #$FF {transparent part is white} else C := #0; {non transparent is black} {again for frames after the 0th, only non-transparent pixels are written} if (i = 0) or (C = #0) then begin MP^ := C; Inc(MP); MP^ := C; Inc(MP); MP^ := C; Inc(MP); end else Inc(MP, 3); end; end; Inc(N); {bump source pixel index} end; end; end; {Now copy this frame to the next (unless it the last one). This serves as a background for the next image. This is all that's needed for the dtDoNothing disposal method but will be fixed up for dtBackground below} if (i < fImageDescriptorList.Count-1) then begin for Y := Height-1 downto 0 do begin {copy line by line} P := Pix + (Y * FullWidth) + i*Width*3; if IsTransparent then MP := MPix + (Y * FullWidth) + i*Width*3; Move(P^, (P+Width*3)^, Width*3); if IsTransparent then Move(MP^, (MP+Width*3)^, Width*3); end; {for dtBackground, fill the mask area occupied by the current copied image with white. This makes it transparent so the original background will appear here (although the next image will no doubt write on part of this area.} if IsTransparent and (ImageDisposal[i] in [2,3]) then {dtToPrevious run as dtBackground as it seems other browsers do this} with id^ do for Y := Height-1 downto IntMax(Height-rHeight, ImageTop[I]) do begin MP := MPix + ((Y-ImageTop[i]) * FullWidth) + (i+1)*Width*3 +ImageLeft[i]*3; FillChar(MP^, rWidth*3, $FF); end; end; end; Result := TBitmap.Create; {$ifndef UseCLX} Result.HandleType := bmDIB; {$endif} Result.LoadFromStream(Stream); {turn the stream just formed into a TBitmap} if IsTransparent then begin Mask := TBitmap.Create; Mask.HandleType := bmDIB; Mask.LoadFromStream(MStream); Mask.Monochrome := True; {crunch mask into a monochrome TBitmap} end; Stream.Free; MStream.Free; except Stream.Free; MStream.Free; Mask.Free; Result.Free; Raise; end; end; { ---------------------------------------------------------------------------- } { find the graphic extension for an image } function TGif.FindGraphicExtension(image: integer): PGifExtensionGraphic; var n: integer; id: PGifImageDescriptor; ex: PGifExtension; gx: PGifExtensionGraphic; begin gx := nil; id := fImageDescriptorList.Items[image]; if (id^.rExtensionList <> nil) then begin for n := 0 to (id^.rExtensionList.Count - 1) do begin ex := id^.rExtensionList.Items[n]; if ((ex^.rLabel = kGifLabelGraphic) and (gx = nil)) then begin gx := @(ex^.rGraphic); end; end; end; FindGraphicExtension := gx; end; { ---------------------------------------------------------------------------- } { find the color within the color table; returns 0..255 } { return -1 if color not found } function TGif.FindColorIndex(c: TColor; ct: PGifColorTable): integer; var i,n: integer; begin n := -1; for i := 0 to (ct^.rSize - 1) do begin if ((n < 0) and (ct^.rColors[i] = c)) then n := i; end; FindColorIndex := n; end; { ---------------------------------------------------------------------------- } { RAISE AN ERROR ------------------------------------------------------------- } procedure GIF_Error(n: integer); begin GIF_ErrorCode := n; GIF_ErrorString := kGifErrorMessages[n]; raise EInvalidGraphicOperation.CreateFmt('TGif: %s', [GIF_ErrorString]); end; procedure GIF_ErrorMessage(m: string); begin GIF_ErrorCode := 6; GIF_ErrorString := m; raise EInvalidGraphicOperation.CreateFmt('TGif: %s', [GIF_ErrorString]); end; end.
{$MODE OBJFPC} program Task; const InputFile = 'INTSLE.INP'; OutputFile = 'INTSLE.OUT'; sNoSol = 'NO SOLUTION'; var fi, fo: TextFile; a1, b1, c1, a2, b2, c2: Int64; d, dx, dy: Int64; function GCD(a, b: Int64): Int64; var r: Int64; begin while b <> 0 do begin r := a mod b; a := b; b := r; end; Result := Abs(a); end; procedure Solve; var sol1, sol2: Boolean; begin d := a1 * b2 - a2 * b1; dx := c1 * b2 - c2 * b1; dy := a1 * c2 - a2 * c1; if d <> 0 then begin if (dx mod d = 0) and (dy mod d = 0) then WriteLn(fo, dx div d, ' ', dy div d) else WriteLn(fo, sNoSol); end else if (dx <> 0) or (dy <> 0) then WriteLn(fo, sNoSol) else //d = dx = dy = 0, infinite solutions iff ONE solution exists. begin if (a1 = 0) and (b1 = 0) then sol1 := c1 = 0 else sol1 := c1 mod GCD(a1, b1) = 0; if (a2 = 0) and (b2 = 0) then sol2 := c2 = 0 else sol2 := c2 mod GCD(a2, b2) = 0; if sol1 and sol2 then WriteLn(fo, 'INFINITE') else WriteLn(fo, sNoSol); end; end; procedure SolveAll; var n, i: Integer; begin ReadLn(fi, n); for i := 1 to n do begin ReadLn(fi, a1, b1, c1, a2, b2, c2); Solve; end; end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try SolveAll; finally CloseFile(fi); CloseFile(fo); end; end.
{ *************************************************************************** Copyright (c) 2014-2017 Kike Pérez Unit : Quick.WebBrowser Description : Web browser functions Author : Kike Pérez Version : 1.0 Created : 10/02/2014 Modified : 03/11/2016 This file is part of QuickLib: https://github.com/exilon/QuickLib Uses code parts of: Thomas Stutz *************************************************************************** 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.WebBrowser; interface uses Classes, Forms, System.SysUtils, SHDocVw, MSHTML, ActiveX, Vcl.Graphics, System.Variants, Winapi.WinInet; procedure WB_SetBorderColor(Sender: TObject; BorderColor: String); procedure WB_SetBorderStyle(Sender: TObject; BorderStyle: String); procedure WB_Set3DBorderStyle(Sender: TObject; bValue: Boolean); procedure WB_SetDessignMode(Sender : TObject; bEnabled : Boolean); procedure WB_SetFontColor(Sender : TObject; aColor : TColor); procedure WB_SetFontBold(Sender : TObject; bEnabled : Boolean); procedure WB_SetFontItalic(Sender : TObject; bEnabled : Boolean); procedure WB_SetFontUnderline(Sender : TObject; bEnabled : Boolean); procedure WB_SetFontFace(Sender : TObject; cFontName : string); procedure WB_SetFontSize(Sender : TObject; nFontSize : Integer); procedure WB_InsertImage(Sender : TObject); procedure WBLoadHTML(const WebBrowser: TWebBrowser; HTMLCode: string) ; function GetHTML(const wbBrowser : TWebBrowser) : string; function GetHTML2(const wbBrowser : TWebBrowser) : string; function GetPlainText(const Html: string): string; function GetWebBrowserHTML(const WebBrowser: TWebBrowser): String; procedure DeleteIECacheAll; procedure DeleteIECache(filenameWildcard : string); implementation procedure WB_SetBorderColor(Sender: TObject; BorderColor: String); { BorderColor: Can be specified in HTML pages in two ways. 1) by using a color name (red, green, gold, firebrick, ...) 2) or by using numbers to denote an RGB color value. (#9400D3, #00CED1,...) See: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/properties/borderstyle.asp } var Document : IHTMLDocument2; Element : IHTMLElement; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; if Assigned(Document) then begin Element := Document.Body; if Element <> nil then begin Element.Style.BorderColor := BorderColor; end; end; end; procedure WB_SetBorderStyle(Sender: TObject; BorderStyle: String); { BorderStyle values: 'none' No border is drawn 'dotted' Border is a dotted line. (as of IE 5.5) 'dashed' Border is a dashed line. (as of IE 5.5) 'solid' Border is a solid line. 'double' Border is a double line 'groove' 3-D groove is drawn //Está se ve perfecto en Windows 7 y Windows 8 'ridge' 3-D ridge is drawn 'inset' 3-D inset is drawn 'window-inset' Border is the same as inset, but is surrounded by an additional single line 'outset' 3-D outset is drawn See: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/properties/borderstyle.asp } var Document : IHTMLDocument2; Element : IHTMLElement; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; if Assigned(Document) then begin Element := Document.Body; if Element <> nil then begin Element.Style.BorderStyle := BorderStyle; end; end; end; procedure WB_Set3DBorderStyle(Sender: TObject; bValue: Boolean); { bValue: True: Show a 3D border style False: Show no border } var Document : IHTMLDocument2; Element : IHTMLElement; StrBorderStyle: string; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; if Assigned(Document) then begin Element := Document.Body; if Element <> nil then begin case BValue of False: StrBorderStyle := 'none'; True: StrBorderStyle := ''; end; Element.Style.BorderStyle := StrBorderStyle; end; end; end; procedure WB_SetDessignMode(Sender : TObject; bEnabled : Boolean); begin ((Sender as TWebBrowser).Document as IHTMLDocument2).designMode := 'On'; end; procedure WB_SetFontColor(Sender : TObject; aColor : TColor); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('ForeColor',True,AColor); end; procedure WB_SetFontBold(Sender : TObject; bEnabled : Boolean); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('Bold',False,bEnabled); end; procedure WB_SetFontItalic(Sender : TObject; bEnabled : Boolean); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('Italic',False,bEnabled); end; procedure WB_SetFontUnderline(Sender : TObject; bEnabled : Boolean); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('Underline',False,bEnabled); end; procedure WB_SetFontFace(Sender : TObject; cFontName : string); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('FontName',False,cFontName); end; procedure WB_SetFontSize(Sender : TObject; nFontSize : Integer); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('FontSize',False,nFontSize); end; procedure WB_InsertImage(Sender : TObject); var Document : IHTMLDocument2; begin Document := TWebBrowser(Sender).Document as IHTMLDocument2; Document.execCommand('InsertImage',True,0); end; procedure WBLoadHTML(const WebBrowser: TWebBrowser; HTMLCode: string) ; var sl: TStringList; ms: TMemoryStream; begin WebBrowser.Navigate('about:blank') ; while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do Application.ProcessMessages; if Assigned(WebBrowser.Document) then begin sl := TStringList.Create; try ms := TMemoryStream.Create; try sl.Text := HTMLCode; sl.SaveToStream(ms) ; ms.Seek(0, 0) ; (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ; finally ms.Free; end; finally sl.Free; end; end; end; function GetHTML(const wbBrowser : TWebBrowser) : string; var iall : IHTMLElement; begin (wbBrowser.Document as IHTMLDocument2).designMode := 'Off'; Result := (wbBrowser.Document as IHTMLDocument2).body.toString; exit; if Assigned(wbBrowser.Document) then begin iall := (wbBrowser.Document as IHTMLDocument2).body; while iall.parentElement <> nil do begin iall := iall.parentElement; end; Result := iall.outerHTML; end; end; function GetHTML2(const wbBrowser : TWebBrowser) : string; var Doc: IHTMLDocument2; BodyElement: IHTMLElement; begin Assert(Assigned(wbBrowser.Document)); if wbBrowser.Document.QueryInterface(IHTMLDocument2, Doc) = S_OK then begin BodyElement := Doc.body; if Assigned(BodyElement) then begin result := '<html>' + BodyElement.outerHTML + '</html>'; end; end; end; function GetWebBrowserHTML(const WebBrowser: TWebBrowser): String; var LStream: TStringStream; Stream : IStream; LPersistStreamInit : IPersistStreamInit; begin if not Assigned(WebBrowser.Document) then exit; LStream := TStringStream.Create(''); try LPersistStreamInit := WebBrowser.Document as IPersistStreamInit; Stream := TStreamAdapter.Create(LStream,soReference); LPersistStreamInit.Save(Stream,true); result := LStream.DataString; finally LStream.Free(); end; end; function GetPlainText(const Html: string): string; var DummyWebBrowser: TWebBrowser; Document : IHtmlDocument2; DummyVar : Variant; begin Result := ''; DummyWebBrowser := TWebBrowser.Create(nil); try //open an blank page to create a IHtmlDocument2 instance DummyWebBrowser.Navigate('about:blank'); Document := DummyWebBrowser.Document as IHtmlDocument2; if (Assigned(Document)) then //Check the Document begin DummyVar := VarArrayCreate([0, 0], varVariant); //Create a variant array to write the html code to the IHtmlDocument2 DummyVar[0] := Html; //assign the html code to the variant array Document.Write(PSafeArray(TVarData(DummyVar).VArray)); //set the html in the document Document.Close; Result :=(Document.body as IHTMLBodyElement).createTextRange.text;//get the plain text end; finally DummyWebBrowser.Free; end; end; procedure DeleteIECacheAll; var lpEntryInfo: PInternetCacheEntryInfo; hCacheDir: LongWord; dwEntrySize: LongWord; begin dwEntrySize := 0; FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize); GetMem(lpEntryInfo, dwEntrySize); if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize; hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize); if hCacheDir <> 0 then begin repeat DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName); FreeMem(lpEntryInfo, dwEntrySize); dwEntrySize := 0; FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^), dwEntrySize); GetMem(lpEntryInfo, dwEntrySize); if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize; until not FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize); end; FreeMem(lpEntryInfo, dwEntrySize); FindCloseUrlCache(hCacheDir); end; //DeleteIECache('?M=P'); procedure DeleteIECache(filenameWildcard : string); var lpEntryInfo: PInternetCacheEntryInfo; hCacheDir: LongWord; dwEntrySize: LongWord; begin dwEntrySize := 0; FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize) ; GetMem(lpEntryInfo, dwEntrySize) ; if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize; hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize) ; if hCacheDir <> 0 then begin repeat if Pos(filenameWildcard, lpEntryInfo^.lpszSourceUrlName) > 0 then begin DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName) ; end; FreeMem(lpEntryInfo, dwEntrySize) ; dwEntrySize := 0; FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^), dwEntrySize) ; GetMem(lpEntryInfo, dwEntrySize) ; if dwEntrySize > 0 then lpEntryInfo^.dwStructSize := dwEntrySize; until not FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize) ; end; FreeMem(lpEntryInfo, dwEntrySize) ; FindCloseUrlCache(hCacheDir) ; end; end.
unit Rankings; interface uses MetaInstances, Classes, Collection, SyncObjs, CacheAgent, Languages; type TRanking = class( TMetaInstance ) public constructor Create( anId, aSuperRanking : string; aName : TMultiString; Max : integer ); destructor Destroy; override; private fName : TMultiString; fSuper : string; fObjects : TSortedCollection; fLock : TCriticalSection; fMax : integer; public property Name : TMultiString read fName; property SuperRanking : string read fSuper; property Objects : TSortedCollection read fObjects; public procedure Update( const Context ); procedure AddObject( Obj : TObject ); procedure DelObject( Obj : TObject ); procedure Lock; procedure Unlock; procedure StoreToCache( Cache : TObjectCache ); virtual; function RankingOf( Obj : TObject ) : integer; public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; virtual; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); virtual; function IsRankeable( const Obj : TObject ) : boolean; virtual; function AppliesTo( const Obj : TObject ) : boolean; virtual; procedure Serialize( Prefix : string; List : TStringList ); virtual; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); virtual; class function IsOverall : boolean; virtual; class function Serializable : boolean; virtual; private fContext : pointer; private function CompareItemsFunc( Obj1, Obj2 : TObject ) : integer; end; const tidClassFamily_Rankings = 'Rankings'; tidCachePath_Rankings = 'Rankings\'; procedure RegisterCachers; implementation uses ModelServerCache, ClassStorage, MathUtils, RankProtocol, SysUtils, Logs; // TRanking constructor TRanking.Create( anId, aSuperRanking : string; aName : TMultiString; Max : integer ); begin inherited Create( anId ); fName := aName; fMax := Max; fSuper := aSuperRanking; fObjects := TSortedCollection.Create( 0, rkUse, CompareItemsFunc ); fLock := TCriticalSection.Create; end; destructor TRanking.Destroy; begin try Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName ); except end; fObjects.Free; fLock.Free; fName.Free; inherited; end; procedure TRanking.Update( const Context ); begin Lock; try fContext := @Context; fObjects.Sort( CompareItemsFunc ); finally Unlock; end; end; procedure TRanking.AddObject( Obj : TObject ); begin Lock; try if fObjects.Indexof(Obj) = noIndex then fObjects.Insert(Obj); finally Unlock; end; end; procedure TRanking.DelObject( Obj : TObject ); begin Lock; try fObjects.Delete( Obj ); finally Unlock; end; end; procedure TRanking.Lock; begin fLock.Enter; end; procedure TRanking.Unlock; begin fLock.Leave; end; procedure TRanking.StoreToCache( Cache : TObjectCache ); var i : integer; count : integer; begin Lock; try //Cache.WriteString( 'Name', fName ); StoreMultiStringToCache( 'RankingName', fName, Cache ); Cache.WriteString( 'Id', Id ); Cache.WriteString( 'SuperRanking', fSuper ); count := 0; for i := 0 to pred(min(fMax, fObjects.Count)) do if IsRankeable( fObjects[i] ) then begin CacheItem( count, fObjects[i], Cache ); inc( count ); end; Cache.WriteInteger( 'Count', count ); finally Unlock; end; end; function TRanking.RankingOf( Obj : TObject ) : integer; begin Lock; try result := fObjects.IndexOf( Obj ); finally Unlock; end; end; function TRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; begin result := 0; end; procedure TRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); begin end; function TRanking.IsRankeable( const Obj : TObject ) : boolean; begin result := true; end; function TRanking.AppliesTo( const Obj : TObject ) : boolean; begin result := true; end; function TRanking.CompareItemsFunc( Obj1, Obj2 : TObject ) : integer; begin result := CompareObjects( Obj1, Obj2, fContext ); end; procedure TRanking.Serialize( Prefix : string; List : TStringList ); var i : integer; count : integer; begin try List.Values[Prefix + tidRankings_RankName] := Name.Values[langDefault]; List.Values[Prefix + tidRankings_RankId] := Id; List.Values[Prefix + tidRankings_RankSuper] := fSuper; count := 0; Lock; try for i := 0 to pred(fObjects.Count) do try if IsRankeable( fObjects[i] ) then begin SerializeItem( Prefix + tidRankings_Member + IntToStr(count), i, fObjects[i], List ); inc( count ); end; except end; finally Unlock; end; List.Values[Prefix + tidRankings_RankMemberCount] := IntToStr(count); except end; end; procedure TRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); begin end; class function TRanking.IsOverall : boolean; begin result := false; end; class function TRanking.Serializable : boolean; begin result := true; end; // TRankingCache type TRankingCacheAgent = class( TCacheAgent ) public class function GetPath ( Obj : TObject; kind, info : integer ) : string; override; class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override; end; class function TRankingCacheAgent.GetPath( Obj : TObject; kind, info : integer ) : string; function GetFullPath( Ranking : TRanking ) : string; begin if Ranking.SuperRanking <> '' then result := GetFullPath( TRanking(TheClassStorage.ClassById[tidClassFamily_Rankings, Ranking.SuperRanking]) ) else result := ''; result := result + Ranking.Id + '.five\'; end; begin result := tidCachePath_Rankings + GetFullPath( TRanking(Obj) ); end; class function TRankingCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; begin result := inherited GetCache( Obj, kind, info, update ); result.WriteString( 'Path', GetPath( Obj, kind, info ) ); TRanking(Obj).StoreToCache( result ); end; // RegisterCachers procedure RegisterCachers; begin RegisterCacher( TRanking.ClassName, TRankingCacheAgent ); end; end.
unit UTreeItem; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ComCtrls, Dialogs, Buttons, ExtCtrls, StdCtrls, IniFiles; type TTreeItem = class Node:TTreeNode; Section:String; procedure ChangeData(Btn:TButton; Pnl:TPanel); function Enter:TFrame;virtual;abstract; function Leave:Boolean;virtual;abstract; function Validate:Boolean;virtual; procedure SaveCfg(Cfg:TIniFile);virtual;abstract; procedure TimerProc;virtual;abstract; procedure WriteToLog(const S:String); end; implementation { TTreeItem } procedure TTreeItem.ChangeData(Btn: TButton; Pnl: TPanel); begin if Btn.Tag=0 then begin Btn.Tag:=1; Pnl.Enabled:=True; Btn.Caption:='Применить'; Pnl.SetFocus; end else if Validate then begin Btn.Tag:=0; Pnl.Enabled:=False; Btn.Caption:='Внесение изменений'; end; end; function TTreeItem.Validate: Boolean; begin Result:=True; end; procedure TTreeItem.WriteToLog(const S: String); var Log:TextFile; LogFileName:String; begin try LogFileName:=Section+'.log'; AssignFile(Log,LogFileName); if not FileExists(LogFileName) then Rewrite(Log) else Append(Log); try Write(Log,S); Flush(Log); finally CloseFile(Log); end; except end; end; end.
namespace Sugar.Collections; interface uses Sugar; type Stack<T> = public class mapped to {$IF COOPER}java.util.Stack<T>{$ELSEIF ECHOES}System.Collections.Generic.Stack<T>{$ELSEIF TOFFEE}Foundation.NSMutableArray{$ENDIF} public constructor; mapped to constructor(); method Contains(Item: T): Boolean; method Clear; method Peek: T; method Pop: T; method Push(Item: T); method ToArray: array of T; property Count: Integer read {$IF COOPER}mapped.size{$ELSEIF ECHOES OR TOFFEE}mapped.Count{$ENDIF}; end; {$IFDEF TOFFEE} StackHelpers = public static class private public method Peek<T>(aStack: Foundation.NSMutableArray): T; method Pop<T>(aStack: Foundation.NSMutableArray): T; end; {$ENDIF} implementation method Stack<T>.Contains(Item: T): Boolean; begin {$IF COOPER OR ECHOES} exit mapped.Contains(Item); {$ELSE} exit mapped.containsObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method Stack<T>.Clear; begin {$IF COOPER OR ECHOES} mapped.Clear; {$ELSE} mapped.removeAllObjects; {$ENDIF} end; method Stack<T>.Peek: T; begin {$IF COOPER OR ECHOES} exit mapped.Peek; {$ELSE} exit StackHelpers.Peek<T>(mapped); {$ENDIF} end; method Stack<T>.Pop: T; begin {$IF COOPER OR ECHOES} exit mapped.Pop; {$ELSE} exit StackHelpers.Pop<T>(mapped); {$ENDIF} end; method Stack<T>.Push(Item: T); begin {$IF COOPER OR ECHOES} mapped.Push(Item); {$ELSE} mapped.addObject(NullHelper.ValueOf(Item)); {$ENDIF} end; method Stack<T>.ToArray: array of T; begin {$IF COOPER} exit ListHelpers.ToArrayReverse<T>(self, new T[Count]); {$ELSEIF ECHOES} exit mapped.ToArray; {$ELSEIF TOFFEE} exit ListHelpers.ToArrayReverse<T>(self); {$ENDIF} end; {$IFDEF TOFFEE} method StackHelpers.Peek<T>(aStack: Foundation.NSMutableArray): T; begin var n := aStack.lastObject; if n = nil then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); exit NullHelper.ValueOf(n); end; method StackHelpers.Pop<T>(aStack: Foundation.NSMutableArray): T; begin var n := aStack.lastObject; if n = nil then raise new SugarInvalidOperationException(ErrorMessage.COLLECTION_EMPTY); n := NullHelper.ValueOf(n); aStack.removeLastObject; exit n; end; {$ENDIF} end.
(* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit rcx_cmd; interface uses Classes, rcx_constants; const kRCX_Cmd_MaxShortLength = 8; type // rcx fragment type TRcxFragment = (kRCX_TaskFragment, kRCX_SubFragment); // variable code TRcxVarCode = (kRCX_SetVar, kRCX_AddVar, kRCX_SubVar, kRCX_DivVar, kRCX_MulVar, kRCX_SgnVar, kRCX_AbsVar, kRCX_AndVar, kRCX_OrVar); TBaseCmd = class protected fLength : integer; fBodyPtr : PByte; fBodyData : array [0..kRCX_Cmd_MaxShortLength] of Byte; function MakeValue16(opcode : Byte; value : integer) : TBaseCmd; function MakeValue8(opcode : Byte; value : integer) : TBaseCmd; procedure ClearBodyPointer; protected fLog : string; procedure WriteToLog(s : string); public constructor Create; destructor Destroy; override; function GetLength : integer; function GetBody : PByte; function CopyOut(dst : PByte) : integer; procedure SetLength(length : integer); function SetVal(data : PByte; length : integer) : TBaseCmd; overload; function SetVal(d0 : Byte) : TBaseCmd; overload; function SetVal(d0, d1 : Byte) : TBaseCmd; overload; function SetVal(d0, d1, d2 : Byte) : TBaseCmd; overload; function SetVal(d0, d1, d2, d3 : Byte) : TBaseCmd; overload; function SetVal(d0, d1, d2, d3, d4 : Byte) : TBaseCmd; overload; function SetVal(d0, d1, d2, d3, d4, d5 : Byte) : TBaseCmd; overload; function SetVal(d0, d1, d2, d3, d4, d5, d6: Byte): TBaseCmd; overload; procedure Print; property Log : string read fLog; end; TNxtCmd = class(TBaseCmd) public function MakeCmdWriteFile(const b1, b2 : byte; const handle : byte; const Count : Word; Data : array of Byte) : TNxtCmd; function MakeCmdWithFilename(const b1, b2 : byte; const filename : string; const filesize : Cardinal = 0) : TNxtCmd; function MakeCmdRenameFile(const b1 : byte; const old, new : string) : TNxtCmd; function MakeBoot(bResponse : boolean) : TNxtCmd; function MakeSetName(const name : string; bResponse : boolean) : TNxtCmd; function MakeCmdWriteIOMap(const b1, b2 : byte; const ModID : Cardinal; const Offset, Count : Word; Data : array of Byte) : TNxtCmd; function MakeCmdReadIOMap(const b1, b2 : byte; const ModID : Cardinal; const Offset, Count : Word) : TNxtCmd; function MakeSetOutputState(port, mode, regmode, runstate : byte; power, turnratio : shortint; tacholimit : cardinal; bResponse : boolean) : TNxtCmd; end; TNINxtCmd = class(TNxtCmd) public function BytePtr : PByte; function Len : integer; end; TRcxCmd = class(TBaseCmd) private protected procedure SetOffset(offset : integer); function DirSpeed(val : integer) : Byte; public // utility functions to create specific commands // variables function MakeVar(code : TRcxVarCode; myvar : Byte; value : integer) : TRcxCmd; // outputs function MakeOutputMode(outputs : Byte; mode : integer) : TRcxCmd; function MakeOutputPower(outputs : Byte; value : integer) : TRcxCmd; function MakeOutputDir(outputs : Byte; dir : integer) : TRcxCmd; // inputs function MakeInputMode(input : Byte; mode : integer) : TRcxCmd; function MakeInputType(input : Byte; itype : integer) : TRcxCmd; // sound function MakePlaySound(sound : Byte) : TRcxCmd; function MakePlayTone(freq : Word; duration : Byte) : TRcxCmd; // control flow function MakeTest(v1 : integer; rel : integer; v2 : integer; offset : smallint) : TRcxCmd; function MakeJump(offset : smallint) : TRcxCmd; function MakeSetLoop(v : integer) : TRcxCmd; function MakeCheckLoop(offset : smallint) : TRcxCmd; // cybermaster stuff function MakeDrive(m0, m1 : integer) : TRcxCmd; function MakeOnWait(outputs : Byte; aNum : integer; aTime : Byte) : TRcxCmd; function MakeOnWaitDifferent(outputs : Byte; aNum0, aNum1, aNum2 : integer; aTime : Byte) : TRcxCmd; // misc function MakeStopTask(task : Byte) : TRcxCmd; function MakeWait(value : integer) : TRcxCmd; function MakeDisplay(value : integer) : TRcxCmd; overload; function MakeDisplay(src, value : integer) : TRcxCmd; overload; function MakeSet(dst, src : integer) : TRcxCmd; // system commands function MakePoll(value : integer) : TRcxCmd; function MakeUnlock : TRcxCmd; function MakeBegin(ftype : TRcxFragment; taskNumber : Byte; length : Word) : TRcxCmd; function MakeDownload(seq : Word; data : PByte; length : Word) : TRcxCmd; function MakeDeleteTasks : TRcxCmd; function MakeDeleteSubs : TRcxCmd; function MakePing : TRcxCmd; function MakeUploadDatalog(start, count : Word) : TRcxCmd; function MakeSetDatalog(size : Word) : TRcxCmd; function MakeBoot : TRcxCmd; // special command to unlock CyberMaster function MakeUnlockCM : TRcxCmd; end; function RCX_VALUE(t : TRcxValueType; d : smallint) : integer; implementation uses SysUtils, uCommonUtils; function RCX_VALUE(t : TRcxValueType; d : smallint) : integer; begin result := integer((t shl 16) or (d and $FFFF)); end; function RCX_VALUE_TYPE(v : integer) : TRcxValueType; begin result := Byte(smallint(v shr 16) and $FF); end; function RCX_VALUE_DATA(v : integer) : smallint; begin result := smallint(v and $FFFF); end; function kRCX_VarOp(code : TRcxVarCode) : integer; begin result := $14 + (Ord(code) * 16); end; { TBaseCmd } procedure TBaseCmd.ClearBodyPointer; begin if fLength > kRCX_Cmd_MaxShortLength then FreeMem(fBodyPtr, fLength); end; function TBaseCmd.CopyOut(dst: PByte): integer; var tmp : PByte; begin tmp := GetBody; Move(tmp^, dst^, fLength); result := fLength; end; constructor TBaseCmd.Create; begin inherited Create; fLog := ''; fLength := 0; end; destructor TBaseCmd.Destroy; begin ClearBodyPointer; inherited Destroy; end; function TBaseCmd.MakeValue16(opcode: Byte; value: integer): TBaseCmd; var data : SmallInt; begin data := RCX_VALUE_DATA(value); result := SetVal(opcode, Byte(RCX_VALUE_TYPE(value)), Lo(data), Hi(data)); end; function TBaseCmd.MakeValue8(opcode: Byte; value: integer): TBaseCmd; begin result := SetVal(opcode, Byte(RCX_VALUE_TYPE(value)), Byte(RCX_VALUE_DATA(value))); end; procedure TBaseCmd.Print; var ptr : PByte; i : integer; tmp : string; begin ptr := GetBody; tmp := ''; for i := 0 to fLength-1 do begin tmp := tmp + Format('%2x', [ptr^]); inc(ptr); end; WriteToLog(tmp + #13#10); end; procedure TBaseCmd.SetLength(length: integer); begin if length = fLength then Exit; ClearBodyPointer; fLength := length; if fLength > kRCX_Cmd_MaxShortLength then fBodyPtr := AllocMem(fLength * sizeof(Byte)); end; function TBaseCmd.SetVal(data: PByte; length: integer): TBaseCmd; var tmp : PByte; begin SetLength(length); tmp := GetBody; Move(data^, tmp^, length); result := self; end; function TBaseCmd.SetVal(d0: Byte): TBaseCmd; begin SetLength(1); fBodyData[0] := d0; result := self; end; function TBaseCmd.SetVal(d0, d1: Byte): TBaseCmd; begin SetLength(2); fBodyData[0] := d0; fBodyData[1] := d1; result := self; end; function TBaseCmd.SetVal(d0, d1, d2: Byte): TBaseCmd; begin SetLength(3); fBodyData[0] := d0; fBodyData[1] := d1; fBodyData[2] := d2; result := self; end; function TBaseCmd.SetVal(d0, d1, d2, d3: Byte): TBaseCmd; begin SetLength(4); fBodyData[0] := d0; fBodyData[1] := d1; fBodyData[2] := d2; fBodyData[3] := d3; result := self; end; function TBaseCmd.SetVal(d0, d1, d2, d3, d4: Byte): TBaseCmd; begin SetLength(5); fBodyData[0] := d0; fBodyData[1] := d1; fBodyData[2] := d2; fBodyData[3] := d3; fBodyData[4] := d4; result := self; end; function TBaseCmd.SetVal(d0, d1, d2, d3, d4, d5: Byte): TBaseCmd; begin SetLength(6); fBodyData[0] := d0; fBodyData[1] := d1; fBodyData[2] := d2; fBodyData[3] := d3; fBodyData[4] := d4; fBodyData[5] := d5; result := self; end; function TBaseCmd.SetVal(d0, d1, d2, d3, d4, d5, d6: Byte): TBaseCmd; begin SetLength(7); fBodyData[0] := d0; fBodyData[1] := d1; fBodyData[2] := d2; fBodyData[3] := d3; fBodyData[4] := d4; fBodyData[5] := d5; fBodyData[6] := d6; result := self; end; procedure TBaseCmd.WriteToLog(s: string); begin fLog := fLog + s; end; function TBaseCmd.GetBody: PByte; begin if fLength <= kRCX_Cmd_MaxShortLength then result := @fBodyData[0] else result := fBodyPtr; end; function TBaseCmd.GetLength: integer; begin result := fLength; end; { TRcxCmd } function TRcxCmd.DirSpeed(val: integer): Byte; begin result := Byte((val) and 8 xor 8 or ((val)*(((val) shr 3) * 2 xor 1)) and 7); end; function TRcxCmd.MakeBegin(ftype: TRcxFragment; taskNumber: Byte; length: Word): TRcxCmd; var op : Byte; begin if ftype = kRCX_TaskFragment then op := kRCX_BeginTaskOp else op := kRCX_BeginSubOp; result := TRcxCmd(SetVal(op, 0, taskNumber, 0, Lo(length), Hi(length))); end; function TRcxCmd.MakeBoot: TRcxCmd; begin SetVal(kRCX_UnlockFirmOp, $4c, $45, $47, $4f, $ae); // LEGO result := self; end; function TRcxCmd.MakeCheckLoop(offset: smallint): TRcxCmd; begin SetVal(kRCX_CheckLoopOp, 0, 0); SetOffset(offset); result := self; end; function TRcxCmd.MakeWait(value: integer): TRcxCmd; begin result := TRcxCmd(MakeValue16(kRCX_WaitOp, value)); end; function TRcxCmd.MakeDeleteSubs: TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_DeleteSubsOp)); end; function TRcxCmd.MakeDeleteTasks: TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_DeleteTasksOp)); end; function TRcxCmd.MakeDisplay(value: integer): TRcxCmd; begin result := TRcxCmd(MakeValue16(kRCX_DisplayOp, value)); end; function TRcxCmd.MakeDisplay(src, value: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_DisplayOp, Byte(src), Lo(SmallInt(value)), Hi(SmallInt(value)))); end; function TRcxCmd.MakeDownload(seq: Word; data: PByte; length: Word): TRcxCmd; var ptr : PByte; checksum, b : Byte; begin SetLength(6 + length); ptr := GetBody; ptr^ := kRCX_DownloadOp; inc(ptr); ptr^ := Lo(seq); inc(ptr); ptr^ := Hi(seq); inc(ptr); ptr^ := Lo(length); inc(ptr); ptr^ := Hi(length); inc(ptr); checksum := 0; while length > 0 do begin b := data^; inc(data); checksum := Byte(checksum + b); ptr^ := b; inc(ptr); dec(length); end; ptr^ := checksum; result := self; end; function TRcxCmd.MakeDrive(m0, m1: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_DriveOp, DirSpeed(m0) or DirSpeed(m1) shl 4)); end; function TRcxCmd.MakeInputMode(input: Byte; mode: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_InputModeOp, input, Byte(mode))); end; function TRcxCmd.MakeInputType(input: Byte; itype: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_InputTypeOp, input, Byte(itype))); end; function TRcxCmd.MakeJump(offset: smallint): TRcxCmd; var ptr : PByte; begin SetLength(3); ptr := GetBody; ptr^ := kRCX_JumpOp; SetOffset(offset); result := self; end; function TRcxCmd.MakeOnWait(outputs: Byte; aNum: integer; aTime: Byte): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_OnWaitOp, Byte((outputs shl 4) or DirSpeed(aNum)), aTime)); end; function TRcxCmd.MakeOnWaitDifferent(outputs: Byte; aNum0, aNum1, aNum2: integer; aTime: Byte): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_OnWaitDifferentOp, Byte((outputs shl 4) or DirSpeed(aNum0)), Byte((DirSpeed(aNum1) shl 4) or DirSpeed(aNum2)), aTime)); end; function TRcxCmd.MakeOutputDir(outputs: Byte; dir: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_OutputDirOp, Byte(dir or outputs))); end; function TRcxCmd.MakeOutputMode(outputs: Byte; mode: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_OutputModeOp, Byte(mode or outputs))); end; function TRcxCmd.MakeOutputPower(outputs: Byte; value: integer): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_OutputPowerOp, outputs, Byte(RCX_VALUE_TYPE(value)), Byte(RCX_VALUE_DATA(value)))); end; function TRcxCmd.MakePing: TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_PingOp)); end; function TRcxCmd.MakePlaySound(sound: Byte): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_PlaySoundOp, sound)); end; function TRcxCmd.MakePlayTone(freq: Word; duration: Byte): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_PlayToneOp, Lo(freq), Hi(freq), duration)); end; function TRcxCmd.MakePoll(value: integer): TRcxCmd; begin result := TRcxCmd(MakeValue8(kRCX_PollOp, value)); end; function TRcxCmd.MakeSet(dst, src: integer): TRcxCmd; var ptr : PByte; begin SetLength(6); ptr := GetBody; ptr^ := kRCX_SetSourceValueOp; inc(ptr); ptr^ := Byte(RCX_VALUE_TYPE(dst)); inc(ptr); ptr^ := Lo(RCX_VALUE_DATA(dst)); inc(ptr); ptr^ := Byte(RCX_VALUE_TYPE(src)); inc(ptr); ptr^ := Lo(RCX_VALUE_DATA(src)); inc(ptr); ptr^ := Hi(RCX_VALUE_DATA(src)); result := self; end; function TRcxCmd.MakeSetDatalog(size: Word): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_SetDatalogOp, Lo(size), Hi(size))); end; function TRcxCmd.MakeSetLoop(v: integer): TRcxCmd; begin result := TRcxCmd(MakeValue8(kRCX_SetLoopOp, v)); end; function TRcxCmd.MakeStopTask(task: Byte): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_StopTaskOp, task)); end; function TRcxCmd.MakeTest(v1, rel, v2: integer; offset: smallint): TRcxCmd; var d1 : SmallInt; ptr : PByte; begin d1 := RCX_VALUE_DATA(v1); SetLength(8); ptr := GetBody; ptr^ := kRCX_LCheckDoOp; inc(ptr); ptr^ := Byte(((rel shl 6) or Byte(RCX_VALUE_TYPE(v1)))); inc(ptr); ptr^ := Byte(RCX_VALUE_TYPE(v2)); inc(ptr); ptr^ := Lo(d1); inc(ptr); ptr^ := Hi(d1); inc(ptr); ptr^ := Byte(RCX_VALUE_DATA(v2)); SetOffset(offset); result := self; end; function TRcxCmd.MakeUnlock: TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_UnlockOp, 1, 3, 5, 7, 11)); end; type MsgType = array[0..26] of Byte; function TRcxCmd.MakeUnlockCM: TRcxCmd; const unlockMsg : MsgType = (kRCX_UnlockFirmOp, Ord('D'),Ord('o'),Ord(' '),Ord('y'),Ord('o'),Ord('u'), Ord(' '),Ord('b'),Ord('y'),Ord('t'),Ord('e'),Ord(','), Ord(' '),Ord('w'),Ord('h'),Ord('e'),Ord('n'),Ord(' '), Ord('I'),Ord(' '),Ord('k'),Ord('n'),Ord('o'),Ord('c'), Ord('k'),Ord('?')); var msg : MsgType; begin msg := unlockMsg; SetVal(@msg[0], sizeof(unlockMsg)); result := self; end; function TRcxCmd.MakeUploadDatalog(start, count: Word): TRcxCmd; begin result := TRcxCmd(SetVal(kRCX_UploadDatalogOp, Lo(start), Hi(start), Lo(count), Hi(count))); end; function TRcxCmd.MakeVar(code: TRcxVarCode; myvar: Byte; value: integer): TRcxCmd; var data : SmallInt; begin data := RCX_VALUE_DATA(value); result := TRcxCmd(SetVal(Byte(kRCX_VarOp(code)), myvar, Byte(RCX_VALUE_TYPE(value)), Lo(data), Hi(data))); end; procedure TRcxCmd.SetOffset(offset: integer); var ptr, tmp : PByte; neg : Byte; begin neg := 0; offset := offset - (fLength - 2); ptr := GetBody; inc(ptr, fLength); dec(ptr, 2); tmp := GetBody; if tmp^ <> kRCX_JumpOp then begin ptr^ := Byte(offset and $FF); inc(ptr); ptr^ := Byte((offset shr 8) and $FF); end else begin if offset < 0 then begin neg := $80; offset := -offset; end; ptr^ := Byte(neg or (offset and $7F)); inc(ptr); ptr^ := Byte((offset shr 7) and $FF); end; end; { TNxtCmd } function TNxtCmd.MakeCmdWriteFile(const b1, b2: byte; const handle : byte; const Count : Word; Data: array of Byte): TNxtCmd; var i, n : integer; orig : PByte; begin n := Count+3; // if n > kNXT_MaxBytes then n := kNXT_MaxBytes; // total bytes must be <= 64 SetLength(n); orig := GetBody; orig^ := b1; inc(orig); orig^ := b2; inc(orig); orig^ := handle; inc(orig); dec(n, 3); // set n back to count (or max - 3, whichever is smaller) for i := Low(Data) to High(Data) do begin dec(n); if n < 0 then Break; orig^ := Data[i]; inc(orig); end; Result := Self; end; function TNxtCmd.MakeCmdWithFilename(const b1, b2: byte; const filename: string; const filesize : cardinal): TNxtCmd; var i : integer; orig : PByte; begin // filename is limited to 19 bytes + null terminator if filesize > 0 then SetLength(26) else SetLength(22); orig := GetBody; orig^ := b1; inc(orig); orig^ := b2; inc(orig); i := 1; while i <= 19 do begin // copy the first nineteen bytes from the filename provided if i > Length(filename) then orig^ := 0 else orig^ := Ord(filename[i]); inc(orig); inc(i); end; orig^ := 0; // set last byte to null inc(orig); if filesize > 0 then begin orig^ := Byte(Word(filesize)); inc(orig); orig^ := HiByte(Word(filesize)); inc(orig); orig^ := Byte(HiWord(filesize)); inc(orig); orig^ := HiByte(HiWord(filesize)); end; Result := Self; end; function TNxtCmd.MakeBoot(bResponse : boolean) : TNxtCmd; var i : integer; orig : PByte; const bootCmd = 'Let''s dance: SAMBA'; begin SetLength(21); orig := GetBody; if bResponse then orig^ := kNXT_SystemCmd else orig^ := kNXT_SystemCmdNoReply; inc(orig); orig^ := kNXT_SCBootCommand; inc(orig); for i := 1 to Length(bootCmd) do begin orig^ := Byte(bootCmd[i]); inc(orig); end; orig^ := 0; // set last byte to null Result := Self; end; function TNxtCmd.MakeSetName(const name: string; bResponse: boolean): TNxtCmd; var i : integer; orig : PByte; begin SetLength(18); orig := GetBody; if bResponse then orig^ := kNXT_SystemCmd else orig^ := kNXT_SystemCmdNoReply; inc(orig); orig^ := kNXT_SCSetBrickName; inc(orig); for i := 1 to kNXT_NameMaxLen do begin if i > Length(name) then orig^ := 0 // pad with nulls to fixed length else orig^ := Byte(name[i]); inc(orig); end; orig^ := 0; // set last byte to null Result := Self; end; function TNxtCmd.MakeCmdWriteIOMap(const b1, b2: byte; const ModID: Cardinal; const Offset, Count: Word; Data: array of Byte): TNxtCmd; var i, n : integer; orig : PByte; begin n := Count+10; // (10 bytes in addition to the actual data if n > kNXT_MaxBytes then n := kNXT_MaxBytes; // total bytes must be <= 64 SetLength(n); orig := GetBody; orig^ := b1; inc(orig); orig^ := b2; inc(orig); orig^ := Lo(Word(ModID)); inc(orig); orig^ := Hi(Word(ModID)); inc(orig); orig^ := Lo(HiWord(ModID)); inc(orig); orig^ := Hi(HiWord(ModID)); inc(orig); orig^ := Lo(Offset); inc(orig); orig^ := Hi(Offset); inc(orig); orig^ := Lo(count); inc(orig); orig^ := Hi(count); inc(orig); dec(n, 10); // set n back to count (or max - 10, whichever is smaller) for i := Low(Data) to High(Data) do begin dec(n); if n < 0 then Break; orig^ := Data[i]; inc(orig); end; Result := Self; end; function TNxtCmd.MakeCmdReadIOMap(const b1, b2: byte; const ModID: Cardinal; const Offset, Count: Word): TNxtCmd; var orig : PByte; begin SetLength(10); orig := GetBody; orig^ := b1; inc(orig); orig^ := b2; inc(orig); orig^ := Lo(Word(ModID)); inc(orig); orig^ := Hi(Word(ModID)); inc(orig); orig^ := Lo(HiWord(ModID)); inc(orig); orig^ := Hi(HiWord(ModID)); inc(orig); orig^ := Lo(Offset); inc(orig); orig^ := Hi(Offset); inc(orig); orig^ := Lo(Count); inc(orig); orig^ := Hi(Count); Result := Self; end; function TNxtCmd.MakeSetOutputState(port, mode, regmode, runstate: byte; power, turnratio: shortint; tacholimit: cardinal; bResponse: boolean): TNxtCmd; var orig : PByte; begin SetLength(12); orig := GetBody; if bResponse then orig^ := kNXT_DirectCmd else orig^ := kNXT_DirectCmdNoReply; inc(orig); orig^ := kNXT_DCSetOutputState; inc(orig); orig^ := port; inc(orig); orig^ := power; inc(orig); orig^ := mode; inc(orig); orig^ := regmode; inc(orig); orig^ := turnratio; inc(orig); orig^ := runstate; inc(orig); orig^ := Lo(Word(tacholimit)); inc(orig); orig^ := Hi(Word(tacholimit)); inc(orig); orig^ := Lo(HiWord(tacholimit)); inc(orig); orig^ := Hi(HiWord(tacholimit)); Result := Self; end; function TNxtCmd.MakeCmdRenameFile(const b1: byte; const old, new: string): TNxtCmd; var i, j : integer; orig : PByte; tmp : string; begin //kNXT_SCRenameFile SetLength(42); orig := GetBody; orig^ := b1; inc(orig); orig^ := kNXT_SCRenameFile; inc(orig); for j := 0 to 1 do begin if j = 0 then tmp := old else tmp := new; i := 1; while i <= 19 do begin // copy the first nineteen bytes from the filename provided if i > Length(tmp) then orig^ := 0 else orig^ := Ord(tmp[i]); inc(orig); inc(i); end; orig^ := 0; // set last byte to null inc(orig); end; Result := Self; end; { TNINxtCmd } function TNINxtCmd.BytePtr: PByte; begin Result := GetBody; inc(Result); end; function TNINxtCmd.Len: integer; begin Result := GetLength; dec(Result); end; end.
unit BackTaskForm; interface uses SysUtils, Types, Classes, Variants, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls; type TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} {function local to the unit} function IsPrime (N: Integer): Boolean; var Test: Integer; begin IsPrime := True; for Test := 2 to N - 1 do if (N mod Test) = 0 then begin IsPrime := False; break; {jump out of the for loop} end; end; const Max = 100000; procedure TForm1.Button1Click(Sender: TObject); var I, Tot: Integer; begin Tot := 0; for I := 1 to Max do begin if IsPrime (I) then Tot := Tot + I; ProgressBar1.Position := I * 100 div Max; end; ShowMessage (IntToStr (Tot)); end; procedure TForm1.Button2Click(Sender: TObject); var I, Tot: Integer; begin Tot := 0; for I := 1 to Max do begin if IsPrime (I) then Tot := Tot + I; ProgressBar1.Position := I * 100 div Max; Application.ProcessMessages; end; ShowMessage (IntToStr (Tot)); end; // custom thread class type TPrimeAdder = class(TThread) private FMax, FTotal, FPosition: Integer; protected procedure Execute; override; procedure ShowTotal; procedure UpdateProgress; public property Max: Integer read FMax write FMax; end; procedure TPrimeAdder.Execute; var I, Tot: Integer; begin Tot := 0; for I := 1 to FMax do begin if IsPrime (I) then Tot := Tot + I; if I mod (fMax div 100) = 0 then begin FPosition := I * 100 div fMax; Synchronize(UpdateProgress); end; end; FTotal := Tot; Synchronize(ShowTotal); end; procedure TPrimeAdder.ShowTotal; begin ShowMessage ('Thread: ' + IntToStr (FTotal)); end; procedure TForm1.Button3Click(Sender: TObject); var AdderThread: TPrimeAdder; begin AdderThread := TPrimeAdder.Create (True); AdderThread.Max := Max; AdderThread.FreeOnTerminate := True; AdderThread.Resume; end; procedure TPrimeAdder.UpdateProgress; begin Form1.ProgressBar1.Position := fPosition; end; end.
unit ConfigFE; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl, ExtCtrls, Mask, JvExMask, JvToolEdit, Inifiles, JvSpin; type TFConfigFe = class(TForm) rgRegien: TRadioGroup; lblCert: TLabel; lblClave: TLabel; bOK: TButton; bAnular: TButton; jvCertif: TJvFilenameEdit; jvPrivada: TJvFilenameEdit; cbDepura: TCheckBox; Label1: TLabel; jvPunto: TJvSpinEdit; Label2: TLabel; edServicioAFIP: TEdit; cbPrueba: TCheckBox; procedure FormCreate(Sender: TObject); procedure bOKClick(Sender: TObject); private { Private declarations } FIni: TIniFile; FEmiteFE: Boolean; FF2904: Boolean; FF2485: Boolean; FFExpo: Boolean; FFLog: Boolean; procedure SetEmiteFE(const Value: Boolean); procedure SetF2485(const Value: Boolean); procedure SetF2904(const Value: Boolean); procedure SetFExpo(const Value: Boolean); procedure SetFLog(const Value: Boolean); public { Public declarations } property EmiteFE: Boolean read FEmiteFE write SetEmiteFE; property F2485: Boolean read FF2485 write SetF2485; property F2904: Boolean read FF2904 write SetF2904; property FExpo: Boolean read FFExpo write SetFExpo; property FLog: Boolean read FFLog write SetFLog; end; function getFacturaE: Boolean; function getClave: string; function getCertif: string; function get2485: Boolean; function get2904: Boolean; function getExpo: Boolean; function getEstadoLog: Boolean; function getPuntoVenta: integer; function getServicio: string; function getHomologacion: boolean; var FConfigFe: TFConfigFe; implementation uses DMCons; {$R *.dfm} function get2485: Boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.F2485; finally FConfigFe.Free; end; end; function get2904: Boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.F2904; finally FConfigFe.Free; end; end; function getExpo: Boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.FExpo; finally FConfigFe.Free; end; end; function getEstadoLog: Boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.cbDepura.Checked; finally FConfigFe.Free; end; end; function getFacturaE: Boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.FEmiteFE; finally FConfigFe.Free; end; end; function getClave: string; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.jvPrivada.FileName; finally FConfigFe.Free; end; end; function getCertif: string; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.jvCertif.FileName; finally FConfigFe.Free; end; end; function getPuntoVenta: integer; begin // el punto de venta se tomara directamente desde el comprobante // esto podra sobrescribirse cuando al facturar se seleccione otro comprobante // distinto. // se emitira factura electronica por diferentes puntos de venta // es responsabilidad del operador desactivar la fe si usara punto de venta manual (Afip no permitira seguir igualmente) // Cada vez que se llama e "emitircompte" se tomara el nuevo punto de venta // Se deja por compatibilidad FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.jvPunto.AsInteger; finally FConfigFe.Free; end; end; function getServicio: string; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.edServicioAFIP.Text; finally FConfigFe.Free; end; end; function getHomologacion: boolean; begin FConfigFE := TFConfigFe.Create(application); try Result := FConfigFe.cbPrueba.checked; finally FConfigFe.Free; end; end; procedure TFConfigFe.bOKClick(Sender: TObject); begin FF2485 := (rgRegien.ItemIndex=0); FF2904 := (rgRegien.ItemIndex=1); FFExpo := (rgRegien.ItemIndex=2); FEmiteFE := not (rgRegien.ItemIndex=3); FIni.WriteBool('FE', '2485', FF2485 ); FIni.WriteBool('FE', '2904', FF2904 ); FIni.WriteBool('FE', 'EXPO', FExpo ); FIni.WriteBool('FE', 'NOUSA', not FEmiteFE ); FIni.WriteString('FE', 'CERTIFICADO', jvCertif.FileName ); FIni.WriteString('FE', 'CLAVE', jvPrivada.FileName ); FIni.WriteBool('FE', 'DEPURACION', cbDepura.Checked ); FIni.WriteInteger('FE', 'PUNTODEVENTA', jvPunto.AsInteger ); FIni.WriteString('FE', 'SERVICIO', edServicioAFIP.Text ); FIni.WriteBool('FE', 'HOMOLOGACION', cbPrueba.Checked ); {with dataing do try configura.open; configura.edit; configura.fieldByName('fe_rg2485').value := FF2485; configura.fieldByName('fe2904').value := FF2904; configura.fieldByName('feexpo').value := FFExpo; configura.fieldByName('fenousa').value := not FEmiteFE; configura.fieldByName('fecertificado').value := jvCertif.FileName; configura.fieldByName('feclave').value := jvPrivada.FileName; configura.fieldByName('fedepura').value := cbDepura.Checked; configura.fieldByName('fepuntoventa').value := jvPunto.AsInteger; configura.fieldByName('feservicio').value := edServicioAFIP.Text; configura.fieldByName('fehomologa').value := cbPrueba.Checked; configura.post; finally configura.close; end; } end; procedure TFConfigFe.FormCreate(Sender: TObject); var FBase: string; begin {with dataing do try configura.open; if configura.fieldByName('fe_rg2485').value then rgRegien.ItemIndex := 0 else if configura.fieldByName('fe2904').value then rgRegien.ItemIndex := 1 else if configura.fieldByName('feexpo').value then rgRegien.ItemIndex := 2 else if configura.fieldByName('fenousa').value then rgRegien.ItemIndex := 3; FF2485 := (rgRegien.ItemIndex = 0); FF2904 := (rgRegien.ItemIndex = 1); FEmiteFE := rgRegien.ItemIndex<>3; jvCertif.filename := configura.fieldByName('fecertificado').value ; jvPrivada.FileName := configura.fieldByName('feclave').value; cbDepura.Checked := configura.fieldByName('fedepura').value; jvPunto.value := configura.fieldByName('fepuntoventa').value; edServicioAFIP.Text := trim(configura.fieldByName('feservicio').value); cbPrueba.Checked := configura.fieldByName('fehomologa').value; finally configura.close; end; } DCons.TDatos.Open; try FBase := trim(DCons.TDatosRUTAEMPRESA.value); finally DCons.TDatos.close; end; FIni := TIniFile.Create(ExtractFilePath( Application.ExeName) + 'Conf\fact_ele' + FBase + '.ini' ); if (FIni.ReadBool('FE', '2485', True ) = True) then rgRegien.ItemIndex := 0 else if (FIni.ReadBool('FE', '2904', false )=true) then rgRegien.ItemIndex := 1 else if (FIni.ReadBool('FE', 'EXPO', false )=true) then rgRegien.ItemIndex := 2 else if (FIni.ReadBool('FE', 'NOUSA', false )=true) then rgRegien.ItemIndex := 3; FF2485 := (rgRegien.ItemIndex = 0); FF2904 := (rgRegien.ItemIndex = 1); FEmiteFE := rgRegien.ItemIndex<>3; jvCertif.filename := FIni.ReadString('FE', 'CERTIFICADO', '' ); jvPrivada.FileName := FIni.ReadString('FE', 'CLAVE', '' ); cbDepura.Checked := FIni.ReadBool('FE', 'DEPURACION', false ); jvPunto.value := FIni.ReadInteger('FE', 'PUNTODEVENTA', 1 ); edServicioAFIP.Text := FIni.ReadString('FE', 'SERVICIO', 'wsfe' ); cbPrueba.Checked := FIni.ReadBool('FE', 'HOMOLOGACION', false ); end; procedure TFConfigFe.SetEmiteFE(const Value: Boolean); begin FEmiteFE := Value; end; procedure TFConfigFe.SetF2485(const Value: Boolean); begin FF2485 := Value; end; procedure TFConfigFe.SetF2904(const Value: Boolean); begin FF2904 := Value; end; procedure TFConfigFe.SetFExpo(const Value: Boolean); begin FFExpo := Value; end; procedure TFConfigFe.SetFLog(const Value: Boolean); begin FFLog := Value; end; end.
unit GX_HideNavbar; { ================================================================================ IDE Expert to hide/disable the Editor Navigation Toolbar (Castalia) from the Delphi 10 Seattle IDE. Contributed by: Achim Kalwa <delphi(at)achim-kalwa.de> Integrated into GExperts by Thomas Mueller (http://blog.dummzeuch.de) ================================================================================ } {$I GX_CondDefine.inc} interface uses ToolsAPI, Classes, DockForm; type IHideNavigationToolbarExpert = interface ['{BC189A61-9313-4ABE-8AB3-2B80B3709DF5}'] procedure SetVisible(_Value: Boolean); end; function CreateHideNavigationToolbarExpert: IHideNavigationToolbarExpert; implementation uses SysUtils, Controls, GX_OtaUtils, GX_DbugIntf, GX_NTAEditServiceNotifier; {$IFDEF GX_VER300_up} // The navigation toolbar exists only in Delphi 10 (for now) type ///<summary> /// We implement INTAEditServicesNotifier only to get a notification when the EditViewActivated /// method is called. This in turn calls the OnEditorViewActivated event. </summary> TEditServiceNotifier = class(TGxNTAEditServiceNotifier, INTAEditServicesNotifier) private type TOnEditorViewActivatedEvent = procedure(_Sender: TObject; _EditView: IOTAEditView) of object; var FOnEditorViewActivated: TOnEditorViewActivatedEvent; protected // INTAEditServicesNotifier procedure EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); override; public constructor Create(_OnEditorViewActivated: TOnEditorViewActivatedEvent); end; {$ENDIF GX_VER300_up} type THideNavigationToolbarExpert = class(TInterfacedObject, IHideNavigationToolbarExpert) {$IFDEF GX_VER300_up} private FNotifierIdx: Integer; FIsNavbarVisible: Boolean; function TryFindComponentByName(const ParentComponent: TComponent; const _Name: string; out _Comp: TComponent): Boolean; function TrySetNavbarVisible(_EditView: IOTAEditView): Boolean; procedure EditorViewActivated(_Sender: TObject; _EditView: IOTAEditView); {$ENDIF GX_VER300_up} private procedure SetVisible(_Value: Boolean); {$IFDEF GX_VER300_up} public constructor Create; destructor Destroy; override; {$ENDIF GX_VER300_up} end; function CreateHideNavigationToolbarExpert: IHideNavigationToolbarExpert; begin Result := THideNavigationToolbarExpert.Create; end; { THideNavigationToolbarExpert } procedure THideNavigationToolbarExpert.SetVisible(_Value: Boolean); {$IFDEF GX_VER300_up} var EditView: IOTAEditView; {$ENDIF GX_VER300_up} begin {$IFDEF GX_VER300_up} if not Assigned(BorlandIDEServices) then Exit; FIsNavbarVisible := _Value; if GxOtaTryGetTopMostEditView(EditView) then begin TrySetNavbarVisible(EditView) end; {$ENDIF GX_VER300_up} end; {$IFDEF GX_VER300_up} constructor THideNavigationToolbarExpert.Create; begin inherited; if Assigned(BorlandIDEServices) then begin FNotifierIdx := (BorlandIDEServices as IOTAEditorServices).AddNotifier( TEditServiceNotifier.Create(EditorViewActivated)); end; end; destructor THideNavigationToolbarExpert.Destroy; begin {$IFOPT D+}SendDebug('THideNavigationToolbarExpert.Destroy');{$ENDIF} if FNotifierIdx <> 0 then begin {$IFOPT D+}SendDebugFmt('FNotifierIdx: %d', [FNotifierIdx]);{$ENDIF} if Assigned(BorlandIDEServices) then begin {$IFOPT D+}SendDebug('BorlandIDEServices is assigned');{$ENDIF} {$IFOPT D+}SendDebug('Calling RemoveNotifyer');{$ENDIF} (BorlandIDEServices as IOTAEditorServices).RemoveNotifier(FNotifierIdx); {$IFOPT D+}SendDebug('Returned from RemoveNotifyer');{$ENDIF} end else begin {$IFOPT D+}SendDebug('BorlandIDEServices is NOT assigned');{$ENDIF} end; end; inherited Destroy; end; procedure THideNavigationToolbarExpert.EditorViewActivated(_Sender: TObject; _EditView: IOTAEditView); begin TrySetNavbarVisible(_EditView) end; function THideNavigationToolbarExpert.TryFindComponentByName(const ParentComponent: TComponent; const _Name: string; out _Comp: TComponent): Boolean; var i: Integer; cmp: TComponent; begin Result := False; if not Assigned(ParentComponent) then Exit; for i := 0 to ParentComponent.ComponentCount - 1 do begin Cmp := ParentComponent.Components[i]; if SameText(cmp.Name, _Name) then begin _Comp := Cmp; Result := True; Exit; end else Result := TryFindComponentByName(Cmp, _Name, _Comp); // Recursion! end; end; function THideNavigationToolbarExpert.TrySetNavbarVisible(_EditView: IOTAEditView): Boolean; var c: TComponent; EditWindow: INTAEditWindow; Ctrl: TWinControl; begin Result := False; if not Assigned(_EditView) then Exit; EditWindow := _EditView.GetEditWindow; if not Assigned(EditWindow) then Exit; ctrl := EditWindow.Form; if not Assigned(Ctrl) then Exit; if TryFindComponentByName(Ctrl, 'TEditorNavigationToolbar', c) then begin TWinControl(C).Visible := FIsNavbarVisible; TWinControl(C).Enabled := FIsNavbarVisible; Result := True; end; end; { TEditServiceNotifier } constructor TEditServiceNotifier.Create(_OnEditorViewActivated: TOnEditorViewActivatedEvent); begin FOnEditorViewActivated := _OnEditorViewActivated; inherited Create; end; procedure TEditServiceNotifier.EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin if Assigned(FOnEditorViewActivated) then FOnEditorViewActivated(Self, EditView); end; {$ENDIF GX_VER300_up} end.
unit SelectDate; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.WinXCalendars, Vcl.ExtCtrls; type TOnSelectRef = reference to procedure (Date: TDate); TSelectDateForm = class(TForm) CalendarView: TCalendarView; Shape1: TShape; procedure FormCreate(Sender: TObject); procedure CalendarViewChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private FOnSelectRef: TOnSelectRef; IsCreating: Boolean; { Private declarations } procedure DeactivateForm(Sender: TObject); public property OnSelect: TOnSelectRef read FOnSelectRef write FOnSelectRef; end; implementation {$R *.dfm} procedure TSelectDateForm.CalendarViewChange(Sender: TObject); begin if IsCreating then Exit; if Assigned(OnSelect) then // fix: CalendarView bug if CalendarView.SelectionCount > 0 then OnSelect(CalendarView.Date) else OnSelect(Date); Close; end; procedure TSelectDateForm.DeactivateForm(Sender: TObject); begin Close; end; procedure TSelectDateForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TSelectDateForm.FormCreate(Sender: TObject); begin IsCreating := True; Application.OnDeactivate := DeactivateForm; CalendarView.Date := Date; IsCreating := False; end; procedure TSelectDateForm.FormDestroy(Sender: TObject); begin Application.OnDeactivate := nil; end; procedure TSelectDateForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Helper module for parsing floating point numbers out of strings, since // Delphi's StrToFloat implementation appears to be locale-based unit convert; interface uses typedefs; function atof(s : string; f : pfloat) : boolean; implementation function atof(s : string; f : pfloat) : boolean; var i : int; neg : boolean; frac : boolean; scale : float; begin atof := false; neg := false; frac := false; scale := 0.1; f^ := 0; for i := 1 to length(s) do begin if (i = 1) and (s[1] = '-') then begin neg := true; continue; end; if s[i] = '.' then begin if frac then // multiple radix chars, error exit; frac := true; continue; end; if not (s[i] in ['0'..'9']) then exit; if not frac then f^ := f^ * 10.0 + ord(s[i]) - ord('0') else begin f^ := f^ + (ord(s[i]) - ord('0')) * scale; scale := scale * 0.1; end; end; if neg then f^ := f^ * -1.0; atof := true; end; end.
program loanapproval(input, output); { chapter 4 assignment alberto villalobos february 12 program to determine the eligibility of a loan applicant ofr a loan. top down design --------------- input: salary(integer); credit rating(integer); cost(integer); loan(integer) output: approved/notapproved message; maximum loan possible main getdata findmax printapproval printmax getdata write on the screen'enter salary in dollars: ' readln(salary) write on the screen 'enter credit rating(0-4):' readln(crating) write on the screen 'enter cost of boat in dollars: ' readln(cost) write on the screen 'enter loan amount in dollars: ' readln(loan) findmax if rating is 3 or 4 then max = 0.85 * cost if rating is 2 then max = (0.7 * cost) if rating is 1 then max = (0.5 * cost) if rating is 0 then max = (0.25 * cost) if max > (salary * 0.5 )then max = salary * 0.5 printapproval if max > loan then loan approved else loan not approved printmax write on the screen maximum loan possible is, round(max) } const rate4 = 0.85; rate3 = 0.85; rate2 = 0.75; rate1 = 0.50; rate0 = 0.25; var loan, salary, cost, crating : integer; max : real; begin (* input *) write('Enter salary in dollars: '); readln(salary); write('Enter credit score(0-5): '); readln(crating); write('Enter cost of boat in dollars: '); readln(cost); write('Enter loan amount in dollars: '); readln(loan); (* end input *) (* begin case (find max boat credit) *) case crating of 0 : begin max := rate0 * cost; end; 1 : begin max := rate1 * cost; end; 2 : begin max := rate2 * cost; end; 3 : begin max := rate3 * cost; end; 4 : begin max := rate4 * cost; end; end; (* end case *) (* get the smaller of cost credit and salary credit *) if max > (salary * 0.5) then max := (salary * 0.5); (* output *) if max > loan then writeln('Loan approved!') else writeln ('Loan not approved :('); writeln('Maximum loan possible is: ', round(max)); end.
unit uVariantInterface; interface type IVariant = interface(IInterface) ['{AE703A4B-0681-467D-9823-1261DB41FB28}'] function GetValue: Variant; stdcall; procedure SetValue(const Value: Variant); stdcall; property Value: Variant read GetValue write SetValue; end; function CreateIVariant(AValue: Variant): IVariant; implementation type TVariant = class(TInterfacedObject, IVariant) private FValue: Variant; public constructor Create(AValue: Variant); function GetValue: Variant; stdcall; procedure SetValue(const Value: Variant); stdcall; property Value: Variant read GetValue write SetValue; end; { *********************************** TVariant *********************************** } constructor TVariant.Create(AValue: Variant); begin inherited Create; FValue := AValue; end; function TVariant.GetValue: Variant; begin // TODO -cMM : Interface wizard: Implement interface method Result := FValue; end; procedure TVariant.SetValue(const Value: Variant); begin // TODO -cMM : Interface wizard: Implement interface method if FValue <> Value then begin FValue := Value; end; end; function CreateIVariant(AValue: Variant): IVariant; begin Result := TVariant.Create(AValue); end; end.
{ Copyright (C) 2013-2021 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit ts.RichEditor.Manager; {$MODE DELPHI} interface uses Classes, SysUtils, FileUtil, ActnList, Dialogs, Menus, Contnrs, Forms, Controls, KMemoDlgTextStyle, KMemoDlgHyperlink, KMemoDlgImage, KMemoDlgNumbering, KMemoDlgContainer, KMemoDlgParaStyle, ts.RichEditor.Interfaces; type TRichEditorViewList = TComponentList; { TdmRichEditorManager } TdmRichEditorManager = class( TDataModule, IRichEditorManager, IRichEditorActions, IRichEditorEvents ) {$REGION 'designer controls'} aclActions : TActionList; actAlignCenter : TAction; actAlignJustify : TAction; actAlignLeft : TAction; actAlignRight : TAction; actBkColor : TAction; actBold : TAction; actColor : TAction; actCopy : TAction; actCut : TAction; actDecFontSize : TAction; actFont : TAction; actIncFontSize : TAction; actInsertHyperLink : TAction; actInsertImage : TAction; actInsertBulletList : TAction; actIncIndent : TAction; actDecIndent : TAction; actAdjustParagraphStyle : TAction; actInsertTextBox : TAction; actClear : TAction; actShowSpecialCharacters : TAction; actItalic : TAction; actOpen : TAction; actPaste : TAction; actRedo : TAction; actSave : TAction; actSaveAs : TAction; actSelectAll : TAction; actStrikeThrough : TAction; actToggleWordWrap : TAction; actUnderline : TAction; actUndo : TAction; dlgColor : TColorDialog; dlgFont : TFontDialog; dlgOpen : TOpenDialog; dlgSave : TSaveDialog; imlMain : TImageList; ppmRichEditor : TPopupMenu; {$ENDREGION} {$REGION 'action handlers'} procedure aclActionsExecute(AAction: TBasicAction; var Handled: Boolean); procedure actAlignCenterExecute(Sender: TObject); procedure actAlignJustifyExecute(Sender: TObject); procedure actAlignLeftExecute(Sender: TObject); procedure actAlignRightExecute(Sender: TObject); procedure actBkColorExecute(Sender: TObject); procedure actBoldExecute(Sender: TObject); procedure actClearExecute(Sender: TObject); procedure actColorExecute(Sender: TObject); procedure actCopyExecute(Sender: TObject); procedure actCutExecute(Sender: TObject); procedure actDecFontSizeExecute(Sender: TObject); procedure actDecIndentExecute(Sender: TObject); procedure actFontExecute(Sender: TObject); procedure actIncFontSizeExecute(Sender: TObject); procedure actIncIndentExecute(Sender: TObject); procedure actInsertBulletListExecute(Sender: TObject); procedure actInsertHyperLinkExecute(Sender: TObject); procedure actInsertImageExecute(Sender: TObject); procedure actInsertTextBoxExecute(Sender: TObject); procedure actItalicExecute(Sender: TObject); procedure actOpenExecute(Sender: TObject); procedure actAdjustParagraphStyleExecute(Sender: TObject); procedure actPasteExecute(Sender: TObject); procedure actRedoExecute(Sender: TObject); procedure actSaveAsExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure actShowSpecialCharactersExecute(Sender: TObject); procedure actStrikeThroughExecute(Sender: TObject); procedure actUnderlineExecute(Sender: TObject); procedure actUndoExecute(Sender: TObject); procedure actToggleWordWrapExecute(Sender: TObject); {$ENDREGION} private FViews : TRichEditorViewList; FActiveView : IRichEditorView; FEvents : IRichEditorEvents; protected {$REGION 'property access mehods'} function GetActions: TActionList; function GetActiveView: IRichEditorView; function GetEditorPopupMenu: TPopupMenu; function GetEvents: IRichEditorEvents; function GetItem(AName: string): TContainedAction; function GetView(AIndex: Integer): IRichEditorView; function GetViewByName(AName: string): IRichEditorView; function GetViewCount: Integer; procedure SetActiveView(const AValue: IRichEditorView); {$ENDREGION} procedure UpdateActions; public procedure AfterConstruction; override; destructor Destroy; override; function AddView( const AName : string = ''; const AFileName : string = '' ): IRichEditorView; function DeleteView(AIndex: Integer): Boolean; procedure ClearViews; procedure BuildRichEditorPopupMenu; { Delegates the implementation of IEditorEvents to an internal object. } property Events: IRichEditorEvents read GetEvents implements IRichEditorEvents; property Actions: TActionList read GetActions; property ActiveView: IRichEditorView read GetActiveView write SetActiveView; property Items[AName: string]: TContainedAction read GetItem; default; property Views[AIndex: Integer]: IRichEditorView read GetView; property ViewByName[AName: string]: IRichEditorView read GetViewByName; property ViewCount: Integer read GetViewCount; property EditorPopupMenu: TPopupMenu read GetEditorPopupMenu; end; implementation {$R *.lfm} uses Graphics, ts.Core.Utils, ts.Core.Logger, ts.RichEditor.Events, ts.RichEditor.View.KMemo; {$REGION 'construction and destruction'} procedure TdmRichEditorManager.AfterConstruction; begin inherited AfterConstruction; FViews := TRichEditorViewList.Create(False); FEvents := TRichEditorEvents.Create(Self); BuildRichEditorPopupMenu; end; destructor TdmRichEditorManager.Destroy; begin FActiveView := nil; FEvents := nil; FreeAndNil(FViews); inherited Destroy; end; {$ENDREGION} {$REGION 'property access mehods'} function TdmRichEditorManager.GetActions: TActionList; begin Result := aclActions; end; function TdmRichEditorManager.GetActiveView: IRichEditorView; begin if not Assigned(FActiveView) then raise Exception.Create('No active view assigned!'); Result := FActiveView; end; procedure TdmRichEditorManager.SetActiveView(const AValue: IRichEditorView); begin if AValue <> FActiveView then begin FActiveView := AValue; end; end; function TdmRichEditorManager.GetEditorPopupMenu: TPopupMenu; begin Result := ppmRichEditor; end; function TdmRichEditorManager.GetItem(AName: string): TContainedAction; begin Result := aclActions.ActionByName(AName); end; function TdmRichEditorManager.GetView(AIndex: Integer): IRichEditorView; begin if (AIndex > -1) and (AIndex < FViews.Count) then begin Result := FViews[AIndex] as IRichEditorView; end else Result := nil; end; function TdmRichEditorManager.GetViewByName(AName: string): IRichEditorView; var I : Integer; B : Boolean; begin I := 0; B := False; while (I < FViews.Count) and not B do begin B := FViews[I].Name = AName; if not B then Inc(I); end; if B then Result := FViews[I] as IRichEditorView else Result := nil; end; function TdmRichEditorManager.GetViewCount: Integer; begin Result := FViews.Count; end; function TdmRichEditorManager.GetEvents: IRichEditorEvents; begin Result := FEvents; end; {$ENDREGION} {$REGION 'action handlers'} procedure TdmRichEditorManager.actOpenExecute(Sender: TObject); begin if dlgOpen.Execute then begin ActiveView.LoadFromFile(dlgOpen.FileName); ActiveView.FileName := dlgOpen.FileName; end; end; procedure TdmRichEditorManager.actAdjustParagraphStyleExecute(Sender: TObject); begin ActiveView.AdjustParagraphStyle; end; procedure TdmRichEditorManager.actPasteExecute(Sender: TObject); begin ActiveView.Paste; end; procedure TdmRichEditorManager.actRedoExecute(Sender: TObject); begin ActiveView.Redo; end; procedure TdmRichEditorManager.actSaveAsExecute(Sender: TObject); begin if dlgSave.Execute then begin ActiveView.SaveToFile(dlgSave.FileName); ActiveView.FileName := dlgSave.FileName; end; end; procedure TdmRichEditorManager.actSaveExecute(Sender: TObject); begin ActiveView.SaveToFile(ActiveView.FileName); end; procedure TdmRichEditorManager.actShowSpecialCharactersExecute(Sender: TObject); begin if Assigned(ActiveView) then begin actShowSpecialCharacters.Checked := not actShowSpecialCharacters.Checked; ActiveView.ShowSpecialChars := actShowSpecialCharacters.Checked; end; end; procedure TdmRichEditorManager.actStrikeThroughExecute(Sender: TObject); begin if Assigned(ActiveView) then begin actStrikeThrough.Checked := not actStrikeThrough.Checked; ActiveView.Font.StrikeThrough := actStrikeThrough.Checked; end; end; procedure TdmRichEditorManager.actBoldExecute(Sender: TObject); begin if Assigned(ActiveView) then begin actBold.Checked := not actBold.Checked; ActiveView.Font.Bold := actBold.Checked; end; end; procedure TdmRichEditorManager.actClearExecute(Sender: TObject); begin ActiveView.Clear; end; procedure TdmRichEditorManager.actAlignRightExecute(Sender: TObject); begin ActiveView.AlignRight := True; end; procedure TdmRichEditorManager.actBkColorExecute(Sender: TObject); begin dlgColor.Width := 300; dlgColor.Handle := Application.MainForm.Handle; if dlgColor.Execute then begin; //ActiveView.TextAttributes.HasBkColor := False; //ActiveView.TextAttributes.HasBkColor := True; //ActiveView.TextAttributes.BkColor := dlgColor.Color; end; end; procedure TdmRichEditorManager.actAlignLeftExecute(Sender: TObject); begin ActiveView.AlignLeft := True; end; procedure TdmRichEditorManager.actAlignCenterExecute(Sender: TObject); begin ActiveView.AlignCenter := True; end; procedure TdmRichEditorManager.aclActionsExecute(AAction: TBasicAction; var Handled: Boolean); begin Logger.Action(AAction); end; procedure TdmRichEditorManager.actAlignJustifyExecute(Sender: TObject); begin ActiveView.AlignJustify := True; end; procedure TdmRichEditorManager.actColorExecute(Sender: TObject); begin dlgColor.Width := 300; dlgColor.Handle := Application.MainForm.Handle; if dlgColor.Execute then begin; ActiveView.Font.Color := dlgColor.Color; end; end; procedure TdmRichEditorManager.actCopyExecute(Sender: TObject); begin ActiveView.Copy; end; procedure TdmRichEditorManager.actCutExecute(Sender: TObject); begin ActiveView.Cut; end; procedure TdmRichEditorManager.actDecFontSizeExecute(Sender: TObject); begin if Assigned(ActiveView) then begin if ActiveView.Font.Size > 0 then ActiveView.Font.Size := ActiveView.Font.Size - 1; end; end; procedure TdmRichEditorManager.actDecIndentExecute(Sender: TObject); begin ActiveView.DecIndent; end; procedure TdmRichEditorManager.actFontExecute(Sender: TObject); begin if dlgFont.Execute then begin ActiveView.Font.Assign(dlgFont.Font); end; end; procedure TdmRichEditorManager.actIncFontSizeExecute(Sender: TObject); begin if Assigned(ActiveView) then begin ActiveView.Font.Size := ActiveView.Font.Size + 1; end; end; procedure TdmRichEditorManager.actIncIndentExecute(Sender: TObject); begin ActiveView.IncIndent; end; procedure TdmRichEditorManager.actInsertBulletListExecute(Sender: TObject); begin ActiveView.InsertBulletList; end; procedure TdmRichEditorManager.actInsertHyperLinkExecute(Sender: TObject); begin ActiveView.InsertHyperlink; end; procedure TdmRichEditorManager.actInsertImageExecute(Sender: TObject); begin ActiveView.InsertImage; end; procedure TdmRichEditorManager.actInsertTextBoxExecute(Sender: TObject); begin ActiveView.InsertTextBox; end; procedure TdmRichEditorManager.actItalicExecute(Sender: TObject); begin if Assigned(ActiveView) then begin actItalic.Checked := not actItalic.Checked; ActiveView.Font.Italic := actItalic.Checked; end; end; procedure TdmRichEditorManager.actUnderlineExecute(Sender: TObject); begin if Assigned(ActiveView) then begin actUnderline.Checked := not actUnderline.Checked; ActiveView.Font.Underline := actUnderline.Checked; end; end; procedure TdmRichEditorManager.actUndoExecute(Sender: TObject); begin ActiveView.Undo; end; procedure TdmRichEditorManager.actToggleWordWrapExecute(Sender: TObject); begin actToggleWordWrap.Checked := not actToggleWordWrap.Checked; ActiveView.WordWrap := actToggleWordWrap.Checked; end; {$ENDREGION} {$REGION 'private methods'} procedure TdmRichEditorManager.BuildRichEditorPopupMenu; var MI : TMenuItem; begin MI := ppmRichEditor.Items; MI.Clear; AddMenuItem(MI, actCut); AddMenuItem(MI, actCopy); AddMenuItem(MI, actPaste); AddMenuItem(MI); AddMenuItem(MI, actUndo); AddMenuItem(MI, actRedo); AddMenuItem(MI); AddMenuItem(MI, actBold); AddMenuItem(MI, actItalic); AddMenuItem(MI, actUnderline); AddMenuItem(MI); AddMenuItem(MI, actAlignLeft); AddMenuItem(MI, actAlignCenter); AddMenuItem(MI, actAlignRight); AddMenuItem(MI, actAlignJustify); AddMenuItem(MI); AddMenuItem(MI, actIncIndent); AddMenuItem(MI, actDecIndent); AddMenuItem(MI); AddMenuItem(MI, actToggleWordWrap); AddMenuItem(MI, actShowSpecialCharacters); AddMenuItem(MI); AddMenuItem(MI, actClear); AddMenuItem(MI); AddMenuItem(MI, actOpen); AddMenuItem(MI, actSave); AddMenuItem(MI, actSaveAs); //AddMenuItem(MI, FilePopupMenu); //AddMenuItem(MI, SettingsPopupMenu); //AddMenuItem(MI, SearchPopupMenu); //AddMenuItem(MI, SelectPopupMenu); //AddMenuItem(MI, SelectionPopupMenu); //AddMenuItem(MI, InsertPopupMenu); //AddMenuItem(MI, ClipboardPopupMenu); //AddMenuItem(MI, ExportPopupMenu); //AddMenuItem(MI, HighlighterPopupMenu); //AddMenuItem(MI, FoldPopupMenu); //AddMenuItem(MI); //AddMenuItem(MI, actClose); //AddMenuItem(MI, actCloseOthers); end; {$ENDREGION} {$REGION 'protected methods'} { Gets called by the active view. } procedure TdmRichEditorManager.UpdateActions; var B : Boolean; begin B := Assigned(ActiveView); actUndo.Enabled := B; actRedo.Enabled := B; actCopy.Enabled := B and ActiveView.SelAvail; actCut.Enabled := B and ActiveView.SelAvail; actPaste.Enabled := B and ActiveView.CanPaste; actAlignCenter.Enabled := B; actAlignJustify.Enabled := B; actAlignLeft.Enabled := B; actAlignRight.Enabled := B; actBkColor.Enabled := B; actColor.Enabled := B; actAdjustParagraphStyle.Enabled := B; actDecFontSize.Enabled := B; actFont.Enabled := B; actIncFontSize.Enabled := B; actInsertHyperLink.Enabled := B; actInsertImage.Enabled := B; actInsertBulletList.Enabled := B; actIncIndent.Enabled := B; actDecIndent.Enabled := B; actInsertTextBox.Enabled := B; actClear.Enabled := B; actShowSpecialCharacters.Enabled := B; actItalic.Enabled := B; actOpen.Enabled := B; actSave.Enabled := B; actSaveAs.Enabled := B; actSelectAll.Enabled := B; actStrikeThrough.Enabled := B; actToggleWordWrap.Enabled := B; actUnderline.Enabled := B; actBold.Checked := B and ActiveView.Font.Bold; actUnderline.Checked := B and ActiveView.Font.Underline; actItalic.Checked := B and ActiveView.Font.Italic; actStrikeThrough.Checked := B and ActiveView.Font.StrikeThrough; //actUndo.Enabled := ActiveView.CanUndo; //actRedo.Enabled := ActiveView.CanRedo; actAlignCenter.Checked := B and ActiveView.AlignCenter; actAlignLeft.Checked := B and ActiveView.AlignLeft; actAlignRight.Checked := B and ActiveView.AlignRight; actAlignJustify.Checked := B and ActiveView.AlignJustify; actToggleWordWrap.Checked := B and ActiveView.WordWrap; end; function TdmRichEditorManager.AddView(const AName: string; const AFileName: string): IRichEditorView; var V : TRichEditorViewKMemo; begin V := TRichEditorViewKMemo.Create(Self); // if no name is provided, the view will get an automatically generated one. if AName <> '' then V.Name := AName; V.FileName := AFileName; V.Caption := ''; FViews.Add(V); Result := V as IRichEditorView; FActiveView := V; end; function TdmRichEditorManager.DeleteView(AIndex: Integer): Boolean; begin { TODO -oTS : Needs implementation } Result := False; end; procedure TdmRichEditorManager.ClearViews; begin FViews.Clear; end; {$ENDREGION} end.
unit uServerPublic; interface uses Windows, System.SysUtils, Generics.Collections, Data.DB, Data.Win.ADODB, uPublic, HPSocketSDKUnit , QMsgPack; type TConfigInfo = record IP: string; Port: Word; DB_Host: string; DB_Name: string; DB_Account: string; DB_PassWord: string; end; var GHPServer: Pointer; GHPListener: Pointer; GAppState: EnAppState; GDeviceInfos: TDictionary<DWORD,TDeviceInfo>; GConfigInfo: TConfigInfo; GAdoConn: TAdoConnection; GConfigFileName: string; const GDBConnString = //'Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s\SQLEXPRESS'; 'Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s'; //'Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s\SQLEXPRESS'; function SendData(AConnID: DWORD; AData: Pointer; ADataLen: integer): Boolean; function SendResult(AConnID: DWORD; ACmdType: TCommType; AResultState: TResultState; ResuleMsg: string): Boolean; procedure AddLogMsg(AFormat: string; Args: array of const); function ConnDataBase: Boolean; function DisConnDataBase: Boolean; function GetModelPoolInfo(QQ: string; var AGroupName: string; var AComName: string): Boolean; implementation function SendData(AConnID: DWORD; AData: Pointer; ADataLen: integer): Boolean; begin Result := False; try Result := HP_Server_Send(GHPServer, AConnID, AData, ADataLen); except AddLogMsg('SendData fail[%s]...', [GetLastError()]); end; end; function SendResult(AConnID: DWORD; ACmdType: TCommType; AResultState: TResultState; ResuleMsg: string): Boolean; var vMsgPack: TQMsgPack; vBin: TBytes; begin Result := False; vMsgPack := TQMsgPack.Create; try try vMsgPack.Add('Cmd', Integer(ACmdType)); vMsgPack.Add('Ret', Integer(AResultState)); vMsgPack.Add('Content', ResuleMsg); vBin := vMsgPack.Encode; SendData(AConnID, vBin, Length(vBin)); Result := True; except AddLogMsg('SendResult fail[%s]...', [GetLastError()]); end; finally FreeAndNil(vMsgPack); end; end; procedure AddLogMsg(AFormat: string; Args: array of const); var sText: string; begin sText := System.SysUtils.Format(AFormat, Args, FormatSettings); if sText <> '' then begin SendMessage(GFrmMainHwnd, WM_ADD_LOG, 0, LPARAM(sText)); end; end; function ConnDataBase: Boolean; var sConnString: string; begin try if GAdoConn.Connected then GAdoConn.Close; sConnString := Format(GDBConnString, [ GConfigInfo.DB_PassWord, GConfigInfo.DB_Account, GConfigInfo.DB_Name, GConfigInfo.DB_Host ]); GAdoConn.ConnectionString := sConnString; GAdoConn.Connected := True; Result := GAdoConn.Connected; AddLogMsg('ConnDataBase OK...', []); except AddLogMsg('ConnDataBase fail[%d]...', [GetLastError()]); end; end; function DisConnDataBase: Boolean; begin Result := False; try if GAdoConn.Connected then GAdoConn.Close; AddLogMsg('DisConnDataBase OK...', []); except AddLogMsg('DisConnDataBase fail[%d]...', [GetLastError()]); end; end; function GetModelPoolInfo(QQ: string; var AGroupName: string; var AComName: string): Boolean; var vQuery: TADOQuery; begin Result := False; AGroupName := ''; AComName := ''; if not GAdoConn.Connected then begin AddLogMsg('DataBase not connected...', []); Exit; end; try vQuery := TADOQuery.Create(nil); try vQuery.Connection := GAdoConn; vQuery.SQL.Clear; vQuery.SQL.Text := 'SELECT * FROM VDeviceInfo WHERE QQ = ' + QuotedStr(QQ); vQuery.Open; if vQuery.RecordCount <= 0 then Exit; AComName := vQuery.FieldByName('ComName').AsString; AGroupName := vQuery.FieldByName('GroupName').AsString; finally if vQuery.Active then vQuery.Close; FreeAndNil(vQuery); end; except AddLogMsg('GetComPortInfo fail[%d]...', [GetLastError()]); end; Result := True; end; //function AddMsgToDataBase(ASmsData: TSmsData): Boolean; //var // vQuery: TADOQuery; // nType: ShortInt; //begin // Result := False; // if not GAdoConn.Connected then begin // AddLogMsg('DataBase not connected...', []); // Exit; // end; // // try // vQuery := TADOQuery.Create(nil); // try // if ASmsData.CommType = ctSendMsg then // nType := 0 // else // nType := 1; // // vQuery.Connection := GAdoConn; // vQuery.SQL.Clear; // vQuery.SQL.Text := 'INSERT INTO [ModelPool].[dbo].[Message] (' + #13#10 + // ' [SendPhoneNum],' + #13#10 + // ' [RecvPhoneNum],' + #13#10 + // ' [MsgType],' + #13#10 + // ' [MsgContent])' + #13#10 + // 'VALUES(' + #13#10 + // QuotedStr(ASmsData.SendPhoneNum) + ',' + #13#10 + // QuotedStr(ASmsData.RecvPhoneNum) + ',' + #13#10 + // IntToStr(nType) + ',' + #13#10 + // QuotedStr(ASmsData.MsgContent) + #13#10 + // ')'; // vQuery.ExecSQL; // finally // if vQuery.Active then vQuery.Close; // FreeAndNil(vQuery); // end; // except // AddLogMsg('AddMsgToDataBase fail[%d]...', [GetLastError()]); // end; // Result := True; //end; initialization GDeviceInfos := TDictionary<DWORD,TDeviceInfo>.Create(); GDeviceInfos.Clear; GAdoConn := TADOConnection.Create(nil); GAdoConn.LoginPrompt := False; GConfigFileName := ExtractFilePath(ParamStr(0)); GConfigFileName := GConfigFileName + 'Config'; if not DirectoryExists(GConfigFileName) then ForceDirectories(GConfigFileName); GConfigFileName := GConfigFileName + '\Config.ini'; finalization GDeviceInfos.Clear; FreeAndNil(GDeviceInfos); if GAdoConn.Connected then GAdoConn.Close; FreeAndNil(GAdoConn); end.
{*********************************************************} {* STNVBITS.PAS 3.01 *} {* Copyright (c) TurboPower Software Co., 1996-2000 *} {* All rights reserved. *} {*********************************************************} {$I STDEFINE.INC} {$IFNDEF WIN32} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} unit StNVBits; {-non visual component for TStBits} interface uses {$IFDEF WIN32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, StBase, StBits, StNVCont; type TStNVBits = class(TStNVContainerBase) {.Z+} protected {private} {property variables} FContainer : TStBits; {instance of the container} FMaxBits : LongInt; {property methods} procedure SetMaxBits(Value : LongInt); protected {virtual property methods} function GetOnLoadData : TStLoadDataEvent; override; function GetOnStoreData : TStStoreDataEvent; override; procedure SetOnLoadData(Value : TStLoadDataEvent); override; procedure SetOnStoreData(Value : TStStoreDataEvent); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z-} property Container : TStBits read FContainer; published property MaxBits : LongInt read FMaxBits write SetMaxBits; property OnLoadData; property OnStoreData; end; implementation {$IFDEF TRIALRUN} uses {$IFDEF Win32} Registry, {$ELSE} Ver, {$ENDIF} Forms, IniFiles, ShellAPI, SysUtils, StTrial; {$I TRIAL00.INC} {FIX} {$I TRIAL01.INC} {CAB} {$I TRIAL02.INC} {CC} {$I TRIAL03.INC} {VC} {$I TRIAL04.INC} {TCC} {$I TRIAL05.INC} {TVC} {$I TRIAL06.INC} {TCCVC} {$ENDIF} {*** TStNVBits ***} constructor TStNVBits.Create(AOwner : TComponent); begin {$IFDEF TRIALRUN} TCCVC; {$ENDIF} inherited Create(AOwner); {defaults} FMaxBits := 100; if Classes.GetClass(TStBits.ClassName) = nil then RegisterClass(TStBits); FContainer := TStBits.Create(FMaxBits-1); end; destructor TStNVBits.Destroy; begin FContainer.Free; FContainer := nil; inherited Destroy; end; function TStNVBits.GetOnLoadData : TStLoadDataEvent; begin Result := FContainer.OnLoadData; end; function TStNVBits.GetOnStoreData : TStStoreDataEvent; begin Result := FContainer.OnStoreData; end; procedure TStNVBits.SetMaxBits(Value : LongInt); var HoldOnLoadData : TStLoadDataEvent; HoldOnStoreData : TStStoreDataEvent; begin {setting MaxBits will destroy exisiting data} if Value < 0 then Value := 0; FMaxBits := Value; HoldOnLoadData := FContainer.OnLoadData; HoldOnStoreData := FContainer.OnStoreData; FContainer.Free; FContainer := TStBits.Create(FMaxBits-1); FContainer.OnLoadData := HoldOnLoadData; FContainer.OnStoreData := HoldOnStoreData; end; procedure TStNVBits.SetOnLoadData(Value : TStLoadDataEvent); begin FContainer.OnLoadData := Value; end; procedure TStNVBits.SetOnStoreData(Value : TStStoreDataEvent); begin FContainer.OnStoreData := Value; end; end.
unit uChamadoDetalhes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, uChamadoController, Data.DB, Datasnap.DBClient, uEnumerador; const COR_ABERTURA: Integer = clRed; COR_OCORR_GERAL: Integer = clPurple; COR_STATUS: Integer = clOlive; type TfrmChamadoDetalhes = class(TForm) Panel1: TPanel; GroupBox1: TGroupBox; Label1: TLabel; shpAbertura: TShape; Label4: TLabel; shpOcorrGeral: TShape; shpOcorrStatus: TShape; Label6: TLabel; CategoryPanelGroup1: TCategoryPanelGroup; ctpOcorrencias: TCategoryPanel; mmoGeral: TRichEdit; ctpAbertura: TCategoryPanel; mmoObs: TRichEdit; cdsDados: TClientDataSet; cdsDadosDocumento: TStringField; cdsDadosData: TDateField; cdsDadosHoraInicial: TStringField; cdsDadosHoraFinal: TStringField; cdsDadosUsuario: TStringField; cdsDadosColaborador1: TStringField; cdsDadosColaborador2: TStringField; cdsDadosColaborador3: TStringField; cdsDadosDescricaoProblema: TStringField; cdsDadosDescricaoSolucao: TStringField; cdsDadosAnexo: TStringField; cdsDadosNomeStatus: TStringField; cdsDadosTipo: TIntegerField; cdsDadosIdOcorrencia: TIntegerField; procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FStatus: string; FIdChamado: Integer; FTipoMovimento: TEnumChamadoAtividade; procedure Legendas; procedure PreencherDados; procedure PreecherAbertura(AObj: TChamadoController); procedure PreecherOcorrencia(AObjChamado: TChamadoController); procedure PreencherStatus(AObjChamado: TChamadoController); procedure ListarOcorrenciaStatus(AObj: TChamadoController); procedure FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean = False); overload; public { Public declarations } constructor create(AIdChamado: integer; ATipo: TEnumChamadoAtividade = caChamado); end; var frmChamadoDetalhes: TfrmChamadoDetalhes; implementation {$R *.dfm} uses uDM, uClienteController; { TfrmChamadoDetalhes } constructor TfrmChamadoDetalhes.create(AIdChamado: integer; ATipo: TEnumChamadoAtividade); begin inherited create(nil); FIdChamado := AIdChamado; FTipoMovimento := ATipo; end; procedure TfrmChamadoDetalhes.Legendas; begin shpAbertura.Brush.Color := COR_ABERTURA; shpOcorrGeral.Brush.Color := COR_OCORR_GERAL; shpOcorrStatus.Brush.Color := COR_STATUS; end; procedure TfrmChamadoDetalhes.ListarOcorrenciaStatus(AObj: TChamadoController); var iColaborador: Integer; begin iColaborador := 1; cdsDados.First; while not cdsDados.Eof do begin case cdsDadosTipo.AsInteger of 1: begin if cdsDadosHoraInicial.AsString <> '' then begin FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Documento: ' + cdsDadosDocumento.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Data: ' + cdsDadosData.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Hora Inicial: ' + cdsDadosHoraInicial.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Hora Final: ' + cdsDadosHoraFinal.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Usuário: ' + cdsDadosUsuario.AsString); // buscar colaboradores if cdsDadosIdOcorrencia.AsInteger > 0 then begin AObj.LocalizarChamadoColaborador(cdsDadosIdOcorrencia.AsInteger); while not AObj.Model.CDSChamadoOcorrColaborador.Eof do begin AObj.Model.CDSChamadoOcorrColaboradorUsu_Nome.AsString; FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Colaborador ' + IntToStr(iColaborador) + ': ' + AObj.Model.CDSChamadoOcorrColaboradorUsu_Nome.AsString); AObj.Model.CDSChamadoOcorrColaborador.Next; Inc(iColaborador); end; end; FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Anexo: ' + cdsDadosAnexo.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Descrição Problema: ' + cdsDadosDescricaoProblema.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, 'Descrição Solução: ' + cdsDadosDescricaoSolucao.AsString); FormatarLinha(mmoGeral,COR_OCORR_GERAL, StringOfChar('=', 100)); mmoGeral.Lines.Add(''); end; end; 2: begin if cdsDadosNomeStatus.AsString <> '' then begin FormatarLinha(mmoGeral,COR_STATUS, 'Data Status: ' + cdsDadosData.AsString); FormatarLinha(mmoGeral,COR_STATUS, 'Hora Status: ' + cdsDadosHoraInicial.AsString); FormatarLinha(mmoGeral,COR_STATUS, 'Status: ' + cdsDadosNomeStatus.AsString); FormatarLinha(mmoGeral,COR_STATUS, 'Usuário Status: ' + cdsDadosUsuario.AsString); mmoGeral.Lines.Add(''); end; end; end; cdsDados.Next; end; FormatarLinha(mmoGeral,COR_STATUS, 'Status: ' + FStatus); end; procedure TfrmChamadoDetalhes.PreecherOcorrencia(AObjChamado: TChamadoController); begin while not AObjChamado.Model.CDSChamadoOcorrenciaCons.Eof do begin cdsDados.Append; cdsDadosTipo.AsInteger := 1; cdsDadosDocumento.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_Docto.AsString; cdsDadosData.AsDateTime := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_Data.AsDateTime; cdsDadosHoraInicial.AsString := FormatDateTime('hh:mm', AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_HoraInicio.AsDateTime); cdsDadosHoraFinal.AsString := FormatDateTime('hh:mm', AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_HoraFim.AsDateTime); cdsDadosUsuario.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsUsu_Nome.AsString; // cdsDadosColaborador1.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsUsu_Nome1.AsString; // cdsDadosColaborador2.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsUsu_Nome2.AsString; // cdsDadosColaborador3.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsUsu_Nome3.AsString; cdsDadosDescricaoProblema.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_DescricaoTecnica.AsString; cdsDadosDescricaoSolucao.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_DescricaoSolucao.AsString; cdsDadosAnexo.AsString := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_Anexo.AsString; cdsDadosIdOcorrencia.AsInteger := AObjChamado.Model.CDSChamadoOcorrenciaConsChOco_Id.AsInteger; cdsDados.Post; AObjChamado.Model.CDSChamadoOcorrenciaCons.Next; end; end; procedure TfrmChamadoDetalhes.FormatarLinha(var AMemo: TRichEdit; ACor: Integer; ATexto: string; ANegrito: Boolean); begin AMemo.SelAttributes.Color := ACor; if ANegrito then AMemo.SelAttributes.Style:=[fsBold]; AMemo.Lines.Add(ATexto); AMemo.SelAttributes.Color:=Color; end; procedure TfrmChamadoDetalhes.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmChamadoDetalhes.FormShow(Sender: TObject); begin Legendas(); PreencherDados(); try mmoObs.SetFocus; except // nada end; end; procedure TfrmChamadoDetalhes.PreecherAbertura(AObj: TChamadoController); var sNivel: string; Cliente: TClienteController; sRevenda: string; sConsultor: string; begin Cliente := TClienteController.Create; try Cliente.LocalizarId(AObj.Model.CDSCadastroCha_Cliente.AsInteger); sRevenda := Cliente.Model.CDSCadastroRev_Nome.AsString; sConsultor := Cliente.Model.CDSCadastroUsu_Nome.AsString; finally FreeAndNil(Cliente); end; if AObj.Model.CDSCadastroCha_Nivel.AsInteger = 1 then sNivel := 'Baixo' else if AObj.Model.CDSCadastroCha_Nivel.AsInteger = 2 then sNivel := 'Normal' else if AObj.Model.CDSCadastroCha_Nivel.AsInteger = 3 then sNivel := 'Alto' else if AObj.Model.CDSCadastroCha_Nivel.AsInteger = 4 then sNivel := 'Crítico'; FormatarLinha(mmoObs,COR_ABERTURA, 'Id: ' + FormatFloat('000000',AObj.Model.CDSCadastroCha_Id.AsFloat) + ' - Data Abertura: ' + AObj.Model.CDSCadastroCha_DataAbertura.AsString + ' - Hora: ' + FormatDateTime('hh:mm',AObj.Model.CDSCadastroCha_HoraAbertura.AsDateTime) + ' - Usuário Abertura: ' + AObj.Model.CDSCadastroUsu_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Cliente: ' + AObj.Model.CDSCadastroCli_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Contato: ' + AObj.Model.CDSCadastroCha_Contato.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Nivel: ' + sNivel); FormatarLinha(mmoObs,COR_ABERTURA, 'Módulo: ' + AObj.Model.CDSCadastroMod_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Produto: ' + AObj.Model.CDSCadastroProd_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Tipo: ' + AObj.Model.CDSCadastroTip_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Status: ' + AObj.Model.CDSCadastroSta_Nome.AsString); FormatarLinha(mmoObs,COR_ABERTURA, 'Revenda: ' + sRevenda); FormatarLinha(mmoObs,COR_ABERTURA, 'Consultor: ' + sConsultor); FormatarLinha(mmoObs,COR_ABERTURA, 'Descrição: ' + AObj.Model.CDSCadastroCha_Descricao.AsString); FStatus := AObj.Model.CDSCadastroSta_Nome.AsString; end; procedure TfrmChamadoDetalhes.PreencherDados; var Obj: TChamadoController; PermissaoAbertura: Boolean; PermissaoOcorrencia: Boolean; PermissaoStatus: Boolean; begin cdsDados.CreateDataSet; cdsDados.IndexFieldNames := 'Tipo;Data'; Obj := TChamadoController.Create; try if FTipoMovimento = caChamado then begin PermissaoAbertura := Obj.PermissaoChamadoAbertura(dm.IdUsuario); PermissaoOcorrencia := Obj.PermissaoChamadoOcorrencia(dm.IdUsuario); PermissaoStatus := Obj.PermissaoChamadoStatus(dm.IdUsuario); end else begin PermissaoAbertura := Obj.PermissaoAtividadeAbertura(dm.IdUsuario); PermissaoOcorrencia := Obj.PermissaoAtividadeOcorrencia(dm.IdUsuario); PermissaoStatus := Obj.PermissaoAtividadeStatus(dm.IdUsuario); end; ctpAbertura.Visible := PermissaoAbertura; if (PermissaoOcorrencia = False) and (PermissaoStatus = False) then ctpOcorrencias.Visible := False; Obj.Editar(FIdChamado, Self, FTipoMovimento); PreecherAbertura(Obj); if PermissaoOcorrencia then PreecherOcorrencia(Obj); if PermissaoStatus then PreencherStatus(obj); ListarOcorrenciaStatus(obj); finally FreeAndNil(Obj); end; end; procedure TfrmChamadoDetalhes.PreencherStatus(AObjChamado: TChamadoController); begin while not AObjChamado.Model.CDSChamadoStatus.Eof do begin cdsDados.Append; cdsDadosTipo.AsInteger := 2; cdsDadosData.AsDateTime := AObjChamado.Model.CDSChamadoStatusChSta_Data.AsDateTime; cdsDadosHoraInicial.AsString:= AObjChamado.Model.CDSChamadoStatusChSta_Hora.AsString; cdsDadosNomeStatus.AsString := AObjChamado.Model.CDSChamadoStatusSta_Nome.AsString; cdsDadosUsuario.AsString := AObjChamado.Model.CDSChamadoStatusUsu_Nome.AsString; cdsDados.Post; AObjChamado.Model.CDSChamadoStatus.Next; end; end; end.
unit GraphicPanel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TGraphicPanel } TGraphicPanel = class(TPanel) private fup:tpicture; fdown:tpicture; fleft:tpicture; fright:tpicture; fupperleft:tpicture; fupperright:tpicture; fdownleft:tpicture; fdownright:tpicture; rright: tpicture; procedure setdown(Value: tpicture); procedure setdownleft(Value: tpicture); procedure setdownright(Value: tpicture); procedure setleft(Value: tpicture); procedure setright(Value: tpicture); procedure setup(Value: tpicture); procedure setupperleft(Value: tpicture); procedure setupperright(Value: tpicture); protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; published { Published declarations } Property ImgUp:tpicture read fup write setup; Property ImgDown:tpicture read fdown write setdown; Property ImgLeft:tpicture read fleft write setleft; Property ImgRight:tpicture read fright write setright; Property ImgUpperleft:tpicture read fupperleft write setupperleft; Property ImgUpperright:tpicture read fupperright write setupperright; Property ImgDownleft:tpicture read fdownleft write setdownleft; Property ImgDownright:tpicture read fdownright write setdownright; end; procedure Register; implementation procedure Register; begin RegisterComponents('Touch',[TGraphicPanel]); end; { TGraphicPanel } procedure TGraphicPanel.setdown(Value: tpicture); begin fdown.assign(value); end; procedure TGraphicPanel.setdownleft(Value: tpicture); begin fdownleft.assign(value); end; procedure TGraphicPanel.setdownright(Value: tpicture); begin fdownright.assign(value); end; procedure TGraphicPanel.setleft(Value: tpicture); begin fleft.assign(value); end; procedure TGraphicPanel.setright(Value: tpicture); begin fright.assign(value); end; procedure TGraphicPanel.setup(Value: tpicture); begin fup.assign(value); end; procedure TGraphicPanel.setupperleft(Value: tpicture); begin fupperleft.assign(value); end; procedure TGraphicPanel.setupperright(Value: tpicture); begin fupperright.assign(value); end; constructor TGraphicPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); fup:=tpicture.create; fdown:=tpicture.create; fleft:=tpicture.create; fright:=tpicture.create; fupperleft:=tpicture.create; fupperright:=tpicture.create; fdownleft:=tpicture.create; fdownright:=tpicture.create; rright:=tpicture.create; caption:=''; BevelInner:=bvnone; BevelOuter:=bvnone; end; destructor TGraphicPanel.Destroy; begin fup.free; fdown.free; fleft.free; fright.free; fupperleft.free; fupperright.free; fdownleft.free; fdownright.free; rright.free; inherited Destroy; end; procedure TGraphicPanel.Paint; var i,d:integer; begin inherited Paint; i:=0; while i<width do begin i:=i+fup.width; canvas.Draw(i,0,fup.Graphic); end; // for i:=0 to width by fup.width do canvas.Draw(i,0,fup.Graphic); i:=0; while i<width do begin i:=i+fdown.width; canvas.Draw(i,height-fdown.height,fdown.Graphic); end; // for i:=0 to width do canvas.Draw(i,height-fdown.height,fdown.Graphic); i:=0; while i<height do begin i:=i+fleft.height; canvas.Draw(0,i,fleft.Graphic); end; // for i:=0 to height do canvas.Draw(0,i,fleft.Graphic); i:=0; while i<height do begin i:=i+fright.height; canvas.Draw(width-fright.width,i,fright.Graphic); end; // for i:=0 to height do canvas.Draw(width-fright.width,i,fright.Graphic); canvas.Draw(0,0,fupperleft.graphic); canvas.draw(0,height-fdownleft.height,fdownleft.graphic); canvas.draw(width-fupperright.width,0,fupperright.graphic); canvas.draw(width-fdownright.width,height-fdownright.height,fdownright.graphic); end; end.
unit QuickExport; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, FB2_to_TXT_TLB, StdVcl,fb2txt_engine; type TFB2AnyQuickExport = class(TAutoObject, IFB2AnyQuickExport) public procedure AfterConstruction; Override; procedure BeforeDestruction; override; protected Converter:TTXTConverter; SettingsLoaded:Boolean; procedure Export(hWnd: Integer; filename: OleVariant; const document: IDispatch; appName: OleVariant); safecall; procedure Setup(hWnd: Integer; appName: OleVariant); safecall; { Protected declarations } end; implementation uses ComServ,Windows,QuickExportSetup, Forms,Registry,MSXML2_TLB,fb2_hyph_TLB, SysUtils,save_txt_dialog; procedure TFB2AnyQuickExport.AfterConstruction; Begin inherited AfterConstruction; Converter:=TTXTConverter.Create; SettingsLoaded:=False; end; procedure TFB2AnyQuickExport.BeforeDestruction; Begin inherited BeforeDestruction; Converter.Free; end; procedure TFB2AnyQuickExport.Export(hWnd: Integer; filename: OleVariant; const document: IDispatch; appName: OleVariant); Var Reg:TRegistry; HyphDescrDOM:IXMLDOMDocument2; begin if not SettingsLoaded then begin Reg:=TRegistry.Create(KEY_READ); Try if Reg.OpenKeyReadOnly(QuickSetupKey+appName) then Begin if Reg.ReadBool('Word wrap') then Converter.TextWidth:=Reg.ReadInteger('Text width') else Converter.TextWidth:=-1; Converter.SkipDescr:=Reg.ReadBool('Skip description'); if Reg.ReadBool('Do indent para') then Converter.Indent:=Reg.ReadString('Indent text') else Converter.Indent:=''; if Reg.ReadBool('Hyphenate') then Begin Converter.HyphControler:=CoFB2Hyphenator.Create; HyphDescrDOM:=CoFreeThreadedDOMDocument40.Create; HyphDescrDOM.preserveWhiteSpace:=True; HyphDescrDOM.loadXML('<device name="Fixed width text"><displays><display-mode name="Default" width="'+IntToStr(Reg.ReadInteger('Text width'))+'"/></displays><fonts><font name="Default"><font-size name="Default"><normal default-width="1"/><strong default-width="1"/><emphasis default-width="1"/><strongemphasis default-width="1"/></font-size></font></fonts></device>'); Converter.HyphControler.deviceDescr:=HyphDescrDOM; Converter.HyphControler.currentDeviceSize:='Default'; Converter.HyphControler.currentFont:='Default'; Converter.HyphControler.currentFontSize:='Default'; Converter.HyphControler.strPrefix:=Converter.Indent; end; Converter.CodePage:=Reg.ReadInteger('File codepage'); Converter.BR:=BRTypes[Reg.ReadInteger('Line breaks type')+1].Chars; Converter.IgnoreBold:=Reg.ReadBool('Ignore strong'); Converter.IgnoreItalic:=Reg.ReadBool('Ignore emphasis'); end; SettingsLoaded:=True; Finally Reg.Free; end; end; Converter.Convert(document,filename); end; procedure TFB2AnyQuickExport.Setup(hWnd: Integer; appName: OleVariant); begin with TQuickExportSetupForm.CreateWithForeighnParent(hWnd,appName) do Begin ShowModal; Free; end; end; initialization TAutoObjectFactory.Create(ComServer, TFB2AnyQuickExport, Class_FB2AnyQuickExport, ciMultiInstance, tmApartment); end.
unit TTSCITMTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSCITMRecord = record PLenderNum: String[4]; PCollCode: String[8]; PTrackCode: String[8]; PModCount: Integer; PCritical: Boolean; PCIFDate: String[8]; End; TTTSCITMBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSCITMRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSCITM = (TTSCITMPrimaryKey, TTSCITMbyTrackCode); TTTSCITMTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCollCode: TStringField; FDFTrackCode: TStringField; FDFModCount: TIntegerField; FDFCritical: TBooleanField; FDFCIFDate: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCollCode(const Value: String); function GetPCollCode:String; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPCritical(const Value: Boolean); function GetPCritical:Boolean; procedure SetPCIFDate(const Value: String); function GetPCIFDate:String; procedure SetEnumIndex(Value: TEITTSCITM); function GetEnumIndex: TEITTSCITM; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSCITMRecord; procedure StoreDataBuffer(ABuffer:TTTSCITMRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCollCode: TStringField read FDFCollCode; property DFTrackCode: TStringField read FDFTrackCode; property DFModCount: TIntegerField read FDFModCount; property DFCritical: TBooleanField read FDFCritical; property DFCIFDate: TStringField read FDFCIFDate; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCollCode: String read GetPCollCode write SetPCollCode; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PModCount: Integer read GetPModCount write SetPModCount; property PCritical: Boolean read GetPCritical write SetPCritical; property PCIFDate: String read GetPCIFDate write SetPCIFDate; published property Active write SetActive; property EnumIndex: TEITTSCITM read GetEnumIndex write SetEnumIndex; end; { TTTSCITMTable } procedure Register; implementation procedure TTTSCITMTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCollCode := CreateField( 'CollCode' ) as TStringField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFCritical := CreateField( 'Critical' ) as TBooleanField; FDFCIFDate := CreateField( 'CIFDate' ) as TStringField; end; { TTTSCITMTable.CreateFields } procedure TTTSCITMTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSCITMTable.SetActive } procedure TTTSCITMTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSCITMTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSCITMTable.SetPCollCode(const Value: String); begin DFCollCode.Value := Value; end; function TTTSCITMTable.GetPCollCode:String; begin result := DFCollCode.Value; end; procedure TTTSCITMTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSCITMTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSCITMTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSCITMTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSCITMTable.SetPCritical(const Value: Boolean); begin DFCritical.Value := Value; end; function TTTSCITMTable.GetPCritical:Boolean; begin result := DFCritical.Value; end; procedure TTTSCITMTable.SetPCIFDate(const Value: String); begin DFCIFDate.Value := Value; end; function TTTSCITMTable.GetPCIFDate:String; begin result := DFCIFDate.Value; end; procedure TTTSCITMTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CollCode, String, 8, N'); Add('TrackCode, String, 8, N'); Add('ModCount, Integer, 0, N'); Add('Critical, Boolean, 0, N'); Add('CIFDate, String, 8, N'); end; end; procedure TTTSCITMTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CollCode;TrackCode, Y, Y, N, N'); Add('byTrackCode, LenderNum;TrackCode, N, N, Y, N'); end; end; procedure TTTSCITMTable.SetEnumIndex(Value: TEITTSCITM); begin case Value of TTSCITMPrimaryKey : IndexName := ''; TTSCITMbyTrackCode : IndexName := 'byTrackCode'; end; end; function TTTSCITMTable.GetDataBuffer:TTTSCITMRecord; var buf: TTTSCITMRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCollCode := DFCollCode.Value; buf.PTrackCode := DFTrackCode.Value; buf.PModCount := DFModCount.Value; buf.PCritical := DFCritical.Value; buf.PCIFDate := DFCIFDate.Value; result := buf; end; procedure TTTSCITMTable.StoreDataBuffer(ABuffer:TTTSCITMRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCollCode.Value := ABuffer.PCollCode; DFTrackCode.Value := ABuffer.PTrackCode; DFModCount.Value := ABuffer.PModCount; DFCritical.Value := ABuffer.PCritical; DFCIFDate.Value := ABuffer.PCIFDate; end; function TTTSCITMTable.GetEnumIndex: TEITTSCITM; var iname : string; begin result := TTSCITMPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSCITMPrimaryKey; if iname = 'BYTRACKCODE' then result := TTSCITMbyTrackCode; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSCITMTable, TTTSCITMBuffer ] ); end; { Register } function TTTSCITMBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('LENDERNUM','COLLCODE','TRACKCODE','MODCOUNT','CRITICAL','CIFDATE' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TTTSCITMBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftBoolean; 6 : result := ftString; end; end; function TTTSCITMBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCollCode; 3 : result := @Data.PTrackCode; 4 : result := @Data.PModCount; 5 : result := @Data.PCritical; 6 : result := @Data.PCIFDate; end; end; end.
unit kwPopComboBoxIndexOf; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopComboBoxIndexOf.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ControlsProcessing::pop_ComboBox_IndexOf // // *Формат:* // {code} // aStr aControlObj pop:ComboBox:IndexOf // {code} // *Описание:* Возвращает номер строки в выпадающем списке TComboBox. Если такой нет, то // возвращается -1 // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses StdCtrls, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} TkwPopComboBoxIndexOf = {final} class(_kwComboBoxFromStack_) {* *Формат:* [code] aStr aControlObj pop:ComboBox:IndexOf [code] *Описание:* Возвращает номер строки в выпадающем списке TComboBox. Если такой нет, то возвращается -1 } protected // realized methods procedure DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopComboBoxIndexOf {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopComboBoxIndexOf; {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} // start class TkwPopComboBoxIndexOf procedure TkwPopComboBoxIndexOf.DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); //#UC START# *5049C8740203_5049D3E90186_var* var l_String: AnsiString; //#UC END# *5049C8740203_5049D3E90186_var* begin //#UC START# *5049C8740203_5049D3E90186_impl* if aCtx.rEngine.IsTopString then begin l_String := aCtx.rEngine.PopDelphiString; aCtx.rEngine.PushInt(aCombobox.Items.IndexOf(l_String)) end else Assert(False, 'Не задана строка для поиска в Combobox'); //#UC END# *5049C8740203_5049D3E90186_impl* end;//TkwPopComboBoxIndexOf.DoWithComboBox class function TkwPopComboBoxIndexOf.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:ComboBox:IndexOf'; end;//TkwPopComboBoxIndexOf.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} {$IfEnd} //not NoScripts end.
unit Bird.Socket.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxGDIPlusClasses, Vcl.ExtCtrls, Vcl.StdCtrls, Bird.Socket; type TFrmMainMenu = class(TForm) Panel7: TPanel; imgHeader: TImage; imgClose: TImage; Panel1: TPanel; lblServer: TLabel; edtServer: TEdit; btnStop: TButton; btnStart: TButton; ListBoxLog: TListBox; lblClients: TLabel; cbxClients: TComboBox; edtMessage: TEdit; btnSend: TButton; lblMessage: TLabel; procedure imgCloseClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnSendClick(Sender: TObject); private FBirdSocket: TBirdSocket; procedure HandlerButtons(const AConnected: Boolean); end; var FrmMainMenu: TFrmMainMenu; implementation {$R *.dfm} procedure TFrmMainMenu.btnClearClick(Sender: TObject); begin ListBoxLog.Clear; end; procedure TFrmMainMenu.btnSendClick(Sender: TObject); var LBird: TBirdSocketConnection; begin for LBird in FBirdSocket.Birds.Items do begin if (LBird.Id.ToString = cbxClients.Text) then begin LBird.Send(edtMessage.Text); Break; end; end; end; procedure TFrmMainMenu.btnStartClick(Sender: TObject); begin FBirdSocket.Start; HandlerButtons(True); end; procedure TFrmMainMenu.btnStopClick(Sender: TObject); begin if FBirdSocket.Active then FBirdSocket.Stop; HandlerButtons(False); end; procedure TFrmMainMenu.FormCreate(Sender: TObject); begin FBirdSocket := TBirdSocket.Create(8080); FBirdSocket.AddEventListener(TEventType.CONNECT, procedure(const ABird: TBirdSocketConnection) begin ListBoxLog.Items.Add(Format('Client %s connected.', [ABird.IPAdress])); cbxClients.Items.Add(ABird.Id.ToString); end); FBirdSocket.AddEventListener(TEventType.EXECUTE, procedure(const ABird: TBirdSocketConnection) var LMessage: string; begin LMessage := ABird.WaitMessage; if LMessage.Trim.Equals('ping') then ABird.Send('pong') else if LMessage.Trim.IsEmpty then ABird.Send('empty message') else ABird.Send(Format('message received: "%s"', [LMessage])); ListBoxLog.Items.Add(Format('Message received from %s: %s.', [ABird.IPAdress, LMessage])); end); FBirdSocket.AddEventListener(TEventType.DISCONNECT, procedure(const ABird: TBirdSocketConnection) var I: Integer; begin ListBoxLog.Items.Add(Format('Client %s disconnected.', [ABird.IPAdress])); for I := 0 to Pred(cbxClients.Items.Count) do if (cbxClients.Items[I] = ABird.Id.ToString) then begin cbxClients.Items.Delete(I); Break; end; end); HandlerButtons(False); end; procedure TFrmMainMenu.FormDestroy(Sender: TObject); begin FBirdSocket.Free; end; procedure TFrmMainMenu.HandlerButtons(const AConnected: Boolean); begin btnStop.Enabled := AConnected; btnStart.Enabled := not(AConnected); end; procedure TFrmMainMenu.imgCloseClick(Sender: TObject); begin Close; end; end.
unit Thread.EDIClient; interface uses System.Classes, Control.Entregas, Control.PlanilhaEntradaTFO, System.SysUtils, System.DateUtils, Control.VerbasExpressas, Control.Bases, Control.EntregadoresExpressas, Generics.Collections, System.StrUtils, Control.PlanilhaEntradaDIRECT, Control.PlanilhaEntradaSimExpress, Control.ControleAWB, Control.PlanilhaBaixasTFO, Control.PlanilhaBaixasDIRECT; type Thread_ImportEDIClient = class(TThread) private FTotalRegistros: Integer; FCliente: Integer; FTotalInconsistencias: Integer; FTotalGravados: Integer; FCancelar: Boolean; FLog: String; FProgresso: Double; FArquivo: String; FProcesso: Boolean; FTipoProcesso: integer; FLoja: boolean; aParam: Array of variant; iPos : Integer; dVerba: Double; sMensagem: String; FEntregas: TEntregasControl; FVerbas: TVerbasExpressasControl; FBases: TBasesControl; FEntregadores: TEntregadoresExpressasControl; FControleAWB : TControleAWBControl; procedure UpdateLOG(sMensagem: String); procedure ProcessTFO; procedure ProcessSIM; procedure ProcessDIRECT; procedure BaixaTFO; procedure BaixaDIRECT; function RetornaVerba(aParam: array of variant): double; function RetornaAgente(iEntregador: integer): integer; function RetornaAgenteDocumento(sChave: String): integer; function RetornaEntregadorDocumento(SChave: string): integer; protected procedure Execute; override; public property Arquivo: String read FArquivo write FArquivo; property Processo: Boolean read FProcesso write FProcesso; property Log: String read FLog write FLog; property Progresso: Double read FProgresso write FProgresso; property TotalRegistros: Integer read FTotalRegistros write FTotalRegistros; property TotalGravados: Integer read FTotalGravados write FTotalGravados; property TotalInconsistencias: Integer read FTotalInconsistencias write FTotalInconsistencias; property Cliente: Integer read FCliente write FCliente; property Cancelar: Boolean read FCancelar write FCancelar; property TipoProcesso : integer read FTipoProcesso write FTipoProcesso; property Loja: boolean read FLoja write FLoja; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_ImportEDIClient.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.ENum, Global.Parametros; { Thread_ImportEDIClient } procedure Thread_ImportEDIClient.BaixaDIRECT; var FPlanilha : TPlanilhaBaixasDIRECTControl; i: integer; dPeso: double; begin try try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaBaixasDIRECTControl.Create; FEntregadores := TEntregadoresExpressasControl.Create; FEntregas := TEntregasControl.Create; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Preparando a importação. Aguarde...'; UpdateLog(sMensagem); if not FPLanilha.GetPlanilha(FArquivo) then begin UpdateLOG(FPlanilha.Planilha.MensagemProcesso); FCancelar := True; Exit; end; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Iniciando a importação das baixas do arquivo ' + FArquivo + '. Aguarde...'; UpdateLog(sMensagem); iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin FEntregas := TEntregasControl.Create; SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].Remessa, FCliente]; if not FEntregas.LocalizarExata(aParam) then begin if UpperCase(FPlanilha.Planilha.Planilha[iPos].Tipo) = 'REVERSA' then begin FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].Remessa; FEntregas.Entregas.Distribuidor := RetornaAgenteDocumento(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Entregador := RetornaEntregadorDocumento(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NF; FEntregas.Entregas.Consumidor := 'REVERSA'; FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Municipio; FEntregas.Entregas.Cep :=FPlanilha.Planilha.Planilha[i].CEP; FEntregas.Entregas.Expedicao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Previsao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Volumes := 1; FEntregas.Entregas.Atribuicao := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixa := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixado := 'S'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.TipoPeso := FPlanilha.Planilha.Planilha[i].Tipo; FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; FEntregas.Entregas.PesoFranquia := FPlanilha.Planilha.Planilha[i].PesoAferido; FEntregas.Entregas.PesoCobrado := 0; FEntregas.Entregas.Advalorem := 0; FEntregas.Entregas.PagoFranquia := 0; FEntregas.Entregas.VerbaEntregador := 0; FEntregas.Entregas.Extrato := '0'; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.Recebimento := StrToDate('30/12/1899'); FEntregas.Entregas.Recebido := 'S'; FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[i].Pedido; FEntregas.Entregas.CodCliente := FCliente; Finalize(aParam); dPeso := 0; if FEntregas.Entregas.PesoCobrado > 0 then dPeso := FEntregas.Entregas.PesoCobrado else if FEntregas.Entregas.PesoFranquia > 0 then dPeso := FEntregas.Entregas.PesoFranquia else dPeso := FEntregas.Entregas.PesoReal; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, dPeso, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); FEntregas.Entregas.Acao := tacIncluir; Finalize(aParam); if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) +' - Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não encontrada !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Erro ao gravar o Remessa ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end; end else begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Entrega NN ' + FPlanilha.Planilha.Planilha[i].Remessa + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não encontrada no banco de dados !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end; end else begin FEntregas.Entregas.Distribuidor := RetornaAgenteDocumento(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Entregador := RetornaEntregadorDocumento(FPlanilha.Planilha.Planilha[i].Documento); FEntregas.Entregas.Baixa := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Baixado := 'S'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := FPlanilha.Planilha.Planilha[i].DataAtualizacao; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; FEntregas.Entregas.PesoFranquia := FPlanilha.Planilha.Planilha[i].PesoAferido; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.TipoPeso := 'Entrega'; Finalize(aParam); dPeso := 0; if FEntregas.Entregas.PesoCobrado > 0 then dPeso := FEntregas.Entregas.PesoCobrado else if FEntregas.Entregas.PesoFranquia > 0 then dPeso := FEntregas.Entregas.PesoFranquia else dPeso := FEntregas.Entregas.PesoReal; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, dPeso, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); Finalize(aParam); if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não encontrada !'; UpdateLog(sMensagem); end else begin if FLoja then begin if FPlanilha.Planilha.Planilha[i].Loja = 'S' then begin dVerba := FEntregas.Entregas.VerbaEntregador; FEntregas.Entregas.VerbaEntregador := (dVerba / 2); FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.TipoPeso := 'Loja'; end; end; end; FEntregas.Entregas.Acao := tacAlterar; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Erro ao gravar a Remessa ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; Except on E: Exception do begin sMensagem := '>> ** ERROR BAIXA DIRECT **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); FProcesso := False; FCancelar := True; end; end; finally FPlanilha.Free; FEntregas.Free; FEntregadores.Free; end; end; procedure Thread_ImportEDIClient.BaixaTFO; var FPlanilha : TPlanilhaBaixasTFOControl; i: integer; begin try try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaBaixasTFOControl.Create; FEntregadores := TEntregadoresExpressasControl.Create; FEntregas := TEntregasControl.Create; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Preparando a importação. Aguarde...'; UpdateLog(sMensagem); if not FPLanilha.GetPlanilha(FArquivo) then begin UpdateLOG(FPlanilha.Planilha.MensagemProcesso); FCancelar := True; Exit; end; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Iniciando a importação das baixas do arquivo ' + FArquivo + '. Aguarde...'; UpdateLog(sMensagem); iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].NNRemessa, FCliente]; if FEntregas.LocalizarExata(aParam) then begin FEntregas.Entregas.Distribuidor := RetornaAgente(FPlanilha.Planilha.Planilha[i].CodigoEntregador); if FPlanilha.Planilha.Planilha[i].CodigoEntregador <> 0 then FEntregas.Entregas.Entregador := FPlanilha.Planilha.Planilha[i].CodigoEntregador else FEntregas.Entregas.Entregador := 781; FEntregas.Entregas.Baixa := FPlanilha.Planilha.Planilha[i].DataDigitacao; FEntregas.Entregas.Baixado := 'S'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := FPlanilha.Planilha.Planilha[i].DataEntrega; if FPlanilha.Planilha.Planilha[i].DataEntrega < FPlanilha.Planilha.Planilha[i].DataDigitacao then begin FEntregas.Entregas.Atraso := DaysBetween(FPlanilha.Planilha.Planilha[iPos].DataDigitacao, FPlanilha.Planilha.Planilha[iPos].DataEntrega); end; FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[I].PesoCobrado; FEntregas.Entregas.PesoCobrado := FPlanilha.Planilha.Planilha[I].PesoCobrado; Fentregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[I].NumeroPedido; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, FEntregas.Entregas.PesoReal, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); Finalize(aParam); // se a verba for zerada, registra no log if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].NomeEntregador + ' não encontrada !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.Acao := tacAlterar; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Erro ao gravar o NN ' + Fentregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; end else begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', now) + ' - Entrega NN ' + FPlanilha.Planilha.Planilha[i].NNRemessa + ' do entregador ' + FPlanilha.Planilha.Planilha[i].NomeEntregador + ' não encontrada no banco de dados !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; Except on E: Exception do begin sMensagem := '>> ** ERROR BAIXA TFO **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); FProcesso := False; FCancelar := True; end; end; finally FPlanilha.Free; FEntregas.Free; FEntregadores.Free; end; end; procedure Thread_ImportEDIClient.Execute; begin if FTipoProcesso = 1 then begin case FCliente of 1 : ProcessTFO; 2 : ProcessSIM; 4 : ProcessDIRECT; 5 : ProcessSIM; else begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Rotina não implementada para este Cliente! Processamento cancelado.'; UpdateLOG(sMensagem); FCancelar := True; end; end; end else if FTipoProcesso = 2 then begin case FCliente of 1 : BaixaTFO; 4 : BaixaDIRECT; else begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Rotina não implementada para este Cliente! Processamento cancelado.'; UpdateLOG(sMensagem); FCancelar := True; end; end; end else begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Tipo de processamento inválido! Processamento cancelado.'; UpdateLOG(sMensagem); FCancelar := True; end; end; procedure Thread_ImportEDIClient.ProcessDIRECT; var FPlanilha : TPlanilhaEntradaDIRECTControl; iTipo, i : integer; sOperacao : string; dPeso: double; begin try try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaEntradaDIRECTControl.Create; FEntregas := TEntregasControl.Create; FControleAWB := TControleAWBControl.Create; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Preparando a importação. Aguarde...'; UpdateLog(sMensagem); if not FPLanilha.GetPlanilha(FArquivo) then begin UpdateLOG(FPlanilha.Planilha.Mensagem); FCancelar := True; Exit; end; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Iniciando a importação do arquivo ' + FArquivo + '. Aguarde...'; UpdateLog(sMensagem); iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].Remessa, FCliente]; if not FEntregas.LocalizarExata(aParam) then begin FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].Remessa; FEntregas.Entregas.Distribuidor := 0; FEntregas.Entregas.Entregador := 0; FEntregas.Entregas.Cliente := FPlanilha.Planilha.Planilha[i].CodigoEmbarcador; FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NF; FEntregas.Entregas.Consumidor := FPlanilha.Planilha.Planilha[i].NomeConsumidor; FEntregas.Entregas.Endereco := ''; FEntregas.Entregas.Complemento := ''; FEntregas.Entregas.Bairro := FPlanilha.Planilha.Planilha[i].Bairro; FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Municipio; FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[i].CEP; FEntregas.Entregas.Telefone := ''; FEntregas.Entregas.Expedicao := FPlanilha.Planilha.Planilha[i].DataRegistro; FEntregas.Entregas.Previsao := IncDay(FPlanilha.Planilha.Planilha[i].DataChegadaLM, 1); FEntregas.Entregas.Volumes := FPlanilha.Planilha.Planilha[i].Volumes; FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899'); FEntregas.Entregas.Baixa := StrToDate('30/12/1899'); FEntregas.Entregas.Baixado := 'N'; FEntregas.Entregas.Pagamento := StrToDate('30/12/1899'); FEntregas.Entregas.Pago := 'N'; FEntregas.Entregas.Fechado := 'N'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := StrToDate('30/12/1899'); FEntregas.Entregas.TipoPeso := FPlanilha.Planilha.Planilha[i].Tipo; dPeso := 0; if FPlanilha.Planilha.Planilha[i].PesoCubado > FPlanilha.Planilha.Planilha[i].PesoNominal then begin FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoCubado; end else begin FEntregas.Entregas.PesoReal := FPlanilha.Planilha.Planilha[i].PesoNominal; end; dPeso := FEntregas.Entregas.PesoReal; FEntregas.Entregas.PesoFranquia := 0; FEntregas.Entregas.Advalorem := 0; FEntregas.Entregas.PagoFranquia := 0; FEntregas.Entregas.VerbaEntregador := 0; FEntregas.Entregas.Extrato := '0'; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.PesoCobrado := FEntregas.Entregas.PesoReal; FEntregas.Entregas.Recebimento := StrToDate('30/12/1899'); FEntregas.Entregas.Recebido := 'N'; FEntregas.Entregas.CTRC := 0; FEntregas.Entregas.Manifesto := 0; FEntregas.Entregas.Rastreio := ''; FEntregas.Entregas.VerbaFranquia := 0; FEntregas.Entregas.Lote := 0; FEntregas.Entregas.Retorno := FPlanilha.Planilha.Planilha[i].Chave; FEntregas.Entregas.Credito := StrToDate('30/12/1899');; FEntregas.Entregas.Creditado := 'N'; FEntregas.Entregas.Container := '0'; FEntregas.Entregas.ValorProduto := FPlanilha.Planilha.Planilha[i].Valor; FEntregas.Entregas.Altura := 0; FEntregas.Entregas.Largura := 0; FEntregas.Entregas.Comprimento := 0; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899'); FEntregas.Entregas.Conferido := 0; FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[i].Pedido; FEntregas.Entregas.CodCliente := FCliente; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Rastreio := ''; FEntregas.Entregas.Acao := tacIncluir; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Erro ao gravar o NN ' + FEntregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; end; Finalize(aParam); iTipo := 0; sOperacao := ''; if Pos('- TD -', FPlanilha.Planilha.Planilha[iPos].Operacao) > 0 then begin sOperacao := 'TD'; end else if Pos('- TC -', FPlanilha.Planilha.Planilha[iPos].Operacao) > 0 then begin sOperacao := 'TC'; end; SetLength(aParam, 3); aParam := ['REMESSAAWB1', FPlanilha.Planilha.Planilha[iPos].Remessa,FPlanilha.Planilha.Planilha[iPos].AWB1]; if not FControleAWB.LocalizarExato(aParam) then begin FControleAWB.ControleAWB.Remessa := FPlanilha.Planilha.Planilha[iPos].Remessa; FControleAWB.ControleAWB.AWB1 := FPlanilha.Planilha.Planilha[iPos].AWB1; FControleAWB.ControleAWB.AWB2 := FPlanilha.Planilha.Planilha[iPos].AWB2; FControleAWB.ControleAWB.CEP := ReplaceStr(FPlanilha.Planilha.Planilha[iPos].CEP,'-',''); FControleAWB.ControleAWB.Operacao := sOperacao; FControleAWB.ControleAWB.Tipo := iTipo; FControleAWB.ControleAWB.Peso := dPeso; FControleAWB.ControleAWB.Acao := tacIncluir; if not FControleAWB.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Erro ao gravar o AWB ' + FControleAWB.ControleAWB.AWB1 + ' !'; UpdateLog(sMensagem); end; end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; Except on E: Exception do begin sMensagem := '>> ** ERROR DIRECT**' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); FProcesso := False; FCancelar := True; end; end; finally FPlanilha.Free; FEntregas.Free; FControleAWB.Free; end; end; procedure Thread_ImportEDIClient.ProcessSIM; var FPlanilha : TPlanilhaEntradaSimExpressControl; i: integer; begin try try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaEntradaSimExpressControl.Create; FEntregadores := TEntregadoresExpressasControl.Create; FEntregas := TEntregasControl.Create; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Preparando a importação. Aguarde...'; UpdateLog(sMensagem); if not FPLanilha.GetPlanilha(FArquivo) then begin UpdateLOG(FPlanilha.Planilha.Mensagem); FCancelar := True; Exit; end; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Iniciando a importação do arquivo ' + FArquivo + '. Aguarde...'; UpdateLog(sMensagem); iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].IDPedido, FCliente]; if not FEntregas.LocalizarExata(aParam) then begin FEntregas.Entregas.Acao := tacIncluir; end else begin FEntregas.Entregas.Acao := tacAlterar; end; Finalize(aParam); SetLength(aParam,3); aParam := ['CHAVECLIENTE', FPlanilha.Planilha.Planilha[i].IdMotorista, FCliente]; if not FEntregadores.LocalizarExato(aParam) then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Entregador não encontrado ' + FPlanilha.Planilha.Planilha[i].Motorista; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); FEntregas.Entregas.Distribuidor := 1; FEntregas.Entregas.Entregador := 781; end else begin FEntregas.Entregas.Distribuidor := FEntregadores.Entregadores.Agente; FEntregas.Entregas.Entregador := Fentregadores.Entregadores.Entregador; end; Finalize(aParam); FEntregas.Entregas.Cliente := 0; FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].IDPedido; FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[I].NF; FEntregas.Entregas.Consumidor := LeftStr(FPlanilha.Planilha.Planilha[I].Destinatario,70); FEntregas.Entregas.Retorno := FormatFloat('00000000000', StrToIntDef(FPlanilha.Planilha.Planilha[i].NREntrega,0)); FEntregas.Entregas.Endereco := LeftStr(FPlanilha.Planilha.Planilha[I].Endereco,70); FEntregas.Entregas.Complemento := ''; FEntregas.Entregas.Bairro := LeftStr(FPlanilha.Planilha.Planilha[I].Bairro, 70); FEntregas.Entregas.Cidade := LeftStr(FPlanilha.Planilha.Planilha[I].Municipio,70); FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[I].CEP; FEntregas.Entregas.Telefone := ''; if FPlanilha.Planilha.Planilha[I].Coleta <> '00/00/0000' then FEntregas.Entregas.Expedicao := StrToDate(FPlanilha.Planilha.Planilha[I].Coleta); FEntregas.Entregas.Previsao := StrToDate(FPlanilha.Planilha.Planilha[I].Viagem); FEntregas.Entregas.Status := 0; if FPlanilha.Planilha.Planilha[i].Ocorrencia = 'REALIZADA' then begin FEntregas.Entregas.Baixa := StrToDate(FPlanilha.Planilha.Planilha[i].DataEntrega); FEntregas.Entregas.Entrega := StrToDate(FPlanilha.Planilha.Planilha[i].DataEntrega); FEntregas.Entregas.Baixado := 'S'; if FEntregas.Entregas.Previsao < FEntregas.Entregas.Entrega then begin FEntregas.Entregas.Atraso := DaysBetween(FEntregas.Entregas.Previsao,FEntregas.Entregas.Entrega); end else begin FEntregas.Entregas.Atraso := 0; end; SetLength(aParam,7); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, FEntregas.Entregas.PesoReal, FEntregas.Entregas.Baixa, 0, 0]; FEntregas.Entregas.VerbaEntregador := RetornaVerba(aParam); Finalize(aParam); if FEntregas.Entregas.VerbaEntregador = 0 then begin sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + 'Verba do NN ' + FEntregas.Entregas.NN + ' do entregador ' + FPlanilha.Planilha.Planilha[i].Motorista + ' não encontrada !'; UpdateLog(sMensagem); if FEntregas.Entregas.Entregador <> 781 then Inc(FTotalInconsistencias,1); end; end else begin FEntregas.Entregas.Baixado := 'N'; end; FEntregas.Entregas.VerbaFranquia := 0; FEntregas.Entregas.PesoReal := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0); FEntregas.Entregas.PesoCobrado := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0); FEntregas.Entregas.Volumes := StrToInt(FPlanilha.Planilha.Planilha[I].Volumes); FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.Container := '0'; FEntregas.Entregas.ValorProduto := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Valor,0); FEntregas.Entregas.Atribuicao := StrToDate(FPlanilha.Planilha.Planilha[I].Viagem); FEntregas.Entregas.Altura := 0; FEntregas.Entregas.Largura := 0; FEntregas.Entregas.Comprimento := 0; FEntregas.Entregas.Rastreio := ''; FEntregas.Entregas.Pedido := FPlanilha.Planilha.Planilha[I].Pedido; FEntregas.Entregas.CodCliente := FCliente; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy-mm-dd hh:mm:ss', Now) + ' - Erro ao gravar o NN ' + FEntregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; Except on E: Exception do begin sMensagem := '>> ** ERROR SIM EXPRESS **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); FProcesso := False; FCancelar := True; end; end; finally FPlanilha.Free; FEntregas.Free; FEntregadores.Free; end; end; procedure Thread_ImportEDIClient.ProcessTFO; var FPlanilha : TPlanilhaEntradaTFOControl; i: integer; begin try try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaEntradaTFOControl.Create; FEntregas := TEntregasControl.Create; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Preparando a importação. Aguarde...'; UpdateLog(sMensagem); if not FPLanilha.GetPlanilha(FArquivo) then begin UpdateLOG(FPlanilha.Planilha.MensagemProcesso); FCancelar := True; Exit; end; sMensagem := '>> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' - Iniciando a importação do arquivo ' + FArquivo + '. Aguarde...'; UpdateLog(sMensagem); iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].NossoNumero, FCliente]; if not FEntregas.LocalizarExata(aParam) then begin FEntregas.Entregas.NN := FPlanilha.Planilha.Planilha[i].NossoNumero; FEntregas.Entregas.Distribuidor := 0; FEntregas.Entregas.Entregador := 0; FEntregas.Entregas.Cliente := StrToIntDef(FPlanilha.Planilha.Planilha[i].CodigoCliente,0); FEntregas.Entregas.NF := FPlanilha.Planilha.Planilha[i].NumeroNF; FEntregas.Entregas.Consumidor := FPlanilha.Planilha.Planilha[i].NomeConsumidor; FEntregas.Entregas.Endereco := FPlanilha.Planilha.Planilha[i].Logradouro; FEntregas.Entregas.Complemento := Copy(FPlanilha.Planilha.Planilha[i].Complemento + ' - ' + FPlanilha.Planilha.Planilha[i].AosCuidados,1,70); FEntregas.Entregas.Bairro := FPlanilha.Planilha.Planilha[i].Bairro; FEntregas.Entregas.Cidade := FPlanilha.Planilha.Planilha[i].Cidade; FEntregas.Entregas.Cep := FPlanilha.Planilha.Planilha[i].CEP; FEntregas.Entregas.Telefone := Copy(FPlanilha.Planilha.Planilha[i].Telefone,1,30); FEntregas.Entregas.Expedicao := StrToDateDef(FPlanilha.Planilha.Planilha[i].Expedicao, StrToDate('30/12/1899')); FEntregas.Entregas.Previsao := StrToDateDef(FPlanilha.Planilha.Planilha[i].Previsao, StrToDate('30/12/1899')); FEntregas.Entregas.Volumes := StrToIntDef(FPlanilha.Planilha.Planilha[i].Volume,1); FEntregas.Entregas.Atribuicao := StrToDate('30/12/1899'); FEntregas.Entregas.Baixa := StrToDate('30/12/1899'); FEntregas.Entregas.Baixado := 'N'; FEntregas.Entregas.Pagamento := StrToDate('30/12/1899'); FEntregas.Entregas.Pago := 'N'; FEntregas.Entregas.Fechado := 'N'; FEntregas.Entregas.Status := 0; FEntregas.Entregas.Entrega := StrToDate('30/12/1899'); FPlanilha.Planilha.Planilha[I].Peso := ReplaceStr(FPlanilha.Planilha.Planilha[I].Peso, ' KG', ''); FPlanilha.Planilha.Planilha[I].Peso := ReplaceStr(FPlanilha.Planilha.Planilha[I].Peso, '.', ','); FEntregas.Entregas.PesoReal := StrToFloatDef(FPlanilha.Planilha.Planilha[I].Peso,0); FEntregas.Entregas.TipoPeso := ''; FEntregas.Entregas.PesoFranquia := 0; FEntregas.Entregas.Advalorem := 0; FEntregas.Entregas.PagoFranquia := 0; FEntregas.Entregas.VerbaEntregador := 0; FEntregas.Entregas.Extrato := '0'; FEntregas.Entregas.Atraso := 0; FEntregas.Entregas.VolumesExtra := 0; FEntregas.Entregas.ValorVolumes := 0; FEntregas.Entregas.PesoCobrado := 0; FEntregas.Entregas.Recebimento := StrToDate('30/12/1899'); FEntregas.Entregas.Recebido := 'N'; FEntregas.Entregas.CTRC := 0; FEntregas.Entregas.Manifesto := 0; FEntregas.Entregas.Rastreio := ''; FPlanilha.Planilha.Planilha[I].ValorVerba := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorVerba, 'R$ ', ''); FEntregas.Entregas.VerbaFranquia := StrToFloatDef(FPlanilha.Planilha.Planilha[I].ValorVerba, 0); FEntregas.Entregas.Lote := 0; FEntregas.Entregas.Retorno := ''; FEntregas.Entregas.Credito := StrToDate('30/12/1899');; FEntregas.Entregas.Creditado := 'N'; FEntregas.Entregas.Container :=FPlanilha.Planilha.Planilha[I].Container; FPlanilha.Planilha.Planilha[I].ValorProuto := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorProuto, 'R$ ', ''); FPlanilha.Planilha.Planilha[I].ValorProuto := ReplaceStr(FPlanilha.Planilha.Planilha[I].ValorProuto, '.', ''); FEntregas.Entregas.ValorProduto := StrToFloatDef(FPlanilha.Planilha.Planilha[i].ValorProuto, 0); FEntregas.Entregas.Altura := StrToIntDef(FPlanilha.Planilha.Planilha[I].Altura, 0); FEntregas.Entregas.Largura := StrToIntDef(FPlanilha.Planilha.Planilha[I].Largura, 0);; FEntregas.Entregas.Comprimento := StrToIntDef(FPlanilha.Planilha.Planilha[I].Comprimento, 0);; FEntregas.Entregas.CodigoFeedback := 0; FEntregas.Entregas.DataFeedback := StrToDate('30/12/1899'); FEntregas.Entregas.Conferido := 0; FEntregas.Entregas.Pedido := '0';; FEntregas.Entregas.CodCliente := FCliente; FEntregas.Entregas.Acao := tacIncluir; if not FEntregas.Gravar() then begin sMensagem := '>> ' + FormatDateTime('yyyy-mm-dd hh:mm:ss', now) + ' - Erro ao gravar o NN ' + FEntregas.Entregas.NN + ' !'; UpdateLog(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; Except on E: Exception do begin sMensagem := '>> ** ERROR TFO **' + Chr(13) + 'Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message; UpdateLog(sMensagem); FProcesso := False; FCancelar := True; end; end; finally FPlanilha.Free; FEntregas.Free; end; end; function Thread_ImportEDIClient.RetornaAgente(iEntregador: integer): integer; var aParam: array of variant; iRetorno: integer; begin Result := 0; iRetorno := 0; SetLength(aParam, 2); aParam := ['ENTREGADOR', iEntregador]; if FEntregadores.LocalizarExato(aParam) then begin iRetorno := FEntregadores.Entregadores.Agente; end else begin iRetorno := 1; end; Result := iRetorno; end; function Thread_ImportEDIClient.RetornaAgenteDocumento(sChave: String): integer; var aParam: array of variant; iRetorno: integer; begin Result := 0; iRetorno := 0; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam, 3); aParam := ['CHAVECLIENTE', sChave, FCliente]; if FEntregadores.LocalizarExato(aParam) then begin iRetorno := FEntregadores.Entregadores.Agente; end else begin iRetorno := 1; end; Result := iRetorno; end; function Thread_ImportEDIClient.RetornaEntregadorDocumento(SChave: string): integer; var aParam: array of variant; iRetorno: integer; begin Result := 0; iRetorno := 0; FEntregadores := TEntregadoresExpressasControl.Create; SetLength(aParam, 3); aParam := ['CHAVECLIENTE', sChave, FCliente]; if Fentregadores.LocalizarExato(aParam) then begin iRetorno := FEntregadores.Entregadores.Entregador; end else begin iRetorno := 1; end; Finalize(aParam); Result := iRetorno; end; function Thread_ImportEDIClient.RetornaVerba(aParam: array of variant): double; var iTabela, iFaixa: Integer; dVerba, dVerbaEntregador: Double; FParam: array of variant; begin try Result := 0; iTabela := 0; iFaixa := 0; dVerba := 0; dVerbaEntregador := 0; FBases := TBasesControl.Create; FVerbas := TVerbasExpressasControl.Create; // procura dos dados da base referentes à verba SetLength(FParam,2); FParam := ['CODIGO',aParam[0]]; if FBases.LocalizarExato(FParam) then begin iTabela := FBases.Bases.Tabela; iFaixa := FBases.Bases.Grupo; dVerba := FBases.Bases.ValorVerba; end; Finalize(FParam); // se a base não possui uma verba fixa, verifica se a base possui uma vinculação a uma // tabela e faixa. if dVerba = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := FCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerba := FVerbas.RetornaVerba(); end; end; end; // pesquisa a tabela de entregadores e apanha os dados referente à verba if dVerba = 0 then begin SetLength(FParam,2); FParam := ['ENTREGADOR', aParam[1]]; if not Fentregadores.Localizar(FParam).IsEmpty then begin iTabela := FEntregadores.Entregadores.Tabela; iFaixa := FEntregadores.Entregadores.Grupo; dVerbaEntregador := FEntregadores.Entregadores.Verba; end; Finalize(FParam); // verifica se o entregador possui uma verba fixa, se estiver zerada, verifica com as informações // de tabela e faixa. if dVerbaEntregador = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := FCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerbaEntregador := FVerbas.RetornaVerba(); end; end; end; if dVerbaEntregador > 0 then begin dVerba := dVerbaEntregador; end; end; Result := dVerba; finally FBases.Free; FVerbas.Free; end; end; procedure Thread_ImportEDIClient.UpdateLOG(sMensagem: String); begin if FLog <> '' then begin FLog := FLog + #13; end; FLog := FLog + sMensagem; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit MemoUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CategoryButtons, Buttons; type TMemoForm = class(TForm) InfoMemo: TMemo; HeadLabel: TLabel; YesBitBtn: TBitBtn; NoBitBtn: TBitBtn; CountLabel: TLabel; procedure YesBitBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure NoBitBtnClick(Sender: TObject); procedure FormDblClick(Sender: TObject); procedure InfoMemoChange(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } Invite: Boolean; UpDate: Boolean; Twit: Boolean; procedure UpDateVersion(M: string); procedure PostInTwitter(M: string); procedure TranslateForm; end; {$ENDREGION} var MemoForm: TMemoForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, IcqProtoUnit, VarsUnit, UtilsUnit, OverbyteIcsUrl, OverbyteIcsHttpProt, LoginUnit, ChatUnit; {$ENDREGION} {$REGION 'TranslateForm'} procedure TMemoForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); end; {$ENDREGION} {$REGION 'FormCreate'} procedure TMemoForm.FormCreate(Sender: TObject); begin TranslateForm; // Присваиваем иконку окну и кнопке MainForm.AllImageList.GetBitmap(139, NoBitBtn.Glyph); MainForm.AllImageList.GetBitmap(140, YesBitBtn.Glyph); // Помещаем кнопку формы в таскбар и делаем независимой SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; {$ENDREGION} {$REGION 'FormShow'} procedure TMemoForm.FormShow(Sender: TObject); begin // Если Твит, то ставим фокус в поле ввода if (Twit) and (InfoMemo.CanFocus) then begin InfoMemo.SetFocus; InfoMemo.SelStart := InfoMemo.GetTextLen; end; end; {$ENDREGION} {$REGION 'Other'} procedure TMemoForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; procedure TMemoForm.FormClose(Sender: TObject; var Action: TCloseAction); begin // Автоматически уничтожаем форму при закрытии Action := CaFree; MemoForm := nil; end; procedure TMemoForm.NoBitBtnClick(Sender: TObject); begin // Закрываем окно Close; end; {$ENDREGION} {$REGION 'InfoMemoChange'} procedure TMemoForm.InfoMemoChange(Sender: TObject); begin // Отображаем счётчик символов if Twit then begin CountLabel.Caption := Format(Lang_Vars[62].L_S, [InfoMemo.GetTextLen, 140]); if InfoMemo.GetTextLen > 140 then CountLabel.Font.Color := clRed else CountLabel.Font.Color := clGreen; end; end; {$ENDREGION} {$REGION 'UpDateVersion'} procedure TMemoForm.UpDateVersion(M: string); begin // Ставим иконку окну MainForm.AllImageList.GetIcon(6, Icon); // Отображаем информацию и запрос на закачку новой версии Caption := Lang_Vars[42].L_S; HeadLabel.Caption := Lang_Vars[41].L_S; CountLabel.Caption := EmptyStr; InfoMemo.Text := Lang_Vars[13].L_S + C_RN + C_RN + M; // Ставим флаги функции окна UpDate := True; Invite := False; Twit := False; // Блокируем мемо InfoMemo.readonly := True; InfoMemo.Color := ClBtnFace; end; {$ENDREGION} {$REGION 'PostInTwitter'} procedure TMemoForm.PostInTwitter(M: string); begin // Ставим иконку окну MainForm.AllImageList.GetIcon(272, Icon); // Отображаем информацию и запрос на закачку новой версии Caption := Format(Lang_Vars[61].L_S, [C_Twitter]); HeadLabel.Caption := Format(Lang_Vars[61].L_S, [C_Twitter]); InfoMemo.Text := M; // Ставим флаги функции окна UpDate := False; Invite := False; Twit := True; // Разблокируем мемо InfoMemo.ReadOnly := False; InfoMemo.Color := ClWindow; // Обновляем счётчик InfoMemoChange(nil); end; {$ENDREGION} {$REGION 'YesBitBtnClick'} procedure TMemoForm.YesBitBtnClick(Sender: TObject); // label // x; var FrmLogin: TLoginForm; begin // Автообновление if UpDate then begin // Открываем офсайт OpenURL(C_SitePage); // Закрываем это окно Close; end else if Twit then // Пост в Твиттер begin V_Twitter_PostMsg := Trim(InfoMemo.Text); if V_Twitter_PostMsg <> EmptyStr then begin // Ограничиваем длинну текста if Length(V_Twitter_PostMsg) > 140 then SetLength(V_Twitter_PostMsg, 140); // Проверяем логин Твита if (V_Twitter_Username = EmptyStr) or (V_Twitter_Password = EmptyStr) then begin FrmLogin := TLoginForm.Create(Application); try MainForm.AllImageList.GetIcon(268, FrmLogin.Icon); FrmLogin.Caption := C_Twitter; // Модально спрашиваем логин и пароль if FrmLogin.ShowModal = MrOk then begin // Сохраняем в настройках логин и пароль для Twitter if FrmLogin.SavePassCheckBox.Checked then begin end; // Запоминаем логин и пароль твиттера V_Twitter_Username := FrmLogin.AccountEdit.Text; V_Twitter_Password := FrmLogin.PasswordEdit.Text; end; finally FreeAndNil(FrmLogin); end; end; // Запускаем авторизацию в твиттер if (V_Twitter_Username <> EmptyStr) and (V_Twitter_Password <> EmptyStr) then begin // Обнуляем параметры Twitter V_Twitter_OAuth_Signature := EmptyStr; V_Twitter_OAuth_Token := EmptyStr; V_Twitter_OAuth_Token_Secret := EmptyStr; V_Twitter_Authenticity_Token := EmptyStr; V_Twitter_OAuth_PIN := EmptyStr; // Начинаем заполнение параметров V_Twitter_Params := TStringList.Create; try V_Twitter_OAuth_Consumer_Key := C_Twitter_OAuth_Consumer_Key + X_Twitter_OAuth_Consumer_Key; V_Twitter_OAuth_Nonce := C_Twitter_OAuth_Nonce + Twitter_Generate_Nonce; V_Twitter_OAuth_Timestamp := C_Twitter_OAuth_Timestamp + IntToStr(DateTimeToUnix(Now)); with V_Twitter_Params do begin Add(V_Twitter_OAuth_Consumer_Key); Add(V_Twitter_OAuth_Nonce); Add(C_Twitter_OAuth_Signature_Method); Add(V_Twitter_OAuth_Timestamp); Add(C_Twitter_OAuth_Version); end; V_Twitter_OAuth_Signature := Twitter_HMAC_SHA1_Signature(C_Twitter_Host + C_Twitter_Request_Token, C_GET, EmptyStr, V_Twitter_Params); finally V_Twitter_Params.Free; end; // Делаем запрос ключей от twitter with MainForm.TwitterClient do begin // Сбрасываем сокет если он занят чем то другим или висит Close; Abort; // Ставим флаг задания Tag := 0; // Запускаем авторизацию в Twitter URL := V_Twitter_OAuth_Signature; XLog(C_Twitter + C_BN + Log_Send, URL, C_Twitter, False); GetASync; end; end; end; // Закрываем это окно Close; end; { if RoasterForm.Roaster_Sel_Button = nil then goto x; // if Invite then begin Sini := TIniFile.Create(Mypath + 'Config.ini'); Sini.WriteString('qwe', 'Invite', Encrypt(Memo1.Text, 12345)); Sini.Free; // ICQ_SendMessage_0406(RoasterForm.Roaster_Sel_Button.UIN, Memo1.Text, true); end else begin ICQ_SendGrandAuth(RoasterForm.Roaster_Sel_Button.UIN); ICQ_ReqAuthSend(RoasterForm.Roaster_Sel_Button.UIN, Memo1.Text); end; // x: ; ModalResult := mrOk; } end; {$ENDREGION} end.
unit Form_GraphViewUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMXTee.Engine, FMXTee.Procs, FMXTee.Chart, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Data.DB, FMXTee.Series, DataFileSaver; type TForm_GraphView = class(TForm) Chart_Graph: TChart; DataSource_Graph: TDataSource; Series1: TLineSeries; BindingsList1: TBindingsList; Series2: TBarSeries; private { Private declarations } protected function GetSeriesFromField(data: TDataSet; fieldNum: Integer): TLineSeries; public procedure SetTitle(title: String); procedure SetData(data: TDataSet); overload; procedure SetData(schResult: IDataSetIterator; index: Integer); overload; end; var Form_GraphView: TForm_GraphView; implementation uses Const_SearchOptionUnit; {$R *.fmx} { TForm_GraphView } procedure TForm_GraphView.SetData(data: TDataSet); var arrSeries: array of TLineSeries; i: Integer; begin Chart_Graph.SeriesList.Clear; SetLength( arrSeries, data.FieldCount - 1 ); //좌측 Datetime 열은 제외 한다. for i := 0 to High( arrSeries ) do begin arrSeries[ i ] := GetSeriesFromField( data, i + 1 ); end; end; function TForm_GraphView.GetSeriesFromField(data: TDataSet; fieldNum: Integer): TLineSeries; var series: TLineSeries; begin series := TLineSeries.Create( nil ); series.ParentChart := Chart_Graph; series.Title := data.FieldList[ fieldNum ].FieldName; series.LegendTitle := data.FieldList[ fieldNum ].FieldName; series.XValues.DateTime := true; while data.Eof = false do begin series.AddXY( data.FieldList[ 0 ].AsDatetime, data.FieldList[ fieldNum ].AsFloat ); data.Next; end; data.First; //series.SeriesColor := TAlphaColor. result := series; end; procedure TForm_GraphView.SetData(schResult: IDataSetIterator; index: Integer); var iCount: Integer; begin iCount := -1; while schResult.MoveNext = true do begin Inc( iCount ); if iCount = index then break; end; if iCount < 0 then exit; SetData( schResult.CurData ); SetTitle( schResult.CurName ); schResult.MoveFirst; end; procedure TForm_GraphView.SetTitle(title: String); begin Chart_Graph.Title.Text[ 0 ] := title; end; end.
unit AdminFormKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы AdminForm } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Admin\AdminFormKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "AdminFormKeywordsPack" MUID: (460F76F86341) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(Admin) AND NOT Defined(NoScripts)} uses l3IntfUses , vtProportionalPanel , vtSizeablePanel , vtPanel ; {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) implementation {$If Defined(Admin) AND NOT Defined(NoScripts)} uses l3ImplUses , Admin_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_AdminForm = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы AdminForm ---- *Пример использования*: [code] 'aControl' форма::AdminForm TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_AdminForm Tkw_AdminForm_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_BackgroundPanel Tkw_AdminForm_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_BackgroundPanel_Push Tkw_AdminForm_Control_PropertyZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола PropertyZone ---- *Пример использования*: [code] контрол::PropertyZone TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_PropertyZone Tkw_AdminForm_Control_PropertyZone_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола PropertyZone ---- *Пример использования*: [code] контрол::PropertyZone:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_PropertyZone_Push Tkw_AdminForm_Control_TreeZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола TreeZone ---- *Пример использования*: [code] контрол::TreeZone TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_TreeZone Tkw_AdminForm_Control_TreeZone_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола TreeZone ---- *Пример использования*: [code] контрол::TreeZone:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AdminForm_Control_TreeZone_Push TkwCfAdminFormBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAdminForm.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtProportionalPanel; {* Реализация слова скрипта .TcfAdminForm.BackgroundPanel } 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;//TkwCfAdminFormBackgroundPanel TkwCfAdminFormPropertyZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAdminForm.PropertyZone } private function PropertyZone(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtSizeablePanel; {* Реализация слова скрипта .TcfAdminForm.PropertyZone } 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;//TkwCfAdminFormPropertyZone TkwCfAdminFormTreeZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAdminForm.TreeZone } private function TreeZone(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtPanel; {* Реализация слова скрипта .TcfAdminForm.TreeZone } 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;//TkwCfAdminFormTreeZone function Tkw_Form_AdminForm.GetString: AnsiString; begin Result := 'cfAdminForm'; end;//Tkw_Form_AdminForm.GetString class function Tkw_Form_AdminForm.GetWordNameForRegister: AnsiString; begin Result := 'форма::AdminForm'; end;//Tkw_Form_AdminForm.GetWordNameForRegister function Tkw_AdminForm_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_AdminForm_Control_BackgroundPanel.GetString class procedure Tkw_AdminForm_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtProportionalPanel); end;//Tkw_AdminForm_Control_BackgroundPanel.RegisterInEngine class function Tkw_AdminForm_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_AdminForm_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_AdminForm_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_AdminForm_Control_BackgroundPanel_Push.DoDoIt class function Tkw_AdminForm_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_AdminForm_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_AdminForm_Control_PropertyZone.GetString: AnsiString; begin Result := 'PropertyZone'; end;//Tkw_AdminForm_Control_PropertyZone.GetString class procedure Tkw_AdminForm_Control_PropertyZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtSizeablePanel); end;//Tkw_AdminForm_Control_PropertyZone.RegisterInEngine class function Tkw_AdminForm_Control_PropertyZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::PropertyZone'; end;//Tkw_AdminForm_Control_PropertyZone.GetWordNameForRegister procedure Tkw_AdminForm_Control_PropertyZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('PropertyZone'); inherited; end;//Tkw_AdminForm_Control_PropertyZone_Push.DoDoIt class function Tkw_AdminForm_Control_PropertyZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::PropertyZone:push'; end;//Tkw_AdminForm_Control_PropertyZone_Push.GetWordNameForRegister function Tkw_AdminForm_Control_TreeZone.GetString: AnsiString; begin Result := 'TreeZone'; end;//Tkw_AdminForm_Control_TreeZone.GetString class procedure Tkw_AdminForm_Control_TreeZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_AdminForm_Control_TreeZone.RegisterInEngine class function Tkw_AdminForm_Control_TreeZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TreeZone'; end;//Tkw_AdminForm_Control_TreeZone.GetWordNameForRegister procedure Tkw_AdminForm_Control_TreeZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('TreeZone'); inherited; end;//Tkw_AdminForm_Control_TreeZone_Push.DoDoIt class function Tkw_AdminForm_Control_TreeZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TreeZone:push'; end;//Tkw_AdminForm_Control_TreeZone_Push.GetWordNameForRegister function TkwCfAdminFormBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtProportionalPanel; {* Реализация слова скрипта .TcfAdminForm.BackgroundPanel } begin Result := acfAdminForm.BackgroundPanel; end;//TkwCfAdminFormBackgroundPanel.BackgroundPanel class function TkwCfAdminFormBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TcfAdminForm.BackgroundPanel'; end;//TkwCfAdminFormBackgroundPanel.GetWordNameForRegister function TkwCfAdminFormBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtProportionalPanel); end;//TkwCfAdminFormBackgroundPanel.GetResultTypeInfo function TkwCfAdminFormBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAdminFormBackgroundPanel.GetAllParamsCount function TkwCfAdminFormBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAdminForm)]); end;//TkwCfAdminFormBackgroundPanel.ParamsTypes procedure TkwCfAdminFormBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwCfAdminFormBackgroundPanel.SetValuePrim procedure TkwCfAdminFormBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_acfAdminForm: TcfAdminForm; begin try l_acfAdminForm := TcfAdminForm(aCtx.rEngine.PopObjAs(TcfAdminForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAdminForm: TcfAdminForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_acfAdminForm)); end;//TkwCfAdminFormBackgroundPanel.DoDoIt function TkwCfAdminFormPropertyZone.PropertyZone(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtSizeablePanel; {* Реализация слова скрипта .TcfAdminForm.PropertyZone } begin Result := acfAdminForm.PropertyZone; end;//TkwCfAdminFormPropertyZone.PropertyZone class function TkwCfAdminFormPropertyZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfAdminForm.PropertyZone'; end;//TkwCfAdminFormPropertyZone.GetWordNameForRegister function TkwCfAdminFormPropertyZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtSizeablePanel); end;//TkwCfAdminFormPropertyZone.GetResultTypeInfo function TkwCfAdminFormPropertyZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAdminFormPropertyZone.GetAllParamsCount function TkwCfAdminFormPropertyZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAdminForm)]); end;//TkwCfAdminFormPropertyZone.ParamsTypes procedure TkwCfAdminFormPropertyZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству PropertyZone', aCtx); end;//TkwCfAdminFormPropertyZone.SetValuePrim procedure TkwCfAdminFormPropertyZone.DoDoIt(const aCtx: TtfwContext); var l_acfAdminForm: TcfAdminForm; begin try l_acfAdminForm := TcfAdminForm(aCtx.rEngine.PopObjAs(TcfAdminForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAdminForm: TcfAdminForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(PropertyZone(aCtx, l_acfAdminForm)); end;//TkwCfAdminFormPropertyZone.DoDoIt function TkwCfAdminFormTreeZone.TreeZone(const aCtx: TtfwContext; acfAdminForm: TcfAdminForm): TvtPanel; {* Реализация слова скрипта .TcfAdminForm.TreeZone } begin Result := acfAdminForm.TreeZone; end;//TkwCfAdminFormTreeZone.TreeZone class function TkwCfAdminFormTreeZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfAdminForm.TreeZone'; end;//TkwCfAdminFormTreeZone.GetWordNameForRegister function TkwCfAdminFormTreeZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwCfAdminFormTreeZone.GetResultTypeInfo function TkwCfAdminFormTreeZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAdminFormTreeZone.GetAllParamsCount function TkwCfAdminFormTreeZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAdminForm)]); end;//TkwCfAdminFormTreeZone.ParamsTypes procedure TkwCfAdminFormTreeZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству TreeZone', aCtx); end;//TkwCfAdminFormTreeZone.SetValuePrim procedure TkwCfAdminFormTreeZone.DoDoIt(const aCtx: TtfwContext); var l_acfAdminForm: TcfAdminForm; begin try l_acfAdminForm := TcfAdminForm(aCtx.rEngine.PopObjAs(TcfAdminForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAdminForm: TcfAdminForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(TreeZone(aCtx, l_acfAdminForm)); end;//TkwCfAdminFormTreeZone.DoDoIt initialization Tkw_Form_AdminForm.RegisterInEngine; {* Регистрация Tkw_Form_AdminForm } Tkw_AdminForm_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_BackgroundPanel } Tkw_AdminForm_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_BackgroundPanel_Push } Tkw_AdminForm_Control_PropertyZone.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_PropertyZone } Tkw_AdminForm_Control_PropertyZone_Push.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_PropertyZone_Push } Tkw_AdminForm_Control_TreeZone.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_TreeZone } Tkw_AdminForm_Control_TreeZone_Push.RegisterInEngine; {* Регистрация Tkw_AdminForm_Control_TreeZone_Push } TkwCfAdminFormBackgroundPanel.RegisterInEngine; {* Регистрация cfAdminForm_BackgroundPanel } TkwCfAdminFormPropertyZone.RegisterInEngine; {* Регистрация cfAdminForm_PropertyZone } TkwCfAdminFormTreeZone.RegisterInEngine; {* Регистрация cfAdminForm_TreeZone } TtfwTypeRegistrator.RegisterType(TypeInfo(TcfAdminForm)); {* Регистрация типа TcfAdminForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtProportionalPanel)); {* Регистрация типа TvtProportionalPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSizeablePanel)); {* Регистрация типа TvtSizeablePanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm9 = class(TForm) MemColuna: TMemo; MemTabelas: TMemo; MemCondicoes: TMemo; Label1: TLabel; Label2: TLabel; Label3: TLabel; Button1: TButton; MemSQL: TMemo; Label4: TLabel; procedure Button1Click(Sender: TObject); private { private declarations } public { Public declarations } end; var Form9: TForm9; implementation uses uGeraSQL; {$R *.dfm} procedure TForm9.Button1Click(Sender: TObject); var GeradorSQL: TGeradorSQL; I: Integer; begin if (MemColuna.Lines.Count = 0) then raise Exception.Create('O campo coluna não foi preenchido!'); if (MemTabelas.Lines.Count = 0) then raise Exception.Create('O campo Tabela não foi preenchido!'); if (MemCondicoes.Lines.Count = 0) then raise Exception.Create('O campo Condição não foi preenchido!'); GeradorSQL := TGeradorSQL.Create; try for I := 0 to MemColuna.Lines.Count -1 do GeradorSQL.AdicionarColuna(MemColuna.Lines[I]); for I := 0 to MemTabelas.Lines.Count -1 do GeradorSQL.AdicionarTabela(MemTabelas.Lines[I]); for I := 0 to MemCondicoes.Lines.Count -1 do GeradorSQL.AdicionarCondicao(MemCondicoes.Lines[I]); MemSQL.Text := GeradorSQL.GerarSQL; finally GeradorSQL.Free; end; end; end.
{ Модуль компонента комбобокса журнала сообщений. } unit ICLogComboBoxEx; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ComboEx; const UNASSIGNED_DATETIME = -693594; type { Журнал сообщений в виде комбобокса. } TICLogComboBoxEx = class(TComboBoxEx) private { Максимально допустимое количество сообщений в комбобоксе. Если -1, то ограничений нет} FMaxItemCount: Integer; { Признак отображения даты-времени } FShowDateTime: Boolean; { Установить максимально допустимое количество сообщений в комбобоксе. Если -1, то ограничений нет} procedure SetMaxItemCount(Value: Integer=-1); protected { Добавить строку элемента в комбобокс @param sMessage Сообщение @param dtValue Дата-время регистрации @param iImgIndex Индекс иконки @param bAutoSelect Автоматически выбрать вновь добавленный элемент? } procedure AddItemMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME; iImgIndex: Integer=-1; bAutoSelect: Boolean=True); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Добавить информационное сообщение } procedure AddInfoMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddInfoMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Добавить отладочное сообщение } procedure AddDebugMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddDebugMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Добавить сообщение о предупреждении } procedure AddWarningMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddWarningMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Добавить сообщение об ошибке } procedure AddErrorMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddErrorMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Добавить сообщение об критической ошибке } procedure AddFatalMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddFatalMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Добавить сервисное сообщение } procedure AddServiceMsg(sMessage: AnsiString; dtValue: TDateTime=UNASSIGNED_DATETIME); procedure AddServiceMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime=UNASSIGNED_DATETIME); { Удалить строку элемента из комбобокса @param iItemIndex Индекс удаляемого элемента } procedure DelItemMsg(iItemIndex: Integer); { Удалить текущий выбранный элемент из комбобокса } procedure DelSelectedItemMsg(); { Удалить не актуальные элементы из комбобокса. Не актуальные считыются первые элементы если количество превышает MaxItemCount } procedure DelOverItems(); published { Максимально допустимое количество сообщений в комбобоксе. Свойство. Если -1, то ограничений нет} property MaxItemCount: Integer read FMaxItemCount write SetMaxItemCount; { Признак отображения даты-времени } property ShowDateTime: Boolean read FShowDateTime write FShowDateTime; end; procedure Register; implementation uses ICLogImageList; procedure Register; begin {$I iclogcomboboxex_icon.lrs} RegisterComponents('IC Tools',[TICLogComboBoxEx]); end; constructor TICLogComboBoxEx.Create(AOwner: TComponent); begin inherited; FMaxItemCount := -1; FShowDateTime := True; end; destructor TICLogComboBoxEx.Destroy; begin inherited; end; procedure TICLogComboBoxEx.SetMaxItemCount(Value: Integer); begin FMaxItemCount := Value; if FMaxItemCount > 0 then // Удаляем лишние элементы DelOverItems; end; { Добавить строку элемента в комбобокс } procedure TICLogComboBoxEx.AddItemMsg(sMessage: AnsiString; dtValue: TDateTime; iImgIndex: Integer; bAutoSelect: Boolean); var item: TComboExItem; begin if (dtValue = UNASSIGNED_DATETIME) and ShowDateTime then dtValue := Now; if Images = nil then iImgIndex := -1; if ShowDateTime then item := ItemsEx.AddItem(Format('%s %s', [FormatDateTime('YYYY-MM-DD hh:mm:ss', dtValue), sMessage]), iImgIndex) else item := ItemsEx.AddItem(sMessage, iImgIndex); if bAutoSelect then ItemIndex := item.Index; end; { Добавить информационное сообщение } procedure TICLogComboBoxEx.AddInfoMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.INFO_IMG_INDEX); end; procedure TICLogComboBoxEx.AddInfoMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddInfoMsg(Format(sMsgFmt, aArgs), dtValue); end; { Добавить отладочное сообщение } procedure TICLogComboBoxEx.AddDebugMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.DEBUG_IMG_INDEX); end; procedure TICLogComboBoxEx.AddDebugMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddDebugMsg(Format(sMsgFmt, aArgs), dtValue); end; { Добавить сообщение о предупреждении } procedure TICLogComboBoxEx.AddWarningMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.WARNING_IMG_INDEX); end; procedure TICLogComboBoxEx.AddWarningMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddWarningMsg(Format(sMsgFmt, aArgs), dtValue); end; { Добавить сообщение об ошибке } procedure TICLogComboBoxEx.AddErrorMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.ERROR_IMG_INDEX); end; procedure TICLogComboBoxEx.AddErrorMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddErrorMsg(Format(sMsgFmt, aArgs), dtValue); end; { Добавить сообщение об критической ошибке } procedure TICLogComboBoxEx.AddFatalMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.FATAL_IMG_INDEX); end; procedure TICLogComboBoxEx.AddFatalMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddFatalMsg(Format(sMsgFmt, aArgs), dtValue); end; { Добавить сервисное сообщение } procedure TICLogComboBoxEx.AddServiceMsg(sMessage: AnsiString; dtValue: TDateTime); begin AddItemMsg(sMessage, dtValue, ICLogImageList.SERVICE_IMG_INDEX); end; procedure TICLogComboBoxEx.AddServiceMsgFmt(sMsgFmt: AnsiString; const aArgs : Array Of Const; dtValue: TDateTime); begin AddServiceMsg(Format(sMsgFmt, aArgs), dtValue); end; { Удалить строку элемента из комбобокса @param iItemIndex Индекс удаляемого элемента } procedure TICLogComboBoxEx.DelItemMsg(iItemIndex: Integer); begin // Выбрать предыдущий элемент if iItemIndex = ItemIndex then if ItemIndex > 0 then ItemIndex := ItemIndex - 1; Delete(iItemIndex); end; { Удалить текущий выбранный элемент из комбобокса } procedure TICLogComboBoxEx.DelSelectedItemMsg(); var i_del: Integer; begin i_del := ItemIndex; // Выбрать предыдущий элемент if ItemIndex > 0 then ItemIndex := ItemIndex - 1; Delete(i_del); end; { Удалить не актуальные элементы из комбобокса. Не актуальные считыются первые элементы если количество превышает MaxItemCount } procedure TICLogComboBoxEx.DelOverItems(); var i, i_del, item_count: Integer; begin item_count := Items.Count; for i := 0 to item_count - 1 do begin i_del := item_count - 1 - i - MaxItemCount; if i_del >= 0 then Delete(i_del) else Break; end; end; end.
unit uDMRelUsuario; interface uses System.SysUtils, System.Classes, uDM, Data.DB, Datasnap.DBClient, ppDB, ppProd, ppClass, ppReport, ppComm, ppRelatv, ppDBPipe, ppCtrls, ppPrnabl, ppVar, ppBands, ppCache, ppDesignLayer, ppParameter, uFuncoesSIDomper, uUsuarioVO, System.Generics.Collections; type TDMRelUsuario = class(TDataModule) CDSRendimento: TClientDataSet; CDSRendimentoTipo: TStringField; CDSRendimentoUsu_Codigo: TIntegerField; CDSRendimentoUsu_Nome: TWideStringField; CDSRendimentoRev_Codigo: TIntegerField; CDSRendimentoRev_Nome: TWideStringField; CDSRendimentoQtde: TIntegerField; CDSRendimentoHoras: TFloatField; CDSRelRendimento: TClientDataSet; CDSRelRendimentoRev_Codigo: TIntegerField; CDSRelRendimentoUsu_Codigo: TIntegerField; CDSRelRendimentoUsu_Nome: TStringField; CDSRelRendimentoCha_Qtde: TFloatField; CDSRelRendimentoCha_Horas: TFloatField; CDSRelRendimentoAti_Qtde: TFloatField; CDSRelRendimentoAti_Horas: TFloatField; CDSRelRendimentoVis_Qtde: TFloatField; CDSRelRendimentoVis_Horas: TFloatField; CDSRelRendimentoSol_Horas: TFloatField; CDSRelRendimentoTotalHoras: TFloatField; CDSRelRendimentoDias: TIntegerField; CDSRelRendimentoMedia: TFloatField; CDSRendimentoValor: TCurrencyField; CDSRelRendimentoVis_Valor: TFloatField; CDSRelRendimentoRev_Nome: TStringField; dsRendimento: TDataSource; RelRendimento: TppReport; ppParameterList1: TppParameterList; ppDesignLayers1: TppDesignLayers; ppDesignLayer1: TppDesignLayer; ppHeaderBand1: TppHeaderBand; ppDetailBand1: TppDetailBand; ppSystemVariable3: TppSystemVariable; ppSystemVariable4: TppSystemVariable; plbl1: TppLabel; lblPeriodo01: TppLabel; ppSystemVariable9: TppSystemVariable; ppLabel1: TppLabel; ppLabel2: TppLabel; ppLabel3: TppLabel; ppLabel4: TppLabel; ppLine1: TppLine; ppLabel7: TppLabel; ppLabel8: TppLabel; ppLabel9: TppLabel; ppLine2: TppLine; ppLabel10: TppLabel; ppLabel11: TppLabel; ppLabel12: TppLabel; ppLine3: TppLine; ppLabel13: TppLabel; ppLabel15: TppLabel; ppLabel16: TppLabel; ppLine4: TppLine; ppLabel17: TppLabel; ppLabel18: TppLabel; ppLabel19: TppLabel; ppLine5: TppLine; ppLabel20: TppLabel; ppGroup1: TppGroup; ppGroupHeaderBand1: TppGroupHeaderBand; ppGroupFooterBand1: TppGroupFooterBand; ppLabel21: TppLabel; ppDBText1: TppDBText; ppDBText2: TppDBText; ppLine6: TppLine; ppLine7: TppLine; ppDBText3: TppDBText; ppDBText4: TppDBText; ppDBText5: TppDBText; ppDBText6: TppDBText; CDSRelRendimentoCha_HorasStr: TStringField; CDSRelRendimentoAti_HorasStr: TStringField; CDSRelRendimentoVis_HorasStr: TStringField; CDSRelRendimentoSol_HorasStr: TStringField; CDSRelRendimentoTotalHorasStr: TStringField; CDSRelRendimentoMeiaHorasStr: TStringField; ppDBText7: TppDBText; ppDBText8: TppDBText; ppDBText9: TppDBText; ppDBText10: TppDBText; ppDBText11: TppDBText; ppDBText12: TppDBText; ppDBText13: TppDBText; ppDBText14: TppDBText; ppDBText15: TppDBText; ppSummaryBand1: TppSummaryBand; ppLabel5: TppLabel; ppDBCalc1: TppDBCalc; ppDBCalc2: TppDBCalc; ppDBCalc3: TppDBCalc; ppDBCalc4: TppDBCalc; CalcMedia: TppDBCalc; lblChaHora: TppLabel; lblAtiHora: TppLabel; lblVisHora: TppLabel; lblSolHora: TppLabel; lblTotalHora: TppLabel; CalChaHora: TppDBCalc; CalcAtiHora: TppDBCalc; CalcVisHora: TppDBCalc; CalcSolHora: TppDBCalc; CalcTotalHora: TppDBCalc; CDSRendimentoDep_Codigo: TIntegerField; CDSRendimentoDep_Nome: TWideStringField; CDSRelRendimentoDep_Codigo: TIntegerField; CDSRelRendimentoDep_Nome: TStringField; dbRendimento: TppDBPipeline; ppGroup2: TppGroup; ppGroupHeaderBand2: TppGroupHeaderBand; ppGroupFooterBand2: TppGroupFooterBand; plbl2: TppLabel; ppDBText16: TppDBText; ppDBText17: TppDBText; ppLine8: TppLine; plbl3: TppLabel; CalcMedia1: TppDBCalc; plbl4: TppLabel; CalcMedia2: TppDBCalc; ppDBCalc8: TppDBCalc; ppDBCalc9: TppDBCalc; ppDBCalc10: TppDBCalc; ppDBCalc11: TppDBCalc; ppDBCalc12: TppDBCalc; ppDBCalc13: TppDBCalc; ppDBCalc14: TppDBCalc; ppDBCalc15: TppDBCalc; lblChaHora1: TppLabel; lblAtiHora1: TppLabel; lblVisHora1: TppLabel; lblSolHora1: TppLabel; lblTotalHora1: TppLabel; lblChaHora2: TppLabel; lblAtiHora2: TppLabel; lblVisHora2: TppLabel; lblSolHora2: TppLabel; lblTotalHora2: TppLabel; CalChaHora2: TppDBCalc; CalcAtiHora2: TppDBCalc; CalcVisHora2: TppDBCalc; CalcSolHora2: TppDBCalc; CalcTotalHora2: TppDBCalc; CalChaHora1: TppDBCalc; CalcAtiHora1: TppDBCalc; CalcVisHora1: TppDBCalc; CalcSolHora1: TppDBCalc; CalcTotalHora1: TppDBCalc; lblMedia2: TppLabel; lblMedia1: TppLabel; lblMedia: TppLabel; CDSRendimentoUsu_Id: TIntegerField; CDSRelRendimentoUsu_Id: TIntegerField; sumTotalDias2: TppDBCalc; sumTotalDias1: TppDBCalc; sumTotalDias: TppDBCalc; ppLabel6: TppLabel; ppLabel14: TppLabel; ppLine9: TppLine; CDSRelRendimentoDiasUteis: TIntegerField; ppDBText18: TppDBText; CDSRelRendimentoMediaHorasDiasUteis: TStringField; lblMediaHoraUtil: TppLabel; ppLabel22: TppLabel; ppLabel23: TppLabel; lblSubMediaUtil: TppLabel; CalcSubMediaHoraUtil: TppDBCalc; lblSubMediaUtil2: TppLabel; CalcSubMediaHoraUtil2: TppDBCalc; CalcMediaHoraUtil2: TppDBCalc; lblMediaUtil2: TppLabel; procedure DataModuleCreate(Sender: TObject); procedure ppSummaryBand1BeforePrint(Sender: TObject); procedure ppGroupFooterBand1BeforePrint(Sender: TObject); procedure ppGroupFooterBand2BeforePrint(Sender: TObject); procedure CDSRelRendimentoCalcFields(DataSet: TDataSet); procedure ppDetailBand1BeforePrint(Sender: TObject); private { Private declarations } FDiasUteis: Integer; procedure FormatarHoras; function RetornarDias(AIdUsuario: Integer; ALista: TObjectList<TUsuarioVO>): Integer; function CalculoMediaDiasUtil(ATotalHoras: double): string; public { Public declarations } procedure ListarRendimento(ADias: Integer; ADataInicial, ADataFinal: string); end; var DMRelUsuario: TDMRelUsuario; implementation uses uUsuarioController; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} function TDMRelUsuario.CalculoMediaDiasUtil(ATotalHoras: double): string; var cMedia: double; begin if FDiasUteis > 0 then begin cMedia := ATotalHoras / FDiasUteis; result := TFuncoes.DecimalToHora(cMedia); end else Result := '00:00'; end; procedure TDMRelUsuario.CDSRelRendimentoCalcFields(DataSet: TDataSet); begin if CDSRelRendimento.State = dsInternalCalc then begin CDSRelRendimentoDiasUteis.AsInteger := FDiasUteis; end; end; procedure TDMRelUsuario.DataModuleCreate(Sender: TObject); begin CDSRendimento.RemoteServer := dm.DSPConexao2; CDSRelRendimento.CreateDataSet(); end; procedure TDMRelUsuario.FormatarHoras; begin CDSRelRendimento.First; while not CDSRelRendimento.Eof do begin CDSRelRendimento.Edit; if CDSRelRendimentoVis_Valor.AsInteger = 0 then CDSRelRendimentoVis_Valor.AsInteger := 0; CDSRelRendimentoCha_HorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoCha_Horas.AsFloat); CDSRelRendimentoAti_HorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoAti_Horas.AsFloat); CDSRelRendimentoVis_HorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoVis_Horas.AsFloat); CDSRelRendimentoSol_HorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoSol_Horas.AsFloat); CDSRelRendimentoTotalHorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoTotalHoras.AsFloat); CDSRelRendimentoMeiaHorasStr.AsString := TFuncoes.DecimalToHora(CDSRelRendimentoMedia.AsFloat); CDSRelRendimento.Post; CDSRelRendimento.Next; end; end; procedure TDMRelUsuario.ListarRendimento(ADias: Integer; ADataInicial, ADataFinal: string); var bAchou: Boolean; ListaUsuario: TObjectList<TUsuarioVO>; UsuarioController: TUsuarioController; MediaDiasUteis: Double; begin FDiasUteis := ADias; UsuarioController := TUsuarioController.Create; try ListaUsuario := UsuarioController.DiasTrabalhados(ADataInicial, ADataFinal); finally FreeAndNil(UsuarioController); end; CDSRelRendimento.First; while not CDSRelRendimento.Eof do CDSRelRendimento.Delete; while not CDSRendimento.Eof do begin bAchou := False; CDSRelRendimento.First; while not CDSRelRendimento.Eof do begin if (CDSRelRendimentoUsu_Codigo.AsInteger = CDSRendimentoUsu_Codigo.AsInteger) and (CDSRelRendimentoRev_Codigo.AsInteger = CDSRendimentoRev_Codigo.AsInteger) and (CDSRelRendimentoDep_Codigo.AsInteger = CDSRendimentoDep_Codigo.AsInteger) then begin bAchou := True; Break; end; CDSRelRendimento.Next; end; ADias := RetornarDias(CDSRendimentoUsu_Id.AsInteger, ListaUsuario); if bAchou then CDSRelRendimento.Edit else begin CDSRelRendimento.Insert; CDSRelRendimentoCha_Qtde.AsFloat := 0; CDSRelRendimentoAti_Qtde.AsFloat := 0; CDSRelRendimentoVis_Qtde.AsFloat := 0; end; CDSRelRendimentoUsu_Id.AsInteger := CDSRendimentoUsu_Id.AsInteger; CDSRelRendimentoUsu_Codigo.AsInteger := CDSRendimentoUsu_Codigo.AsInteger; CDSRelRendimentoUsu_Nome.AsString := CDSRendimentoUsu_Nome.AsString; CDSRelRendimentoRev_Codigo.AsString := CDSRendimentoRev_Codigo.AsString; CDSRelRendimentoRev_Nome.AsString := CDSRendimentoRev_Nome.AsString; CDSRelRendimentoDep_Codigo.AsString := CDSRendimentoDep_Codigo.AsString; CDSRelRendimentoDep_Nome.AsString := CDSRendimentoDep_Nome.AsString; if ADias <= 0 then ADias := 1; CDSRelRendimentoDias.AsInteger := ADias; if (CDSRendimentoTipo.AsString = 'CHAM') or (CDSRendimentoTipo.AsString = 'CHAC') then // chamado ou colobaroador begin CDSRelRendimentoCha_Qtde.AsFloat := CDSRelRendimentoCha_Qtde.AsFloat + CDSRendimentoQtde.AsFloat; CDSRelRendimentoCha_Horas.AsFloat := CDSRelRendimentoCha_Horas.AsFloat + CDSRendimentoHoras.AsFloat; end; if (CDSRendimentoTipo.AsString = 'ATIV') or (CDSRendimentoTipo.AsString = 'ATIC') then // ATIVIDADES begin CDSRelRendimentoAti_Qtde.AsFloat := CDSRelRendimentoAti_Qtde.AsFloat + CDSRendimentoQtde.AsFloat; CDSRelRendimentoAti_Horas.AsFloat := CDSRelRendimentoAti_Horas.AsFloat + CDSRendimentoHoras.AsFloat; end; if (CDSRendimentoTipo.AsString = 'VISI') then // VISITAS begin CDSRelRendimentoVis_Qtde.AsFloat := CDSRelRendimentoVis_Qtde.AsFloat + CDSRendimentoQtde.AsFloat; CDSRelRendimentoVis_Horas.AsFloat := CDSRelRendimentoVis_Horas.AsFloat + CDSRendimentoHoras.AsFloat; CDSRelRendimentoVis_Valor.AsFloat := CDSRelRendimentoVis_Valor.AsFloat + CDSRendimentoValor.AsFloat; end; if (CDSRendimentoTipo.AsString = 'TEMP') then // Tempo do chamado CDSRelRendimentoSol_Horas.AsFloat := CDSRelRendimentoSol_Horas.AsFloat + CDSRendimentoHoras.AsFloat; // totais CDSRelRendimentoTotalHoras.AsFloat := CDSRelRendimentoCha_Horas.AsFloat + CDSRelRendimentoAti_Horas.AsFloat + CDSRelRendimentoVis_Horas.AsFloat + CDSRelRendimentoSol_Horas.AsFloat; // média try CDSRelRendimentoMedia.AsFloat := (CDSRelRendimentoTotalHoras.AsFloat / ADias); MediaDiasUteis := CDSRelRendimentoTotalHoras.AsFloat / FDiasUteis; CDSRelRendimentoMediaHorasDiasUteis.AsString := TFuncoes.DecimalToHora(MediaDiasUteis); except CDSRelRendimentoMedia.AsFloat := 1; end; CDSRelRendimento.Post; CDSRendimento.Next; end; FormatarHoras(); if Assigned(ListaUsuario) then FreeAndNil(ListaUsuario); CDSRelRendimento.IndexFieldNames := 'Rev_Nome;Dep_Nome;Usu_Nome'; lblPeriodo01.Caption := 'Período de: ' + ADataInicial + ' Até: ' + ADataFinal; RelRendimento.Print; end; procedure TDMRelUsuario.ppDetailBand1BeforePrint(Sender: TObject); var vMedia: Double; begin lblMediaHoraUtil.Caption := CDSRelRendimentoMediaHorasDiasUteis.AsString; lblMediaHoraUtil.Caption := CalculoMediaDiasUtil(CDSRelRendimentoTotalHoras.AsFloat); end; procedure TDMRelUsuario.ppGroupFooterBand1BeforePrint(Sender: TObject); var vMedia: Double; begin lblChaHora2.Caption := TFuncoes.DecimalToHora(CalChaHora2.Value); lblAtiHora2.Caption := TFuncoes.DecimalToHora(CalcAtiHora2.Value); lblVisHora2.Caption := TFuncoes.DecimalToHora(CalcVisHora2.Value); lblSolHora2.Caption := TFuncoes.DecimalToHora(CalcSolHora2.Value); lblTotalHora2.Caption := TFuncoes.DecimalToHora(CalcTotalHora2.Value); try // vMedia := (CalcTotalHora2.Value / FDiasUteis) / CalcMedia2.Value; vMedia := (CalcTotalHora2.Value / sumTotalDias2.Value); except vMedia := 1; end; lblMedia2.Caption := TFuncoes.DecimalToHora(vMedia); lblSubMediaUtil.Caption := CalculoMediaDiasUtil(CalcSubMediaHoraUtil.Value); end; procedure TDMRelUsuario.ppGroupFooterBand2BeforePrint(Sender: TObject); var vMedia: Double; begin lblChaHora1.Caption := TFuncoes.DecimalToHora(CalChaHora1.Value); lblAtiHora1.Caption := TFuncoes.DecimalToHora(CalcAtiHora1.Value); lblVisHora1.Caption := TFuncoes.DecimalToHora(CalcVisHora1.Value); lblSolHora1.Caption := TFuncoes.DecimalToHora(CalcSolHora1.Value); lblTotalHora1.Caption := TFuncoes.DecimalToHora(CalcTotalHora1.Value); try // vMedia := (CalcTotalHora1.Value / FDiasUteis) / CalcMedia1.Value; vMedia := (CalcTotalHora1.Value / sumTotalDias1.Value); except vMedia := 1; end; lblMedia1.Caption := TFuncoes.DecimalToHora(vMedia); lblSubMediaUtil2.Caption := CalculoMediaDiasUtil(CalcSubMediaHoraUtil2.Value); end; procedure TDMRelUsuario.ppSummaryBand1BeforePrint(Sender: TObject); var vMedia: Double; begin lblChaHora.Caption := TFuncoes.DecimalToHora(CalChaHora.Value); lblAtiHora.Caption := TFuncoes.DecimalToHora(CalcAtiHora.Value); lblVisHora.Caption := TFuncoes.DecimalToHora(CalcVisHora.Value); lblSolHora.Caption := TFuncoes.DecimalToHora(CalcSolHora.Value); lblTotalHora.Caption := TFuncoes.DecimalToHora(CalcTotalHora.Value); try // vMedia := (CalcTotalHora.Value / FDiasUteis) / CalcMedia.Value; vMedia := (CalcTotalHora.Value / sumTotalDias.Value); except vMedia := 1; end; lblMedia.Caption := TFuncoes.DecimalToHora(vMedia); lblMediaUtil2.Caption := CalculoMediaDiasUtil(CalcMediaHoraUtil2.Value); end; function TDMRelUsuario.RetornarDias(AIdUsuario: Integer; ALista: TObjectList<TUsuarioVO>): Integer; var Item: TUsuarioVO; iResult: Integer; begin iResult := 0; for Item In ALista do begin if Item.Id = AIdUsuario then begin iResult := Item.QtdeDias; Break; end; end; Result := iResult; end; end.
{----------------------------------------------------------------------------- hpp_services (historypp project) Version: 1.5 Created: 05.08.2004 Author: Oxygen [ Description ] Module with history's own services [ History ] 1.5 (05.08.2004) First version [ Modifications ] none [ Known Issues ] none Copyright (c) Art Fedorov, 2004 -----------------------------------------------------------------------------} unit hpp_services; interface uses Classes, Windows, m_globaldefs, m_api, hpp_options, HistoryForm; var hHppRichEditItemProcess, hHppGetVersion, hHppShowGlobalSearch, hHppOpenHistoryEvent: THandle; HstWindowList:TList; procedure hppRegisterServices; procedure hppUnregisterServices; procedure CloseGlobalSearchWindow; procedure CloseHistoryWindows; function FindContactWindow(hContact: THandle): THistoryFrm; function OpenContactHistory(hContact: THandle; index: integer = -1): THistoryFrm; implementation uses {Dialogs, }GlobalSearch, hpp_global; procedure CloseHistoryWindows; var i: Integer; begin try for i := 0 to HstWindowList.Count-1 do THistoryFrm(HstWindowList[i]).Free; except end; end; procedure CloseGlobalSearchWindow; begin if Assigned(fmGlobalSearch) then fmGlobalSearch.Close; end; function FindContactWindow(hContact: THandle): THistoryFrm; var i: Integer; begin Result := nil; for i := 0 to HstWindowList.Count-1 do begin if THistoryFrm(HstWindowList[i]).hContact = hContact then begin Result := THistoryFrm(HstWindowList[i]); exit; end; end; end; function OpenContactHistory(hContact: THandle; index: integer = -1): THistoryFrm; var wHistory: THistoryFrm; begin //check if window exists, otherwise create one wHistory := FindContactWindow(hContact); if not Assigned(wHistory) then begin wHistory := THistoryFrm.Create(nil); HstWindowList.Add(wHistory); wHistory.WindowList := HstWindowList; wHistory.hg.Options := GridOptions; wHistory.hContact := hContact; wHistory.Load; if index <> -1 then wHistory.hg.Selected := index; wHistory.Show; wHistory.ApplyFilter(index = -1); end else begin if index <> -1 then wHistory.hg.Selected := index; wHistory.Show; end; Result := wHistory; end; // MS_HISTORY_SHOWCONTACTHISTORY service // show history called by miranda function OnHistoryShow(wParam{hContact},lParam{0}: DWord): Integer; cdecl; begin OpenContactHistory(wParam); Result:=0; end; // MS_HPP_GETVERSION service // See m_historypp.inc for details function HppGetVersion(wParam{0}, lParam{0}: DWord): Integer; cdecl; begin Result := hppVersion; end; // MS_HPP_SHOWGLOBALSEARCH service // See m_historypp.inc for details function HppShowGlobalSearch(wParam{0}, lParam{0}: DWord): Integer; cdecl; begin if not Assigned(fmGlobalSearch) then begin fmGlobalSearch := TfmGlobalSearch.Create(nil); fmGlobalSearch.Show; end; fmGlobalSearch.BringToFront; Result := 0; end; // MS_HPP_OPENHISTORYEVENT service // See m_historypp.inc for details function HppOpenHistoryEvent(wParam{hDBEvent}, lParam{hContact}: DWord): Integer; cdecl; var hContact: THandle; wHistory: THistoryFrm; hDbEvent,item,sel: Integer; begin // first, let's get contact // WHAT THE F*CK? Why this service always return ZERO? // Because of that I had to change API to include hContact! // DAMN! //hContact := PluginLink.CallService(MS_DB_EVENT_GETCONTACT, wParam,0); hContact := lParam; //PluginLink.CallService(MS_HISTORY_SHOWCONTACTHISTORY,hContact,0); //wHistory := FindContactWindow(hContact); hDbEvent := PluginLink.CallService(MS_DB_EVENT_FINDLAST,hContact,0); item := 0; sel := -1; while (hDbEvent <> wParam) and (hDbEvent <> 0) do begin hDbEvent:=PluginLink.CallService(MS_DB_EVENT_FINDPREV,hDbEvent,0); inc(item); end; if hDbEvent = wParam then sel := item; wHistory := OpenContactHistory(hContact,sel); // if we have password prompt -- remove wHistory.PasswordMode := False; // and find the item //item := wHistory.hg.SearchItem(wParam); // make it selected Result := 0; end; procedure hppRegisterServices; begin HstWindowList := TList.Create; PluginLink.CreateServiceFunction(MS_HISTORY_SHOWCONTACTHISTORY,OnHistoryShow); hHppGetVersion := PluginLink.CreateServiceFunction(MS_HPP_GETVERSION,HppGetVersion); hHppShowGlobalSearch := PluginLink.CreateServiceFunction(MS_HPP_SHOWGLOBALSEARCH,HppShowGlobalSearch); hHppOpenHistoryEvent := PluginLink.CreateServiceFunction(MS_HPP_OPENHISTORYEVENT,HppOpenHistoryEvent); hHppRichEditItemProcess := PluginLink.CreateHookableEvent(ME_HPP_RICHEDIT_ITEMPROCESS); end; procedure hppUnregisterServices; begin PluginLink.DestroyServiceFunction(hHppGetVersion); PluginLink.DestroyServiceFunction(hHppShowGlobalSearch); PluginLink.DestroyServiceFunction(hHppOpenHistoryEvent); PluginLink.DestroyHookableEvent(hHppRichEditItemProcess); CloseHistoryWindows; HstWindowList.Free; CloseGlobalSearchWindow; end; end.
/// <summary> /// <para> /// MQTT 消息队列客户端实现: <br />使用方法: <br />1、创建一个 TQMQTTMessageClient /// 实例,也可以直接用全局的 DefaultMQTTClient 实例。 <br />2、调用 RegisterDispatch /// 关联主题与处理函数之间的关系。 <br />3、调用 Subscribe /// 函数添加订阅,注意如果网络没有连接,则不会实际注册,在网络连接后会自动注册。 <br />4、调用 Start 启动客户端。 <br /> /// 5、要发布主题,调用 Publish 方法发布 <br />6、停止连接可以调用 Stop 方法。 /// </para> /// <para> /// 还是老规矩,开源免费,但需要申明版权,并不承担由于使用本代码引起的任何后果。由于使用匿名函数,所以不兼容2007 /// </para> /// </summary> unit QMqttClient; interface { 要自动记录日志,请启用此选项,本单元发送的日志都带有QMQTT标记以便在写入时可以独立写入到一个特定的日志文件中 } { .$DEFINE LogMqttContent } {$I qdac.inc} {$WARN UNIT_PLATFORM OFF} {$WARN SYMBOL_PLATFORM OFF} uses classes, sysutils, qstring, qworker, netencoding, generics.collections, syncobjs, variants, RegularExpressionsCore{$IFDEF POSIX} , Posix.Base, Posix.Stdio, Posix.Pthread, Posix.UniStd, IOUtils, Posix.NetDB, Posix.SysSocket, Posix.Fcntl, Posix.StrOpts, Posix.Errno, Posix.NetinetIn, Posix.arpainet, Posix.SysSelect, Posix.Systime {$ELSE} , windows, messages, winsock, TlHelp32 {$ENDIF}{$IFDEF LogMqttContent}, qlog{$ENDIF}, qdac_ssl; const /// <summary> /// 连接失败 /// </summary> MQERR_CONNECT = 0; /// <summary> /// 协议版本错误 /// </summary> MQERR_PROTOCOL_VERSION = 1; /// <summary> /// 客户端ID被拒绝 /// </summary> MQERR_CLIENT_ID_REJECT = 2; /// <summary> /// 服务器不可用 /// </summary> MQERR_SERVER_UNUSED = 3; /// <summary> /// 认证失败 /// </summary> MQERR_BAD_AUTH = 4; /// <summary> /// 无权访问 /// </summary> MQERR_NO_AUTH = 5; /// <summary> /// 订阅失败 /// </summary> MQERR_SUBSCRIBE_FAILED = 20; /// <summary> /// 发布失败 /// </summary> MQERR_PUBLISH_FAILED = 21; // 属性ID定义 MP_PAYLOAD_FORMAT = 1; MP_MESSAGE_EXPIRE = 2; MP_CONTENT_TYPE = 3; MP_RESPONSE_TOPIC = 8; MP_DATA = 9; MP_ID = 11; MP_SESSION_EXPIRE = 17; MP_CLIENT_ID = 18; MP_KEEP_ALIVE = 19; MP_AUTH_METHOD = 21; MP_AUTH_DATA = 22; MP_NEED_PROBLEM_INFO = 23; MP_WILL_DELAY = 24; MP_NEED_RESPONSE_INFO = 24; MP_RESPONSE_INFO = 26; MP_REASON = 31; MP_RECV_MAX = 33; MP_ALIAS_MAX = 34; MP_TOPIC_ALIAS = 35; MP_MAX_QOS = 36; MP_HAS_RETAIN = 37; MP_USER_PROP = 38; MP_MAX_PACKAGE_SIZE = 39; MP_HAS_WILDCARD_SUBSCRIBES = 40; MP_HAS_SUBSCRIBE_ID = 41; MP_HAS_SHARE_SUBSCRIBES = 42; type /// <summary> /// 控制类型,客户端只使用部分,具体参考 MQTT 协议标准 /// </summary> TQMQTTControlType = ( /// <summary> /// 保留未用 /// </summary> ctReserved, /// <summary> /// 客户端-&gt;服务器:发送连接到服务器命令 /// </summary> ctConnect, /// <summary> /// 服务器-&gt;客户端:连接结果确认 /// </summary> ctConnectAck, /// <summary> /// 发送者-&gt;接收者:发布一个新消息 /// </summary> ctPublish, /// <summary> /// 接收者&lt;-&gt;发送者:发送收到新消息确认 /// </summary> ctPublishAck, /// <summary> /// 接收者-&gt;发布者:收到发布 /// </summary> ctPublishRecv, /// <summary> /// 发送者-&gt;接收者:发布释放 /// </summary> ctPublishRelease, /// <summary> /// 接收者-&gt;发送者:发布完成 /// </summary> ctPublishDone, /// <summary> /// 客户端-&gt;服务器:订阅一组主题,注意 QoS 级别可能会降级为服务器支持的级别 /// </summary> ctSubscribe, /// <summary> /// 服务器-&gt;客户端:订阅结果通知 /// </summary> ctSubscribeAck, /// <summary> /// 客户端-&gt;服务器:取消订阅 /// </summary> ctUnsubscribe, /// <summary> /// 服务器-&gt;客户端:取消订阅结果确认 /// </summary> ctUnsubscribeAck, /// <summary> /// 客户端-&gt;服务器:发送保活指令 /// </summary> ctPing, /// <summary> /// 服务器-&gt;客户端:保活指令回复 /// </summary> ctPingResp, /// <summary> /// 客户端-&gt;服务器:断开连接 /// </summary> ctDisconnect); /// <summary> /// MQTT 协议的标志位 /// </summary> TQMQTTFlag = ( /// <summary> /// Retain /// 标志位用于在发布消息时,确认消息是否保留。保留的消息会被保存并被新的同类消息替换,一旦有新订阅者接入,这类消息将发送给新的订阅者。具体参考 /// MQTT 协议3.3.1。 /// </summary> mfRetain, /// <summary> /// 重发标志 /// </summary> mfDup); /// <summary> /// MQTT 服务质量等级 /// </summary> TQMQTTQoSLevel = ( /// <summary> /// 最多完成分发一次,接收端如果在接收过程中出错,也不再重发 /// </summary> qlMax1, /// <summary> /// 最少完成分发一次,对于大部分需要保证接收到的消息来说,这个级别足够 /// </summary> qlAtLeast1, /// <summary> /// 保证完成且只进行一次分发 /// </summary> qlOnly1); TQMQTTFlags = set of TQMQTTFlag; PQMQTTMessage = ^TQMQTTMessage; /// <summary> /// 内部消息流转状态 /// </summary> TQMQTMessageState = (msSending, msSent, msRecving, msRecved, msDispatching, msDispatched, msNeedAck, msNeedWait, msWaiting); TQMQTMessageStates = set of TQMQTMessageState; TQMQTTMessageClient = class; // 主题派发全部放到主线程,上层不需要考虑线程安全 /// <summary> /// 订阅结果通知条目定义 /// </summary> TQMQTTSubscribeResult = record /// <summary> /// 主题名称 /// </summary> Topic: String; /// <summary> /// 错误代码 /// </summary> ErrorCode: Byte; /// <summary> /// 服务器返回的最终实际的 QoS 级别 /// </summary> Qos: TQMQTTQoSLevel; function GetSuccess: Boolean; property Success: Boolean read GetSuccess; end; TQMQTTSubscribeResults = array of TQMQTTSubscribeResult; PQMQTTSubscribeResults = ^TQMQTTSubscribeResults; /// <summary> /// 订阅结果通知事件 /// </summary> TQMQTTTopicSubscribeResultNotify = procedure(ASender: TQMQTTMessageClient; const AResults: TQMQTTSubscribeResults) of object; /// <summary> /// 取消订阅结果通知事件 /// </summary> TQMQTTTopicUnsubscribeEvent = procedure(ASender: TQMQTTMessageClient; const ATopic: String) of object; /// <summary> /// 消息派发事件,ATopic 指明了被派发的消息主题,当然您也可以从 AReq 参数中取其 TopicName 属性的值。这里 ATopic /// 是从 AReq.TopicName 缓存的值。 /// </summary> TQMQTTTopicDispatchEvent = procedure(ASender: TQMQTTMessageClient; const ATopic: String; const AReq: PQMQTTMessage) of object; TQMQTTTopicDispatchEventG = procedure(ASender: TQMQTTMessageClient; const ATopic: String; const AReq: PQMQTTMessage); TQMQTTTopicDispatchEventA = reference to procedure (ASender: TQMQTTMessageClient; const ATopic: String; const AReq: PQMQTTMessage); /// <summary> /// 系统出错时的触发事件 /// </summary> TQMQTTErrorEvent = procedure(ASender: TQMQTTMessageClient; const AErrorCode: Integer; const AErrorMsg: String) of object; /// <summary> /// 常规通知事件 /// </summary> TQMQTTNotifyEvent = procedure(ASender: TQMQTTMessageClient) of object; /// <summary> /// 消息通知事件 /// </summary> TQMQTTMessageNotifyEvent = procedure(const AMessage: PQMQTTMessage) of object; /// <summary> /// MQTT 交互消息实现 /// </summary> TQMQTTMessage = record private FData: TBytes; FCurrent: PByte; FVarHeader: PByte; FStates: TQMQTMessageStates; FClient: TQMQTTMessageClient; FAfterSent: TQMQTTMessageNotifyEvent; FRecvTime, FSentTime, FSentTimes, FSize: Cardinal; // 用于发送队列,内部使用 FNext: PQMQTTMessage; FWaitEvent: TEvent; function GetControlType: TQMQTTControlType; procedure SetControlType(const AType: TQMQTTControlType); function GetHeaderFlags(const Index: Integer): Boolean; procedure SetHeaderFlags(const Index: Integer; const Value: Boolean); function GetPayloadSize: Cardinal; procedure SetPayloadSize(Value: Cardinal); procedure EncodeInt(var ABuf: PByte; V: Cardinal); procedure EncodeInt64(var ABuf: PByte; V: UInt64); function DecodeInt(var ABuf: PByte; AMaxCount: Integer; var AResult: Cardinal): Boolean; function DecodeInt64(var ABuf: PByte; AMaxCount: Integer; var AResult: Int64): Boolean; function GetBof: PByte; function GetEof: PByte; function GetPosition: Integer; procedure SetQosLevel(ALevel: TQMQTTQoSLevel); function GetQoSLevel: TQMQTTQoSLevel; procedure SetPosition(const Value: Integer); function GetByte(const AIndex: Integer): Byte; procedure SetByte(const AIndex: Integer; const Value: Byte); function GetVarHeaderOffset: Integer; function GetRemainSize: Integer; function GetTopicText: String; function GetTopicId: Word; function GetTopicContent: TBytes; function GetCapacity: Cardinal; procedure SetCapacity(const Value: Cardinal); function GetTopicName: String; function ReloadSize(AKnownBytes: Integer): Boolean; function GetTopicContentSize: Integer; function GetTopicOriginContent: PByte; function GetPackageId: Word; property Next: PQMQTTMessage read FNext write FNext; public class function IntEncodedSize(const V: Cardinal): Byte; static; /// <summary> /// 复制一个新的消息出来,需要自行调用 Dispose 释放 /// </summary> function Copy: PQMQTTMessage; /// <summary> /// 创建并初始化一个新的消息实例 /// </summary> class function Create(AClient: TQMQTTMessageClient): PQMQTTMessage; static; /// <summary> /// 向当前位置写入一个字符串 /// </summary> function Cat(const S: QStringW; AWriteZeroLen: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个字符串 /// </summary> function Cat(const S: QStringA; AWriteZeroLen: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入指定的数据 /// </summary> function Cat(const ABuf: Pointer; const ALen: Cardinal) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入指定的数据 /// </summary> function Cat(const ABytes: TBytes): PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个8位无符号整数 /// </summary> function Cat(const V: Byte): PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个16位无符号整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Word; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个32位无符号整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Cardinal; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个64位无符号整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: UInt64; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个8位整数 /// </summary> function Cat(const V: Shortint): PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个16位整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Smallint; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个32位整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Integer; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个64位整数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Int64; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个32位浮点数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Single; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 向当前位置写入一个64位浮点数 /// </summary> /// <param name="V"> /// 要写入的数值 /// </param> /// <param name="AEncode"> /// 是否对其进行编码(具体编码规则参考 EncodeInt 和 EncodeInt64 的实现) /// </param> function Cat(const V: Double; AEncode: Boolean = false) : PQMQTTMessage; overload; /// <summary> /// 从当前位置读取下一个字节的值(8位无符号整数) /// </summary> function NextByte: Byte; /// <summary> /// 从当前位置读取下一个16位无符号整数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextWord(AIsEncoded: Boolean): Word; /// <summary> /// 读取下一个32位无符号整数 /// </summary> /// <param name="AIsEncoded"> /// 从当前位置是否是编码过的数值 /// </param> function NextDWord(AIsEncoded: Boolean = false): Cardinal; /// <summary> /// 读取下一个64位无符号整数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextUInt64(AIsEncoded: Boolean = false): UInt64; /// <summary> /// 从当前位置读取下一个8位整数 /// </summary> function NextTinyInt: Shortint; /// <summary> /// 从当前位置读取下一个16位整数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextSmallInt(AIsEncoded: Boolean = false): Smallint; /// <summary> /// 从当前位置读取下一个32位整数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextInt(AIsEncoded: Boolean = false): Integer; /// <summary> /// 从当前位置读取下一个64位整数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextInt64(AIsEncoded: Boolean = false): Int64; /// <summary> /// 从当前位置读取下一个32位浮点数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextSingle(AIsEncoded: Boolean = false): Single; /// <summary> /// 从当前位置读取下一个64位浮点数 /// </summary> /// <param name="AIsEncoded"> /// 是否是编码过的数值 /// </param> function NextFloat(AIsEncoded: Boolean = false): Double; /// <summary> /// 从当前位置读取指定长度的内容 /// </summary> function NextBytes(ASize: Integer): TBytes; overload; /// <summary> /// 从当前位置读取指定长度的内容 /// </summary> function NextBytes(ABuf: Pointer; ALen: Integer): Integer; overload; /// <summary> /// 从当前位置读取一个字符串 /// </summary> function NextString: String; /// <summary> /// 向前或向后移动指定的位置。如果调整后的位置小于Bof,则设置为Bof,如果大于Eof,则设置为Eof的值。 /// </summary> function MoveBy(const ADelta: Integer): PQMQTTMessage; inline; procedure MoveToVarHeader; /// <summary> /// 控制命令类型 /// </summary> property ControlType: TQMQTTControlType read GetControlType write SetControlType; /// <summary> /// 以十六进制视图方式来显示整个消息内容(用于记录日志分析) /// </summary> function ContentAsHexText: String; /// <summary> /// 保留标志 /// </summary> property IsRetain: Boolean index 0 read GetHeaderFlags write SetHeaderFlags; /// <summary> /// 重发标志 /// </summary> property IsDup: Boolean index 1 read GetHeaderFlags write SetHeaderFlags; /// <summary> /// 服务质量级别 /// </summary> property QosLevel: TQMQTTQoSLevel read GetQoSLevel write SetQosLevel; /// <summary> /// 载荷大小 /// </summary> property PayloadSize: Cardinal read GetPayloadSize write SetPayloadSize; /// <summary> /// 内容开始地址 /// </summary> property Bof: PByte read GetBof; /// <summary> /// 内容 结束地址 /// </summary> property Eof: PByte read GetEof; /// <summary> /// 内容当前地址 /// </summary> property Current: PByte read FCurrent; /// <summary> /// 可变头部的起始位置,是固定头+剩余长度后的起始位置,从这个地址开始是根据类型不同填充的 /// </summary> property VarHeader: PByte read FVarHeader; /// <summary> /// 可变头部的偏移量 /// </summary> property VarHeaderOffset: Integer read GetVarHeaderOffset; /// <summary> /// 当前位置 /// </summary> property Position: Integer read GetPosition write SetPosition; /// <summary> /// 整个消息内容长度(注意它小于等于 Capacity 属性的值) /// </summary> property Size: Cardinal read FSize; /// <summary> /// 剩余大小,等于 Size-Position /// </summary> property RemainSize: Integer read GetRemainSize; /// <summary> /// 内容中特定字节的值 /// </summary> property Bytes[const AIndex: Integer]: Byte read GetByte write SetByte; default; /// <summary> /// 当前状态 /// </summary> property States: TQMQTMessageStates read FStates write FStates; /// <summary> /// 消息关联的 TQMQTTMessageClient 实例 /// </summary> property Client: TQMQTTMessageClient read FClient write FClient; /// <summary> /// 接收或发送的消息的PackageId,仅对部分类型的消息有效,无效的类型返回 0 /// </summary> property TopicId: Word read GetTopicId; /// <summary> /// 消息主题,仅在类型为 ctPublish 时有意义 /// </summary> property TopicName: String read GetTopicName; /// <summary> /// 消息体文本内容,注意请自行确认消息是文本格式的内容,否则可能出现异常(无法将内容当成 UTF-8 编码的字符串来处理) /// </summary> property TopicText: String read GetTopicText; /// <summary> /// 消息体的二进制内容 /// </summary> property TopicContent: TBytes read GetTopicContent; /// <summary> /// 接收到的消息内容总大小(注意和 Size 的区别),它不包含消息的其它部分所占用的空间 /// </summary> property TopicContentSize: Integer read GetTopicContentSize; /// <summary> /// 消息体原始内容地址 /// </summary> property TopicOriginContent: PByte read GetTopicOriginContent; /// <summary> /// 容量大小 /// </summary> /// property Capacity: Cardinal read GetCapacity write SetCapacity; property RecvTime: Cardinal read FRecvTime; property SentTime: Cardinal read FSentTime; property SentTimes: Cardinal read FSentTimes; property PackageId: Word read GetPackageId; end; /// <summary> /// 主题匹配模式 /// </summary> TTopicMatchType = ( /// <summary> /// 完整匹配(注意消息主题区分大小写) /// </summary> mtFull, /// <summary> /// 模式匹配,支持通配符($,#+) /// </summary> mtPattern, /// <summary> /// 正则表达式匹配 /// </summary> mtRegex); /// <summary> /// 消息订阅请求内部记录使用,用于记录用户申请订阅的消息主题 /// </summary> TQMQTTSubscribeItem = record Topic: String; Qos: TQMQTTQoSLevel; end; TQMQTTProtocolVersion = (pv3_1_1 = 4, pv5_0 = 5); TQMQTT5AuthMode = (amNone); TQMQTTPropId = (piFormat = 1, piMsgTimeout = 2, piContentType = 3, piRespTopic = 8, piRelData = 9, piIdentDef = 11, piSessionTimeout = 17, piClientId = 18, piKeepAlive = 19, piAuthMode = 21, piAuthData = 22, piErrorData = 23, piWillDelay = 24, piRequestResp = 25, piRequst = 26, piServerRef = 28, piReason = 31, piMaxRecv = 33, piMaxTopicLen = 34, piTopicAlias = 35, piMaxQoS = 36, piUserProp = 38, piMaxPackageSize = 39, piAcceptPatten = 40, piAcceptTopicId = 41, piAcceptShareTopic = 42); TQMQTT5PropDataType = (ptUnknown, ptByte, ptWord, ptInt, ptVarInt, ptString, ptBinary); TQMQTT5PropType = record private FName: String; FId: Byte; FDataType: TQMQTT5PropDataType; function GetDataSize: Integer; public property Id: Byte read FId; property DataType: TQMQTT5PropDataType read FDataType; property DataSize: Integer read GetDataSize; property Name: String read FName; end; PQMQTT5PropType = ^TQMQTT5PropType; TQMQTT5Prop = record case Integer of 0: (AsByte: Byte); 1: (AsWord: Word); 2: (AsInteger: Cardinal); 3: (AsString: PQStringA; IsSet: Boolean); 4: (AsBytes: ^TBytes); end; EMQTTError = class(Exception) end; EMQTTAbortError = class(EAbort) end; PQMQTT5Prop = ^TQMQTT5Prop; TQMQTT5Props = class private function GetPropTypes(const APropId: Byte): PQMQTT5PropType; function GetAsInt(const APropId: Byte): Cardinal; function GetAsString(const APropId: Byte): String; function GetAsVariant(const APropId: Byte): Variant; procedure SetAsInt(const APropId: Byte; const Value: Cardinal); procedure SetAsString(const APropId: Byte; const Value: String); procedure SetAsVariant(const APropId: Byte; const Value: Variant); function GetIsSet(const APropId: Byte): Boolean; function GetDataSize(const APropId: Byte): Integer; function GetPayloadSize: Integer; function GetMinMaxId(const Index: Integer): Byte; protected FItems: TArray<TQMQTT5Prop>; public constructor Create; destructor Destroy; override; function Copy: TQMQTT5Props; procedure ReadProps(const AMessage: PQMQTTMessage); procedure WriteProps(AMessage: PQMQTTMessage); procedure Replace(AProps: TQMQTT5Props); property PropTypes[const APropId: Byte]: PQMQTT5PropType read GetPropTypes; property Values[const APropId: Byte]: Variant read GetAsVariant write SetAsVariant; property AsInt[const APropId: Byte]: Cardinal read GetAsInt write SetAsInt; property AsString[const APropId: Byte]: String read GetAsString write SetAsString; property IsSet[const APropId: Byte]: Boolean read GetIsSet; property DataSize[const APropId: Byte]: Integer read GetDataSize; property PayloadSize: Integer read GetPayloadSize; property MinId: Byte index 0 read GetMinMaxId; property MaxId: Byte index 1 read GetMinMaxId; end; TQMQTTClientState = (qcsConnecting, qcsReconnecting, qcsRunning, qcsStopping); TQMQTTClientStates = set of TQMQTTClientState; PQMQTTPublishPendingItem = ^TQMQTTPublishPendingItem; TQMQTTPublishPendingItem = record Topic: String; Content: TBytes; Qos: TQMQTTQoSLevel; Props: TQMQTT5Props; PushTime: Cardinal; Prior, Next: PQMQTTPublishPendingItem; // forms.pas end; TQMQTTPublishPendings = record First, Last: PQMQTTPublishPendingItem; end; TQMQTTPublishOption = (poCacheUnpublish, poCleanOnDisconnect); TQMQTTPublishOptions = set of TQMQTTPublishOption; /// <summary> /// QMQTT 消息客户端实现,注意目前版本并没有实现消息的重发(主要是作者懒) /// </summary> TQMQTTMessageClient = class(TComponent) private protected // 事件列表 FBeforeConnect: TQMQTTNotifyEvent; FAfterDispatch: TQMQTTTopicDispatchEvent; FAfterConnected: TQMQTTNotifyEvent; FBeforeDispatch: TQMQTTTopicDispatchEvent; FBeforePublish: TQMQTTTopicDispatchEvent; FAfterSubscribed: TQMQTTTopicSubscribeResultNotify; FAfterUnsubscribed: TQMQTTTopicUnsubscribeEvent; FAfterPublished: TQMQTTTopicDispatchEvent; FBeforeSubscribe: TQMQTTTopicDispatchEvent; FBeforeUnsubscribe: TQMQTTTopicDispatchEvent; FBeforeSend: TQMQTTMessageNotifyEvent; FAfterSent: TQMQTTMessageNotifyEvent; FOnRecvTopic: TQMQTTTopicDispatchEvent; FAfterDisconnected: TQMQTTNotifyEvent; // FSSL: IQSSLItem; FConnectionTimeout, FReconnectInterval, FMaxTopicAckTimeout: Cardinal; FWaitAckTopics: Integer; FServerHost, FUserName, FPassword, FClientId, FWillTopic: String; FWillMessage: TBytes; FRecvThread, FSendThread: TThread; FThreadCount: Integer; FSocket: THandle; FOnError: TQMQTTErrorEvent; FPackageId: Integer; FWaitAcks: TArray<PQMQTTMessage>; FPublishPendings: TQMQTTPublishPendings; FSubscribes: TStringList; FTopicHandlers: TStringList; FNotifyEvent: TEvent; FConnectJob: IntPtr; FLastIoTick, FPublishTTL: Cardinal; FPingStarted, FPingTime: Cardinal; FReconnectTimes, FReconnectTime: Cardinal; FLastConnectTime: Cardinal; FSentTopics: Cardinal; FRecvTopics: Cardinal; FConnectProps: TQMQTT5Props; FStates: TQMQTTClientStates; FPublishOptions: TQMQTTPublishOptions; FLocker: TCriticalSection; FPeekInterval: Word; FServerPort: Word; FProtocolVersion: TQMQTTProtocolVersion; FQoSLevel: TQMQTTQoSLevel; FIsRetain: Boolean; FUseSSL: Boolean; FCleanLastSession: Boolean; FConnected: Boolean; FEventInThread: Boolean; {$IFDEF LogMqttContent} FLogPackageContent: Boolean; {$ENDIF} procedure RecreateSocket; procedure DoConnect; procedure DoMQTTConnect(AJob: PQJob); procedure DoDispatch(var AReq: TQMQTTMessage); procedure DispatchTopic(AMsg: PQMQTTMessage); procedure DispatchProps(AMsg: PQMQTTMessage); procedure InvokeTopicHandlers(const ATopic: String; AMsg: PQMQTTMessage); procedure DoError(AErrorCode: Integer); procedure DoBeforeConnect; procedure DoAfterConnected; procedure DoConnectFailed; procedure DoBeforePublish(ATopic: String; AMsg: PQMQTTMessage); procedure DoAfterSubcribed(AResult: PQMQTTSubscribeResults); procedure DoAfterUnsubscribed(ASource: PQMQTTMessage); procedure ValidClientId; procedure SetWillMessage(const AValue: TBytes); procedure DoBeforeSend(const AReq: PQMQTTMessage); procedure DoAfterSent(const AReq: PQMQTTMessage); function DoSend(AReq: PQMQTTMessage): Boolean; procedure DoRecv; function GetClientId: String; procedure Lock; inline; procedure Unlock; inline; procedure ClearWaitAcks; procedure ClearHandlers; function PopWaitAck(APackageId: Word): PQMQTTMessage; function DNSLookupV4(const AHost: QStringW): Cardinal; overload; procedure DoFreeAfterSent(const AMessage: PQMQTTMessage); procedure DoTopicPublished(const AMessage: PQMQTTMessage); procedure Disconnect; procedure DoAfterDisconnected; procedure DoPing; procedure FreeMessage(AMsg: PQMQTTMessage); function AcquirePackageId(AReq: PQMQTTMessage; AIsWaitAck: Boolean): Word; procedure Queue(ACallback: TThreadProcedure; AIsForce: Boolean = false); procedure DoQueueCallback(AJob: PQJob); procedure DoCloseSocket; function GetIsRunning: Boolean; function GetConnectProps: TQMQTT5Props; function GetSSLManager: TQSSLManager; procedure DoTimer(AJob: PQJob); procedure ReconnectNeeded; procedure DoCleanup; procedure CheckPublished; procedure CleanPublishPendings; procedure SubscribePendings; procedure RemoveSubscribePendings(const ATopics: array of String); function CompareTopic(const ATopic1, ATopic2: String): Integer; procedure PublishFirstPending; public /// <summary> /// 构造函数 /// </summary> constructor Create(AOwner: TComponent); override; /// <summary> /// 析构前调用 /// </summary> procedure BeforeDestruction; override; /// <summary> /// 析构函数 /// </summary> destructor Destroy; override; /// <summary> /// 启动服务 /// </summary> procedure Start; /// <summary> /// 停止服务 /// </summary> procedure Stop; /// <summary> /// 订阅服务 /// </summary> /// <param name="ATopics"> /// 主题列表,支持模式匹配 /// </param> /// <param name="AQoS"> /// 服务质量要求 /// </param> /// <param name="AProps"> /// 额外属性设置(仅5.0版协议有效) /// </param> /// <remarks> /// 1、 服务质量要求并不合最终的服务质量要求一致,服务器不支持该级别时,可能降级。 <br /> /// 2、如果尚未连接到服务器,则对应的请求会在服务连接完成后尝试自动订阅(先买票后上车和先上车后买票的区别)。 /// </remarks> procedure Subscribe(const ATopics: array of String; const AQoS: TQMQTTQoSLevel; AProps: TQMQTT5Props = nil); /// <summary> /// 取消指定的主题订阅 /// </summary> /// <param name="ATopics"> /// 要取消的主题列表 /// </param> /// <remarks> /// 这个请求只能在连接完成后才可以,暂时不支持离线取消 /// </remarks> procedure Unsubscribe(const ATopics: array of String); /// <summary> /// 清除所有的主题订阅 /// </summary> procedure ClearSubscribes; /// <summary> /// 发布一个消息 /// </summary> /// <param name="ATopic"> /// 消息主题,注意不能使用任何通配符 /// </param> /// <param name="AContent"> /// 消息内容 /// </param> /// <param name="AQoSLevel"> /// 服务质量要求 /// </param> procedure Publish(const ATopic, AContent: String; AQoSLevel: TQMQTTQoSLevel); overload; /// <summary> /// 发布一个消息 /// </summary> /// <param name="ATopic"> /// 消息主题,注意不能使用任何通配符 /// </param> /// <param name="AContent"> /// 消息内容 /// </param> /// <param name="AQoSLevel"> /// 服务质量要求 /// </param> procedure Publish(const ATopic: String; AContent: TBytes; AQoSLevel: TQMQTTQoSLevel); overload; /// <summary> /// 发布一个消息 /// </summary> /// <param name="ATopic"> /// 消息主题,注意不能使用任何通配符 /// </param> /// <param name="AContent"> /// 消息内容 /// </param> /// <param name="AQoSLevel"> /// 服务质量要求 /// </param> procedure Publish(const ATopic: String; const AContent; ALen: Cardinal; AQoSLevel: TQMQTTQoSLevel); overload; /// <summary> /// 注册一个消息派发处理过程 /// </summary> /// <param name="ATopic"> /// 要关联的主题,格式与 AType 参数的类型要求保持一致 /// </param> /// <param name="AHandler"> /// 消息处理函数 /// </param> /// <param name="AType"> /// 消息主题类型 /// </param> procedure RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEvent; AType: TTopicMatchType = mtFull); overload; procedure RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEventG; AType: TTopicMatchType = mtFull); overload; procedure RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEventA; AType: TTopicMatchType = mtFull); overload; /// <summary> /// 移除一个消息派发函数注册 /// </summary> procedure UnregisterDispatch(AHandler: TQMQTTTopicDispatchEvent); overload; property EventInThread: Boolean read FEventInThread write FEventInThread; /// <summary> /// 服务器IP或域名 /// </summary> property ServerHost: String read FServerHost write FServerHost; /// <summary> /// 服务器端口号,默认1883 /// </summary> property ServerPort: Word read FServerPort write FServerPort; /// <summary> /// 用户名 /// </summary> property UserName: String read FUserName write FUserName; /// <summary> /// 密码 /// </summary> property Password: String read FPassword write FPassword; /// <summary> /// 客户ID,如果不指定会随机生成。当然最好你自己保留好这个ID。 /// </summary> property ClientId: String read GetClientId write FClientId; /// <summary> /// 连接超时,单位为秒 /// </summary> property ConnectionTimeout: Cardinal read FConnectionTimeout write FConnectionTimeout; /// <summary> /// 默认服务质量要求 /// </summary> property QosLevel: TQMQTTQoSLevel read FQoSLevel write FQoSLevel; /// <summary> /// 遗言的主题 /// </summary> property WillTopic: String read FWillTopic write FWillTopic; /// <summary> /// 遗言的内容,如果如果是字符串,请使用 UTF 8 编码 /// </summary> property WillMessage: TBytes read FWillMessage write SetWillMessage; /// <summary> /// 默认保留标志 /// </summary> property IsRetain: Boolean read FIsRetain write FIsRetain; /// <summary> /// 是否连接时清除上次会话信息 /// </summary> property CleanLastSession: Boolean read FCleanLastSession write FCleanLastSession; /// <summary> /// 保活间隔,单位为秒 /// </summary> property PeekInterval: Word read FPeekInterval write FPeekInterval; /// <summary> /// 重连间隔,单位为秒 /// </summary> property ReconnectInterval: Cardinal read FReconnectInterval write FReconnectInterval; property MaxTopicAckTimeout: Cardinal read FMaxTopicAckTimeout write FMaxTopicAckTimeout; /// <summary> /// 客户端是否已经成功连接到服务器 /// </summary> property IsRunning: Boolean read GetIsRunning; property Connected: Boolean read FConnected; /// <summary> /// 接收到的消息数量 /// </summary> property RecvTopics: Cardinal read FRecvTopics; /// <summary> /// 发送的消息数量 /// </summary> property SentTopics: Cardinal read FSentTopics; {$IFDEF LogMqttContent} property LogPackageContent: Boolean read FLogPackageContent write FLogPackageContent; {$ENDIF} property UseSSL: Boolean read FUseSSL write FUseSSL; property SSLManager: TQSSLManager read GetSSLManager; // MQTT 5.0 Added property ProtocolVersion: TQMQTTProtocolVersion read FProtocolVersion write FProtocolVersion; property ConnectProps: TQMQTT5Props read GetConnectProps; property PublishOptions: TQMQTTPublishOptions read FPublishOptions write FPublishOptions; property PublishTTL: Cardinal read FPublishTTL write FPublishTTL; /// <summary> /// 出错通知 /// </summary> property OnError: TQMQTTErrorEvent read FOnError write FOnError; /// <summary> /// 连接前通知 /// </summary> property BeforeConnect: TQMQTTNotifyEvent read FBeforeConnect write FBeforeConnect; /// <summary> /// 连接后通知 /// </summary> property AfterConnected: TQMQTTNotifyEvent read FAfterConnected write FAfterConnected; /// <summary> /// 断开后通知 /// </summary> property AfterDisconnected: TQMQTTNotifyEvent read FAfterDisconnected write FAfterDisconnected; /// <summary> /// 派发前通知 /// </summary> property BeforeDispatch: TQMQTTTopicDispatchEvent read FBeforeDispatch write FBeforeDispatch; /// <summary> /// 派发后通知 /// </summary> property AfterDispatch: TQMQTTTopicDispatchEvent read FAfterDispatch write FAfterDispatch; /// <summary> /// 发布前通知 /// </summary> property BeforePublish: TQMQTTTopicDispatchEvent read FBeforePublish write FBeforePublish; /// <summary> /// 发布后通知 /// </summary> property AfterPublished: TQMQTTTopicDispatchEvent read FAfterPublished write FAfterPublished; /// <summary> /// 订阅前通知 /// </summary> property BeforeSubscribe: TQMQTTTopicDispatchEvent read FBeforeSubscribe write FBeforeSubscribe; /// <summary> /// 订阅后通知 /// </summary> property AfterSubscribed: TQMQTTTopicSubscribeResultNotify read FAfterSubscribed write FAfterSubscribed; /// <summary> /// 取消订阅前通知 /// </summary> property BeforeUnsubscribe: TQMQTTTopicDispatchEvent read FBeforeUnsubscribe write FBeforeUnsubscribe; /// <summary> /// 取消订阅后通知 /// </summary> property AfterUnsubscribed: TQMQTTTopicUnsubscribeEvent read FAfterUnsubscribed write FAfterUnsubscribed; /// <summary> /// 发送数据前通知 /// </summary> property BeforeSend: TQMQTTMessageNotifyEvent read FBeforeSend write FBeforeSend; /// <summary> /// 发送数据后通知 /// </summary> property AfterSent: TQMQTTMessageNotifyEvent read FAfterSent write FAfterSent; /// <summary> /// 收到消息时通知 /// </summary> property OnRecvTopic: TQMQTTTopicDispatchEvent read FOnRecvTopic write FOnRecvTopic; end; /// <summary> /// 默认的全局 MQTT 客户端实例 /// </summary> function DefaultMqttClient: TQMQTTMessageClient; implementation resourcestring SServerHostUnknown = 'MQTT 服务器地址未设置'; SServerPortInvalid = '无效的服务器端口号'; STooLargePayload = '载荷大小 %d 超出包限制'; SClientNotRunning = '客户端未连接到服务器,不能订阅'; SInitSSLFailed = '初始化 SSL 失败,请检查目录下是否存在 libssl-1_1.dll 和 libcrypto-1_1.dll'; const MQTT5PropTypes: array [0 .. 41] of TQMQTT5PropType = ( // (FName: 'PayloadFormat'; FId: 1; FDataType: ptByte), // (FName: 'MessageExpire'; FId: 2; FDataType: ptInt), // (FName: 'ContentType'; FId: 3; FDataType: ptString), // (FName: ''; FId: 4; FDataType: ptUnknown), // (FName: ''; FId: 5; FDataType: ptUnknown), // (FName: ''; FId: 6; FDataType: ptUnknown), // (FName: ''; FId: 7; FDataType: ptUnknown), // (FName: 'ResponseTopic'; FId: 8; FDataType: ptString), // (FName: 'Data'; FId: 9; FDataType: ptBinary), // (FName: ''; FId: 10; FDataType: ptUnknown), // (FName: 'Identifier'; FId: 11; FDataType: ptInt), // (FName: ''; FId: 12; FDataType: ptUnknown), // (FName: ''; FId: 13; FDataType: ptUnknown), // (FName: ''; FId: 14; FDataType: ptUnknown), // (FName: ''; FId: 15; FDataType: ptUnknown), // (FName: ''; FId: 16; FDataType: ptUnknown), // (FName: 'SessionExpire'; FId: 17; FDataType: ptInt), // (FName: 'AssignClientId'; FId: 18; FDataType: ptString), // (FName: 'KeepAlive'; FId: 19; FDataType: ptWord), // (FName: ''; FId: 20; FDataType: ptUnknown), // (FName: 'AuthMethod'; FId: 21; FDataType: ptString), // (FName: 'AuthData'; FId: 22; FDataType: ptBinary), // (FName: 'NeedProblemInfo'; FId: 23; FDataType: ptByte), // (FName: 'WillDelay'; FId: 24; FDataType: ptInt), // (FName: 'NeedRespInfo'; FId: 25; FDataType: ptByte), // (FName: 'ResponseInfo'; FId: 26; FDataType: ptString), // (FName: ''; FId: 27; FDataType: ptUnknown), // (FName: 'ServerRefer'; FId: 28; FDataType: ptString), // (FName: ''; FId: 29; FDataType: ptUnknown), // (FName: ''; FId: 30; FDataType: ptUnknown), // (FName: 'Reason'; FId: 31; FDataType: ptString), // (FName: ''; FId: 32; FDataType: ptUnknown), // (FName: 'RecvMax'; FId: 33; FDataType: ptWord), // (FName: 'AliasMax'; FId: 34; FDataType: ptWord), // (FName: 'TopicAlias'; FId: 35; FDataType: ptWord), // (FName: 'MaxQoS'; FId: 36; FDataType: ptByte), // (FName: 'HasRetain'; FId: 37; FDataType: ptByte), // (FName: 'UserProp'; FId: 38; FDataType: ptString), // (FName: 'MaxPkgSize'; FId: 39; FDataType: ptInt), // (FName: 'HasWildcardSubcribes'; FId: 40; FDataType: ptByte), // (FName: 'HasSubscribeId'; FId: 41; FDataType: ptByte), // (FName: 'HasShareSubscribes'; FId: 42; FDataType: ptByte) // ); type TQMQTTConnectHeader = packed record Protocol: array [0 .. 5] of Byte; Level: Byte; // Level Flags: Byte; // Flags Interval: Word; // Keep Alive end; PMQTTConnectHeader = ^TQMQTTConnectHeader; TSocketThread = class(TThread) protected [unsafe] FOwner: TQMQTTMessageClient; public constructor Create(AOwner: TQMQTTMessageClient); overload; end; TSocketRecvThread = class(TSocketThread) protected procedure Execute; override; public constructor Create(AOwner: TQMQTTMessageClient); overload; end; TSocketSendThread = class(TSocketThread) protected FNotifyEvent: TEvent; FFirst, FLast: PQMQTTMessage; procedure Execute; override; public constructor Create(AOwner: TQMQTTMessageClient); overload; destructor Destroy; override; procedure Post(AMessage: PQMQTTMessage); function Send(AMessage: PQMQTTMessage; ATimeout: Cardinal = INFINITE): Boolean; procedure Clear; end; TTopicHandler = class protected FRegex: TPerlRegex; FTopic: String; FOnDispatch: TQMQTTTopicDispatchEvent; FNext: TTopicHandler; FMatchType: TTopicMatchType; public constructor Create(const ATopic: String; AHandler: TQMQTTTopicDispatchEvent; AMatchType: TTopicMatchType); destructor Destroy; override; function IsMatch(const ATopic: String): Boolean; property Topic: String read FTopic; end; const RegexTopic = '@regex@'; PatternTopic = '@topic@'; var _DefaultClient: TQMQTTMessageClient = nil; function DefaultMqttClient: TQMQTTMessageClient; var AClient: TQMQTTMessageClient; begin if not Assigned(_DefaultClient) then begin AClient := TQMQTTMessageClient.Create(nil); if AtomicCmpExchange(Pointer(_DefaultClient), Pointer(AClient), nil) <> nil then FreeAndNil(AClient); {$IFDEF AUTOREFCOUNT} AClient.__ObjAddRef; {$ENDIF} end; Result := _DefaultClient; end; { TMessageQueue } function TQMQTTMessageClient.AcquirePackageId(AReq: PQMQTTMessage; AIsWaitAck: Boolean): Word; var ALast: Word; ATryTimes: Integer; begin ATryTimes := 0; repeat Lock; try ALast := FPackageId; repeat Result := Word(AtomicIncrement(FPackageId)); if not Assigned(FWaitAcks[Result]) then begin if AIsWaitAck then begin FWaitAcks[Result] := AReq; Inc(FWaitAckTopics); end; Break; end; until Result = ALast; finally Unlock; end; if Result = ALast then begin Result := 0; // 给出时间来确空出可用的PackageId,如果重试超过3次仍不行,放弃 // 这里给出较大的延时,是因为到这种情况下,明显待确认的已经有65536项, // 明显是太多了 Sleep(50); Inc(ATryTimes); end; until (Result > 0) and (ATryTimes < 3); // 投递的太多,造成等待确认的包已经达到上限,那么放弃 Assert(Result <> ALast); end; procedure TQMQTTMessageClient.BeforeDestruction; begin inherited; Stop; CheckSynchronize; end; procedure TQMQTTMessageClient.CheckPublished; var I: Integer; ATick, ATimeout: Cardinal; begin if (FWaitAckTopics > 0) and Assigned(FSendThread) then begin ATick := {$IF RTLVersion>=23}TThread.{$IFEND}GetTickCount; ATimeout := MaxTopicAckTimeout * 1000; Lock; try for I := 0 to High(FWaitAcks) do begin if Assigned(FWaitAcks[I]) and (FWaitAcks[I].SentTime > 0) and (ATick - FWaitAcks[I].SentTime > ATimeout) then TSocketSendThread(FSendThread).Post(FWaitAcks[I]); end; finally Unlock; end; end; end; procedure TQMQTTMessageClient.CleanPublishPendings; var AItem, ANext: PQMQTTPublishPendingItem; begin if Assigned(FPublishPendings.First) then begin AItem := FPublishPendings.First; FPublishPendings.First := nil; FPublishPendings.Last := nil; while Assigned(AItem) do begin ANext := AItem.Next; if Assigned(AItem.Props) then FreeAndNil(AItem.Props); Dispose(AItem); AItem := ANext; end; end; end; procedure TQMQTTMessageClient.ClearHandlers; var I: Integer; AHandler, ANext: TTopicHandler; begin for I := 0 to FTopicHandlers.Count - 1 do begin AHandler := TTopicHandler(FTopicHandlers.Objects[I]); while Assigned(AHandler) do begin ANext := AHandler.FNext; FreeAndNil(AHandler); AHandler := ANext; end; end; FTopicHandlers.Clear; end; procedure TQMQTTMessageClient.ClearSubscribes; var I: Integer; ATopics: array of String; AList: TStringList; AProps: TQMQTT5Props; begin AList := TStringList.Create; try AList.Duplicates := dupIgnore; AList.Sorted := True; for I := 0 to FSubscribes.Count - 1 do begin AList.Add(ValueOfW(FSubscribes[I], '|')); AProps := TQMQTT5Props(AList.Objects[I]); if Assigned(AProps) then FreeAndNil(AProps); end; SetLength(ATopics, AList.Count); for I := 0 to AList.Count - 1 do ATopics[I] := AList[I]; Unsubscribe(ATopics); FSubscribes.Clear; finally FreeAndNil(AList); end; end; procedure TQMQTTMessageClient.ClearWaitAcks; var I, C: Integer; ATemp: TArray<PQMQTTMessage>; begin SetLength(ATemp, 65536); C := 0; Lock; try for I := 0 to High(FWaitAcks) do begin if Assigned(FWaitAcks[I]) then begin ATemp[C] := FWaitAcks[I]; Inc(C); FWaitAcks[I] := nil; end; end; finally Unlock; end; for I := 0 to C - 1 do FreeMessage(ATemp[I]); end; constructor TQMQTTMessageClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FPeekInterval := 60; // 默认 Ping 时间间隔 FConnectionTimeout := 15; // 默认连接超时 FReconnectInterval := 30; // 默认重连间隔 FMaxTopicAckTimeout := 15; // 对于QoS1/2消息,从发出到确认的最大间隔时间 FPublishTTL := INFINITE; FStates := []; FNotifyEvent := TEvent.Create(nil, false, false, ''); FTopicHandlers := TStringList.Create; FTopicHandlers.Sorted := True; FSubscribes := TStringList.Create; FSubscribes.Sorted := True; FSubscribes.Duplicates := dupIgnore; FProtocolVersion := pv3_1_1; FLocker := TCriticalSection.Create; end; destructor TQMQTTMessageClient.Destroy; var I: Integer; AProps: TQMQTT5Props; begin AtomicCmpExchange(Pointer(_DefaultClient), nil, Pointer(Self)); //DebugOut('Free MQTT client %x', [IntPtr(Self)]); FreeAndNil(FNotifyEvent); ClearHandlers; FreeAndNil(FTopicHandlers); for I := 0 to FSubscribes.Count - 1 do begin AProps := TQMQTT5Props(FSubscribes.Objects[I]); if Assigned(AProps) then FreeAndNil(AProps); end; CleanPublishPendings; FreeAndNil(FSubscribes); FreeAndNil(FConnectProps); FreeAndNil(FLocker); inherited; end; procedure TQMQTTMessageClient.Disconnect; var AReq: PQMQTTMessage; begin if Assigned(FSendThread) then begin AReq := TQMQTTMessage.Create(Self); AReq.PayloadSize := 0; AReq.ControlType := TQMQTTControlType.ctDisconnect; AReq.FAfterSent := DoFreeAfterSent; AReq.States := [msNeedWait]; TSocketSendThread(FSendThread).Send(AReq, 1000); end; end; procedure TQMQTTMessageClient.InvokeTopicHandlers(const ATopic: String; AMsg: PQMQTTMessage); var AIdx: Integer; procedure InvokeItem(AItem: TTopicHandler); begin while Assigned(AItem) do begin if Assigned(AItem.FOnDispatch) and AItem.IsMatch(ATopic) then begin case IntPtr(TMethod(AItem.FOnDispatch).Data) of 0: TQMQTTTopicDispatchEventG(TMethod(AItem.FOnDispatch).Code) (Self, ATopic, AMsg); 1: TQMQTTTopicDispatchEventA(TMethod(AItem.FOnDispatch).Code) (Self, ATopic, AMsg); else AItem.FOnDispatch(Self, ATopic, AMsg); end; end; AItem := AItem.FNext; end; end; begin try if Assigned(FBeforeDispatch) then FBeforeDispatch(Self, ATopic, AMsg); if FTopicHandlers.Find(ATopic, AIdx) then InvokeItem(TTopicHandler(FTopicHandlers.Objects[AIdx])); if FTopicHandlers.Find(PatternTopic, AIdx) then InvokeItem(TTopicHandler(FTopicHandlers.Objects[AIdx])); if FTopicHandlers.Find(RegexTopic, AIdx) then InvokeItem(TTopicHandler(FTopicHandlers.Objects[AIdx])); finally if Assigned(FAfterDispatch) then FAfterDispatch(Self, ATopic, AMsg); end; end; procedure TQMQTTMessageClient.DispatchProps(AMsg: PQMQTTMessage); var AProps: TQMQTT5Props; begin if ProtocolVersion = pv5_0 then begin AProps := TQMQTT5Props.Create; try AProps.ReadProps(AMsg); ConnectProps.Replace(AProps); finally FreeAndNil(AProps); end; end; end; procedure TQMQTTMessageClient.DispatchTopic(AMsg: PQMQTTMessage); var ACopy: PQMQTTMessage; begin ACopy := AMsg.Copy; Queue( procedure var ATopic: String; begin try Inc(FRecvTopics); ATopic := ACopy.TopicName; if Assigned(FOnRecvTopic) then FOnRecvTopic(Self, ATopic, ACopy); InvokeTopicHandlers(ATopic, ACopy); finally FreeMessage(ACopy); end; end); end; function TQMQTTMessageClient.DNSLookupV4(const AHost: QStringW): Cardinal; var Utf8Host: QStringA; AEntry: PHostEnt; function TryAsAddr( var AResult: Cardinal): Boolean; var p: PQCharW; I, V: Integer; B: array [0 .. 3] of Byte absolute AResult; begin p := PQCharW(AHost); V := 0; I := 0; while p^ <> #0 do begin if (p^ >= '0') and (p^ <= '9') then V := V * 10 + Ord(p^) - Ord('0') else if p^ = '.' then begin if V > 255 then begin Result := false; Exit; end; B[I] := Byte(V); Inc(I); V := 0; end else begin Result := false; Exit; end; Inc(p); end; Result := (p^ = #0) and (I = 3) and (V < 256); if Result then B[I] := V; end; begin if not TryAsAddr(Result) then begin Result := 0; Utf8Host := qstring.Utf8Encode(AHost); AEntry := gethostbyname ({$IFDEF UNICODE}MarshaledAString{$ELSE}PAnsiChar{$ENDIF}(PQCharA(Utf8Host))); if Assigned(AEntry) then begin if AEntry.h_addrtype = AF_INET then begin if AEntry.h_addr_list^ <> nil then Result := PCardinal(AEntry.h_addr_list^)^; end; end; end; end; procedure TQMQTTMessageClient.DoAfterConnected; begin Queue( procedure begin FConnected := True; FReconnectTimes := 0; // 清空重连计数 FReconnectTime := 0; FPingTime := {$IF RTLVersion>=23}TThread.{$IFEND}GetTickCount; FStates := FStates - [qcsConnecting, qcsReconnecting]; if Assigned(FAfterConnected) then FAfterConnected(Self); SubscribePendings; PublishFirstPending; end); end; procedure TQMQTTMessageClient.DoAfterSent(const AReq: PQMQTTMessage); begin if Assigned(AReq.FAfterSent) or Assigned(FAfterSent) then begin Queue( procedure begin if Assigned(AReq.FAfterSent) then AReq.FAfterSent(AReq); if Assigned(FAfterSent) then FAfterSent(AReq); end); end; end; procedure TQMQTTMessageClient.DoAfterDisconnected; begin if poCleanOnDisconnect in FPublishOptions then CleanPublishPendings; if Assigned(FAfterDisconnected) then FAfterDisconnected(Self); end; procedure TQMQTTMessageClient.DoAfterSubcribed(AResult: PQMQTTSubscribeResults); begin if Assigned(FAfterSubscribed) then begin Queue( procedure begin try if Assigned(FAfterSubscribed) then FAfterSubscribed(Self, AResult^); finally Dispose(AResult); end; end); end else Dispose(AResult); end; procedure TQMQTTMessageClient.DoAfterUnsubscribed(ASource: PQMQTTMessage); begin if Assigned(FAfterUnsubscribed) and Assigned(ASource) then begin Queue( procedure var ATopic: String; begin try if Assigned(FAfterUnsubscribed) then begin ASource.Position := ASource.VarHeaderOffset + 2; while ASource.Current < ASource.Eof do begin ATopic := ASource.NextString; FAfterUnsubscribed(Self, ATopic); end; end; finally FreeMessage(ASource); end; end); end else FreeMessage(ASource); end; procedure TQMQTTMessageClient.DoBeforeConnect; begin if Assigned(FBeforeConnect) then begin Queue( procedure begin FStates := FStates + [qcsConnecting]; if Assigned(FBeforeConnect) then FBeforeConnect(Self); end) end; end; procedure TQMQTTMessageClient.DoBeforePublish(ATopic: String; AMsg: PQMQTTMessage); var ATemp: PQMQTTMessage; begin if Assigned(FBeforePublish) then begin ATemp := AMsg.Copy; // 已知:如果正在处理时程序溢出,内存可能泄露 Queue( procedure begin try if Assigned(FBeforePublish) then FBeforePublish(Self, ATemp.TopicName, ATemp); finally Dispose(ATemp); end; end); end; end; procedure TQMQTTMessageClient.DoBeforeSend(const AReq: PQMQTTMessage); begin if Assigned(FBeforeSend) then begin end; end; procedure TQMQTTMessageClient.DoCleanup; begin FSSL := nil; end; procedure TQMQTTMessageClient.DoCloseSocket; const SD_BOTH = 2; begin if (FSocket <> 0) then begin if Assigned(FSSL) then begin FSSL := nil; end; Shutdown(FSocket, SD_BOTH); {$IFDEF MSWINDOWS} closesocket(FSocket); {$ELSE} __close(FSocket); {$ENDIF} FSocket := 0; FPingStarted := 0; DoAfterDisconnected; end; end; procedure TQMQTTMessageClient.DoConnect; var AReq: PQMQTTMessage; AUserName, APassword, AClientId, AWillTopic: QStringA; APayloadSize: Integer; AHeader: PMQTTConnectHeader; const Protocol: array [0 .. 5] of Byte = (0, 4, Ord('M'), Ord('Q'), Ord('T'), Ord('T')); begin FConnected := false; AReq := TQMQTTMessage.Create(Self); APayloadSize := SizeOf(TQMQTTConnectHeader); if Length(FUserName) > 0 then begin AUserName := qstring.Utf8Encode(FUserName); Inc(APayloadSize, 2 + AUserName.Length); end; if Length(FPassword) > 0 then begin APassword := qstring.Utf8Encode(FPassword); Inc(APayloadSize, 2 + APassword.Length); end; ValidClientId; AClientId := qstring.Utf8Encode(FClientId); Inc(APayloadSize, 2 + AClientId.Length); if (Length(FWillTopic) > 0) and (Length(FWillMessage) > 0) then begin AWillTopic := qstring.Utf8Encode(FWillTopic); Inc(APayloadSize, 4 + AWillTopic.Length + Length(FWillMessage)); end; if (ProtocolVersion = pv5_0) then begin if Assigned(FConnectProps) then Inc(APayloadSize, FConnectProps.PayloadSize) else Inc(APayloadSize, 1); end; AReq.PayloadSize := APayloadSize; AReq.ControlType := ctConnect; AReq.IsRetain := IsRetain; AReq.QosLevel := QosLevel; AHeader := PMQTTConnectHeader(AReq.Current); Move(Protocol, AHeader^.Protocol, 6); with AHeader^ do begin Level := Ord(ProtocolVersion); // MQTT 3.1.1 Flags := 0; if Length(FUserName) > 0 then Flags := Flags or $80; if Length(FPassword) > 0 then Flags := Flags or $40; if IsRetain then Flags := Flags or $20; Flags := Flags or (Ord(QosLevel) shl 3); if Length(FWillTopic) > 0 then Flags := Flags or $04; if CleanLastSession then Flags := Flags or $02; Interval := ExchangeByteOrder(FPeekInterval); end; AReq.MoveBy(SizeOf(TQMQTTConnectHeader)); if (ProtocolVersion = pv5_0) then begin if Assigned(FConnectProps) then FConnectProps.WriteProps(AReq) else AReq.Cat(Byte(0)); end; AReq.Cat(AClientId); if (Length(FWillTopic) > 0) and (Length(FWillMessage) > 0) then AReq.Cat(AWillTopic).Cat(Word(Length(FWillMessage))).Cat(FWillMessage); if Length(FUserName) > 0 then AReq.Cat(AUserName); if Length(FPassword) > 0 then AReq.Cat(APassword); AReq.FAfterSent := DoFreeAfterSent; if Assigned(FSendThread) then TSocketSendThread(FSendThread).Post(AReq); end; procedure TQMQTTMessageClient.DoConnectFailed; begin FStates := FStates - [qcsConnecting]; end; procedure TQMQTTMessageClient.DoDispatch(var AReq: TQMQTTMessage); procedure DispatchConnectAck; var AErrorCode: Byte; begin Assert(AReq.PayloadSize >= 2); // RemainSize=2 if ProtocolVersion = pv5_0 then begin AReq.MoveToVarHeader; AReq.MoveBy(1); // 跳过标志位,只有一个会话是否是已经存在的标记,忽略掉(0x01) AErrorCode := AReq.NextByte; if AErrorCode = 0 then begin DispatchProps(@AReq); DoAfterConnected; end else begin DoConnectFailed; DoError(MQERR_CONNECT + AErrorCode); end end else begin // 错误代码 case AReq[3] of 0: // DoAfterConnected else begin DoError(MQERR_CONNECT + AReq[3]); DoConnectFailed; Queue(Stop, True); end; end; end; end; procedure DispatchSubscribeAck; var APackageId: Word; AAckPayload: Cardinal; ASource: PQMQTTMessage; AResults: PQMQTTSubscribeResults; AIdx: Integer; Ack: Byte; begin // 跳过固定报头 AReq.Position := 1; // 载荷大小 AAckPayload := AReq.NextDWord(True); // 消息ID APackageId := AReq.NextWord(false); // 属性(5.0+) DispatchProps(@AReq); ASource := PopWaitAck(APackageId); if Assigned(ASource) then begin New(AResults); try ASource.Position := ASource.VarHeaderOffset + 2; SetLength(AResults^, AAckPayload - 2); // 去掉PackageId,剩下的每个字节处理一个结果 AIdx := 0; while ASource.Current < ASource.Eof do begin with AResults^[AIdx] do begin Topic := ASource.NextString; Ack := AReq.NextByte; if (Ack and $80) <> 0 then begin DoError(MQERR_SUBSCRIBE_FAILED); ErrorCode := Ack; Qos := TQMQTTQoSLevel(ASource.NextByte); end else begin Qos := TQMQTTQoSLevel(Ack); ErrorCode := 0; ASource.NextByte; end; end; Inc(AIdx); end; DoAfterSubcribed(AResults); AResults := nil; finally FreeMessage(ASource); if Assigned(AResults) then Dispose(AResults); end; end; end; procedure DispatchPublish; var Ack: PQMQTTMessage; APackageId, ATopicLen: Word; AQoSLevel: TQMQTTQoSLevel; begin DispatchTopic(@AReq); AReq.Position := AReq.VarHeaderOffset; ATopicLen := AReq.NextWord(false); AReq.MoveBy(ATopicLen); AQoSLevel := AReq.QosLevel; if AQoSLevel > qlMax1 then begin APackageId := AReq.NextWord(false); Ack := TQMQTTMessage.Create(Self); Ack.PayloadSize := 2; if AQoSLevel = qlAtLeast1 then Ack.ControlType := TQMQTTControlType.ctPublishAck else Ack.ControlType := TQMQTTControlType.ctPublishRecv; Ack.Cat(APackageId); Ack.FAfterSent := DoFreeAfterSent; TSocketSendThread(FSendThread).Post(Ack); end; end; procedure DoPublishAck; var APackageId: Word; begin AReq.Position := AReq.VarHeaderOffset; APackageId := AReq.NextWord(false); Queue( procedure begin DoTopicPublished(PopWaitAck(APackageId)); end); end; procedure DoPublishRelease; var APackageId: Word; Ack: PQMQTTMessage; begin AReq.Position := AReq.VarHeaderOffset; APackageId := AReq.NextWord(false); Queue( procedure var ASource: PQMQTTMessage; begin ASource := PopWaitAck(APackageId); if Assigned(ASource) then FreeMessage(ASource); end); Ack := TQMQTTMessage.Create(Self); Ack.PayloadSize := 2; Ack.QosLevel := TQMQTTQoSLevel.qlAtLeast1; Ack.ControlType := TQMQTTControlType.ctPublishDone; Ack.Cat(APackageId); Ack.FAfterSent := DoFreeAfterSent; TSocketSendThread(FSendThread).Post(Ack); end; procedure DoPublishRecv; var Ack: PQMQTTMessage; APackageId: Word; begin Ack := TQMQTTMessage.Create(Self); AReq.Position := AReq.VarHeaderOffset; APackageId := AReq.NextWord(false); Ack.PayloadSize := 2; Ack.IsRetain := false; Ack.QosLevel := TQMQTTQoSLevel.qlAtLeast1; Ack.ControlType := TQMQTTControlType.ctPublishRelease; Ack.Position := AReq.VarHeaderOffset; Ack.Cat(APackageId); Ack.FAfterSent := DoFreeAfterSent; TSocketSendThread(FSendThread).Post(Ack); end; procedure DoUnsubscribeAck; var APackageId: Word; begin AReq.Position := AReq.VarHeaderOffset; APackageId := AReq.NextWord(false); Queue( procedure begin DoAfterUnsubscribed(PopWaitAck(APackageId)); end); end; procedure DoPingAck; begin Queue( procedure begin {$IFDEF LogMqttContent} PostLog(llDebug, 'Ping 服务器往返用时 %d ms', [GetTickCount - FPingStarted], 'QMQTT'); {$ENDIF} FPingStarted := 0; end); end; begin {$IFDEF LogMqttContent} if LogPackageContent then PostLog(llDebug, '[接收]收到命令 %d,TopicId=%d,载荷大小:%d,总大小:%d 内容:'#13#10'%s', [Ord(AReq.ControlType), Integer(AReq.TopicId), Integer(AReq.PayloadSize), Integer(AReq.Size), AReq.ContentAsHexText], 'QMQTT') else PostLog(llDebug, '[接收]收到命令 %d,TopicId=%d,载荷大小:%d,总大小:%d', [Ord(AReq.ControlType), Integer(AReq.TopicId), Integer(AReq.PayloadSize), Integer(AReq.Size)], 'QMQTT'); {$ENDIF} AReq.States := AReq.States + [msDispatching]; case AReq.ControlType of ctConnectAck: // 连接成功 DispatchConnectAck; ctPublish: // 收到服务器发布的消息 DispatchPublish; ctPublishAck: // 收到发布主题服务器端的确认 DoPublishAck; ctPublishRecv: DoPublishRecv; ctPublishRelease: DoPublishRelease; ctPublishDone: DoPublishAck; ctSubscribeAck: DispatchSubscribeAck; ctUnsubscribeAck: DoUnsubscribeAck; ctPingResp: DoPingAck; end; AReq.States := AReq.States + [msDispatched]; end; procedure TQMQTTMessageClient.DoError(AErrorCode: Integer); const KnownErrorMessages: array [0 .. 6] of String = ('操作成功完成', '协议版本号不受支持', '客户端ID被拦截', '服务不可用', '用户名或密码错误', '客户端未被授权连接', '订阅指定的主题失败'); var AMsg: String; begin if Assigned(FOnError) then begin if AErrorCode < Length(KnownErrorMessages) then AMsg := KnownErrorMessages[AErrorCode] else begin AMsg := '未知的错误代码:' + IntToStr(AErrorCode); end; Queue( procedure begin FOnError(Self, AErrorCode, AMsg); end); end; end; procedure TQMQTTMessageClient.DoFreeAfterSent(const AMessage: PQMQTTMessage); begin FreeMessage(AMessage); end; procedure TQMQTTMessageClient.DoMQTTConnect(AJob: PQJob); var Addr: sockaddr_in; tm: TIMEVAL; mode: Integer; ASocket: THandle; fdWrite, fdError: {$IFDEF MSWINDOWS}TFdSet{$ELSE}FD_SET{$ENDIF}; begin if (csDestroying in ComponentState) then // 未处于析构状态 Exit; FLastConnectTime := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; DoBeforeConnect; ASocket := Socket(PF_INET, SOCK_STREAM, 0); if ASocket = THandle(-1) then RaiseLastOSError; try // 连接到远程地址 Addr.sin_family := AF_INET; Addr.sin_port := htons(FServerPort); Addr.sin_addr.S_addr := DNSLookupV4(FServerHost); if Addr.sin_addr.S_addr = 0 then RaiseLastOSError; tm.tv_sec := FConnectionTimeout; tm.tv_usec := 0; {$IFDEF MSWINDOWS} mode := 1; {$ENDIF} if {$IFDEF MSWINDOWS}ioctlsocket(ASocket, FIONBIO, mode) <> NO_ERROR{$ELSE}Fcntl(ASocket, F_SETFL, Fcntl(ASocket, F_GETFL, 0) or O_NONBLOCK) = -1{$ENDIF} then RaiseLastOSError; CONNECT(ASocket, {$IFDEF MSWINDOWS}sockaddr_in{$ELSE}sockaddr{$ENDIF}(Addr), SizeOf(Addr)); FD_ZERO(fdWrite); FD_ZERO(fdError); {$IFDEF MSWINDOWS} FD_SET(ASocket, fdWrite); FD_SET(ASocket, fdError); {$ELSE} _FD_SET(ASocket, fdWrite); _FD_SET(ASocket, fdError); {$ENDIF} mode := select(ASocket + 1, nil, @fdWrite, @fdError, @tm); if mode >= 0 then begin if FD_ISSET(ASocket, fdError) then RaiseLastOSError; if FD_ISSET(ASocket, fdWrite) then //DebugOut('Socket writable') else begin raise EMQTTAbortError.Create('连接服务器失败'); end; end else RaiseLastOSError; {$IFDEF MSWINDOWS} mode := 0; {$ENDIF} if {$IFDEF MSWINDOWS}ioctlsocket(ASocket, FIONBIO, mode) <> NO_ERROR{$ELSE}Fcntl(ASocket, F_SETFL, Fcntl(ASocket, F_GETFL, 0) or O_NONBLOCK) = -1{$ENDIF} then RaiseLastOSError; if UseSSL and (not Assigned(FSSL)) then begin if TQSSLManager.ActiveFactory <> nil then begin // SSL 使用阻塞模式,异步模式控制有点小复杂:) {$IFDEF MSWINDOWS} mode := 0; {$ENDIF} if {$IFDEF MSWINDOWS}ioctlsocket(ASocket, FIONBIO, mode) <> NO_ERROR{$ELSE}Fcntl(ASocket, F_SETFL, Fcntl(ASocket, F_GETFL, 0) or O_NONBLOCK) = -1{$ENDIF} then RaiseLastOSError; FSSL := TQSSLManager.ActiveFactory.NewItem; if not Assigned(FSSL) then raise EMQTTAbortError.Create(SInitSSLFailed); FSSL.Handle := ASocket; if not FSSL.CONNECT then begin raise EMQTTAbortError.Create(FSSL.GetFactory.LastErrorMsg); end; // raise Exception.Create(FSSL.LastErrorMsg); // 连接完再调整回去:) mode := 1; if {$IFDEF MSWINDOWS}ioctlsocket(ASocket, FIONBIO, mode) <> NO_ERROR {$ELSE}Fcntl(ASocket, F_SETFL, Fcntl(ASocket, F_GETFL, 0) and (not O_NONBLOCK)) = -1{$ENDIF} then RaiseLastOSError; end else begin Stop; raise Exception.Create(SInitSSLFailed); end; end; FSocket := ASocket; DoConnect; FConnectJob := 0; except on E: Exception do begin mode := GetLastError; FConnectJob := 0; if not(csDestroying in ComponentState) then // 未处于析构状态 begin TThread.Synchronize(nil, procedure begin if Assigned(FOnError) then FOnError(Self, mode, E.Message); end); end; FStates := FStates - [qcsConnecting]; FReconnectTime := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; if not(qcsReconnecting in FStates) then begin if qcsRunning in FStates then FStates := FStates + [qcsReconnecting]; end; {$IFDEF MSWINDOWS} closesocket(ASocket); {$ELSE} __close(ASocket); {$ENDIF} if ASocket = FSocket then FSocket := 0; TThread.ForceQueue(nil, DoCloseSocket); end; end; end; procedure TQMQTTMessageClient.DoPing; var AReq: PQMQTTMessage; begin if (FPingStarted = 0) and Assigned(FSendThread) then begin FPingStarted := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; FPingTime := FPingStarted; AReq := TQMQTTMessage.Create(Self); AReq.PayloadSize := 0; AReq.ControlType := TQMQTTControlType.ctPing; AReq.FAfterSent := DoFreeAfterSent; TSocketSendThread(FSendThread).Post(AReq); end; end; procedure TQMQTTMessageClient.DoQueueCallback(AJob: PQJob); begin TThreadProcedure(AJob.Data)(); end; procedure TQMQTTMessageClient.FreeMessage(AMsg: PQMQTTMessage); var APkgId: Word; begin if Assigned(AMsg) then begin if msNeedAck in AMsg.States then begin APkgId := AMsg.PackageId; Lock; try if FWaitAcks[APkgId] = AMsg then begin FWaitAcks[APkgId] := nil; Dec(FWaitAckTopics); end; finally Unlock; end; end; Dispose(AMsg); end; end; function TQMQTTMessageClient.GetClientId: String; begin ValidClientId; Result := FClientId; end; function TQMQTTMessageClient.GetConnectProps: TQMQTT5Props; begin if not Assigned(FConnectProps) then FConnectProps := TQMQTT5Props.Create; Result := FConnectProps; end; function TQMQTTMessageClient.GetIsRunning: Boolean; begin Result := Assigned(FRecvThread) and Assigned(FSendThread) and (FSocket <> 0); end; function TQMQTTMessageClient.GetSSLManager: TQSSLManager; begin Result := TQSSLManager.Current; end; procedure TQMQTTMessageClient.Lock; begin FLocker.Enter; end; procedure TQMQTTMessageClient.Publish(const ATopic, AContent: String; AQoSLevel: TQMQTTQoSLevel); var AUtf8Content: QStringA; begin AUtf8Content := qstring.Utf8Encode(AContent); Publish(ATopic, AUtf8Content.Data^, AUtf8Content.Length, AQoSLevel); end; procedure TQMQTTMessageClient.Publish(const ATopic: String; AContent: TBytes; AQoSLevel: TQMQTTQoSLevel); begin Publish(ATopic, AContent[0], Length(AContent), AQoSLevel) end; function TQMQTTMessageClient.PopWaitAck(APackageId: Word): PQMQTTMessage; begin Lock; try if APackageId < Length(FWaitAcks) then begin Result := FWaitAcks[APackageId]; FWaitAcks[APackageId] := nil; if Assigned(Result) then Dec(FWaitAckTopics); end else Result := nil; finally Unlock; end; if Assigned(Result) then Result.States := Result.States - [msNeedAck]; end; procedure TQMQTTMessageClient.Publish(const ATopic: String; const AContent; ALen: Cardinal; AQoSLevel: TQMQTTQoSLevel); var AReq: PQMQTTMessage; AUtf8Topic: QStringA; APackageId: Word; ANeedAck: Boolean; APayloadSize: Cardinal; procedure PushPendings; var AItem: PQMQTTPublishPendingItem; begin New(AItem); AItem.Topic := ATopic; SetLength(AItem.Content, ALen); Move(AContent, AItem.Content[0], ALen); AItem.Qos := AQoSLevel; AItem.Next := nil; AItem.PushTime := {$IF RTLVersion>=23}TThread.{$IFEND}GetTickCount; AItem.Prior := nil; AItem.Props := nil; // Support for MQTT 5.0 Queue( procedure begin AItem.Prior := FPublishPendings.Last; if Assigned(FPublishPendings.Last) then FPublishPendings.Last.Next := AItem else FPublishPendings.First := AItem; FPublishPendings.Last := AItem; end); end; begin if not(IsRunning and Connected) then begin if poCacheUnpublish in FPublishOptions then // 发布的主题是否放到待发送队列中 PushPendings; Exit; end; Assert(Length(ATopic) > 0); AUtf8Topic := qstring.Utf8Encode(ATopic); // 判断总长度不能超过限制 APayloadSize := SizeOf(Word) + Cardinal(AUtf8Topic.Length) + ALen; AReq := TQMQTTMessage.Create(Self); ANeedAck := AQoSLevel <> TQMQTTQoSLevel.qlMax1; if ANeedAck then begin AReq.States := AReq.States + [msNeedAck]; Inc(APayloadSize, 2); AReq.PayloadSize := APayloadSize; APackageId := AcquirePackageId(AReq, ANeedAck); if APackageId = 0 then begin Dispose(AReq); if poCacheUnpublish in FPublishOptions then PushPendings else DoError(MQERR_PUBLISH_FAILED); Exit; end; end else begin AReq.PayloadSize := APayloadSize; APackageId := 0; end; AReq.ControlType := TQMQTTControlType.ctPublish; AReq.QosLevel := AQoSLevel; AReq.IsRetain := IsRetain; // 主题名 AReq.Cat(AUtf8Topic); // 标志符 if ANeedAck then AReq.Cat(APackageId); AReq.Cat(@AContent, ALen); DoBeforePublish(ATopic, AReq); if AQoSLevel = TQMQTTQoSLevel.qlMax1 then AReq.FAfterSent := DoTopicPublished; TSocketSendThread(FSendThread).Post(AReq); end; procedure TQMQTTMessageClient.PublishFirstPending; var AItem: PQMQTTPublishPendingItem; begin if Assigned(FPublishPendings.First) then begin AItem := FPublishPendings.First; FPublishPendings.First := AItem.Next; if not Assigned(AItem.Next) then FPublishPendings.Last := nil; Publish(AItem.Topic, AItem.Content, AItem.Qos); if Assigned(AItem.Props) then FreeAndNil(AItem.Props); Dispose(AItem); end; end; procedure TQMQTTMessageClient.Queue(ACallback: TThreadProcedure; AIsForce: Boolean); type PInterface = ^IInterface; begin if AIsForce then Workers.Post(DoQueueCallback, Pointer(PInterface(@ACallback)^), not EventInThread, jdfFreeAsInterface) else begin if EventInThread or (GetCurrentThreadId = MainThreadId) then ACallback else Workers.Post(DoQueueCallback, Pointer(PInterface(@ACallback)^), True, jdfFreeAsInterface); end; end; procedure TQMQTTMessageClient.ReconnectNeeded; begin if [qcsConnecting, qcsReconnecting] * FStates <> [] then Exit; if Assigned(FSendThread) then TSocketSendThread(FSendThread).Clear; DoCloseSocket; FStates := FStates + [qcsReconnecting]; if FReconnectTimes = 0 then FReconnectTime := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; if FReconnectTimes < 5 then // 5次尽快连接,超过5次,就要去靠定时器延时重连 begin Inc(FReconnectTimes); if not(qcsStopping in FStates) then RecreateSocket; end; end; procedure TQMQTTMessageClient.RecreateSocket; begin if FConnectJob = 0 then begin DoCloseSocket; FConnectJob := Workers.Post(DoMQTTConnect, nil); end; end; procedure TQMQTTMessageClient.RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEventG; AType: TTopicMatchType); var AMethod: TMethod; ATemp: TQMQTTTopicDispatchEvent absolute AMethod; begin AMethod.Data := nil; AMethod.Code := @AHandler; RegisterDispatch(ATopic, ATemp, AType); end; procedure TQMQTTMessageClient.RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEventA; AType: TTopicMatchType); var AMethod: TMethod; ATemp: TQMQTTTopicDispatchEvent absolute AMethod; begin AMethod.Data := nil; TQMQTTTopicDispatchEventA(AMethod.Code) := AHandler; RegisterDispatch(ATopic, ATemp, AType); end; procedure TQMQTTMessageClient.RemoveSubscribePendings(const ATopics : array of String); var I: Integer; procedure RemoveItem(const ATopic: String); var J: Integer; begin J := 0; while J < FSubscribes.Count - 1 do begin if CompareTopic(ATopic, ValueOfW(FSubscribes[J], '|')) >= 0 then FSubscribes.Delete(J) else Inc(J); end; end; begin I := 0; while (FSubscribes.Count > 0) and (I < Length(ATopics)) do begin RemoveItem(ATopics[I]); Inc(I); end; end; procedure TQMQTTMessageClient.RegisterDispatch(const ATopic: String; AHandler: TQMQTTTopicDispatchEvent; AType: TTopicMatchType); var AItem, AFirst: TTopicHandler; AIdx: Integer; ARealTopic: String; begin if AType = TTopicMatchType.mtRegex then ARealTopic := RegexTopic else if AType = TTopicMatchType.mtPattern then ARealTopic := PatternTopic else ARealTopic := ATopic; if FTopicHandlers.Find(ARealTopic, AIdx) then AFirst := TTopicHandler(FTopicHandlers.Objects[AIdx]) else AFirst := nil; AItem := AFirst; // 检查主题响应是否注册过,以避免重复注册 while Assigned(AItem) do begin if MethodEqual(TMethod(AItem.FOnDispatch), TMethod(AHandler)) and (AItem.Topic = ATopic) then Exit; AItem := AItem.FNext; end; // 没找到创建一个新的添加进去 AItem := TTopicHandler.Create(ATopic, AHandler, AType); AItem.FNext := AFirst; if Assigned(AFirst) then FTopicHandlers.Objects[AIdx] := AItem else FTopicHandlers.AddObject(ARealTopic, AItem); end; procedure TQMQTTMessageClient.DoRecv; var AReq: PQMQTTMessage; AReaded, ATotal, ATick, ALastLargeIoTick: Cardinal; ARecv: Integer; tm: TIMEVAL; fdRead, fdError: {$IFDEF MSWINDOWS}TFdSet{$ELSE}FD_SET{$ENDIF}; rc: Integer; AErrorCode: Integer; const InvalidSize = Cardinal(-1); MinBufferSize = 4096; function ReadSize: Boolean; begin Result := AReq.ReloadSize(AReaded); if Result then ATotal := AReq.Size else ATotal := InvalidSize; end; begin AReq := TQMQTTMessage.Create(Self); try FReconnectTimes := 0; ALastLargeIoTick := 0; if FSocket = 0 then Queue(RecreateSocket); repeat while (FSocket = 0) do begin if TSocketRecvThread(TThread.Current).Terminated then Exit; Sleep(10); end; AReq.States := [msRecving]; AReq.Capacity := MinBufferSize; AReaded := 0; ATotal := Cardinal(-1); AErrorCode := 0; repeat FD_ZERO(fdRead); FD_ZERO(fdError); {$IFDEF MSWINDOWS} FD_SET(FSocket, fdRead); FD_SET(FSocket, fdError); {$ELSE} __FD_SET(FSocket, fdRead); __FD_SET(FSocket, fdError); {$ENDIF} try tm.tv_sec := 1; tm.tv_usec := 0; rc := select(FSocket + 1, @fdRead, nil, @fdError, @tm); if (rc > 0) then begin if FD_ISSET(FSocket, fdRead) and (not FD_ISSET(FSocket, fdError)) then begin if UseSSL then begin if Assigned(FSSL) then ARecv := FSSL.Read(AReq.FData[AReaded], Cardinal(Length(AReq.FData)) - AReaded) else Exit; end else ARecv := Recv(FSocket, AReq.FData[AReaded], Cardinal(Length(AReq.FData)) - AReaded, 0); if TSocketRecvThread(TThread.Current).Terminated then Break; if ARecv = -1 then begin if GetLastError = {$IFDEF MSWINDOWS}WSAEWOULDBLOCK{$ELSE}EWOULDBLOCK{$ENDIF} then begin Sleep(10); continue; end else begin AErrorCode := GetLastError; Break; end; end else if ARecv = 0 then // 没有进一步的数据时,让出CPU begin Queue(DoPing); Sleep(10); continue; end; Inc(AReaded, ARecv); FLastIoTick := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; if AReaded > 4096 then ALastLargeIoTick := FLastIoTick; if ATotal = InvalidSize then ReadSize; // 尝试解析总字节数 if ATotal <= AReaded then begin if AReaded >= AReq.Size then begin AReq.FRecvTime := FLastIoTick; AReq.States := AReq.States + [msRecved]; repeat DoDispatch(AReq^); ATotal := AReq.Size; if AReaded > AReq.Size then Move(AReq.FData[ATotal], AReq.FData[0], AReaded - ATotal); Dec(AReaded, ATotal); if not ReadSize then Break; until AReaded < AReq.Size; end; end; end else begin AErrorCode := GetLastError; Break; end; end else if rc < 0 then begin AErrorCode := GetLastError; Break; end else if rc = 0 then // 超时,检查是否需要Ping begin ATick := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; // 连续5秒读取不到填充够缓冲的数据,则缩小内存占用 if (AReq.Capacity > MinBufferSize) and (AReaded < MinBufferSize) and (ATick - ALastLargeIoTick > 5000) then begin AReq.PayloadSize := 0; AReq.Capacity := MinBufferSize; end; end; except end; until TSocketRecvThread(TThread.Current).Terminated; if (AErrorCode <> 0) and (not TSocketThread(TThread.Current).Terminated) and (FSocket <> 0) then begin //DebugOut(SysErrorMessage(AErrorCode)); if not(csDestroying in ComponentState) then // 未处于析构状态 TThread.Synchronize(nil, ReconnectNeeded); end; until TSocketThread(TThread.Current).Terminated; finally TThread.ForceQueue(nil, DoCloseSocket); FreeMessage(AReq); FRecvThread := nil; end; end; function TQMQTTMessageClient.DoSend(AReq: PQMQTTMessage): Boolean; var ASent: Integer; p: PByte; ASize: Integer; begin {$IFDEF LogMqttContent} if LogPackageContent then PostLog(llDebug, '发送请求 %d(%x),ID=%d,载荷大小:%d,总大小:%d,内容:'#13#10'%s', [Ord(AReq.ControlType), IntPtr(AReq), Integer(AReq.TopicId), Integer(AReq.PayloadSize), Integer(AReq.Size), AReq.ContentAsHexText], 'QMQTT') else PostLog(llDebug, '发送请求 %d(%x),ID=%d,载荷大小:%d,总大小:%d', [Ord(AReq.ControlType), IntPtr(AReq), Integer(AReq.TopicId), Integer(AReq.PayloadSize), Integer(AReq.Size)], 'QMQTT'); {$ENDIF} try if FSocket <> 0 then begin Result := false; DoBeforeSend(AReq); try p := AReq.Bof; ASize := AReq.Size; while (ASize > 0) and (not TSocketThread(TThread.Current).Terminated) do begin if UseSSL then begin if not Assigned(FSSL) then Exit; ASent := FSSL.Write(p^, ASize); if ASent > 0 then begin Inc(p, ASent); Dec(ASize, ASent); end else begin // 暂时不了解SSL这块,待定 end; end else begin ASent := Send(FSocket, p^, ASize, 0); if ASent <> -1 then begin Inc(p, ASent); Dec(ASize, ASent); end else if GetLastError = {$IFDEF MSWINDOWS} WSAEWOULDBLOCK{$ELSE}EWOULDBLOCK{$ENDIF} then begin Sleep(10); continue end else Break; end; end; if ASize = 0 then begin AReq.States := AReq.States + [msSent]; AReq.FSentTime := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; Inc(AReq.FSentTimes); Result := True; FLastIoTick := AReq.FSentTime; end; except on E: Exception do begin //DebugOut('发送数据时发生异常:' + E.Message); end end; end; finally AReq.States := AReq.States - [msSending]; if Assigned(AReq.FWaitEvent) then AReq.FWaitEvent.SetEvent; DoAfterSent(AReq); end; end; procedure TQMQTTMessageClient.DoTimer(AJob: PQJob); var ATick: Cardinal; procedure CheckPublishPendings; var AItem: PQMQTTPublishPendingItem; begin while Assigned(FPublishPendings.First) do begin AItem := FPublishPendings.First; if ATick - AItem.PushTime >= FPublishTTL then begin FPublishPendings.First := AItem.Next; if not Assigned(AItem.Next) then FPublishPendings.Last := nil; if Assigned(AItem.Props) then FreeAndNil(AItem.Props); Dispose(AItem); end else Break; end; end; begin ATick := {$IF RTLVersion>=23}TThread.{$IFEND} GetTickCount; CheckPublishPendings; if ([qcsConnecting, qcsReconnecting] * FStates) <> [] then // 连接中 begin if (ATick - FLastConnectTime) > (FConnectionTimeout * 1000) then RecreateSocket; Exit; end else if (qcsRunning in FStates) then // QoS 1等 begin if ((ATick - FPingTime) >= (FPeekInterval * 1000)) then DoPing else if (FPingStarted > 0) and ((ATick - FPingStarted) > 1000) then // Ping 必需在1秒内返回,如果不返回直接重连 ReconnectNeeded else CheckPublished; end; end; procedure TQMQTTMessageClient.DoTopicPublished(const AMessage: PQMQTTMessage); var ATopic: String; begin if Assigned(FAfterPublished) and Assigned(AMessage) then begin Queue( procedure begin try Inc(FSentTopics); if Assigned(FAfterPublished) then begin AMessage.Position := AMessage.VarHeaderOffset; ATopic := AMessage.NextString; FAfterPublished(Self, ATopic, AMessage); end; finally FreeMessage(AMessage); end; end); end else FreeMessage(AMessage); end; procedure TQMQTTMessageClient.SetWillMessage(const AValue: TBytes); begin FWillMessage := Copy(AValue, 0, Length(AValue)); end; procedure TQMQTTMessageClient.Start; begin if UseSSL then begin end; if Length(FServerHost) = 0 then raise EMQTTError.Create(SServerHostUnknown); if FServerPort = 0 then raise EMQTTError.Create(SServerPortInvalid); FStates := [qcsConnecting, qcsRunning]; ClearWaitAcks; SetLength(FWaitAcks, 65536); if not Assigned(FRecvThread) then FRecvThread := TSocketRecvThread.Create(Self); if not Assigned(FSendThread) then FSendThread := TSocketSendThread.Create(Self); Workers.Delay(DoTimer, 1000, nil, True, jdfFreeByUser, True); end; procedure TQMQTTMessageClient.Stop; var T: Cardinal; begin FStates := FStates + [qcsStopping] - [qcsRunning]; FReconnectTimes := 0; FReconnectTime := 0; Workers.Clear(Self, -1, false); if [qcsConnecting, qcsReconnecting] * FStates = [] then Disconnect; DoCloseSocket; if Assigned(FRecvThread) then begin FRecvThread.Terminate; FRecvThread := nil; end; if Assigned(FSendThread) then begin FSendThread.Terminate; TSocketSendThread(FSendThread).FNotifyEvent.SetEvent; FSendThread := nil; end; T := TThread.GetTickCount; while (FThreadCount > 0) and (TThread.GetTickCount - T < 5000) do Sleep(10); ClearWaitAcks; FStates := FStates - [qcsStopping]; end; procedure TQMQTTMessageClient.Subscribe(const ATopics: array of String; const AQoS: TQMQTTQoSLevel; AProps: TQMQTT5Props); var AReq: PQMQTTMessage; APayloadSize: Integer; APayloads: TArray<QStringA>; I, C: Integer; APackageId: Word; begin for I := Low(ATopics) to High(ATopics) do begin if Assigned(AProps) then FSubscribes.AddObject(IntToStr(Ord(AQoS)) + '|' + ATopics[I], AProps.Copy) else FSubscribes.AddObject(IntToStr(Ord(AQoS)) + '|' + ATopics[I], nil); end; if not IsRunning then Exit; SetLength(APayloads, Length(ATopics)); APayloadSize := Length(ATopics) * 3 + 2; C := 0; for I := 0 to High(ATopics) do begin APayloads[I] := qstring.Utf8Encode(ATopics[I]); if APayloads[I].Length > 0 then begin Inc(APayloadSize, APayloads[I].Length); Inc(C); end; end; if C > 0 then begin if (ProtocolVersion = pv5_0) then begin if Assigned(AProps) then Inc(APayloadSize, AProps.PayloadSize) else Inc(APayloadSize); end; AReq := TQMQTTMessage.Create(Self); AReq.PayloadSize := APayloadSize; AReq.ControlType := TQMQTTControlType.ctSubscribe; AReq.QosLevel := TQMQTTQoSLevel.qlAtLeast1; AReq.States := AReq.States + [msNeedAck]; // 报文标志符 APackageId := AcquirePackageId(AReq, True); AReq.Cat(APackageId); if (ProtocolVersion = pv5_0) then begin if Assigned(AProps) then AProps.WriteProps(AReq) else AReq.Cat(Byte(0)); // EncodeInt end; for I := 0 to High(APayloads) do AReq.Cat(APayloads[I]).Cat(Byte(Ord(AQoS))); TSocketSendThread(FSendThread).Post(AReq); end; end; procedure TQMQTTMessageClient.SubscribePendings; var ALevel, ALastLevel: TQMQTTQoSLevel; ATopics: array of String; ATopic: String; I, C: Integer; begin if FSubscribes.Count > 0 then begin SetLength(ATopics, FSubscribes.Count); ALevel := qlMax1; ALastLevel := ALevel; C := 0; for I := 0 to FSubscribes.Count - 1 do begin ATopic := FSubscribes[I]; ALevel := TQMQTTQoSLevel(StrToIntDef(NameOfW(ATopic, '|'), 0)); if ALevel <> ALastLevel then begin Subscribe(Copy(ATopics, 0, C), ALastLevel); C := 0; ALastLevel := ALevel; end; ATopics[C] := ValueOfW(ATopic, '|'); Inc(C); end; if C > 0 then Subscribe(Copy(ATopics, 0, C), ALastLevel); end; end; function TQMQTTMessageClient.CompareTopic(const ATopic1, ATopic2: String): Integer; // 需要实现一个主题的比较算法,1和2都包含模式匹配符时,要确定 function IsContains(p1, p2: PChar): Boolean; begin Result := false; end; begin if ATopic1 = ATopic2 then Result := 0 else if IsContains(PChar(ATopic1), PChar(ATopic2)) then Result := 1 else Result := -1; end; procedure TQMQTTMessageClient.Unlock; begin FLocker.Leave; end; procedure TQMQTTMessageClient.UnregisterDispatch (AHandler: TQMQTTTopicDispatchEvent); var AItem, APrior, ANext: TTopicHandler; I: Integer; begin I := 0; while I < FTopicHandlers.Count do begin AItem := TTopicHandler(FTopicHandlers.Objects[I]); APrior := nil; while Assigned(AItem) do begin if MethodEqual(TMethod(AItem.FOnDispatch), TMethod(AHandler)) then begin if Assigned(APrior) then APrior.FNext := AItem.FNext else FTopicHandlers.Objects[I] := AItem.FNext; ANext := AItem.FNext; FreeAndNil(AItem); AItem := ANext; end else AItem := AItem.FNext; end; if FTopicHandlers.Objects[I] = nil then FTopicHandlers.Delete(I) else Inc(I); end; end; procedure TQMQTTMessageClient.Unsubscribe(const ATopics: array of String); var AReq: PQMQTTMessage; APayloadSize: Integer; AUtf8Topics: TArray<QStringA>; I, C: Integer; APackageId: Word; begin RemoveSubscribePendings(ATopics); if not IsRunning then Exit; if Length(ATopics) > 0 then begin SetLength(AUtf8Topics, Length(ATopics)); C := 0; APayloadSize := 2; for I := 0 to High(ATopics) do begin if Length(ATopics[I]) > 0 then begin AUtf8Topics[C] := qstring.Utf8Encode(ATopics[I]); Inc(APayloadSize, AUtf8Topics[C].Length + 2); Inc(C); end; end; if C = 0 then // 没有要取消的订阅,退出 Exit; AReq := TQMQTTMessage.Create(Self); AReq.PayloadSize := APayloadSize; AReq.ControlType := TQMQTTControlType.ctUnsubscribe; AReq.QosLevel := TQMQTTQoSLevel.qlAtLeast1; AReq.States := AReq.States + [msNeedAck]; APackageId := AcquirePackageId(AReq, True); AReq.Cat(APackageId); for I := 0 to C - 1 do AReq.Cat(AUtf8Topics[I]); if Assigned(BeforeUnsubscribe) then begin for I := 0 to High(ATopics) do begin if Length(ATopics[I]) > 0 then BeforeUnsubscribe(Self, ATopics[I], AReq); end; end; TSocketSendThread(FSendThread).Post(AReq); end; end; procedure TQMQTTMessageClient.ValidClientId; var AId: TGuid; begin if Length(FClientId) = 0 then begin CreateGUID(AId); FClientId := DeleteRightW(TNetEncoding.Base64.EncodeBytesToString(@AId, SizeOf(AId)), '=', false, 1); end; end; { TQMQTTMessage } function TQMQTTMessage.Cat( const V: Cardinal; AEncode: Boolean): PQMQTTMessage; begin Result := @Self; if AEncode then EncodeInt(FCurrent, V) else begin PCardinal(FCurrent)^ := ExchangeByteOrder(V); Inc(FCurrent, SizeOf(V)); end; end; function TQMQTTMessage.Cat( const V: Shortint): PQMQTTMessage; begin Result := @Self; PShortint(FCurrent)^ := V; Inc(FCurrent, SizeOf(V)); end; function TQMQTTMessage.Cat( const V: Smallint; AEncode: Boolean): PQMQTTMessage; begin Result := @Self; if AEncode then EncodeInt(FCurrent, Word(V)) else begin PSmallint(FCurrent)^ := ExchangeByteOrder(V); Inc(FCurrent, SizeOf(V)); end; end; function TQMQTTMessage.Cat( const S: QStringW; AWriteZeroLen: Boolean): PQMQTTMessage; var T: QStringA; begin Result := @Self; if (Length(S) > 0) or AWriteZeroLen then begin T := qstring.Utf8Encode(S); Cat(Word(T.Length)).Cat(PQCharA(S), T.Length); end; end; function TQMQTTMessage.Cat( const V: Byte): PQMQTTMessage; begin Result := @Self; FCurrent^ := V; Inc(FCurrent); Assert(FCurrent <= Eof); end; function TQMQTTMessage.Cat( const V: Word; AEncode: Boolean): PQMQTTMessage; begin Result := @Self; if AEncode then EncodeInt(FCurrent, V) else begin PWord(FCurrent)^ := ExchangeByteOrder(V); Inc(FCurrent, SizeOf(V)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.Cat( const V: Double; AEncode: Boolean): PQMQTTMessage; var T: UInt64 absolute V; begin Result := Cat(T, AEncode); end; function TQMQTTMessage.Copy: PQMQTTMessage; begin Result := Create(Client); Result.PayloadSize := PayloadSize; Move(FData[0], Result.FData[0], FSize); Result.FStates := FStates; Result.FRecvTime := FRecvTime; Result.FSentTime := FSentTime; Result.FSentTimes := FSentTimes; end; class function TQMQTTMessage.Create(AClient: TQMQTTMessageClient) : PQMQTTMessage; begin New(Result); Result.FClient := AClient; Result.FAfterSent := nil; Result.FNext := nil; Result.FCurrent := nil; Result.FVarHeader := nil; Result.FStates := []; Result.FRecvTime := 0; Result.FSentTime := 0; Result.FSentTimes := 0; Result.FSize := 0; Result.FWaitEvent := nil; end; function TQMQTTMessage.Cat(const S: QStringA; AWriteZeroLen: Boolean) : PQMQTTMessage; var T: QStringA; begin Result := @Self; if (S.Length > 0) or AWriteZeroLen then begin if S.IsUtf8 then Cat(Word(S.Length)).Cat(PQCharA(S), S.Length) else begin T := qstring.Utf8Encode(AnsiDecode(S)); Cat(Word(T.Length)).Cat(PQCharA(T), T.Length) end; Assert(FCurrent <= Eof); end; end; function TQMQTTMessage.Cat( const ABytes: TBytes): PQMQTTMessage; begin if Length(ABytes) > 0 then Result := Cat(@ABytes[0], Length(ABytes)) else Result := @Self; end; function TQMQTTMessage.Cat( const V: Int64; AEncode: Boolean): PQMQTTMessage; begin Result := Cat(UInt64(V), AEncode); end; function TQMQTTMessage.Cat( const V: UInt64; AEncode: Boolean): PQMQTTMessage; begin Result := @Self; if AEncode then EncodeInt64(FCurrent, V) else begin PInt64(FCurrent)^ := ExchangeByteOrder(Int64(V)); Inc(FCurrent, SizeOf(V)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.Cat( const ABuf: Pointer; const ALen: Cardinal): PQMQTTMessage; begin if ALen > 0 then begin Assert((FCurrent >= Bof) and (FCurrent + ALen <= Eof)); Move(ABuf^, FCurrent^, ALen); Inc(FCurrent, ALen); Assert(FCurrent <= Eof); end; Result := @Self; end; function TQMQTTMessage.DecodeInt( var ABuf: PByte; AMaxCount: Integer; var AResult: Cardinal): Boolean; var C: Integer; AStart: PByte; begin Result := false; C := 0; AResult := 0; AStart := ABuf; if AMaxCount < 0 then begin if (ABuf >= AStart) and (ABuf <= Eof) then AMaxCount := Integer(FSize) - (IntPtr(ABuf) - IntPtr(AStart)) else AMaxCount := 4; end else if AMaxCount > 4 then AMaxCount := 4; while ABuf - AStart < AMaxCount do begin if (ABuf^ and $80) <> 0 then begin AResult := AResult + ((ABuf^ and $7F) shl (C * 7)); Inc(ABuf); end else begin Inc(AResult, ABuf^ shl (C * 7)); Inc(ABuf); Exit(True); end; Inc(C); end; // 走到这里,说明格式无效 AResult := 0; end; function TQMQTTMessage.DecodeInt64(var ABuf: PByte; AMaxCount: Integer; var AResult: Int64): Boolean; var C: Integer; AStart: PByte; begin Result := false; C := 0; AStart := ABuf; AResult := 0; if AMaxCount < 0 then begin if (ABuf >= AStart) and (ABuf <= Eof) then AMaxCount := Integer(FSize) - (IntPtr(ABuf) - IntPtr(AStart)) else AMaxCount := 8; end else if AMaxCount > 8 then AMaxCount := 8; while ABuf - AStart < AMaxCount do begin if (ABuf^ and $80) <> 0 then begin AResult := AResult + ((ABuf^ and $7F) shl (C * 7)); Inc(ABuf); end else begin Inc(AResult, ABuf^ shl (C * 7)); Inc(ABuf); Exit(True); end; Inc(C); end; // 走到这里,说明格式无效 AResult := 0; end; procedure TQMQTTMessage.EncodeInt(var ABuf: PByte; V: Cardinal); begin repeat ABuf^ := V and $7F; V := V shr 7; if V > 0 then ABuf^ := ABuf^ or $80; Inc(ABuf); until V = 0; end; procedure TQMQTTMessage.EncodeInt64(var ABuf: PByte; V: UInt64); begin repeat ABuf^ := V and $7F; V := V shr 7; if V > 0 then ABuf^ := ABuf^ or $80; Inc(ABuf); until V = 0; end; function TQMQTTMessage.Cat(const V: Single; AEncode: Boolean): PQMQTTMessage; var T: Cardinal absolute V; begin Result := @Self; if AEncode then EncodeInt(FCurrent, T) else begin PCardinal(FCurrent)^ := ExchangeByteOrder(T); Inc(FCurrent, SizeOf(V)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.Cat(const V: Integer; AEncode: Boolean): PQMQTTMessage; var T: Cardinal absolute V; begin Result := @Self; if AEncode then EncodeInt(FCurrent, T) else begin PInteger(FCurrent)^ := ExchangeByteOrder(V); Inc(FCurrent, SizeOf(V)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.GetBof: PByte; begin Result := @FData[0]; end; function TQMQTTMessage.GetByte(const AIndex: Integer): Byte; begin Result := FData[AIndex]; end; function TQMQTTMessage.GetCapacity: Cardinal; begin Result := Length(FData); end; function TQMQTTMessage.GetControlType: TQMQTTControlType; begin Assert(Length(FData) > 1); Result := TQMQTTControlType((FData[0] and $F0) shr 4); end; function TQMQTTMessage.GetEof: PByte; begin Result := @FData[Length(FData)]; end; function TQMQTTMessage.GetHeaderFlags(const Index: Integer): Boolean; const AMasks: array [0 .. 1] of Byte = (1, 8); begin Result := (FData[0] and AMasks[Index]) <> 0; end; function TQMQTTMessage.GetPackageId: Word; begin Result := 0; case ControlType of ctPublish: // 发布 begin if QosLevel > qlMax1 then // 可变头+主题长度+主题内容+PackageId Result := ExchangeByteOrder (PWord(IntPtr(FVarHeader) + SizeOf(Word) + ExchangeByteOrder(PWord(FVarHeader)^))^); end; ctPublishAck, ctPublishRecv, ctPublishRelease, ctPublishDone, ctSubscribe, ctSubscribeAck, ctUnsubscribe, ctUnsubscribeAck: Result := ExchangeByteOrder(PWord(FVarHeader)^); end; end; function TQMQTTMessage.GetPayloadSize: Cardinal; var p: PByte; begin if Length(FData) > 1 then begin p := @FData[1]; DecodeInt(p, Size - 1, Result); end else Result := 0; end; function TQMQTTMessage.GetPosition: Integer; begin Result := IntPtr(FCurrent) - IntPtr(@FData[0]); end; function TQMQTTMessage.GetQoSLevel: TQMQTTQoSLevel; begin Result := TQMQTTQoSLevel((FData[0] shr 1) and 3); end; function TQMQTTMessage.GetRemainSize: Integer; begin Result := FSize - Cardinal(Position); end; function TQMQTTMessage.GetTopicContent: TBytes; var p: PByte; begin if ControlType = ctPublish then begin p := TopicOriginContent; SetLength(Result, Length(FData) - (IntPtr(p) - IntPtr(@FData[0]))); Move(p^, Result[0], Length(Result)); end else SetLength(Result, 0); end; function TQMQTTMessage.GetTopicContentSize: Integer; begin if ControlType = ctPublish then Result := Length(FData) - (IntPtr(TopicOriginContent) - IntPtr(@FData[0])) else Result := 0; end; function TQMQTTMessage.GetTopicId: Word; var p: PByte; begin case ControlType of ctPublish: begin p := FVarHeader; Inc(p, ExchangeByteOrder(PWord(p)^) + 2); if QosLevel > qlMax1 then // 跳过可能存在的PackageId Result := ExchangeByteOrder(PWord(p)^) else Result := 0; end; ctPublishAck: Result := ExchangeByteOrder(PWord(FVarHeader)^); ctPublishRecv, ctPublishRelease, ctPublishDone, ctSubscribe: Result := ExchangeByteOrder(PWord(FVarHeader)^) else Result := 0; end; end; function TQMQTTMessage.GetTopicName: String; var p: PByte; ASize: Word; begin if ControlType = ctPublish then begin p := FVarHeader; ASize := ExchangeByteOrder(PWord(p)^); Inc(p, 2); Result := qstring.Utf8Decode(PQCharA(p), ASize); end else Result := ''; end; function TQMQTTMessage.GetTopicOriginContent: PByte; begin if ControlType = ctPublish then begin Result := FVarHeader; Inc(Result, ExchangeByteOrder(PWord(Result)^) + 2); if QosLevel > qlMax1 then // 跳过可能存在的PackageId Inc(Result, 2); end else Result := nil; end; function TQMQTTMessage.GetTopicText: String; var p: PByte; L: Integer; begin if ControlType = ctPublish then begin p := FVarHeader; Inc(p, ExchangeByteOrder(PWord(p)^) + 2); if QosLevel > qlMax1 then // 跳过可能存在的PackageId Inc(p, 2); L := Length(FData) - (IntPtr(p) - IntPtr(@FData[0])); if L > 0 then Result := qstring.Utf8Decode(PQCharA(p), L) else Result := ''; end else Result := ''; end; function TQMQTTMessage.GetVarHeaderOffset: Integer; begin Result := IntPtr(FVarHeader) - IntPtr(Bof); end; class function TQMQTTMessage.IntEncodedSize(const V: Cardinal): Byte; begin Result := 1; if V >= 128 then begin Inc(Result); if V >= 16384 then begin Inc(Result); if V >= 2097152 then Inc(Result) else if V > 268435455 then raise Exception.CreateFmt(STooLargePayload, [V]); end; end; end; function TQMQTTMessage.MoveBy(const ADelta: Integer): PQMQTTMessage; begin Inc(FCurrent, ADelta); if FCurrent < Bof then FCurrent := Bof else if FCurrent > Eof then FCurrent := Eof; Result := @Self; end; procedure TQMQTTMessage.MoveToVarHeader; begin FCurrent := Bof + VarHeaderOffset; end; function TQMQTTMessage.NextByte: Byte; begin Result := FCurrent^; Inc(FCurrent); Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextBytes(ABuf: Pointer; ALen: Integer): Integer; begin Result := Length(FData) - (IntPtr(FCurrent) - IntPtr(@FData[0])); if Result > ALen then Result := ALen; Move(FCurrent^, ABuf^, Result); Inc(FCurrent, Result); Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextBytes(ASize: Integer): TBytes; begin SetLength(Result, ASize); if ASize > 0 then begin Move(FCurrent^, Result[0], ASize); Assert(FCurrent <= Eof); end; end; function TQMQTTMessage.NextDWord(AIsEncoded: Boolean): Cardinal; begin if AIsEncoded then Assert(DecodeInt(FCurrent, -1, Result)) else begin Result := ExchangeByteOrder(PCardinal(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextFloat(AIsEncoded: Boolean): Double; var T: Int64 absolute Result; begin if AIsEncoded then Assert(DecodeInt64(FCurrent, -1, T)) else begin Result := ExchangeByteOrder(PCardinal(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextInt(AIsEncoded: Boolean): Integer; begin if AIsEncoded then Assert(DecodeInt(FCurrent, -1, Cardinal(Result))) else begin Result := ExchangeByteOrder(PInteger(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextInt64(AIsEncoded: Boolean): Int64; begin if AIsEncoded then Assert(DecodeInt64(FCurrent, -1, Result)) else begin Result := ExchangeByteOrder(PInt64(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextSingle(AIsEncoded: Boolean): Single; var T: Cardinal absolute Result; begin if AIsEncoded then Assert(DecodeInt(FCurrent, -1, T)) else begin T := ExchangeByteOrder(PInteger(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextSmallInt(AIsEncoded: Boolean): Smallint; begin if AIsEncoded then Result := NextInt(True) else begin Result := ExchangeByteOrder(PSmallint(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextString: String; var ALen, ARemain: Integer; begin ALen := NextWord(false); ARemain := RemainSize; if ALen > ARemain then ALen := ARemain; Result := qstring.Utf8Decode(PQCharA(Current), ALen); Inc(FCurrent, ALen); Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextTinyInt: Shortint; begin Result := FCurrent^; Inc(FCurrent); Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextUInt64(AIsEncoded: Boolean): UInt64; begin if AIsEncoded then Assert(DecodeInt64(FCurrent, -1, Int64(Result))) else begin Result := UInt64(ExchangeByteOrder(PInt64(FCurrent)^)); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.NextWord(AIsEncoded: Boolean): Word; begin if AIsEncoded then Result := Word(NextInt(True)) else begin Result := ExchangeByteOrder(PWord(FCurrent)^); Inc(FCurrent, SizeOf(Result)); end; Assert(FCurrent <= Eof); end; function TQMQTTMessage.ReloadSize(AKnownBytes: Integer): Boolean; var AVarOffset: Integer; begin if AKnownBytes > 1 then begin FCurrent := @FData[1]; Result := DecodeInt(FCurrent, AKnownBytes - 1, FSize); if Result then begin AVarOffset := Position; Inc(FSize, Position); if Cardinal(Length(FData)) < FSize then begin SetLength(FData, (FSize + 15) and $FFFFFFF0); FCurrent := Bof + AVarOffset; end; FVarHeader := FCurrent; end; end else Result := false; end; procedure TQMQTTMessage.SetByte(const AIndex: Integer; const Value: Byte); begin Assert((AIndex >= 0) and (AIndex < Length(FData))); FData[AIndex] := Value; end; procedure TQMQTTMessage.SetCapacity( const Value: Cardinal); begin if Value > FSize then begin if (Value and $F) <> 0 then SetLength(FData, (Value and $FFFFFFF0) + 16) else SetLength(FData, Value); end; end; procedure TQMQTTMessage.SetControlType( const AType: TQMQTTControlType); begin Assert(Length(FData) > 0); FData[0] := (FData[0] and $0F) or (Ord(AType) shl 4); end; procedure TQMQTTMessage.SetHeaderFlags( const Index: Integer; const Value: Boolean); const AMasks: array [0 .. 1] of Byte = (1, 8); begin Assert(Length(FData) > 1); if Value then FData[0] := FData[0] or AMasks[Index] else FData[0] := FData[0] and (not AMasks[Index]); end; procedure TQMQTTMessage.SetPayloadSize(Value: Cardinal); var AReqSize: Integer; begin AReqSize := SizeOf(Byte) + Value + IntEncodedSize(Value); if Length(FData) < AReqSize then SetLength(FData, AReqSize); FSize := AReqSize; FCurrent := @FData[1]; EncodeInt(FCurrent, Value); FVarHeader := FCurrent; Assert(FCurrent <= Eof); end; procedure TQMQTTMessage.SetPosition( const Value: Integer); begin FCurrent := Bof; Inc(FCurrent, Value); Assert(FCurrent <= Eof); if FCurrent < Bof then FCurrent := Bof else if FCurrent > Eof then FCurrent := Eof; end; procedure TQMQTTMessage.SetQosLevel(ALevel: TQMQTTQoSLevel); begin Assert(Length(FData) > 0); FData[0] := (FData[0] and $F9) or (Ord(ALevel) shl 1); end; function TQMQTTMessage.ContentAsHexText: String; var ABuilder: TQStringCatHelperW; C, R, L, ARows, ACols: Integer; B: Byte; T: array [0 .. 15] of Char; begin ABuilder := TQStringCatHelperW.Create; try L := Length(FData); ARows := (L shr 4); if (L and $F) <> 0 then Inc(ARows); ABuilder.Cat(' '); for C := 0 to 15 do ABuilder.Cat(IntToHex(C, 2)).Cat(' '); ABuilder.Cat(SLineBreak); for R := 0 to ARows - 1 do begin ABuilder.Cat(IntToHex(R, 4)).Cat(' '); ACols := L - (R shl 4); if ACols > 16 then ACols := 16; for C := 0 to ACols - 1 do begin B := FData[R * 16 + C]; Result := Result + IntToHex(B, 2) + ' '; if (B >= $20) and (B <= $7E) then T[C] := Char(B) else T[C] := '.'; end; for C := ACols to 15 do T[C] := ' '; ABuilder.Cat(@T[0], 16).Cat(SLineBreak); end; Result := ABuilder.Value; finally FreeAndNil(ABuilder); end; end; { TSocketRecvThread } constructor TSocketRecvThread.Create(AOwner: TQMQTTMessageClient); begin inherited; Suspended := false; end; procedure TSocketRecvThread.Execute; begin try FOwner.DoRecv; except on E: Exception do end; if AtomicDecrement(FOwner.FThreadCount) = 0 then FOwner.DoCleanup; end; {$IFDEF MSWINDOWS} procedure StartSocket; var AData: WSAData; begin if WSAStartup($202, &AData) <> NO_ERROR then RaiseLastOSError(); end; procedure CleanSocket; begin WSACleanup; end; {$ELSE} procedure StartSocket; inline; begin end; procedure CleanSocket; inline; begin end; {$ENDIF} { TTopicHandler } constructor TTopicHandler.Create( const ATopic: String; AHandler: TQMQTTTopicDispatchEvent; AMatchType: TTopicMatchType); begin inherited Create; FMatchType := AMatchType; FTopic := ATopic; if AMatchType = TTopicMatchType.mtRegex then begin FRegex := TPerlRegex.Create; try FRegex.RegEx := ATopic; FRegex.Compile; except FreeAndNil(FRegex); raise; end; end; FOnDispatch := AHandler; end; destructor TTopicHandler.Destroy; begin if Assigned(FRegex) then FreeAndNil(FRegex); if TMethod(FOnDispatch).Data = Pointer(-1) then TQMQTTTopicDispatchEventA(TMethod(FOnDispatch).Code) := nil; inherited; end; function TTopicHandler.IsMatch( const ATopic: String): Boolean; function PatternMatch: Boolean; var ps, pd: PChar; ARegex: String; begin // 先不实现具体的算法,转换为正则匹配 if not Assigned(FRegex) then begin FRegex := TPerlRegex.Create; SetLength(ARegex, Length(FTopic) shl 2); ps := PChar(FTopic); pd := PChar(ARegex); while ps^ <> #0 do begin if ps^ = '#' then begin pd[0] := '.'; pd[1] := '*'; Inc(pd, 2); end else if ps^ = '+' then begin pd[0] := '['; pd[1] := '^'; pd[2] := '/'; pd[3] := ']'; pd[4] := '+'; Inc(pd, 5); end else if ps^ = '$' then begin pd^ := '.'; Inc(pd); end else begin pd^ := ps^; Inc(pd); end; Inc(ps); end; pd^ := #0; FRegex.RegEx := PChar(ARegex); FRegex.Compile; end; FRegex.Subject := ATopic; Result := FRegex.Match; end; begin if FMatchType = mtRegex then begin FRegex.Subject := ATopic; Result := FRegex.Match; end else if FMatchType = mtPattern then Result := PatternMatch else Result := True; end; { TSocketThread } constructor TSocketThread.Create(AOwner: TQMQTTMessageClient); begin inherited Create(True); FOwner := AOwner; FreeOnTerminate := True; AtomicIncrement(AOwner.FThreadCount); end; { TSocketSendThread } procedure TSocketSendThread.Clear; var AFirst, ANext: PQMQTTMessage; begin FOwner.Lock; try AFirst := FFirst; FFirst := nil; FLast := nil; finally FOwner.Unlock; end; while Assigned(AFirst) do begin ANext := AFirst.Next; FOwner.FreeMessage(AFirst); AFirst := ANext; end; end; constructor TSocketSendThread.Create(AOwner: TQMQTTMessageClient); begin inherited; FNotifyEvent := TEvent.Create(nil, false, false, ''); Suspended := false; end; destructor TSocketSendThread.Destroy; begin FreeAndNil(FNotifyEvent); inherited; end; procedure TSocketSendThread.Execute; var AFirst, ANext: PQMQTTMessage; begin try AFirst := nil; while not Terminated do begin if FNotifyEvent.WaitFor = wrSignaled then begin if Terminated then Break; if not Assigned(AFirst) then begin // 全部弹出 FOwner.Lock; try AFirst := FFirst; FFirst := nil; FLast := nil; finally FOwner.Unlock; end; end; while Assigned(AFirst) do begin ANext := AFirst.Next; FOwner.DoSend(AFirst); AFirst := ANext end; Queue(FOwner.PublishFirstPending); end; end; finally Clear; if AtomicDecrement(FOwner.FThreadCount) = 0 then FOwner.DoCleanup; end; end; procedure TSocketSendThread.Post(AMessage: PQMQTTMessage); begin FOwner.Lock; try if Assigned(FLast) then FLast.Next := AMessage; if not Assigned(FFirst) then FFirst := AMessage; FLast := AMessage; finally FOwner.Unlock; FNotifyEvent.SetEvent; end; end; function TSocketSendThread.Send(AMessage: PQMQTTMessage; ATimeout: Cardinal): Boolean; var AEvent: TEvent; begin AEvent := TEvent.Create(nil, false, false, ''); try AMessage.FWaitEvent := AEvent; Post(AMessage); Result := AEvent.WaitFor(ATimeout) = wrSignaled; finally FreeAndNil(AEvent); end; end; { TQMQTT5Props } function TQMQTT5Props.Copy: TQMQTT5Props; begin Result := TQMQTT5Props.Create; Result.Replace(Self); end; constructor TQMQTT5Props.Create; begin SetLength(FItems, 42); end; destructor TQMQTT5Props.Destroy; var I: Integer; begin for I := 0 to High(FItems) do begin if (MQTT5PropTypes[I].DataType in [ptString, ptBinary]) and Assigned(FItems[I].AsString) then begin if MQTT5PropTypes[I].DataType = ptString then Dispose(FItems[I].AsString) else Dispose(FItems[I].AsBytes); end; end; inherited; end; function TQMQTT5Props.GetAsInt(const APropId: Byte): Cardinal; begin case MQTT5PropTypes[APropId - 1].DataType of ptByte: Result := FItems[APropId - 1].AsByte; ptWord: Result := FItems[APropId - 1].AsWord; ptInt, ptVarInt: Result := FItems[APropId - 1].AsInteger; ptString: begin if Assigned(FItems[APropId - 1].AsString) then Result := StrToInt(FItems[APropId - 1].AsString^) else raise Exception.Create('不支持的类型转换'); end else raise Exception.Create('不支持的类型转换'); end; end; function TQMQTT5Props.GetAsString(const APropId: Byte): String; begin case MQTT5PropTypes[APropId - 1].DataType of ptByte: Result := IntToStr(FItems[APropId - 1].AsByte); ptWord: Result := IntToStr(FItems[APropId - 1].AsWord); ptInt, ptVarInt: Result := IntToStr(FItems[APropId - 1].AsInteger); ptString: begin if Assigned(FItems[APropId - 1].AsString) then Result := FItems[APropId - 1].AsString^ else SetLength(Result, 0); end; ptBinary: begin if Assigned(FItems[APropId - 1].AsBytes) then Result := BinToHex(FItems[APropId - 1].AsBytes^) else SetLength(Result, 0); end else raise Exception.Create('不支持的类型转换'); end; end; function TQMQTT5Props.GetAsVariant(const APropId: Byte): Variant; var p: PByte; begin case MQTT5PropTypes[APropId - 1].DataType of ptByte: Result := FItems[APropId - 1].AsByte; ptWord: Result := FItems[APropId - 1].AsWord; ptInt, ptVarInt: Result := FItems[APropId - 1].AsInteger; ptString: begin if Assigned(FItems[APropId - 1].AsString) then Result := Utf8Decode(FItems[APropId - 1].AsString^) else Result := ''; end; ptBinary: begin if Assigned(FItems[APropId - 1].AsBytes) then begin Result := VarArrayCreate([0, Length(FItems[APropId - 1].AsBytes^) - 1], varByte); p := VarArrayLock(Result); Move(FItems[APropId - 1].AsBytes^[0], p^, Length(FItems[APropId - 1].AsBytes^)); VarArrayUnlock(Result); end else Result := Null; end else raise Exception.Create('不支持的类型转换'); end; end; function TQMQTT5Props.GetDataSize(const APropId: Byte): Integer; var AType: PQMQTT5PropType; begin AType := @MQTT5PropTypes[APropId - 1]; Result := AType.DataSize; if Result < 0 then begin if AType.DataType = ptVarInt then Result := TQMQTTMessage.IntEncodedSize(AsInt[APropId]) else if AType.DataType = ptString then Result := FItems[APropId - 1].AsString^.Length else if AType.DataType = ptBinary then Result := Length(FItems[APropId - 1].AsBytes^); end; end; function TQMQTT5Props.GetIsSet(const APropId: Byte): Boolean; begin Result := FItems[APropId - 1].IsSet; end; function TQMQTT5Props.GetMinMaxId(const Index: Integer): Byte; begin if Index = 0 then Result := 1 else Result := Length(FItems); end; function TQMQTT5Props.GetPayloadSize: Integer; var I: Integer; begin Result := 0; for I := 0 to High(FItems) do begin if FItems[I].IsSet then Inc(Result, DataSize[I + 1] + 1); end; Inc(Result, TQMQTTMessage.IntEncodedSize(Result)); end; function TQMQTT5Props.GetPropTypes(const APropId: Byte): PQMQTT5PropType; begin Result := @MQTT5PropTypes[APropId - 1]; end; procedure TQMQTT5Props.ReadProps(const AMessage: PQMQTTMessage); var APropLen: Cardinal; pe: PByte; I: Integer; APropId: Byte; begin APropLen := AMessage.NextDWord(True); pe := AMessage.Current + APropLen; for I := 0 to High(FItems) do FItems[I].IsSet := false; while AMessage.Current < pe do begin APropId := AMessage.NextByte; if APropId in [1 .. 42] then begin with FItems[APropId - 1] do begin case MQTT5PropTypes[APropId - 1].DataType of ptByte: AsByte := AMessage.NextByte; ptWord: AsWord := AMessage.NextWord(false); ptInt: AsInteger := AMessage.NextDWord(false); ptVarInt: AsInteger := AMessage.NextDWord(True); ptString: begin if not Assigned(AsString) then New(AsString); AsString^.Length := AMessage.NextWord(false); AsString^.IsUtf8 := True; AMessage.NextBytes(PQCharA(AsString^), AsString^.Length); end; ptBinary: begin if not Assigned(AsBytes) then New(AsBytes); SetLength(AsBytes^, AMessage.NextWord(false)); AMessage.NextBytes(@AsBytes^[0], Length(AsBytes^)); end; end; IsSet := True; end; end; end; end; procedure TQMQTT5Props.Replace(AProps: TQMQTT5Props); var I: Integer; begin for I := 0 to High(FItems) do begin if AProps.FItems[I].IsSet then begin case MQTT5PropTypes[I].DataType of ptString: begin if not Assigned(FItems[I].AsString) then New(FItems[I].AsString); FItems[I].AsString^ := AProps.FItems[I].AsString^; end; ptBinary: begin if not Assigned(FItems[I].AsBytes) then New(FItems[I].AsBytes); FItems[I].AsBytes^ := AProps.FItems[I].AsBytes^; end else FItems[I].AsInteger := AProps.FItems[I].AsInteger; end; end; end; end; procedure TQMQTT5Props.SetAsInt(const APropId: Byte; const Value: Cardinal); begin FItems[APropId - 1].IsSet := True; case MQTT5PropTypes[APropId - 1].DataType of ptByte: FItems[APropId - 1].AsByte := Value; ptWord: FItems[APropId - 1].AsWord := Value; ptInt, ptVarInt: FItems[APropId - 1].AsInteger := Value; ptString: begin if not Assigned(FItems[APropId - 1].AsString) then New(FItems[APropId - 1].AsString); FItems[APropId - 1].AsString^ := IntToStr(Value); end else begin FItems[APropId - 1].IsSet := false; raise Exception.Create('不支持的类型转换'); end; end; end; procedure TQMQTT5Props.SetAsString(const APropId: Byte; const Value: String); begin FItems[APropId - 1].IsSet := True; case MQTT5PropTypes[APropId - 1].DataType of ptByte: FItems[APropId - 1].AsByte := Byte(StrToInt(Value)); ptWord: FItems[APropId - 1].AsWord := Word(StrToInt(Value)); ptInt, ptVarInt: FItems[APropId - 1].AsInteger := Cardinal(StrToInt(Value)); ptString: begin if not Assigned(FItems[APropId - 1].AsString) then New(FItems[APropId - 1].AsString); FItems[APropId - 1].AsString^ := qstring.Utf8Encode(Value); end; ptBinary: begin if not Assigned(FItems[APropId - 1].AsBytes) then New(FItems[APropId - 1].AsBytes); FItems[APropId - 1].AsBytes^ := qstring.Utf8Encode(Value); end; end; end; procedure TQMQTT5Props.SetAsVariant(const APropId: Byte; const Value: Variant); begin FItems[APropId - 1].IsSet := True; case MQTT5PropTypes[APropId - 1].DataType of ptByte: FItems[APropId - 1].AsByte := Value; ptWord: FItems[APropId - 1].AsWord := Value; ptInt, ptVarInt: FItems[APropId - 1].AsInteger := Value; ptString: begin if not Assigned(FItems[APropId - 1].AsString) then New(FItems[APropId - 1].AsString); FItems[APropId - 1].AsString^ := qstring.Utf8Encode(VarToStr(Value)); end; ptBinary: begin if not Assigned(FItems[APropId - 1].AsBytes) then New(FItems[APropId - 1].AsBytes); SetLength(FItems[APropId - 1].AsBytes^, VarArrayHighBound(Value, 1) + 1); Move(VarArrayLock(Value)^, FItems[APropId - 1].AsBytes^[0], Length(FItems[APropId - 1].AsBytes^)); VarArrayUnlock(Value); end; end; end; procedure TQMQTT5Props.WriteProps(AMessage: PQMQTTMessage); var I: Integer; ASize: Cardinal; APropType: PQMQTT5PropType; begin ASize := 0; for I := 0 to High(FItems) do begin if FItems[I].IsSet then Inc(ASize, DataSize[I + 1] + 1); end; AMessage.Cat(ASize, True); for I := 0 to High(FItems) do begin if FItems[I].IsSet then begin APropType := @MQTT5PropTypes[I]; AMessage.Cat(APropType.Id); case APropType.DataType of ptByte: AMessage.Cat(FItems[I].AsByte); ptWord: AMessage.Cat(FItems[I].AsWord); ptInt: AMessage.Cat(FItems[I].AsInteger); ptVarInt: AMessage.Cat(FItems[I].AsInteger, True); ptString: AMessage.Cat(FItems[I].AsString^); ptBinary: AMessage.Cat(FItems[I].AsBytes^); end; end; end; end; { TQMQTT5PropType } function TQMQTT5PropType.GetDataSize: Integer; const DataSizes: array [TQMQTT5PropDataType] of Integer = (0, 1, 2, 4, -4, -1, -1); begin Result := DataSizes[DataType]; end; { TQMQTTSubscribeResult } function TQMQTTSubscribeResult.GetSuccess: Boolean; begin Result := (ErrorCode = 0); end; initialization StartSocket; finalization if Assigned(_DefaultClient) then FreeAndNil(_DefaultClient); CleanSocket; end.
{ --------------------------------------------------- String Manager Copyright (r) by DreamFactory Version : 1.75 Author : William Yang Last Update 25 - Aug - 97 --------------------------------------------------- } unit StrMan; { String Manager } interface { -- Declaretion Part -- } uses Windows, SysUtils, Math, Classes, Registry; type TCharSet = set of Char; const Decimals = ['0' .. '9']; FloatNums = ['0' .. '9', '.']; Operators = ['+', '-', '*', '/']; HexDecimals = ['0' .. '9', 'A' .. 'F']; Letters = ['a' .. 'z', 'A' .. 'Z']; Symbols = ['"', '''', '<', '>', '{', '}', '[', ']', '(', ',', ')']; Masks: array [1 .. 3] of Char = ('*', '?', '#'); function ReplaceOne(Src, Ch: String; iStart, iCount: Integer): String; function FillStr(Amount: Byte; C: Char): String; function TitleCase(SourceStr: String): String; function ReplaceAll(Source, Target, ChangeTo: String): String; function Instr(iStart: Integer; Src, Find: String): Integer; function CompareStrAry(Source: String; CmpTo: Array of string): Integer; function LowCaseStr(S: String): String; function LoCase(C: Char): Char; procedure StrSplit(SrcStr: String; BreakDownPos: Integer; var S1, S2: String); function LeftStr(S: String; ToPos: Integer): String; function RightStr(S: String; ToPos: Integer): String; function CharCount(S: String; C: Char): Integer; function RemoveChars(S: String; C: TCharSet): String; function StrBrief(AString: String; AMaxChar: Integer): String; function EStrToInt(S: String): Integer; function EStrToFloat(S: String): Real; function LastDir(Dir: String): String; function RPos(C: String; Src: String): Integer; overload; function RPos(C: String; Src: String; nStart: Integer): Integer; overload; function ReturnLine(SList: TStringList; Find: String): String; procedure SplitStrC(S: string; C: Char; var head, queue: string); procedure Split(StringList: TStringList; S: string; C: Char); function AppPath: String; function ReadBetween(Src, Mark1, Mark2: String): String; procedure RemoveQuate(var Src: String); function strFileLoad(const aFile: String): String; procedure strFileSave(const aFile, AString: String); function JoinStrings(AStrings: TStrings): String; overload; function JoinStrings(strings: TStrings; delimiter: String): String; overload; function AddSlashes(AString: String): String; function StripSlashes(AString: String): String; implementation function StrBrief(AString: String; AMaxChar: Integer): String; begin if Length(AString) <= AMaxChar then Result := AString else begin Result := Copy(AString, 0, AMaxChar - 3) + '...'; end; end; function AddSlashes(AString: String): String; begin Result := ReplaceAll(AString, '''', '\'''); Result := ReplaceAll(Result, '"', '\"'); end; function StripSlashes(AString: String): String; begin Result := ReplaceAll(AString, '\''', ''''); Result := ReplaceAll(Result, '\"', '"'); end; function JoinStrings(AStrings: TStrings): String; var i: Integer; begin Result := ''; for i := 0 to AStrings.Count - 2 do begin Result := Result + AStrings[i] + '\'; end; Result := Result + AStrings[AStrings.Count - 1]; end; function JoinStrings(strings: TStrings; delimiter: String): String; var i: Integer; begin if strings.Count = 0 then Exit; Result := strings[0]; if strings.Count > 0 then for i := 1 to strings.Count - 1 do begin Result := Result + delimiter + strings[i] end; end; function strFileLoad(const aFile: String): String; var aStr: TStrings; begin Result := ''; aStr := TStringList.Create; try aStr.LoadFromFile(aFile); Result := aStr.Text; finally aStr.Free; end; end; procedure strFileSave(const aFile, AString: String); var Stream: TStream; begin Stream := TFileStream.Create(aFile, fmCreate); try Stream.WriteBuffer(Pointer(AString)^, Length(AString)); finally Stream.Free; end; end; procedure RemoveQuate(var Src: String); begin if Src = '' then Exit; if Src[1] = '"' then Delete(Src, 1, 1); if Src[Length(Src)] = '"' then Delete(Src, Length(Src), 1); if Src[1] = '''' then Delete(Src, 1, 1); if Src[Length(Src)] = '''' then Delete(Src, Length(Src), 1); end; function ReadBetween(Src, Mark1, Mark2: String): String; var i, j: Integer; begin if Mark1 = '' then i := 1 else i := Pos(Mark1, Src); if Mark2 = '' then j := Length(Src) else j := Instr(i + Length(Mark1), Src, Mark2); if j <= 0 then j := Length(Src) + 1; if (i > 0) and (j > 0) then Result := Copy(Src, i + Length(Mark1), j - i - Length(Mark1)); end; function AppPath: String; begin Result := ExtractFilepath(ParamStr(0)); end; function LastDir(Dir: String): String; begin if Dir[Length(Dir)] = '\' then Delete(Dir, Length(Dir), 1); Result := RightStr(Dir, RPos('\', Dir) + 1); end; procedure SplitStrC(S: string; C: Char; var head, queue: string); var i: Integer; Quated: Boolean; begin head := ''; queue := ''; Quated := False; for i := 1 to Length(S) do // Iterate begin if S[i] = '"' then begin if Quated then begin if head <> '' then Break; Quated := False; end else begin if i = 1 then Quated := True end; end else if S[i] = C then begin Break end else head := head + S[i]; end; // for Delete(S, 1, i); queue := S; end; procedure Split(StringList: TStringList; S: string; C: Char); var Line: String; begin while S <> '' do begin SplitStrC(S, C, Line, S); StringList.Add(Trim(Line)); end; end; function ReturnLine(SList: TStringList; Find: String): String; var i: Integer; S: String; begin Result := ''; for i := 0 to SList.Count - 1 do begin S := SList[i]; if Pos(Find, S) > 0 then begin Result := SList[i]; Exit; end; end; end; function EStrToFloat(S: String): Real; var i: Integer; r: String; begin r := ''; for i := 1 to Length(S) do if S[i] in FloatNums then r := r + S[i]; if r = '' then Result := 0 else Result := StrToFloat(r); end; function EStrToInt(S: String): Integer; var i: Integer; r: String; begin r := ''; for i := 1 to Length(S) do if S[i] in Decimals then r := r + S[i]; if r = '' then Result := 0 else Result := StrToInt(r); end; function RemoveChars(S: String; C: TCharSet): String; var j: Integer; begin // Result := S; j := 1; Result := ''; while j <= Length(S) do begin if not(S[j] in C) then Result := Result + S[j]; Inc(j); end; end; function ReplaceOne(Src, Ch: String; iStart, iCount: Integer): String; var mResult: String; begin mResult := Src; Delete(mResult, iStart, iCount); Insert(Ch, mResult, iStart); ReplaceOne := mResult; end; function Instr(iStart: Integer; Src, Find: String): Integer; var CS: String; begin CS := Copy(Src, iStart, Length(Src) - iStart + 1); if Pos(Find, CS) <> 0 then Result := Pos(Find, CS) + iStart - 1 else Result := 0; end; function LeftStr(S: String; ToPos: Integer): String; begin Result := Copy(S, 1, ToPos); end; function RightStr(S: String; ToPos: Integer): String; begin Result := Copy(S, ToPos, Length(S) - ToPos + 1); end; procedure StrSplit(SrcStr: String; BreakDownPos: Integer; var S1, S2: String); begin S1 := LeftStr(SrcStr, BreakDownPos - 1); S2 := RightStr(SrcStr, BreakDownPos - 1); end; function ReplaceAll(Source, Target, ChangeTo: String): String; var Index: Integer; Src, Tgt, Cht: String; begin Src := Source; Tgt := Target; Cht := ChangeTo; Index := Pos(Tgt, Src); while Index > 0 do begin Src := ReplaceOne(Src, Cht, Index, Length(Tgt)); Index := Index + Length(Cht); Index := Instr(Index, Src, Tgt); end; Result := Src; end; function LoCase(C: Char): Char; begin if (Ord(C) >= Ord('A')) and (Ord(C) <= Ord('Z')) then Result := Chr(Ord(C) - (Ord('A') - Ord('a'))) else LoCase := C; end; function LowCaseStr(S: String): String; var i: Integer; begin for i := 1 to Length(S) do S[i] := LoCase(S[i]); end; { Make The First Letter Of Each Word To Upper Case } function TitleCase(SourceStr: String): String; var i: Integer; First: Boolean; begin Result := SourceStr; First := True; for i := 1 to Length(SourceStr) do begin if First then Result[i] := UpCase(Result[i]) else Result[i] := LoCase(Result[i]); First := False; if Result[i] in [' ', '=', '"', '''', ',', ';', '.'] then First := True; end; TitleCase := Result; end; { Fill The String With Parameter 'C' } function FillStr(Amount: Byte; C: Char): String; var r: String; i: Byte; begin for i := 1 to Amount do r := r + C; Result := r; end; function CompareStrAry(Source: String; CmpTo: Array of string): Integer; var i: Integer; begin Result := -1; for i := Low(CmpTo) to High(CmpTo) do begin if LowCaseStr(Source) = LowCaseStr(CmpTo[i]) then begin Result := i; Exit; end; end; end; function RPos(C: String; Src: String): Integer; begin Result := RPos(C, Src, 1); end; function RPos(C: String; Src: String; nStart: Integer): Integer; var i: Integer; begin Result := 0; for i := Length(Src) downto nStart do if Src[i] = C then begin Result := i; Break; end; end; function CharCount(S: String; C: Char): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(S) do if S[i] = C then Result := Result + 1; end; end.
unit ExtAILogDLL; interface uses Classes, SysUtils, ExtAILog; type // DLL logger TLogDLL = class private fFileS: TFileStream; fLogs: TStringList; public fLog: TExtAILog; constructor Create(); destructor Destroy; override; property GetTLog: TExtAILog read fLog write fLog; procedure Log(const aText: String); function RemoveFirstLog(var aText: String): Boolean; end; implementation const LOG_TO_FILE = True; LOG_FILE_NAME = 'LOG_ExtAI_Delphi_DLL.txt'; { TLogDLL } constructor TLogDLL.Create(); begin Inherited Create; fLogs := TStringList.Create; fFileS := nil; if LOG_TO_FILE then fFileS := TFileStream.Create(LOG_FILE_NAME, fmCreate OR fmOpenWrite); Log('TLogDLL-Create'); fLog := TExtAILog.Create(Log,False); end; destructor TLogDLL.Destroy(); begin fLog.Free; Log('TLogDLL-Destroy'); fLogs.Free; fFileS.Free; Inherited; end; procedure TLogDLL.Log(const aText: String); const NEW_LINE: String = #13#10; begin if (Self = nil) then Exit; fLogs.Add(aText); if (fFileS <> nil) then begin fFileS.Write(aText[1], Length(aText) * SizeOf(aText[1])); fFileS.Write(NEW_LINE[1], Length(NEW_LINE) * SizeOf(NEW_LINE[1])); end; end; function TLogDLL.RemoveFirstLog(var aText: String): Boolean; begin Result := (fLogs.Count > 0); if Result then begin aText := fLogs[0]; fLogs.Delete(0); end; end; end.
unit EmailOrdering.Views.SettingsForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ValEdit, Vcl.ComCtrls, EmailOrdering.Models.Config, EmailOrdering.Controllers.MainControllerInt, Vcl.StdCtrls; type TSettingsForm = class(TForm) PageControlSettings: TPageControl; Email: TTabSheet; API: TTabSheet; ValueListEditorSettingsEmail: TValueListEditor; ValueListEditorSettingsApi: TValueListEditor; Member: TTabSheet; ValueListEditorSettingsMember: TValueListEditor; Button1: TButton; TabSheet1: TTabSheet; ValueListEditorApplication: TValueListEditor; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button1Click(Sender: TObject); private FController: IMainController; procedure SetController(const Value: IMainController); { Private declarations } public { Public declarations } property Controller: IMainController read FController write SetController; end; var SettingsForm: TSettingsForm; implementation {$R *.dfm} procedure TSettingsForm.Button1Click(Sender: TObject); var LConfig: TConfig; password: string; begin LConfig := TConfig.GetInstance; try password := InputBox('Change Password', #31'New Password:', ''); LConfig.smtpPassword := password; LConfig.Save; finally LConfig.Free; end; end; procedure TSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); var LConfig: TConfig; begin LConfig := TConfig.GetInstance; try LConfig.smtpHost := self.ValueListEditorSettingsEmail.Values['smtpHost']; LConfig.smtpPort := StrToInt(self.ValueListEditorSettingsEmail.Values['smtpPort']); LConfig.smtpAuthType := self.ValueListEditorSettingsEmail.Values['smtpAuthType'] ; LConfig.smtpUsername := self.ValueListEditorSettingsEmail.Values['smtpUsername']; LConfig.requestBaseUrl := self.ValueListEditorSettingsApi.Values['requestBaseUrl']; LConfig.requestAccept := self.ValueListEditorSettingsApi.Values['requestAccept']; LConfig.requestAcceptCharset := self.ValueListEditorSettingsApi.Values['requestAcceptCharset']; LConfig.requestResource := self.ValueListEditorSettingsApi.Values['requestResource']; LConfig.requestConfirmationURL := self.ValueListEditorSettingsApi.Values['requestConfirmationURL']; LConfig.memberNumber := self.ValueListEditorSettingsMember.Values['memberNumber']; LConfig.apiKey := self.ValueListEditorSettingsMember.Values['apiKey']; LConfig.serverPort := self.ValueListEditorApplication.Values['serverPort']; LConfig.Save; finally LConfig.Free; end; end; procedure TSettingsForm.FormCreate(Sender: TObject); var LConfig: TConfig; begin LConfig := TConfig.GetInstance; try self.ValueListEditorSettingsEmail.Values['smtpHost'] := LConfig.smtpHost; self.ValueListEditorSettingsEmail.Values['smtpPort'] := LConfig.smtpPort.ToString; self.ValueListEditorSettingsEmail.Values['smtpAuthType'] := LConfig.smtpAuthType; self.ValueListEditorSettingsEmail.Values['smtpUsername'] := LConfig.smtpUsername; self.ValueListEditorSettingsApi.Values['requestBaseUrl'] := LConfig.requestBaseUrl; self.ValueListEditorSettingsApi.Values['requestAccept'] := LConfig.requestAccept; self.ValueListEditorSettingsApi.Values['requestAcceptCharset'] := LConfig.requestAcceptCharset; self.ValueListEditorSettingsApi.Values['requestResource'] := LConfig.requestResource; self.ValueListEditorSettingsApi.Values['requestConfirmationURL'] := LConfig.requestConfirmationURL; self.ValueListEditorSettingsMember.Values['memberNumber'] := LConfig.memberNumber; self.ValueListEditorSettingsMember.Values['apiKey'] := LConfig.apiKey; self.ValueListEditorApplication.Values['serverPort'] := LConfig.serverPort; Left:=(Screen.Width-Width) div 2; Top:=(Screen.Height-Height) div 2; finally LConfig.Free; end; end; procedure TSettingsForm.SetController(const Value: IMainController); begin FController := Value; end; end.
UNIT CountingWords; INTERFACE TYPE Tree = ^Node; Node = RECORD Word: STRING; //поле ячейки, содержит в себе слово-символы Counter: INTEGER; //счётчик, показывает, кол-во одинаково обработанных Word при вставке в дерево Left, Right: Tree //указатели в бинарном дереве END; TempNode = RECORD Word: STRING; Counter: INTEGER END; NodeFile = FILE OF TempNode; PROCEDURE WriteTempFile(VAR TempFile: NodeFile); PROCEDURE CountWord(Word: STRING); { Вставляет слово Word в бинарное дерево } PROCEDURE PrintFileStatistic(VAR DataFile: TEXT); { Печать содержимого дерева } IMPLEMENTATION { Реализовано бинарным деревом, с контролем по памяти } VAR WordAmount: INTEGER; Root: Tree; HadOverflow, TreeSaved: BOOLEAN; LastWord: STRING; PROCEDURE WriteTempFile(VAR TempFile: NodeFile); VAR Temp: TempNode; BEGIN RESET(TempFile); WHILE NOT EOF(TempFile) DO BEGIN READ(TempFile, Temp); WRITELN(Temp.Word) END END; PROCEDURE SaveTreeIntoFile(VAR Pointer: Tree; VAR SavedTree: NodeFile); { Пройди по всем элементам дерева и сохрани их } VAR SavedNode: TempNode; BEGIN { SaveTree } IF Pointer <> NIL THEN BEGIN SaveTreeIntoFile(Pointer^.Left, SavedTree); SavedNode.Word := Pointer^.Word; SavedNode.Counter := Pointer^.Counter; WRITE(SavedTree, SavedNode); SaveTreeIntoFile(Pointer^.Right, SavedTree) END END; { SaveTree } PROCEDURE MergeTreeBackUpWithHistory(VAR BackUpFile, HistoryFile: NodeFile); VAR Temp1, Temp2: TempNode; BEGIN { MergeTreeBackUpWithHistory } RESET(BackUpFile); WHILE NOT EOF(BackUpFile) DO BEGIN READ(BackUpFile, Temp1); WRITE(HistoryFile, Temp1) END; WriteTempFile(HistoryFile); WRITELN; REWRITE(BackUpFile) END; { MergeTreeBackUpWithHistory } {PROCEDURE MergeTreeBackUpWithHistory(VAR BackUpFile: NodeFile; VAR HistoryFile: NodeFile); VAR TempFile: NodeFile; Temp1, Temp2: TempNode; BEGIN MergeTreeBackUpWithHistory //WriteTempFile(BackUpFile); //WRITELN; REWRITE(TempFile); RESET(HistoryFile); WHILE NOT EOF(HistoryFile) DO BEGIN READ(HistoryFile, Temp1); WRITE(TempFile, Temp1) END; REWRITE(HistoryFile); RESET(BackUpFile); RESET(TempFile); WHILE NOT EOF(BackUpFile) DO BEGIN //WRITELN('HERE!!!!'); IF NOT EOF(TempFile) THEN READ(TempFile, Temp1); READ(BackUpFile, Temp2); WRITE(HistoryFile, Temp2); WRITELN(Temp1.Word, Temp2.Word); IF Temp1.Word < Temp2.Word THEN WRITE(HistoryFile, Temp1); IF Temp1.Word > Temp2.Word THEN WRITE(HistoryFile, Temp2, Temp1); IF Temp1.Word = Temp2.Word THEN BEGIN Temp1.Counter := Temp1.Counter + Temp2.Counter; WRITE(HistoryFile, Temp1) END; IF EOF(TempFile) AND (Temp1.Word <> Temp2.Word) THEN WRITE(HistoryFile, Temp2) END; //WriteTempFile(HistoryFile); //WRITELN; WHILE NOT EOF(TempFile) DO BEGIN READ(TempFile, Temp1); WRITE(HistoryFile, Temp1) END; WriteTempFile(HistoryFile); WRITELN; REWRITE(BackUpFile) END; { MergeTreeBackUpWithHistory } PROCEDURE EmptyTree(VAR Pointer: Tree); { Используй для полного уничтожения дерева } BEGIN { EmptyTree } IF Pointer <> NIL THEN BEGIN EmptyTree(Pointer^.Left); EmptyTree(Pointer^.Right); DISPOSE(Pointer); Pointer := NIL; WordAmount := WordAmount - 1 END END; { EmptyTree } VAR CurrentTreeBackUp, TreeHistory, TempFile: NodeFile; CONST MaxWordAmount = 3; PROCEDURE Insert(VAR Pointer: Tree; Word: STRING); { Кладёт слово в бинарное дерево, реализован контроль переполнения } //Требуется знать устройтсво бинарного дерева!// VAR Temp: TempNode; BEGIN { Insert } IF Pointer = NIL THEN BEGIN NEW(Pointer); LastWord := Word; Pointer^.Word := Word; Pointer^.Counter := 1; Pointer^.Left := NIL; Pointer^.Right := NIL; WordAmount := WordAmount + 1 END ELSE BEGIN IF Pointer^.Word > Word THEN Insert(Pointer^.Left, Word); IF Pointer^.Word < Word THEN Insert(Pointer^.Right, Word); { Слово уже есть в дереве? Тогда просто увеличить счётчик на 1, без вставки в дерево } IF Pointer^.Word = Word THEN Pointer^.Counter := Pointer^.Counter + 1 END END; { Insert } PROCEDURE PrintTree(Pointer: Tree; VAR DataFile: TEXT); { Печать бинарного дерева } BEGIN { PrintTree } IF Pointer <> NIL THEN BEGIN PrintTree(Pointer^.Left, DataFile); { Pointer^.Word = '' - пробел, если хочешь отобразить кол-во пробелов в тексте - убери условие } IF Pointer^.Word <> '' THEN WRITELN(DataFile, Pointer^.Word, ' ', Pointer^.Counter); PrintTree(Pointer^.Right, DataFile); END END; { PrintTree } PROCEDURE CountWord(Word: STRING); BEGIN { CountWord } IF HadOverflow = TRUE THEN BEGIN MergeTreeBackUpWithHistory(CurrentTreeBackUp, TreeHistory); HadOverflow := FALSE END; IF WordAmount < MaxWordAmount THEN Insert(Root, Word) ELSE BEGIN //контроль переполнения Insert(Root, Word); HadOverflow := TRUE; SaveTreeIntoFile(Root, CurrentTreeBackUp); EmptyTree(Root) END END; { CountWord } PROCEDURE PrintFileStatistic(VAR DataFile: TEXT); BEGIN { PrintFileStatistic } //WRITELN; //WriteTempFile(TreeHistory); PrintTree(Root, DataFile) END; { PrintFileStatistic } BEGIN { InsertTree } WordAmount := 0; HadOverflow := FALSE; TreeSaved := FALSE; Root := NIL; //tree's root ASSIGN(CurrentTreeBackUp, '~Temp1.txt'); //file, which contains saved tree after tree's overflow event REWRITE(CurrentTreeBackUp); ASSIGN(TreeHistory, '~Temp2.txt'); REWRITE(TempFile); ASSIGN(TempFile, '~Temp3.txt'); REWRITE(TreeHistory) END. { InsertTree }
unit GX_UsesExpertOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfmUsesExpertOptions = class(TForm) chkSingleActionMode: TCheckBox; chkReplaceFileUnit: TCheckBox; btnOK: TButton; btnCancel: TButton; private procedure SetData(const _CanReplaceFindUseUnit, _SingleActionMode, _ReplaceFileUseUnit: Boolean); procedure GetData(out _SingleActionMode, _ReplaceFileUseUnit: Boolean); public class function Execute(_Owner: TComponent; _CanReplaceFindUseUnit: Boolean; var _SingleActionMode, _ReplaceFileUseUnit: Boolean): Boolean; end; implementation {$R *.dfm} { TfmUsesExpertOptions } class function TfmUsesExpertOptions.Execute(_Owner: TComponent; _CanReplaceFindUseUnit: Boolean; var _SingleActionMode, _ReplaceFileUseUnit: Boolean): Boolean; var frm: TfmUsesExpertOptions; begin frm := TfmUsesExpertOptions.Create(_Owner); try frm.SetData(_CanReplaceFindUseUnit, _SingleActionMode, _ReplaceFileUseUnit); Result := (frm.ShowModal = mrOk); if Result then frm.GetData(_SingleActionMode, _ReplaceFileUseUnit); finally FreeAndNil(frm); end; end; procedure TfmUsesExpertOptions.GetData(out _SingleActionMode, _ReplaceFileUseUnit: Boolean); begin _SingleActionMode := chkSingleActionMode.Checked; _ReplaceFileUseUnit := chkReplaceFileUnit.Checked; end; procedure TfmUsesExpertOptions.SetData(const _CanReplaceFindUseUnit, _SingleActionMode, _ReplaceFileUseUnit: Boolean); begin chkReplaceFileUnit.Enabled := _CanReplaceFindUseUnit; chkSingleActionMode.Checked := _SingleActionMode; chkReplaceFileUnit.Checked := _ReplaceFileUseUnit; 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, Vcl.Buttons, Vcl.ExtCtrls, System.Json; type TForm1 = class(TForm) gbAjout: TGroupBox; gbListe: TGroupBox; btnAjouter: TBitBtn; btnQuitter: TBitBtn; LabeledEdit1: TLabeledEdit; btnOk: TBitBtn; btnCancel: TBitBtn; btnFermer2: TBitBtn; Panel1: TPanel; ScrollBox1: TScrollBox; btnReload: TBitBtn; procedure btnQuitterClick(Sender: TObject); procedure btnAjouterClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnReloadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FlisteModifiee: boolean; { Déclarations privées } procedure displayListe; procedure displayAjout; procedure ajoutLigne(jso: TJSONObject; vraiAjout: boolean = false); procedure chargeListe; procedure SauveListe; procedure SetlisteModifiee(const Value: boolean); public { Déclarations publiques } property listeModifiee: boolean read FlisteModifiee write SetlisteModifiee; end; var Form1: TForm1; implementation {$R *.dfm} uses System.IOUtils, Unit3; const FichName = 'Presentation-RADStudio-Delphi.json'; procedure TForm1.ajoutLigne(jso: TJSONObject; vraiAjout: boolean); var libelle: string; coche: boolean; ligne: tligne; begin try try libelle := (jso.GetValue('libelle') as TJSONString).Value; except libelle := ''; end; try coche := (jso.GetValue('coche') as TJSONBool).AsBoolean; except coche := false; end; ligne := tligne.Create(Self); try ligne.Name := ''; ligne.Parent := ScrollBox1; ligne.Align := alTop; ligne.CheckBox1.Checked := coche; ligne.CheckBox1.Caption := libelle; if vraiAjout then listeModifiee := true; except FreeAndNil(ligne); end; finally if vraiAjout then FreeAndNil(jso); end; end; procedure TForm1.btnOkClick(Sender: TObject); var ch: string; begin ch := LabeledEdit1.text; if (ch.Trim.Length > 0) then ajoutLigne(TJSONObject.Create.AddPair('libelle', ch.Trim).AddPair('coche', TJSONBool.Create(false)), true); displayListe; end; procedure TForm1.btnCancelClick(Sender: TObject); begin { TODO 5 -oDeveloppeurPascal : ok, voir si on fait quelque chose de plus } displayListe; end; procedure TForm1.btnAjouterClick(Sender: TObject); begin displayAjout; end; procedure TForm1.btnQuitterClick(Sender: TObject); begin Close; end; procedure TForm1.btnReloadClick(Sender: TObject); begin chargeListe; end; procedure TForm1.chargeListe; var jso: TJSONObject; jsa: TJSONArray; jsv: TJSONValue; c: tcontrol; i: integer; filename: string; begin for i := ScrollBox1.ControlCount - 1 downto 0 do begin c := ScrollBox1.Controls[i]; if (c is tligne) then FreeAndNil(c); end; filename := TPath.Combine(TPath.GetDocumentsPath, FichName); if tfile.Exists(filename) then begin jso := TJSONObject.ParseJSONValue(tfile.ReadAllText(filename, TEncoding.UTF8)) as TJSONObject; try try jsa := jso.GetValue('liste') as TJSONArray; except jsa := TJSONArray.Create; end; try for jsv in jsa do begin ajoutLigne(jsv as TJSONObject); end; finally // FreeAndNil(jsa); end; finally FreeAndNil(jso); end; end; end; procedure TForm1.displayAjout; begin gbListe.Visible := false; gbAjout.Visible := true; LabeledEdit1.text := ''; LabeledEdit1.setFocus; end; procedure TForm1.displayListe; begin gbListe.Visible := true; gbAjout.Visible := false; end; procedure TForm1.FormCreate(Sender: TObject); begin gbListe.Align := alClient; gbAjout.Align := alClient; displayListe; end; procedure TForm1.FormDestroy(Sender: TObject); begin if listeModifiee then SauveListe; end; procedure TForm1.SauveListe; var jso: TJSONObject; jsa: TJSONArray; i: integer; c: tcontrol; l: tligne; begin jso := TJSONObject.Create; try jsa := TJSONArray.Create; try jso.AddPair('liste', jsa); for i := 0 to ScrollBox1.ControlCount - 1 do begin c := ScrollBox1.Controls[i]; if (c is tligne) then begin l := c as tligne; jsa.AddElement(TJSONObject.Create.AddPair('libelle', l.CheckBox1.Caption).AddPair('coche', TJSONBool.Create(l.CheckBox1.Checked))); end; end; tfile.WriteAllText(TPath.Combine(TPath.GetDocumentsPath, FichName), jso.ToJSON, TEncoding.UTF8); listeModifiee := false; finally // FreeAndNil(jsa); end; finally FreeAndNil(jso); end; end; procedure TForm1.SetlisteModifiee(const Value: boolean); begin FlisteModifiee := Value; end; initialization ReportMemoryLeaksOnShutdown := true; end.
{ Double Commander ------------------------------------------------------------------------- This unit contains TFileViewPage and TFileViewNotebook objects. Copyright (C) 2016-2018 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit uFileViewNotebook; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, ComCtrls, LMessages, LCLType, Forms, uFileView, uFilePanelSelect, DCXmlConfig; type TTabLockState = ( tlsNormal, //<en Default state. tlsPathLocked, //<en Path changes are not allowed. tlsPathResets, //<en Path is reset when activating the tab. tlsDirsInNewTab); //<en Path change opens a new tab. TFileViewNotebook = class; { TFileViewPage } TFileViewPage = class(TWinControl) private FLockState: TTabLockState; FLockPath: String; //<en Path on which tab is locked FOnActivate: TNotifyEvent; FCurrentTitle: String; FPermanentTitle: String; FBackupViewClass: TFileViewClass; procedure AssignPage(OtherPage: TFileViewPage); procedure AssignProperties(OtherPage: TFileViewPage); {en Retrieves the file view on this page. } function GetFileView: TFileView; {en Retrieves notebook on which this page is. } function GetNotebook: TFileViewNotebook; function GetPageIndex: Integer; {en Frees current file view and assigns a new one. } procedure SetFileView(aFileView: TFileView); procedure SetLockState(NewLockState: TTabLockState); procedure SetPermanentTitle(AValue: String); procedure DoActivate; protected procedure PaintWindow(DC: HDC); override; procedure RealSetText(const AValue: TCaption); override; procedure WMEraseBkgnd(var Message: TLMEraseBkgnd); message LM_ERASEBKGND; public constructor Create(TheOwner: TComponent); override; function IsActive: Boolean; procedure MakeActive; procedure UpdateTitle; procedure LoadConfiguration(AConfig: TXmlConfig; ANode: TXmlNode); procedure SaveConfiguration(AConfig: TXmlConfig; ANode: TXmlNode); property PageIndex: Integer read GetPageIndex; property LockState: TTabLockState read FLockState write SetLockState; property LockPath: String read FLockPath write FLockPath; property FileView: TFileView read GetFileView write SetFileView; property Notebook: TFileViewNotebook read GetNotebook; property PermanentTitle: String read FPermanentTitle write SetPermanentTitle; property CurrentTitle: String read FCurrentTitle; property OnActivate: TNotifyEvent read FOnActivate write FOnActivate; property BackupViewClass: TFileViewClass read FBackupViewClass write FBackupViewClass; end; { TFileViewPageControl } TFileViewPageControl = class(TPageControl) private FStartDrag: Boolean; FDraggedPageIndex: Integer; FHintPageIndex: Integer; FLastMouseDownTime: TDateTime; FLastMouseDownPageIndex: Integer; {$IFDEF MSWINDOWS} FRowCount: Integer; {$ENDIF} function GetNoteBook: TFileViewNotebook; private procedure DragOverEvent(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragDropEvent(Sender, Source: TObject; X, Y: Integer); protected procedure CreateHandle; override; procedure TabControlBoundsChange(Data: PtrInt); protected procedure DoChange; override; procedure DblClick; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(ParentControl: TWinControl); reintroduce; procedure DoCloseTabClicked(APage: TCustomPage); override; {$IFDEF MSWINDOWS} {en Removes the rectangle of the pages contents from erasing background to reduce flickering. This is not needed on non-Windows because EraseBackground is not used there. } procedure EraseBackground(DC: HDC); override; procedure WndProc(var Message: TLMessage); override; {$ENDIF} property Notebook: TFileViewNotebook read GetNoteBook; end; { TFileViewNotebook } TFileViewNotebook = class(TCustomControl) private FOnPageChanged: TNotifyEvent; FNotebookSide: TFilePanelSelect; FOnCloseTabClicked: TNotifyEvent; FPageControl: TFileViewPageControl; function GetActivePage: TFileViewPage; function GetActiveView: TFileView; function GetFileViewOnPage(Index: Integer): TFileView; function GetShowTabs: Boolean; function GetMultiLine: Boolean; function GetPageIndex: Integer; function GetPageCount: Integer; function GetTabPosition: TTabPosition; function GetOptions: TCTabControlOptions; function GetLastMouseDownPageIndex: Integer; function GetPage(Index: Integer): TFileViewPage; reintroduce; procedure SetShowTabs(AValue: Boolean); procedure SetPageIndex(AValue: Integer); procedure SetMultiLine(AValue: Boolean); procedure SetTabPosition(AValue: TTabPosition); procedure SetOptions(AValue: TCTabControlOptions); protected procedure DoChange; procedure UpdatePagePosition(AIndex, ASpacing: Integer); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(ParentControl: TWinControl; NotebookSide: TFilePanelSelect); reintroduce; function AddPage: TFileViewPage; function IndexOfPageAt(P: TPoint): Integer; function GetCapabilities: TCTabControlCapabilities; function InsertPage(Index: Integer): TFileViewPage; reintroduce; function NewEmptyPage: TFileViewPage; function NewPage(CloneFromPage: TFileViewPage): TFileViewPage; function NewPage(CloneFromView: TFileView): TFileViewPage; procedure DeletePage(Index: Integer); procedure RemovePage(Index: Integer); reintroduce; procedure RemovePage(var APage: TFileViewPage); procedure DestroyAllPages; procedure ActivatePrevTab; procedure ActivateNextTab; procedure ActivateTabByIndex(Index: Integer); property ActivePage: TFileViewPage read GetActivePage; property ActiveView: TFileView read GetActiveView; property DoubleClickPageIndex: Integer read GetLastMouseDownPageIndex; property Page[Index: Integer]: TFileViewPage read GetPage; property View[Index: Integer]: TFileView read GetFileViewOnPage; default; property Side: TFilePanelSelect read FNotebookSide; property PageCount: Integer read GetPageCount; property PageIndex: Integer read GetPageIndex write SetPageIndex; property ShowTabs: Boolean read GetShowTabs write SetShowTabs; property MultiLine: Boolean read GetMultiLine write SetMultiLine; property Options: TCTabControlOptions read GetOptions write SetOptions; property TabPosition: TTabPosition read GetTabPosition write SetTabPosition; property OnChange: TNotifyEvent read FOnPageChanged write FOnPageChanged; property OnCloseTabClicked: TNotifyEvent read FOnCloseTabClicked write FOnCloseTabClicked; published property OnDblClick; property OnMouseDown; property OnMouseUp; end; implementation uses Math, LCLIntf, LazUTF8, DCStrUtils, uGlobs, uColumnsFileView, uArchiveFileSource {$IF DEFINED(LCLGTK2)} , InterfaceBase, Glib2, Gtk2, Gtk2Proc, Gtk2Def {$ENDIF} {$IF DEFINED(MSWINDOWS)} , win32proc, Windows, Messages {$ENDIF} ; // -- TFileViewPage ----------------------------------------------------------- procedure TFileViewPage.AssignPage(OtherPage: TFileViewPage); begin AssignProperties(OtherPage); SetFileView(nil); // Remove previous view. OtherPage.FileView.Clone(Self); end; procedure TFileViewPage.AssignProperties(OtherPage: TFileViewPage); begin FLockState := OtherPage.FLockState; FLockPath := OtherPage.FLockPath; FCurrentTitle := OtherPage.FCurrentTitle; FPermanentTitle := OtherPage.FPermanentTitle; end; constructor TFileViewPage.Create(TheOwner: TComponent); begin FLockState := tlsNormal; FBackupViewClass := TColumnsFileView; inherited Create(TheOwner); ControlStyle := ControlStyle + [csAcceptsControls, csDesignFixedBounds, csNoDesignVisible, csNoFocus]; // Height and width depends on parent, align to client rect Caption := ''; Visible := False; end; procedure TFileViewPage.RealSetText(const AValue: TCaption); begin inherited RealSetText(AValue); Notebook.FPageControl.Pages[PageIndex].Caption:= AValue; end; function TFileViewPage.IsActive: Boolean; begin Result := Assigned(Notebook) and (Notebook.PageIndex = PageIndex); end; procedure TFileViewPage.LoadConfiguration(AConfig: TXmlConfig; ANode: TXmlNode); begin FLockState := TTabLockState(AConfig.GetValue(ANode, 'Options', Integer(tlsNormal))); FLockPath := AConfig.GetValue(ANode, 'LockPath', ''); FPermanentTitle := AConfig.GetValue(ANode, 'Title', ''); end; procedure TFileViewPage.SaveConfiguration(AConfig: TXmlConfig; ANode: TXmlNode); begin AConfig.AddValueDef(ANode, 'Options', Integer(FLockState), Integer(tlsNormal)); AConfig.AddValueDef(ANode, 'LockPath', FLockPath, ''); AConfig.AddValueDef(ANode, 'Title', FPermanentTitle, ''); end; procedure TFileViewPage.MakeActive; var aFileView: TFileView; begin if Assigned(Notebook) then begin Notebook.PageIndex := PageIndex; aFileView := FileView; if Assigned(aFileView) then aFileView.SetFocus; end; end; procedure TFileViewPage.PaintWindow(DC: HDC); begin // Don't paint anything. end; procedure TFileViewPage.UpdateTitle; {$IFDEF MSWINDOWS} function LocalGetDriveName(A:string):string; begin result:=LowerCase(ExtractFileDrive(A)); if length(result)>2 then // Server path name are shown simply like \: in TC so let's do the same for those who get used to that. result:='\:' else if Lowercase(A) = (result+DirectorySeparator) then result:=''; //To avoid to get "c:C:" :-) end; {$ENDIF} var NewCaption: String; begin if Assigned(FileView) then begin if FPermanentTitle <> '' then begin NewCaption := FPermanentTitle; FCurrentTitle := FPermanentTitle; end else begin if (FileView.FileSource is TArchiveFileSource) and (FileView.FileSource.IsPathAtRoot(FileView.CurrentPath)) then begin with (FileView.FileSource as TArchiveFileSource) do NewCaption := ExtractFileName(ArchiveFileName); end else begin NewCaption := FileView.CurrentPath; if NewCaption <> '' then NewCaption := GetLastDir(NewCaption); end; FCurrentTitle := NewCaption; end; {$IFDEF MSWINDOWS} if tb_show_drive_letter in gDirTabOptions then begin if (FileView.FileSource is TArchiveFileSource) then with (FileView.FileSource as TArchiveFileSource) do NewCaption := LocalGetDriveName(ArchiveFileName) + NewCaption else NewCaption := LocalGetDriveName(FileView.CurrentPath) + NewCaption; end; {$ENDIF} if (FLockState in [tlsPathLocked, tlsPathResets, tlsDirsInNewTab]) and (tb_show_asterisk_for_locked in gDirTabOptions) then NewCaption := '*' + NewCaption; if (tb_text_length_limit in gDirTabOptions) and (UTF8Length(NewCaption) > gDirTabLimit) then NewCaption := UTF8Copy(NewCaption, 1, gDirTabLimit) + '...'; {$IF DEFINED(LCLGTK2)} Caption := NewCaption; {$ELSE} Caption := StringReplace(NewCaption, '&', '&&', [rfReplaceAll]); {$ENDIF} end; end; procedure TFileViewPage.WMEraseBkgnd(var Message: TLMEraseBkgnd); begin Message.Result := 1; end; function TFileViewPage.GetFileView: TFileView; begin if ComponentCount > 0 then Result := TFileView(Components[0]) else Result := nil; end; procedure TFileViewPage.SetFileView(aFileView: TFileView); var aComponent: TComponent; begin if ComponentCount > 0 then begin aComponent := Components[0]; aComponent.Free; end; if Assigned(aFileView) then begin aFileView.Parent := Self; end; end; function TFileViewPage.GetNotebook: TFileViewNotebook; begin Result := Owner as TFileViewNotebook; end; function TFileViewPage.GetPageIndex: Integer; var Index: Integer; begin if Assigned(Notebook) then begin for Index:= 0 to Notebook.PageCount - 1 do begin if (Notebook.GetPage(Index) = Self) then Exit(Index); end; end; Result := -1; end; procedure TFileViewPage.SetLockState(NewLockState: TTabLockState); begin if FLockState = NewLockState then Exit; if NewLockState in [tlsPathLocked, tlsPathResets, tlsDirsInNewTab] then begin LockPath := FileView.CurrentPath; if (FLockState <> tlsNormal) or (Length(FPermanentTitle) = 0) then FPermanentTitle := GetLastDir(LockPath); end else begin LockPath := ''; if not (tb_keep_renamed_when_back_normal in gDirTabOptions) then FPermanentTitle := ''; end; FLockState := NewLockState; UpdateTitle; end; procedure TFileViewPage.SetPermanentTitle(AValue: String); begin if FPermanentTitle = AValue then Exit; FPermanentTitle := AValue; UpdateTitle; end; procedure TFileViewPage.DoActivate; begin if Assigned(FOnActivate) then FOnActivate(Self); end; { TFileViewPageControl } function TFileViewPageControl.GetNoteBook: TFileViewNotebook; begin Result:= TFileViewNotebook(Parent); end; procedure TFileViewPageControl.DragOverEvent(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var ATabIndex: Integer; begin if (Source is TFileViewPageControl) and (Sender is TFileViewPageControl) then begin ATabIndex := IndexOfPageAt(Classes.Point(X, Y)); Accept := (Source <> Sender) or ((ATabIndex <> -1) and (ATabIndex <> FDraggedPageIndex)); end else Accept := False; end; procedure TFileViewPageControl.DragDropEvent(Sender, Source: TObject; X, Y: Integer); var ATabIndex: Integer; ANewPage, DraggedPage: TFileViewPage; SourcePageControl: TFileViewPageControl; begin if (Source is TFileViewPageControl) and (Sender is TFileViewPageControl) then begin ATabIndex := IndexOfPageAt(Classes.Point(X, Y)); if Source = Sender then begin // Move within the same panel. if ATabIndex <> -1 then Tabs.Move(FDraggedPageIndex, ATabIndex); end else begin // Move page between panels. SourcePageControl:= TFileViewPageControl(Source); DraggedPage := SourcePageControl.Notebook.Page[SourcePageControl.FDraggedPageIndex]; if ATabIndex = -1 then ATabIndex := PageCount; // Create a clone of the page in the panel. ANewPage := Notebook.InsertPage(ATabIndex); ANewPage.AssignPage(DraggedPage); ANewPage.MakeActive; if (ssShift in GetKeyShiftState) and (SourcePageControl.Notebook.PageCount > 1) then begin // Remove page from source panel. SourcePageControl.Notebook.RemovePage(DraggedPage); end; end; end; end; procedure TFileViewPageControl.CreateHandle; begin inherited CreateHandle; TabControlBoundsChange(0); end; procedure TFileViewPageControl.TabControlBoundsChange(Data: PtrInt); var AIndex: Integer; ASpacing: Integer; begin if PageIndex >= 0 then begin if not Visible then ASpacing:= 0 else begin case TabPosition of tpTop: ASpacing:= (Page[PageIndex].ClientOrigin.Y - Notebook.ClientOrigin.Y); tpBottom: ASpacing:= (Notebook.ClientOrigin.Y + Notebook.Height) - (Page[PageIndex].ClientOrigin.Y + Page[PageIndex].Height); end; end; for AIndex:= 0 to PageCount - 1 do begin Notebook.UpdatePagePosition(AIndex, ASpacing); end; end; Invalidate; end; procedure TFileViewPageControl.DoChange; begin inherited DoChange; Notebook.DoChange; end; procedure TFileViewPageControl.DblClick; begin inherited DblClick; if Assigned(Notebook.OnDblClick) then Notebook.OnDblClick(Notebook); end; procedure TFileViewPageControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var APoint: TPoint; {$IF DEFINED(LCLGTK2)} var ArrowWidth: Integer; arrow_spacing: gint = 0; scroll_arrow_hlength: gint = 16; {$ENDIF} begin inherited MouseDown(Button, Shift, X, Y); if Assigned(Notebook.OnMouseDown) then begin APoint:= ClientToParent(Classes.Point(X, Y)); Notebook.OnMouseDown(Notebook, Button, Shift, APoint.X, APoint.Y); end; if Button = mbLeft then begin FDraggedPageIndex := IndexOfPageAt(Classes.Point(X, Y)); FStartDrag := (FDraggedPageIndex <> -1); end; // Emulate double click if (Button = mbLeft) and Assigned(Notebook.OnDblClick) then begin if ((Now - FLastMouseDownTime) > ((1/86400)*(GetDoubleClickTime/1000))) then begin FLastMouseDownTime:= Now; FLastMouseDownPageIndex:= FDraggedPageIndex; end else if (FDraggedPageIndex = FLastMouseDownPageIndex) then begin {$IF DEFINED(LCLGTK2)} gtk_widget_style_get({%H-}PGtkWidget(Self.Handle), 'arrow-spacing', @arrow_spacing, 'scroll-arrow-hlength', @scroll_arrow_hlength, nil); ArrowWidth:= arrow_spacing + scroll_arrow_hlength; if (X > ArrowWidth) and (X < ClientWidth - ArrowWidth) then {$ENDIF} Notebook.DblClick; FStartDrag:= False; FLastMouseDownTime:= 0; FLastMouseDownPageIndex:= -1; end; end; end; procedure TFileViewPageControl.MouseMove(Shift: TShiftState; X, Y: Integer); var ATabIndex: Integer; begin inherited MouseMove(Shift, X, Y); if ShowHint then begin ATabIndex := IndexOfPageAt(Classes.Point(X, Y)); if (ATabIndex >= 0) and (ATabIndex <> FHintPageIndex) then begin FHintPageIndex := ATabIndex; Application.CancelHint; if (ATabIndex <> PageIndex) and (Length(Notebook.Page[ATabIndex].LockPath) <> 0) then Hint := Notebook.Page[ATabIndex].LockPath else Hint := Notebook.View[ATabIndex].CurrentPath; end; end; if FStartDrag then begin FStartDrag := False; BeginDrag(False); end; end; procedure TFileViewPageControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var APoint: TPoint; begin inherited MouseUp(Button, Shift, X, Y); if Assigned(Notebook.OnMouseUp) then begin APoint:= ClientToParent(Classes.Point(X, Y)); Notebook.OnMouseUp(Notebook, Button, Shift, APoint.X, APoint.Y); end; FStartDrag := False; end; constructor TFileViewPageControl.Create(ParentControl: TWinControl); begin inherited Create(ParentControl); ControlStyle := ControlStyle + [csNoFocus]; Align := alClient; TabStop := False; ShowHint := True; Parent := ParentControl; FHintPageIndex := -1; FStartDrag := False; {$IFDEF MSWINDOWS} // The pages contents are removed from drawing background in EraseBackground. // But double buffering could be enabled to eliminate flickering of drawing // the tabs buttons themselves. But currently there's a bug where the buffer // bitmap is temporarily drawn in different position, probably at (0,0) and // not where pages contents start (after applying TCM_ADJUSTRECT). //DoubleBuffered := True; {$ENDIF} OnDragOver := @DragOverEvent; OnDragDrop := @DragDropEvent; TabControlBoundsChange(0); end; procedure TFileViewPageControl.DoCloseTabClicked(APage: TCustomPage); begin inherited DoCloseTabClicked(APage); if Assigned(Notebook.OnCloseTabClicked) then Notebook.OnCloseTabClicked(Notebook.Page[APage.PageIndex]); end; {$IFDEF MSWINDOWS} procedure TFileViewPageControl.EraseBackground(DC: HDC); var ARect: TRect; SaveIndex: Integer; Clip: Integer; begin if HandleAllocated and (DC <> 0) then begin ARect := Classes.Rect(0, 0, Width, Height); Windows.TabCtrl_AdjustRect(Handle, False, ARect); SaveIndex := SaveDC(DC); Clip := ExcludeClipRect(DC, ARect.Left, ARect.Top, ARect.Right, ARect.Bottom); if Clip <> NullRegion then begin ARect := Classes.Rect(0, 0, Width, Height); FillRect(DC, ARect, HBRUSH(Brush.Reference.Handle)); end; RestoreDC(DC, SaveIndex); end; end; procedure TFileViewPageControl.WndProc(var Message: TLMessage); var ARowCount: Integer; ARect: PRect absolute Message.LParam; begin inherited WndProc(Message); if Message.Msg = TCM_ADJUSTRECT then begin if Message.WParam = 0 then ARect^.Left := ARect^.Left - 2 else begin ARect^.Left := ARect^.Left + 2; end; if MultiLine then begin ARowCount := SendMessage(Handle, TCM_GETROWCOUNT, 0, 0); if (FRowCount <> ARowCount) then begin FRowCount:= ARowCount; PostMessage(Handle, WM_USER, 0, 0); end; end; end else if Message.Msg = WM_USER then begin TabControlBoundsChange(FRowCount); end; end; {$ENDIF} // -- TFileViewNotebook ------------------------------------------------------- constructor TFileViewNotebook.Create(ParentControl: TWinControl; NotebookSide: TFilePanelSelect); begin inherited Create(ParentControl); ControlStyle := ControlStyle + [csNoFocus]; FPageControl:= TFileViewPageControl.Create(Self); Constraints.MinHeight:= FPageControl.GetMinimumTabHeight * 2; Parent := ParentControl; TabStop := False; ShowHint := True; FNotebookSide := NotebookSide; end; function TFileViewNotebook.GetActivePage: TFileViewPage; begin if PageIndex <> -1 then Result := GetPage(PageIndex) else Result := nil; end; function TFileViewNotebook.GetActiveView: TFileView; var APage: TFileViewPage; begin APage := GetActivePage; if Assigned(APage) then Result := APage.FileView else Result := nil; end; function TFileViewNotebook.GetFileViewOnPage(Index: Integer): TFileView; var APage: TFileViewPage; begin APage := GetPage(Index); Result := APage.FileView; end; function TFileViewNotebook.GetLastMouseDownPageIndex: Integer; begin Result:= FPageControl.FLastMouseDownPageIndex; end; function TFileViewNotebook.GetMultiLine: Boolean; begin Result:= FPageControl.MultiLine; end; function TFileViewNotebook.GetOptions: TCTabControlOptions; begin Result:= FPageControl.Options; end; function TFileViewNotebook.GetPage(Index: Integer): TFileViewPage; var APage: PtrInt absolute Result; begin APage:= FPageControl.Page[Index].Tag; end; function TFileViewNotebook.AddPage: TFileViewPage; begin Result := InsertPage(PageCount); end; function TFileViewNotebook.InsertPage(Index: Integer): TFileViewPage; var ATag: PtrInt absolute Result; begin Result:= TFileViewPage.Create(Self); FPageControl.Tabs.Insert(Index, ''); FPageControl.Page[Index].Tag:= ATag; {$IF DEFINED(LCLGTK2)} if FPageControl.PageCount = 1 then WidgetSet.AppProcessMessages; {$ENDIF} Result.Parent:= Self; Result.BringToFront; Result.AnchorAsAlign(alClient, 0); Result.Visible:= (PageIndex = Index); ShowTabs:= ((PageCount > 1) or (tb_always_visible in gDirTabOptions)) and gDirectoryTabs; FPageControl.TabControlBoundsChange(0); end; function TFileViewNotebook.NewEmptyPage: TFileViewPage; begin if tb_open_new_near_current in gDirTabOptions then Result := InsertPage(PageIndex + 1) else Result := InsertPage(PageCount); end; function TFileViewNotebook.NewPage(CloneFromPage: TFileViewPage): TFileViewPage; begin if Assigned(CloneFromPage) then begin Result := NewEmptyPage; Result.AssignPage(CloneFromPage); end else Result := nil; end; function TFileViewNotebook.NewPage(CloneFromView: TFileView): TFileViewPage; begin if Assigned(CloneFromView) then begin Result := NewEmptyPage; CloneFromView.Clone(Result); end else Result := nil; end; procedure TFileViewNotebook.DeletePage(Index: Integer); var APage: TFileViewPage; begin APage:= GetPage(Index); FPageControl.Pages[Index].Free; APage.Free; end; procedure TFileViewNotebook.RemovePage(Index: Integer); begin {$IFDEF LCLGTK2} // If removing currently active page, switch to another page first. // Otherwise there can be no page selected. if (PageIndex = Index) and (PageCount > 1) then begin if Index = PageCount - 1 then Page[Index - 1].MakeActive else Page[Index + 1].MakeActive; end; {$ENDIF} DeletePage(Index); ShowTabs:= ((PageCount > 1) or (tb_always_visible in gDirTabOptions)) and gDirectoryTabs; {$IFNDEF LCLGTK2} // Force-activate current page. if PageIndex <> -1 then Page[PageIndex].MakeActive; {$ENDIF} end; procedure TFileViewNotebook.RemovePage(var APage: TFileViewPage); begin RemovePage(APage.PageIndex); APage := nil; end; procedure TFileViewNotebook.DestroyAllPages; begin while PageCount > 0 do DeletePage(0); end; procedure TFileViewNotebook.ActivatePrevTab; begin if PageIndex = 0 then Page[PageCount - 1].MakeActive else Page[PageIndex - 1].MakeActive; end; procedure TFileViewNotebook.ActivateNextTab; begin if PageIndex = PageCount - 1 then Page[0].MakeActive else Page[PageIndex + 1].MakeActive; end; function TFileViewNotebook.GetCapabilities: TCTabControlCapabilities; begin Result:= FPageControl.GetCapabilities; end; function TFileViewNotebook.IndexOfPageAt(P: TPoint): Integer; begin P:= ClientToScreen(P); Result:= FPageControl.IndexOfPageAt(FPageControl.ScreenToClient(P)); end; function TFileViewNotebook.GetPageCount: Integer; begin Result:= FPageControl.PageCount; end; function TFileViewNotebook.GetShowTabs: Boolean; begin Result:= FPageControl.Visible; end; function TFileViewNotebook.GetPageIndex: Integer; begin Result:= FPageControl.PageIndex; end; function TFileViewNotebook.GetTabPosition: TTabPosition; begin Result:= FPageControl.TabPosition; end; procedure TFileViewNotebook.SetMultiLine(AValue: Boolean); begin FPageControl.MultiLine:= AValue; Application.QueueAsyncCall(@FPageControl.TabControlBoundsChange, 0); end; procedure TFileViewNotebook.SetOptions(AValue: TCTabControlOptions); begin FPageControl.Options:= AValue; Application.QueueAsyncCall(@FPageControl.TabControlBoundsChange, 0); end; procedure TFileViewNotebook.SetShowTabs(AValue: Boolean); begin if (FPageControl.Visible <> AValue) then begin FPageControl.Visible:= AValue; Application.QueueAsyncCall(@FPageControl.TabControlBoundsChange, 0); end; end; procedure TFileViewNotebook.SetPageIndex(AValue: Integer); begin FPageControl.PageIndex:= AValue; end; procedure TFileViewNotebook.SetTabPosition(AValue: TTabPosition); begin if FPageControl.TabPosition <> AValue then begin FPageControl.TabPosition:= AValue; {$IF DEFINED(LCLWIN32) or DEFINED(LCLCARBON)} // Fix Z-order, it's wrong after tab position change RecreateWnd(Self); {$ENDIF} Application.QueueAsyncCall(@FPageControl.TabControlBoundsChange, 0); end; end; procedure TFileViewNotebook.DoChange; var Index: Integer; APage: TFileViewPage; begin if Assigned(FOnPageChanged) then FOnPageChanged(Self); for Index:= 0 to PageCount - 1 do begin APage:= GetPage(Index); if Assigned(APage) then begin if Index <> PageIndex then APage.Hide else begin APage.Show; end; end; end; ActivePage.DoActivate; end; procedure TFileViewNotebook.UpdatePagePosition(AIndex, ASpacing: Integer); begin with Page[AIndex] do begin case FPageControl.TabPosition of tpTop: begin BorderSpacing.Bottom:= 0; BorderSpacing.Top:= ASpacing; end; tpBottom: begin BorderSpacing.Top:= 0; BorderSpacing.Bottom:= ASpacing; end; end; {$IF DEFINED(LCLCOCOA)} if Visible then BringToFront; {$ELSE} BringToFront; {$ENDIF} end; end; procedure TFileViewNotebook.ActivateTabByIndex(Index: Integer); begin if Index < -1 then Exit; if Index = -1 then Page[PageCount - 1].MakeActive else if PageCount >= Index + 1 then Page[Index].MakeActive; end; procedure TFileViewNotebook.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FPageControl.FLastMouseDownPageIndex:= -1; inherited MouseDown(Button, Shift, X, Y); end; end.
unit AServicos; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, DBTables, Db, DBCtrls, Grids, DBGrids, Buttons, Menus, formularios, PainelGradiente, Tabela, Componentes1, LabelCorMove, Localizacao, Mask, EditorImagem, ImgList, numericos, UnClassificacao; type TFServicos = class(TFormularioPermissao) Splitter1: TSplitter; CadClassificacao: TQuery; Imagens: TImageList; CadServicos: TQuery; PainelGradiente1: TPainelGradiente; PanelColor2: TPanelColor; Arvore: TTreeView; PanelColor4: TPanelColor; BAlterar: TBitBtn; BExcluir: TBitBtn; BServicos: TBitBtn; BitBtn1: TBitBtn; Localiza: TConsultaPadrao; BClasssificao: TBitBtn; BFechar: TBitBtn; BConsulta: TBitBtn; PopupMenu1: TPopupMenu; NovaClassificao1: TMenuItem; NovoProduto1: TMenuItem; N1: TMenuItem; Alterar1: TMenuItem; Excluir1: TMenuItem; Consultar1: TMenuItem; Localizar1: TMenuItem; N2: TMenuItem; ImageList1: TImageList; Aux: TQuery; EditColor1: TEditColor; CAtiPro: TCheckBox; BBAjuda: TBitBtn; procedure FormCreate(Sender: TObject); procedure ArvoreExpanded(Sender: TObject; Node: TTreeNode); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ArvoreChange(Sender: TObject; Node: TTreeNode); procedure ArvoreCollapsed(Sender: TObject; Node: TTreeNode); Procedure Excluir(Sender : TObject); procedure BAlterarClick(Sender: TObject); procedure BExcluirClick(Sender: TObject); procedure BClasssificaoClick(Sender: TObject); procedure BServicosClick(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure BConsultaClick(Sender: TObject); procedure ArvoreDblClick(Sender: TObject); procedure ArvoreKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ArvoreKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure AtiProClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BBAjudaClick(Sender: TObject); private Listar : boolean; QtdNiveis : Byte; VetorMascara : array [1..6] of byte; VetorNo: array [0..6] of TTreeNode; VprPrimeiroNo : TTreeNode; function DesmontaMascara(var Vetor : array of byte; mascara:string):byte; procedure CadastraClassificacao; function LimpaArvore : TTreeNode; procedure CarregaClassificacao(VpaVetorInfo : array of byte); procedure CarregaServico(VetorInfo : array of byte; nivel : byte; Codigo : string; NoSelecao : TTreeNode); procedure Habilita( Node: TTreeNode ); procedure RecarregaLista; procedure CadatraServico; procedure Alterar(Sender: TObject;Alterar : Boolean); public { Public declarations } end; var FServicos: TFServicos; implementation uses APrincipal, Fundata, constantes, funObjeto, FunSql, constMsg, funstring, ANovaClassificacao, ANovoServico; {$R *.DFM} {***********************No fechamento do Formulario****************************} procedure TFServicos.FormClose(Sender: TObject; var Action: TCloseAction); begin CadServicos.Close; CadClassificacao.Close; Action := CaFree; end; {************************Quanto criado novo formulario*************************} procedure TFServicos.FormCreate(Sender: TObject); begin FillChar(VetorMascara, SizeOf(VetorMascara), 0); Self.HelpFile := Varia.PathHelp + 'MPONTOLOJA.HLP>janela'; // Indica o Paph e o nome do arquivo de Help Listar := true; CadServicos.open; QtdNiveis := DesmontaMascara(VetorMascara, varia.MascaraClaSer); // busca em constantes CarregaClassificacao(VetorMascara); Arvore.Color := EditColor1.Color; Arvore.Font := EditColor1.font; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Chamadas diversas dos Tree )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*****cada deslocamento no TreeView causa uma mudança na lista da direita******} procedure TFServicos.ArvoreChange(Sender: TObject; Node: TTreeNode); begin habilita(node); if listar then begin if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin CarregaServico(VetorMascara,node.Level,TClassificacao(TTreeNode(node).Data).Codigo, node); end; arvore.Update; end; end; { *******************Cada vez que expandir um no*******************************} procedure TFServicos.ArvoreExpanded(Sender: TObject; Node: TTreeNode); begin CarregaServico(VetorMascara,node.Level,TClassificacao(TTreeNode(node).Data).Codigo,node); if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin Node.SelectedIndex:=1; Node.ImageIndex:=1; end; end; {********************Cada vez que voltar a expanção de um no*******************} procedure TFServicos.ArvoreCollapsed(Sender: TObject; Node: TTreeNode); begin if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then begin Node.SelectedIndex:=0; Node.ImageIndex:=0; end; end; { **************** se presionar a setas naum atualiza movimentos ************ } procedure TFServicos.ArvoreKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key in[37..40] then Listar := False; end; { ************ apos soltar setas atualiza movimentos ************************ } procedure TFServicos.ArvoreKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin Listar := true; ArvoreChange(sender,arvore.Selected); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações de localizacao do servico )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {************************ localiza o servico **********************************} procedure TFServicos.BitBtn1Click(Sender: TObject); var codigo, select : string; somaNivel,nivelSelecao : integer; begin select :=' Select * from cadservico ' + ' where c_nom_ser like ''@%''' + ' order by c_nom_ser '; Localiza.info.DataBase := Fprincipal.BaseDados; Localiza.info.ComandoSQL := select; Localiza.info.caracterProcura := '@'; Localiza.info.ValorInicializacao := ''; Localiza.info.CamposMostrados[0] := 'I_cod_SER'; Localiza.info.CamposMostrados[1] := 'c_nom_SER'; Localiza.info.CamposMostrados[2] := ''; Localiza.info.DescricaoCampos[0] := 'Código'; Localiza.info.DescricaoCampos[1] := 'Nome Serviço'; Localiza.info.DescricaoCampos[2] := ''; Localiza.info.TamanhoCampos[0] := 8; Localiza.info.TamanhoCampos[1] := 40; Localiza.info.TamanhoCampos[2] := 0; Localiza.info.CamposRetorno[0] := 'I_cod_ser'; Localiza.info.CamposRetorno[1] := 'C_cod_cla'; Localiza.info.SomenteNumeros := false; Localiza.info.CorFoco := FPrincipal.CorFoco; Localiza.info.CorForm := FPrincipal.CorForm; Localiza.info.CorPainelGra := FPrincipal.CorPainelGra; Localiza.info.TituloForm := ' Localizar Serviços '; if Localiza.execute then if localiza.retorno[0] <> '' Then begin SomaNivel := 1; NivelSelecao := 1; listar := false; arvore.Selected := VprPrimeiroNo; while SomaNivel <= Length(localiza.retorno[1]) do begin codigo := copy(localiza.retorno[1], SomaNivel, VetorMascara[nivelSelecao]); SomaNivel := SomaNivel + VetorMascara[nivelSelecao]; arvore.Selected := arvore.Selected.GetNext; while TClassificacao(arvore.Selected.Data).CodigoRed <> Codigo do arvore.Selected := arvore.Selected.GetNextChild(arvore.selected); inc(NivelSelecao); end; CarregaServico(VetorMascara,arvore.selected.Level,TClassificacao(arvore.selected.Data).Codigo,arvore.selected); arvore.Selected := arvore.Selected.GetNext; while TClassificacao(arvore.Selected.Data).Sequencial <> localiza.retorno[0] do arvore.Selected := arvore.Selected.GetNextChild(arvore.selected); end; listar := true; ArvoreChange(sender,arvore.Selected); self.ActiveControl := arvore; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos da classificacao )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******Desmonata a mascara pardão para a configuração das classificações*******} function TFServicos.DesmontaMascara(var Vetor : array of byte; mascara:string):byte; var x, posicao:byte; begin posicao:=0; x:=0; while Pos('.', mascara) > 0 do begin vetor[x]:=(Pos('.', mascara)-posicao)-1; inc(x); posicao:=Pos('.', mascara); mascara[Pos('.', mascara)] := '*'; end; vetor[x]:=length(mascara)-posicao; vetor[x+1] := 1; DesmontaMascara:=x+1; end; {********************* cadastra uma nova classificacao ************************} procedure TFServicos.CadastraClassificacao; var VpfDado : TClassificacao; VpfDescricao : string; begin if (QtdNiveis <= Arvore.Selected.Level) then //acabou os niveis para incluir a nova classificacao begin Erro(CT_FimInclusaoClassificacao); abort; end; VpfDado := TClassificacao.Create; VpfDado.Codigo := TClassificacao(TTreeNode(arvore.Selected).Data).Codigo; // envia o codigo pai para insercao; FNovaClassificacao := TFNovaClassificacao.CriarSDI(application,'', Fprincipal.VerificaPermisao('FNovaClassificacao')); if FNovaClassificacao.Inseri(VpfDado, VpfDescricao, VetorMascara[Arvore.Selected.Level+1], 'S') then begin VpfDado.tipo := 'CL'; VpfDado.PathFoto := ''; Arvore.Items.AddChildObject( TTreeNode(arvore.Selected),Vpfdado.codigoRed + ' - ' + VpfDescricao, VpfDado); arvore.OnChange(self,arvore.selected); Arvore.Update; end else Vpfdado.free; end; {****************** limpa a arvore e cria o no inicial ************************} function TFServicos.LimpaArvore : TTreeNode; var VpfDado : TClassificacao; begin Arvore.Items.Clear; VpfDado:= TClassificacao.Create; VpfDado.codigo:=''; VpfDado.CodigoRed:=''; VpfDado.Tipo := 'CL'; result := arvore.Items.AddObject(arvore.Selected, 'Serviços', VpfDado); result.ImageIndex:=0; result.SelectedIndex:=0; end; {************************carrega Classificacao*********************************} procedure TFServicos.CarregaClassificacao(VpaVetorInfo : array of byte); var VpfNo : TTreeNode; Vpfdado : TClassificacao; VpfTamanho, nivel : word; Vpfcodigo :string; begin VpfNo := LimpaArvore; // limpa a arvore e retorna o no inicial; VprPrimeiroNo := VpfNo; VetorNo[0]:= VpfNo; Arvore.Update; AdicionaSQLAbreTabela(CadClassificacao,'SELECT * FROM CADCLASSIFICACAO '+ 'WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and c_tip_cla = ''S''' + ' ORDER BY C_COD_CLA '); while not(CadClassificacao.EOF) do begin VpfTamanho := VpaVetorInfo[0]; nivel := 0; while length(CadClassificacao.FieldByName('C_COD_CLA').AsString)<>VpfTamanho do begin inc(nivel); Vpftamanho:= VpfTamanho+VpaVetorInfo[nivel]; end; Vpfcodigo :=CadClassificacao.FieldByName('C_COD_CLA').AsString; Vpfdado:= TClassificacao.Create; VpfDado.codigo:= CadClassificacao.FieldByName('C_COD_CLA').AsString; VpfDado.CodigoRed := copy(Vpfcodigo, (length(Vpfcodigo)-VpaVetorInfo[nivel])+1, VpaVetorInfo[nivel]); VpfDado.tipo := 'CL'; VpfDado.Situacao := true; VpfNo :=Arvore.Items.AddChildObject(VetorNo[nivel],VpfDado.CodigoRed+ ' - '+ CadClassificacao.FieldByName('C_NOM_CLA').AsString, VpfDado); VetorNo[nivel+1]:=VpfNo; CadClassificacao.Next; end; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos dos servicos )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {********************* cadastra um novo servico *******************************} procedure TFServicos.CadatraServico; var Vpfdado:TClassificacao; VpfNo : TTreeNode; VpfDescricao, VpfCodServico, VpfCodClassificacao : string; begin if (arvore.Selected.Level = 0) then // se estiver no no inicial nao cadastra begin erro(CT_ClassificacacaoServicoInvalida); abort; end; if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'PA' then // se estiver selecionado um servico nao cadastra pois nao pode cadastrar um servico dentro de outro begin erro(CT_ErroInclusaoServico); abort; end; VpfDado := TClassificacao.Create; VpfCodClassificacao:= TClassificacao(TTreeNode(Arvore.selected).data).codigo; FNovoServico := TFNovoServico.CriarSDI(application,'',FPrincipal.VerificaPermisao('FNovoServico')); if FNovoServico.InsereNovoServico(VpfCodClassificacao, VpfCodServico,VpfDescricao, False) then begin VpfDado.Codigo := VpfCodClassificacao; VpfDado.tipo := 'SE'; VpfDado.Situacao := true; Vpfdado.sequencial := VpfCodServico; Vpfno:= Arvore.Items.AddChildObject( TTreeNode(arvore.Selected),VpfDado.Sequencial + ' - ' + VpfDescricao, VpfDado); Vpfno.ImageIndex := 2; Vpfno.SelectedIndex := 2; arvore.OnChange(Self,arvore.selected); Arvore.Update; end; end; {**************alteração de Classificação ou o servico*************************} procedure TFServicos.Alterar(Sender: TObject; Alterar : Boolean); var Vpfcodigo, VpfDescricao : string; begin if (arvore.Selected.Level=0) then {não é possível alterar o primeiro item} abort; if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'CL' then begin FNovaClassificacao := TFNovaClassificacao.CriarSDI(application,'',FPrincipal.VerificaPermisao('FNovaClassificacao')); if FNovaClassificacao.Alterar(TClassificacao(arvore.Selected.Data).Codigo, TClassificacao(Arvore.Selected.Data).CodigoRed, VpfDescricao, 'S', Alterar) then begin VpfCodigo := TClassificacao(TTreeNode(Arvore.Selected).Data).CodigoRed; arvore.Selected.Text := VpfCodigo + ' - ' + VpfDescricao; arvore.OnChange(sender,arvore.selected); arvore.Update; end; end else if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then begin Vpfcodigo := TClassificacao(TTreeNode(arvore.Selected).Data).Sequencial ; Vpfdescricao := ''; FNovoServico := TFNovoServico.CriarSDI(application, '',FPrincipal.VerificaPermisao('FNovoServico')); if FNovoServico.AlteraServico(TClassificacao(TTreeNode(arvore.Selected).Data).Codigo, VpfCodigo,VpfDescricao, Alterar) then arvore.Selected.Text := VpfCodigo + ' - ' + VpfDescricao; end; end; {****************** carrega os servicos na arvore *****************************} procedure TFServicos.CarregaServico(VetorInfo : array of byte; nivel : byte; Codigo : string; NoSelecao : TTreeNode ); var No : TTreeNode; Dado : TClassificacao; VpfAtividade : String; begin if TClassificacao(TTreeNode(NoSelecao).Data).Situacao then begin if CAtiPro.Checked Then VpfAtividade := ' and C_Ati_Ser = ''S''' else VpfAtividade := ''; AdicionaSQLAbreTabela(CadServicos, ' Select * from CadServico ' + ' Where I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and C_COD_CLA = ''' + codigo + '''' + VpfAtividade + ' Order by I_Cod_Ser'); while not CadServicos.EOF do begin dado:= TClassificacao.Create; Dado.Codigo := Codigo; Dado.Sequencial := CadServicos.FieldByName('I_COD_SER').AsString; Dado.Situacao := true; Dado.tipo := 'SE'; No := Arvore.Items.AddChildObject(NoSelecao, Dado.Sequencial + ' - ' + CadServicos.FieldByName('C_NOM_SER').AsString, Dado); VetorNo[nivel+1] := no; No.ImageIndex := 2; No.SelectedIndex := 2; CadServicos.Next; end; TClassificacao(TTreeNode(NoSelecao).Data).Situacao := False; end; end; {*****************Exclusão de Classificação e produtos*************************} procedure TFServicos.Excluir(Sender : TObject); var no : TTreeNode; begin if (arvore.Selected.Level=0) then abort; no := arvore.Selected; listar := false; if (Arvore.Selected.HasChildren) then// Nao permite excluir se possui filhos begin erro(CT_ErroExclusaoClassificaca); arvore.Selected := no; Listar := true; abort; end; if confirmacao(CT_DeletarItem) then // verifica se deseja excluir begin if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'CL' then try // caso seja uma classificacao ExecutaComandoSql(Aux,'DELETE FROM CADCLASSIFICACAO'+ ' WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and C_COD_CLA='''+ TClassificacao(TTreeNode(arvore.Selected).Data).Codigo+ ''''+ ' and C_Tip_CLA = ''S'''); TClassificacao(TTreeNode(arvore.selected).Data).Free; arvore.items.Delete(arvore.Selected); except erro(CT_ErroDeletaRegistroPai); end; // caso seja um serviço if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then begin try ExecutaComandoSql(Aux,' DELETE FROM CADSERVICO WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) + ' and I_COD_SER ='+ TClassificacao(TTreeNode(arvore.Selected).Data).Sequencial); TClassificacao(TTreeNode(arvore.selected).Data).Free; arvore.items.Delete(arvore.Selected); except erro(CT_ErroDeletaRegistroPai); end; end; listar := true; arvore.OnChange(sender,arvore.selected); end; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos dos botoes )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {***************** cadastra uma nova classificacao ****************************} procedure TFServicos.BClasssificaoClick(Sender: TObject); begin CadastraClassificacao; end; { ***************** altera a mostra entre produtos em atividades ou naum ******} procedure TFServicos.AtiProClick(Sender: TObject); begin RecarregaLista; end; {*************Chamada de alteração de produtos ou classificações***************} procedure TFServicos.BConsultaClick(Sender: TObject); begin Alterar(sender,false); // Consulta o servico ou a classificacao end; {*************Chamada de alteração de produtos ou classificações***************} procedure TFServicos.BAlterarClick(Sender: TObject); begin Alterar(sender,true); // chamada de alteração end; {***************Chama a rotina para cadastrar um novo produto******************} procedure TFServicos.BServicosClick(Sender: TObject); begin CadatraServico; end; {****************************Fecha o Formulario corrente***********************} procedure TFServicos.BFecharClick(Sender: TObject); begin Close; end; {************Chamada de Exclusão de produtos ou classificações*****************} procedure TFServicos.BExcluirClick(Sender: TObject); begin Excluir(sender); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*********************** recarrega a lista ************************************} procedure TFServicos.RecarregaLista; begin Listar := false; Arvore.Items.Clear; Listar := true; CarregaClassificacao(VetorMascara); end; {************** quando se da um duplo clique na arvore ************************} procedure TFServicos.ArvoreDblClick(Sender: TObject); begin if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then BAlterar.Click; end; {****************** habilita ou nao os botoes ********************************} procedure TFServicos.Habilita( Node: TTreeNode ); begin if TClassificacao(node.Data).tipo = 'CL' then begin BAlterar.Enabled := true; BExcluir.Enabled := true; BConsulta.Enabled := true; end; if TClassificacao(node.Data).tipo = 'SE' then begin BAlterar.Enabled := true; BExcluir.Enabled := true; BConsulta.enabled := true; end; end; procedure TFServicos.BBAjudaClick(Sender: TObject); begin Application.HelpCommand(HELP_CONTEXT,FServicos.HelpContext); end; end.
unit JSONNullableAttributeUnit; interface uses REST.Json.Types, REST.JsonReflect; type BaseJSONNullableAttribute = class abstract(JsonReflectAttribute) private FIsRequired: boolean; protected constructor CreateCommon; public /// <summary> /// Constructor of JSONNullableAttribute /// <param name="IsRequired"> Required attribute or not. </param> /// </summary> constructor Create(IsRequired: boolean = False); overload; property IsRequired: boolean read FIsRequired; end; NullableAttribute = class(BaseJSONNullableAttribute) end; NullableArrayAttribute = class(JsonReflectAttribute) private FClass: TClass; FIsRequired: boolean; public constructor Create(Clazz: TClass; IsRequired: boolean = False); reintroduce; property Clazz: TClass read FClass; end; NullableObjectAttribute = class(NullableAttribute) private FClass: TClass; public /// <summary> /// Constructor of JSONNullableAttribute /// <param name="IsRequired"> Required attribute or not. </param> /// </summary> constructor Create(Clazz: TClass; IsRequired: boolean = False); reintroduce; property Clazz: TClass read FClass; end; implementation uses NullableInterceptorUnit, NullableArrayInterceptorUnit; { NullableObjectAttribute } constructor NullableObjectAttribute.Create(Clazz: TClass; IsRequired: boolean = False); begin Inherited Create(IsRequired); FClass := Clazz; end; { BaseJSONNullableAttribute } constructor BaseJSONNullableAttribute.Create(IsRequired: boolean = False); begin CreateCommon; FIsRequired := IsRequired; end; constructor BaseJSONNullableAttribute.CreateCommon; begin Inherited Create(ctObject, rtString, TNullableInterceptor); end; { NullableArrayAttribute } constructor NullableArrayAttribute.Create(Clazz: TClass; IsRequired: boolean); begin Inherited Create(ctObject, rtStrings, TNullableArrayInterceptor); FIsRequired := IsRequired; FClass := Clazz; end; end.
{ Subroutine SST_NAME_NEW_OUT (NAME,NAME_P,SYM_PP,STAT) * * Add a new name to the output symbol table at the current scope. * * NAME is the name to add. The current character case setting for output symbol * names will be applied before adding NAME to the symbol table. * * NAME_P is returned pointing to the symbol name string stored in the hash * table entry. * * SYM_PP is returned pointing to the start of the user data area in the * hash table entry. The only thing stored there is the pointer to the symbol * descriptor. This need not exist if the name is added to the symbol table * only to prevent use of the name later. * * STAT is the returned completion status code. It will be set to the * SST_STAT_SYM_FOUND_K status if the symbol name was already in the symbol * table at or above the current scope. } module sst_NAME_NEW_OUT; define sst_name_new_out; %include 'sst2.ins.pas'; procedure sst_name_new_out ( {add symbol to output table at curr scope} in name: univ string_var_arg_t; {name of new symbol} out name_p: univ string_var_p_t; {will point to name stored in hash table} out sym_pp: sst_symbol_pp_t; {points to hash table entry user data area} out stat: sys_err_t); {completion status code} var namec: string_var132_t; {name after case rules applied} pos_curr: string_hash_pos_t; {position handle for hash table at curr scope} pos: string_hash_pos_t; {position handle for other hash tables} scope_p: sst_scope_p_t; {points to scope looking for name at} found: boolean; {TRUE if name found in hash table} begin namec.max := sizeof(namec.str); {init local var string} sys_error_none (stat); {init to no error occurred} string_copy (name, namec); {make local copy of name supplied by caller} case sst_config.charcase of {apply current output name case rule} syo_charcase_down_k: string_downcase (namec); syo_charcase_up_k: string_upcase (namec); end; {end of character case rule cases} scope_p := sst_scope_p; {set first scope to look for name in} while scope_p <> nil do begin {once for each scope up to root scope} if scope_p = sst_scope_p then begin {we are looking for name in most local scope} string_hash_pos_lookup ( {look up name in output symbol table} scope_p^.hash_out_h, {hash table handle} namec, {symbol name} pos_curr, {save position handle for most local scope} found); {returned TRUE if name existed here} end else begin {not looking in table where symbol goes later} string_hash_pos_lookup ( {look up name in output symbol table} scope_p^.hash_out_h, {hash table handle} namec, {symbol name} pos, {returned hash table position handle} found); {returned TRUE if name existed here} end ; if found then begin {name already exists ?} sys_stat_set ( {set STAT to indicate name already exists} sst_subsys_k, sst_stat_sym_found_k, stat); sys_stat_parm_vstr (namec, stat); {pass symbol name to error code} return; {return with SYMBOL ALREADY EXISTS status} end; scope_p := scope_p^.parent_p; {advance to next most global scope} end; {back and look for symbol in new scope} { * The symbol exists in none of the currently active scopes. POS_CURR is the * hash table position handle to where the symbol goes in the current scope. } string_hash_ent_add ( {add name to hash table} pos_curr, {position handle of where to add name} name_p, {returned pointing to name stored in table} sym_pp); {returned pointing to start of user data area} sym_pp^ := nil; {init to this name has no symbol descriptor} end;
unit Integrals_; interface uses Unit4; function IntRectR(F: TFunc2d; a,b: extended; N: integer): TReal; overload; function IntRectM(F: TFunc2d; a,b: extended; N: integer): TReal; function IntRectL(F: TFunc2d; a,b: extended; N: integer): TReal; overload; function IntTrapz(F: TFunc2d; a,b: extended; N: integer): TReal; function IntSimps(F: TFunc2d; a,b: extended; N: integer): TReal; function IntRectR(FP: TpointsArray2d): TReal; overload; function IntRectL(FP: TpointsArray2d): TReal; overload; function IntTrap2d(F: TFormula; a,b,c,d: extended; Nx,Ny: integer):TReal; implementation function IntRectR(F: TFunc2d; a,b: extended; N: integer): TReal; var opres: TReal; steph: extended; i: integer; begin result.error:=false; result.result:=0; setlength(varvect,1); steph:=(b-a)/N; for i := 1 to N do begin varvect[0]:=a+i*steph; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result; end; result.result:=result.result*steph; end; function IntRectL(F: TFunc2d; a,b: extended; N: integer): TReal; var opres: TReal; steph: extended; i: integer; begin result.error:=false; result.result:=0; setlength(varvect,1); steph:=(b-a)/N; for i := 0 to N-1 do begin varvect[0]:=a+i*steph; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result; end; result.result:=result.result*steph; end; function IntRectM(F: TFunc2d; a,b: extended; N: integer): TReal; var opres: TReal; steph,steph2: extended; i: integer; begin result.error:=false; result.result:=0; setlength(varvect,1); steph:=(b-a)/N; steph2:=steph/2; for i := 1 to N do begin varvect[0]:=a+i*steph-steph2; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result; end; result.result:=result.result*steph; end; function IntTrapz(F: TFunc2d; a,b: extended; N: integer): TReal; var opres: TReal; steph: extended; i: integer; begin result.error:=false; result.result:=0; setlength(varvect,1); steph:=(b-a)/N; varvect[0]:=a; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=opres.result/2; for i := 1 to N-1 do begin varvect[0]:=a+i*steph; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result; end; varvect[0]:=b; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result/2; result.result:=result.result*steph; end; function IntSimps(F: TFunc2d; a,b: extended; N: integer): TReal; var opres: TReal; steph: extended; i: integer; begin result.error:=false; result.result:=0; if not odd(N) then begin result.Error:=true; exit; end; setlength(varvect,1); steph:=(b-a)/N; varvect[0]:=a; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=opres.result; for i := 1 to N-1 do begin varvect[0]:=a+i*steph; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; if odd(i) then result.result:=result.result+4*opres.result else result.result:=result.result+2*opres.result; end; varvect[0]:=b; opres:=GetOpres(F.DataAr,F.OperAr,VarVect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+opres.result; result.result:=result.result*steph/3; end; function IntRectR(FP: TpointsArray2d): TReal; overload; var i,N: integer; begin result.error:=false; result.result:=0; N:=length(FP)-1; for i := 1 to N do begin if not FP[i].IsMathEx then begin result.Error:=true; exit; end; result.result:=result.result+(FP[i].y*FP[i].x-FP[i-1].x); end; end; function IntRectL(FP: TpointsArray2d): TReal; overload; var i,N: integer; begin result.error:=false; result.result:=0; N:=length(FP)-2; for i := 0 to N do begin if not FP[i].IsMathEx then begin result.Error:=true; exit; end; result.result:=result.result+(FP[i].y*FP[i+1].x-FP[i].x); end; end; function IntTrap2d(F:TFormula; a,b,c,d: extended; Nx,Ny: integer):Treal; var i: integer; opres:TReal; stepx,stepy: extended; j: Integer; begin result.Error:=false; result.result:=0; setlength(varvect,2); stepx:=(b-a)/Nx; stepy:=(d-c)/Ny; for i := 1 to Nx-1 do//01..03 begin varvect[0]:=a+stepx*i; varvect[1]:=c; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; end; for i := 1 to Nx-1 do//31..33 begin varvect[0]:=a+stepx*i; varvect[1]:=d; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; end; for j := 1 to Ny-1 do//10..20 begin varvect[0]:=a; varvect[1]:=c+stepy*j; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; end; for j := 1 to Ny-1 do//14..24 begin varvect[0]:=b; varvect[1]:=c+stepy*j; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; end; for i := 0 to Nx-1 do //11..23 for j := 0 to Ny-1 do begin varvect[0]:=a+stepx*i; varvect[1]:=c+stepy*j; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+6*opres.result; end; //00 varvect[0]:=a; varvect[1]:=c; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+2*opres.result; //34 varvect[0]:=b; varvect[1]:=d; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+2*opres.result; //04 varvect[0]:=b; varvect[1]:=c; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; //30 varvect[0]:=a; varvect[1]:=d; opres:=GetOpres(F.DataAr,F.OperAr,varvect); if opres.Error then begin result.Error:=true; exit; end; result.result:=result.result+3*opres.result; result.result:=result.result/6*stepx*stepy; //// __.__.__.__ узлы 00, 01, 02, 03, 04 /// |\ |\ |\ |\ | /// |_\|_\|_\|_\| узлы 10, 11, 12, 13, 14 /// |\ |\ |\ |\ | /// |_\|_\|_\|_\| узлы 20, 21, 22, 23, 24 /// |\ |\ |\ |\ | /// |_\|_\|_\|_\| узлы 30, 31, 32, 33, 34 /// Nx=4, Ny=3 /// узел\к-т /// 01..03 1/2 верхняя граница, кроме углов /// 31..33 1/2 нижняя граница, кроме углов /// 10..20 1/2 левая граница, кроме углов /// 14..24 1/2 правая граница, кроме углов /// 11..23 1 центральные узлы /// 30,04 1/6 нижний левый, верхний правый узел /// 00,34 1/3 верхний левый и нижний правый /// end; end.
unit caUserManager; // Модуль: "w:\common\components\rtl\Garant\ComboAccess\caUserManager.pas" // Стереотип: "SimpleClass" // Элемент модели: "TcaUserManager" MUID: (56C428E4014A) {$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc} interface {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes , l3DatLst , l3LongintList , Classes ; type TcaUserManager = class(Tl3ProtoObject, IdaUserManager) private f_HTManager: IdaUserManager; f_PGManager: IdaUserManager; f_PriorityCalculator: IdaPriorityCalculator; protected function CheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): TdaLoginError; function IsUserAdmin(anUserID: TdaUserID): Boolean; function Get_AllUsers: Tl3StringDataList; function Get_AllGroups: Tl3StringDataList; function GetUserName(anUserID: TdaUserID): AnsiString; function GetUserPriorities(aGroupId: TdaUserID; var aImportPriority: TdaPriority; var aExportPriority: TdaPriority): Boolean; procedure ReSortUserList; function Get_ArchiUsersCount: Integer; function UserByID(aID: TdaUserID): IdaArchiUser; function UserByLogin(const aLogin: AnsiString): IdaArchiUser; procedure UpdateUserInfo(aUserID: TdaUserID; aIsGroup: Boolean); procedure MakeFullArchiUsersList; function GetUserDisplayName(anID: TdaUserID): AnsiString; function IsUserExists(anID: TdaUserID): Boolean; procedure RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); procedure UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); procedure NotifyUserActiveChanged(anUserID: TdaUserID; anActive: Boolean); function CSCheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): Boolean; procedure GetUserInfo(aUser: TdaUserID; var aUserName: AnsiString; var aLoginName: AnsiString; var aActFlag: Byte); function Get_PriorityCalculator: IdaPriorityCalculator; function IsMemberOfGroup(aUserGroupID: TdaUserGroupID; aUserID: TdaUserID): Boolean; function GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray; procedure GetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); overload; procedure GetUserGroupsList(aUser: TdaUserID; aList: Tl3LongintList); overload; procedure SetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); function AddUserGroup(const aName: AnsiString): TdaUserGroupID; procedure EditUserGroup(aGroupID: TdaUserGroupID; const aName: AnsiString; aImportPriority: TdaPriority; aExportPriority: TdaPriority); procedure DelUserGroup(aGroupID: TdaUserGroupID); procedure RemoveUserFromAllGroups(aUser: TdaUserID); procedure SetUserGroup(aUser: TdaUserID; aGroup: TdaUserGroupID; Add: Boolean = True); procedure AdminChangePassWord(aUser: TdaUserID; const NewPass: AnsiString); procedure GetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList; NeedSort: Boolean = False); procedure SetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList); function AddUser(const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; function AddUserID(anID: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; procedure EditUser(aUser: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; ActFlag: Byte; const EditMask: TdaUserEditMask); procedure DelUser(aUser: TdaUserID); procedure GetUserListOnGroup(aUsGroup: TdaUserGroupID; aList: Tl3StringDataList; GetActiveUsersOnly: Boolean = False); procedure GetFiltredUserList(aList: TStrings; aOnlyActive: Boolean = False); procedure GetDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); procedure PutDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aHTManager: IdaUserManager; const aPGManager: IdaUserManager); reintroduce; class function Make(const aHTManager: IdaUserManager; const aPGManager: IdaUserManager): IdaUserManager; reintroduce; procedure IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action); procedure IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action); end;//TcaUserManager {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) implementation {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3ImplUses , l3ListUtils , caPriorityCalculator , caArchiUser , SysUtils , l3Base //#UC START# *56C428E4014Aimpl_uses* //#UC END# *56C428E4014Aimpl_uses* ; constructor TcaUserManager.Create(const aHTManager: IdaUserManager; const aPGManager: IdaUserManager); //#UC START# *56C429340002_56C428E4014A_var* //#UC END# *56C429340002_56C428E4014A_var* begin //#UC START# *56C429340002_56C428E4014A_impl* inherited Create; f_HTManager := aHTManager; f_PGManager := aPGManager; //#UC END# *56C429340002_56C428E4014A_impl* end;//TcaUserManager.Create class function TcaUserManager.Make(const aHTManager: IdaUserManager; const aPGManager: IdaUserManager): IdaUserManager; var l_Inst : TcaUserManager; begin l_Inst := Create(aHTManager, aPGManager); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TcaUserManager.Make function TcaUserManager.CheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): TdaLoginError; //#UC START# *5628D14D0151_56C428E4014A_var* var l_Result: TdaLoginError; l_UserID: TdaUserID; //#UC END# *5628D14D0151_56C428E4014A_var* begin //#UC START# *5628D14D0151_56C428E4014A_impl* Result := f_HTManager.CheckPassword(aLogin, aPassword, RequireAdminRights, theUserID); l_Result := f_PGManager.CheckPassword(aLogin, aPassword, RequireAdminRights, l_UserID); Assert((Result = l_Result) and (theUserID = l_UserID)) //#UC END# *5628D14D0151_56C428E4014A_impl* end;//TcaUserManager.CheckPassword function TcaUserManager.IsUserAdmin(anUserID: TdaUserID): Boolean; //#UC START# *56EA993D0218_56C428E4014A_var* //#UC END# *56EA993D0218_56C428E4014A_var* begin //#UC START# *56EA993D0218_56C428E4014A_impl* Result := f_HTManager.IsUserAdmin(anUserID); Assert(Result = f_PGManager.IsUserAdmin(anUserID)); //#UC END# *56EA993D0218_56C428E4014A_impl* end;//TcaUserManager.IsUserAdmin function TcaUserManager.Get_AllUsers: Tl3StringDataList; //#UC START# *5715DEF20209_56C428E4014Aget_var* //#UC END# *5715DEF20209_56C428E4014Aget_var* begin //#UC START# *5715DEF20209_56C428E4014Aget_impl* Result := f_HTManager.AllUsers; Assert(l3IsIdenticalLists(Result, f_PGManager.AllUsers)); //#UC END# *5715DEF20209_56C428E4014Aget_impl* end;//TcaUserManager.Get_AllUsers function TcaUserManager.Get_AllGroups: Tl3StringDataList; //#UC START# *5715DF0D03C2_56C428E4014Aget_var* //#UC END# *5715DF0D03C2_56C428E4014Aget_var* begin //#UC START# *5715DF0D03C2_56C428E4014Aget_impl* Result := f_HTManager.AllGroups; Assert(l3IsIdenticalLists(Result, f_PGManager.AllGroups)); //#UC END# *5715DF0D03C2_56C428E4014Aget_impl* end;//TcaUserManager.Get_AllGroups function TcaUserManager.GetUserName(anUserID: TdaUserID): AnsiString; //#UC START# *5718B5CF0399_56C428E4014A_var* //#UC END# *5718B5CF0399_56C428E4014A_var* begin //#UC START# *5718B5CF0399_56C428E4014A_impl* Result := f_HTManager.GetUserName(anUserID); Assert(Result = f_PGManager.GetUserName(anUserID)); //#UC END# *5718B5CF0399_56C428E4014A_impl* end;//TcaUserManager.GetUserName function TcaUserManager.GetUserPriorities(aGroupId: TdaUserID; var aImportPriority: TdaPriority; var aExportPriority: TdaPriority): Boolean; //#UC START# *571DCFB50217_56C428E4014A_var* var l_ImportPriority: TdaPriority; l_ExportPriority: TdaPriority; l_Check: Boolean; //#UC END# *571DCFB50217_56C428E4014A_var* begin //#UC START# *571DCFB50217_56C428E4014A_impl* l_ImportPriority := aImportPriority; l_ExportPriority := aExportPriority; Result := f_HTManager.GetUserPriorities(aGroupId, aImportPriority, aExportPriority); l_Check := f_PGManager.GetUserPriorities(aGroupId, l_ImportPriority, l_ExportPriority); Assert(l_Check = Result); if Result then Assert((aImportPriority = l_ImportPriority) and (aExportPriority = l_ExportPriority)); //#UC END# *571DCFB50217_56C428E4014A_impl* end;//TcaUserManager.GetUserPriorities procedure TcaUserManager.ReSortUserList; //#UC START# *5721F5E60367_56C428E4014A_var* //#UC END# *5721F5E60367_56C428E4014A_var* begin //#UC START# *5721F5E60367_56C428E4014A_impl* f_HTManager.ReSortUserList; f_PGManager.ReSortUserList; //#UC END# *5721F5E60367_56C428E4014A_impl* end;//TcaUserManager.ReSortUserList function TcaUserManager.Get_ArchiUsersCount: Integer; //#UC START# *5729C59E00D5_56C428E4014Aget_var* //#UC END# *5729C59E00D5_56C428E4014Aget_var* begin //#UC START# *5729C59E00D5_56C428E4014Aget_impl* Result := f_HTManager.ArchiUsersCount; Assert(Result = f_PGManager.ArchiUsersCount); //#UC END# *5729C59E00D5_56C428E4014Aget_impl* end;//TcaUserManager.Get_ArchiUsersCount procedure TcaUserManager.IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action); //#UC START# *5729DD530330_56C428E4014A_var* //#UC END# *5729DD530330_56C428E4014A_var* begin //#UC START# *5729DD530330_56C428E4014A_impl* f_HTManager.IterateArchiUsersF(anAction); f_PGManager.IterateArchiUsersF(anAction); // ??? Неоднозначно. // Если накапливаем в список - излишне. // Если модифицируем пользователей - необходимо //#UC END# *5729DD530330_56C428E4014A_impl* end;//TcaUserManager.IterateArchiUsersF function TcaUserManager.UserByID(aID: TdaUserID): IdaArchiUser; //#UC START# *57358B940211_56C428E4014A_var* var l_HTUser: IdaArchiUser; l_PGUser: IdaArchiUser; //#UC END# *57358B940211_56C428E4014A_var* begin //#UC START# *57358B940211_56C428E4014A_impl* l_HTUser := f_HTManager.UserByID(aID); l_PGUser := f_PGManager.UserByID(aID); Result := TcaArchiUser.Make(l_HTUser, l_PGUser); //#UC END# *57358B940211_56C428E4014A_impl* end;//TcaUserManager.UserByID function TcaUserManager.UserByLogin(const aLogin: AnsiString): IdaArchiUser; //#UC START# *57358BCB0360_56C428E4014A_var* var l_HTUser: IdaArchiUser; l_PGUser: IdaArchiUser; //#UC END# *57358BCB0360_56C428E4014A_var* begin //#UC START# *57358BCB0360_56C428E4014A_impl* l_HTUser := f_HTManager.UserByLogin(aLogin); l_PGUser := f_PGManager.UserByLogin(aLogin); Result := TcaArchiUser.Make(l_HTUser, l_PGUser); //#UC END# *57358BCB0360_56C428E4014A_impl* end;//TcaUserManager.UserByLogin procedure TcaUserManager.UpdateUserInfo(aUserID: TdaUserID; aIsGroup: Boolean); //#UC START# *5735AE4D0017_56C428E4014A_var* //#UC END# *5735AE4D0017_56C428E4014A_var* begin //#UC START# *5735AE4D0017_56C428E4014A_impl* f_HTManager.UpdateUserInfo(aUserID, aIsGroup); f_PGManager.UpdateUserInfo(aUserID, aIsGroup); //#UC END# *5735AE4D0017_56C428E4014A_impl* end;//TcaUserManager.UpdateUserInfo procedure TcaUserManager.MakeFullArchiUsersList; //#UC START# *5735AE7F0071_56C428E4014A_var* //#UC END# *5735AE7F0071_56C428E4014A_var* begin //#UC START# *5735AE7F0071_56C428E4014A_impl* f_HTManager.MakeFullArchiUsersList; f_PGManager.MakeFullArchiUsersList; //#UC END# *5735AE7F0071_56C428E4014A_impl* end;//TcaUserManager.MakeFullArchiUsersList function TcaUserManager.GetUserDisplayName(anID: TdaUserID): AnsiString; //#UC START# *5735AECA0121_56C428E4014A_var* //#UC END# *5735AECA0121_56C428E4014A_var* begin //#UC START# *5735AECA0121_56C428E4014A_impl* Result := f_HTManager.GetUserDisplayName(anID); Assert(Result = f_PGManager.GetUserDisplayName(anID)); //#UC END# *5735AECA0121_56C428E4014A_impl* end;//TcaUserManager.GetUserDisplayName function TcaUserManager.IsUserExists(anID: TdaUserID): Boolean; //#UC START# *5739732402E4_56C428E4014A_var* //#UC END# *5739732402E4_56C428E4014A_var* begin //#UC START# *5739732402E4_56C428E4014A_impl* Result := f_HTManager.IsUserExists(anID); Assert(Result = f_PGManager.IsUserExists(anID)); //#UC END# *5739732402E4_56C428E4014A_impl* end;//TcaUserManager.IsUserExists procedure TcaUserManager.RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); //#UC START# *5739832A00A2_56C428E4014A_var* //#UC END# *5739832A00A2_56C428E4014A_var* begin //#UC START# *5739832A00A2_56C428E4014A_impl* f_HTManager.RegisterUserStatusChangedSubscriber(aSubscriber); f_PGManager.RegisterUserStatusChangedSubscriber(aSubscriber); //#UC END# *5739832A00A2_56C428E4014A_impl* end;//TcaUserManager.RegisterUserStatusChangedSubscriber procedure TcaUserManager.UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); //#UC START# *5739834700B2_56C428E4014A_var* //#UC END# *5739834700B2_56C428E4014A_var* begin //#UC START# *5739834700B2_56C428E4014A_impl* f_HTManager.UnRegisterUserStatusChangedSubscriber(aSubscriber); f_PGManager.UnRegisterUserStatusChangedSubscriber(aSubscriber); //#UC END# *5739834700B2_56C428E4014A_impl* end;//TcaUserManager.UnRegisterUserStatusChangedSubscriber procedure TcaUserManager.NotifyUserActiveChanged(anUserID: TdaUserID; anActive: Boolean); //#UC START# *5739835200CF_56C428E4014A_var* //#UC END# *5739835200CF_56C428E4014A_var* begin //#UC START# *5739835200CF_56C428E4014A_impl* f_HTManager.NotifyUserActiveChanged(anUserID, anActive); // f_PGManager.NotifyUserActiveChanged(anUserID, anActive); // ??? Неоднозначно. // будет приходить удвоенная нотификация. //#UC END# *5739835200CF_56C428E4014A_impl* end;//TcaUserManager.NotifyUserActiveChanged function TcaUserManager.CSCheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): Boolean; //#UC START# *573AC17202BF_56C428E4014A_var* var l_Check: Boolean; l_CheckUser: TdaUserID; //#UC END# *573AC17202BF_56C428E4014A_var* begin //#UC START# *573AC17202BF_56C428E4014A_impl* Result := f_HTManager.CSCheckPassword(aLogin, aPassword, RequireAdminRights, theUserID); l_Check := f_PGManager.CSCheckPassword(aLogin, aPassword, RequireAdminRights, l_CheckUser); Assert(Result = l_Check); if Result then Assert(theUserID = l_CheckUser); //#UC END# *573AC17202BF_56C428E4014A_impl* end;//TcaUserManager.CSCheckPassword procedure TcaUserManager.GetUserInfo(aUser: TdaUserID; var aUserName: AnsiString; var aLoginName: AnsiString; var aActFlag: Byte); //#UC START# *573AEE9902DF_56C428E4014A_var* var l_UserName: AnsiString; l_LoginName: AnsiString; l_ActFlag: Byte; //#UC END# *573AEE9902DF_56C428E4014A_var* begin //#UC START# *573AEE9902DF_56C428E4014A_impl* f_HTManager.GetUserInfo(aUser, aUserName, aLoginName, aActFlag); f_PGManager.GetUserInfo(aUser, l_UserName, l_LoginName, l_ActFlag); Assert((aUserName = l_UserName) and (aLoginName = l_LoginName) and (aActFlag = l_ActFlag)); //#UC END# *573AEE9902DF_56C428E4014A_impl* end;//TcaUserManager.GetUserInfo function TcaUserManager.Get_PriorityCalculator: IdaPriorityCalculator; //#UC START# *575020410175_56C428E4014Aget_var* //#UC END# *575020410175_56C428E4014Aget_var* begin //#UC START# *575020410175_56C428E4014Aget_impl* if f_PriorityCalculator = nil then f_PriorityCalculator := TcaPriorityCalculator.Make(f_HTManager.PriorityCalculator, f_PGManager.PriorityCalculator); Result := f_PriorityCalculator; //#UC END# *575020410175_56C428E4014Aget_impl* end;//TcaUserManager.Get_PriorityCalculator procedure TcaUserManager.IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action); //#UC START# *5757D9BB0116_56C428E4014A_var* //#UC END# *5757D9BB0116_56C428E4014A_var* begin //#UC START# *5757D9BB0116_56C428E4014A_impl* f_HTManager.IterateUserGroupsF(anAction); // f_PGManager.IterateUserGroupsF(anAction); //!! !!! Непонятно что с PG группами... //#UC END# *5757D9BB0116_56C428E4014A_impl* end;//TcaUserManager.IterateUserGroupsF function TcaUserManager.IsMemberOfGroup(aUserGroupID: TdaUserGroupID; aUserID: TdaUserID): Boolean; //#UC START# *575A8B790353_56C428E4014A_var* //#UC END# *575A8B790353_56C428E4014A_var* begin //#UC START# *575A8B790353_56C428E4014A_impl* Result := f_HTManager.IsMemberOfGroup(aUserGroupID, aUserID); Assert(Result = f_PGManager.IsMemberOfGroup(aUserGroupID, aUserID)); //#UC END# *575A8B790353_56C428E4014A_impl* end;//TcaUserManager.IsMemberOfGroup function TcaUserManager.GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray; //#UC START# *57625B5002DD_56C428E4014A_var* var l_Check: TdaUserGroupIDArray; l_IDX: Integer; //#UC END# *57625B5002DD_56C428E4014A_var* begin //#UC START# *57625B5002DD_56C428E4014A_impl* Result := f_HTManager.GetUserGroups(aUserID); l_Check := f_PGManager.GetUserGroups(aUserID); Assert(Length(Result) = Length(l_Check)); for l_IDX := Low(Result) to High(Result) do Assert(Result[l_IDX] = l_Check[l_IDX]); //#UC END# *57625B5002DD_56C428E4014A_impl* end;//TcaUserManager.GetUserGroups procedure TcaUserManager.GetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); //#UC START# *576289510024_56C428E4014A_var* var l_Check: Tl3StringDataList; //#UC END# *576289510024_56C428E4014A_var* begin //#UC START# *576289510024_56C428E4014A_impl* l_Check := Tl3StringDataList.Create; try l_Check.DataSize := aList.DataSize; l_Check.Assign(aList); f_HTManager.GetUserGroupsList(aUser, aList); f_PGManager.GetUserGroupsList(aUser, l_Check); Assert(l3IsIdenticalLists(aList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *576289510024_56C428E4014A_impl* end;//TcaUserManager.GetUserGroupsList procedure TcaUserManager.GetUserGroupsList(aUser: TdaUserID; aList: Tl3LongintList); //#UC START# *57628A9403C6_56C428E4014A_var* var l_Check: Tl3LongintList; //#UC END# *57628A9403C6_56C428E4014A_var* begin //#UC START# *57628A9403C6_56C428E4014A_impl* l_Check := Tl3LongintList.Make; try l_Check.Assign(aList); f_HTManager.GetUserGroupsList(aUser, aList); f_PGManager.GetUserGroupsList(aUser, l_Check); Assert(l3IsIdenticalLists(aList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *57628A9403C6_56C428E4014A_impl* end;//TcaUserManager.GetUserGroupsList procedure TcaUserManager.SetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); //#UC START# *5767ABE002DC_56C428E4014A_var* //#UC END# *5767ABE002DC_56C428E4014A_var* begin //#UC START# *5767ABE002DC_56C428E4014A_impl* f_HTManager.SetUserGroupsList(aUser, aList); f_PGManager.SetUserGroupsList(aUser, aList); //#UC END# *5767ABE002DC_56C428E4014A_impl* end;//TcaUserManager.SetUserGroupsList function TcaUserManager.AddUserGroup(const aName: AnsiString): TdaUserGroupID; //#UC START# *576B95A600B9_56C428E4014A_var* //#UC END# *576B95A600B9_56C428E4014A_var* begin //#UC START# *576B95A600B9_56C428E4014A_impl* Result := f_HTManager.AddUserGroup(aName); if Result <> 0 then (f_PGManager as IdaComboAccessUserManagerHelper).AddUserGroupShadow(Result, aName); //#UC END# *576B95A600B9_56C428E4014A_impl* end;//TcaUserManager.AddUserGroup procedure TcaUserManager.EditUserGroup(aGroupID: TdaUserGroupID; const aName: AnsiString; aImportPriority: TdaPriority; aExportPriority: TdaPriority); //#UC START# *576B960500C5_56C428E4014A_var* //#UC END# *576B960500C5_56C428E4014A_var* begin //#UC START# *576B960500C5_56C428E4014A_impl* f_HTManager.EditUserGroup(aGroupID, aName, aImportPriority, aExportPriority); f_PGManager.EditUserGroup(aGroupID, aName, aImportPriority, aExportPriority); //#UC END# *576B960500C5_56C428E4014A_impl* end;//TcaUserManager.EditUserGroup procedure TcaUserManager.DelUserGroup(aGroupID: TdaUserGroupID); //#UC START# *576BAC4402D8_56C428E4014A_var* //#UC END# *576BAC4402D8_56C428E4014A_var* begin //#UC START# *576BAC4402D8_56C428E4014A_impl* f_HTManager.DelUserGroup(aGroupID); f_PGManager.DelUserGroup(aGroupID); //#UC END# *576BAC4402D8_56C428E4014A_impl* end;//TcaUserManager.DelUserGroup procedure TcaUserManager.RemoveUserFromAllGroups(aUser: TdaUserID); //#UC START# *577F6AD90170_56C428E4014A_var* //#UC END# *577F6AD90170_56C428E4014A_var* begin //#UC START# *577F6AD90170_56C428E4014A_impl* f_HTManager.RemoveUserFromAllGroups(aUser); f_PGManager.RemoveUserFromAllGroups(aUser); //#UC END# *577F6AD90170_56C428E4014A_impl* end;//TcaUserManager.RemoveUserFromAllGroups procedure TcaUserManager.SetUserGroup(aUser: TdaUserID; aGroup: TdaUserGroupID; Add: Boolean = True); //#UC START# *577F80C503AF_56C428E4014A_var* //#UC END# *577F80C503AF_56C428E4014A_var* begin //#UC START# *577F80C503AF_56C428E4014A_impl* f_HTManager.SetUserGroup(aUser, aGroup, Add); f_PGManager.SetUserGroup(aUser, aGroup, Add); //#UC END# *577F80C503AF_56C428E4014A_impl* end;//TcaUserManager.SetUserGroup procedure TcaUserManager.AdminChangePassWord(aUser: TdaUserID; const NewPass: AnsiString); //#UC START# *5783537E00A1_56C428E4014A_var* //#UC END# *5783537E00A1_56C428E4014A_var* begin //#UC START# *5783537E00A1_56C428E4014A_impl* f_HTManager.AdminChangePassWord(aUser, NewPass); f_PGManager.AdminChangePassWord(aUser, NewPass); //#UC END# *5783537E00A1_56C428E4014A_impl* end;//TcaUserManager.AdminChangePassWord procedure TcaUserManager.GetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList; NeedSort: Boolean = False); //#UC START# *578392E7026A_56C428E4014A_var* var l_Check: Tl3StringDataList; //#UC END# *578392E7026A_56C428E4014A_var* begin //#UC START# *578392E7026A_56C428E4014A_impl* l_Check := Tl3StringDataList.Create; try l_Check.DataSize := aList.DataSize; l_Check.Assign(aList); f_HTManager.GetHostUserListOnGroup(aGroupID, aList, NeedSort); f_PGManager.GetHostUserListOnGroup(aGroupID, l_Check, NeedSort); Assert(l3IsIdenticalLists(aList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *578392E7026A_56C428E4014A_impl* end;//TcaUserManager.GetHostUserListOnGroup procedure TcaUserManager.SetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList); //#UC START# *5783933A010B_56C428E4014A_var* //#UC END# *5783933A010B_56C428E4014A_var* begin //#UC START# *5783933A010B_56C428E4014A_impl* f_HTManager.SetHostUserListOnGroup(aGroupID, aList); f_PGManager.SetHostUserListOnGroup(aGroupID, aList); //#UC END# *5783933A010B_56C428E4014A_impl* end;//TcaUserManager.SetHostUserListOnGroup function TcaUserManager.AddUser(const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; //#UC START# *5784BBF10299_56C428E4014A_var* //#UC END# *5784BBF10299_56C428E4014A_var* begin //#UC START# *5784BBF10299_56C428E4014A_impl* Result := f_HTManager.AddUser(aUserName, aLoginName, aPassword, ActFlag); Assert(Result = f_PGManager.AddUserID(Result, aUserName, aLoginName, aPassword, ActFlag)); //#UC END# *5784BBF10299_56C428E4014A_impl* end;//TcaUserManager.AddUser function TcaUserManager.AddUserID(anID: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; //#UC START# *5784BC420208_56C428E4014A_var* //#UC END# *5784BC420208_56C428E4014A_var* begin //#UC START# *5784BC420208_56C428E4014A_impl* Result := f_HTManager.AddUserID(anID, aUserName, aLoginName, aPassword, ActFlag); Assert((anID = 0) or (anID = Result)); Assert(Result = f_PGManager.AddUserID(Result, aUserName, aLoginName, aPassword, ActFlag)); //#UC END# *5784BC420208_56C428E4014A_impl* end;//TcaUserManager.AddUserID procedure TcaUserManager.EditUser(aUser: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; ActFlag: Byte; const EditMask: TdaUserEditMask); //#UC START# *5784BD1501E8_56C428E4014A_var* //#UC END# *5784BD1501E8_56C428E4014A_var* begin //#UC START# *5784BD1501E8_56C428E4014A_impl* f_HTManager.EditUser(aUser, aUserName, aLoginName, ActFlag, EditMask); f_PGManager.EditUser(aUser, aUserName, aLoginName, ActFlag, EditMask); //#UC END# *5784BD1501E8_56C428E4014A_impl* end;//TcaUserManager.EditUser procedure TcaUserManager.DelUser(aUser: TdaUserID); //#UC START# *5784BE1E02F7_56C428E4014A_var* //#UC END# *5784BE1E02F7_56C428E4014A_var* begin //#UC START# *5784BE1E02F7_56C428E4014A_impl* f_HTManager.DelUser(aUser); f_PGManager.DelUser(aUser); //#UC END# *5784BE1E02F7_56C428E4014A_impl* end;//TcaUserManager.DelUser procedure TcaUserManager.GetUserListOnGroup(aUsGroup: TdaUserGroupID; aList: Tl3StringDataList; GetActiveUsersOnly: Boolean = False); //#UC START# *57A87EF901F3_56C428E4014A_var* var l_Check: Tl3StringDataList; //#UC END# *57A87EF901F3_56C428E4014A_var* begin //#UC START# *57A87EF901F3_56C428E4014A_impl* l_Check := Tl3StringDataList.Create; try l_Check.DataSize := aList.DataSize; l_Check.Assign(aList); f_HTManager.GetUserListOnGroup(aUsGroup, aList, GetActiveUsersOnly); f_PGManager.GetUserListOnGroup(aUsGroup, l_Check, GetActiveUsersOnly); Assert(l3IsIdenticalLists(aList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *57A87EF901F3_56C428E4014A_impl* end;//TcaUserManager.GetUserListOnGroup procedure TcaUserManager.GetFiltredUserList(aList: TStrings; aOnlyActive: Boolean = False); //#UC START# *57A9DF2103CE_56C428E4014A_var* var l_Check: TStringList; //#UC END# *57A9DF2103CE_56C428E4014A_var* begin //#UC START# *57A9DF2103CE_56C428E4014A_impl* l_Check := TStringList.Create; try l_Check.Assign(aList); f_HTManager.GetFiltredUserList(aList, aOnlyActive); f_PGManager.GetFiltredUserList(l_Check, aOnlyActive); Assert(l3IsIdenticalLists(aList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *57A9DF2103CE_56C428E4014A_impl* end;//TcaUserManager.GetFiltredUserList procedure TcaUserManager.GetDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); //#UC START# *57AC28890131_56C428E4014A_var* var l_Check: Tl3StringDataList; //#UC END# *57AC28890131_56C428E4014A_var* begin //#UC START# *57AC28890131_56C428E4014A_impl* l_Check := Tl3StringDataList.Create; try l_Check.DataSize := aDocDataList.DataSize; l_Check.Assign(aDocDataList); f_HTManager.GetDocGroupData(aUserGroup, aFamily, aDocDataList); f_PGManager.GetDocGroupData(aUserGroup, aFamily, l_Check); Assert(l3IsIdenticalLists(aDocDataList, l_Check)); finally FreeAndNil(l_Check); end; //#UC END# *57AC28890131_56C428E4014A_impl* end;//TcaUserManager.GetDocGroupData procedure TcaUserManager.PutDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); //#UC START# *57AC289F0257_56C428E4014A_var* //#UC END# *57AC289F0257_56C428E4014A_var* begin //#UC START# *57AC289F0257_56C428E4014A_impl* f_HTManager.PutDocGroupData(aUserGroup, aFamily, aDocDataList); f_PGManager.PutDocGroupData(aUserGroup, aFamily, aDocDataList); //#UC END# *57AC289F0257_56C428E4014A_impl* end;//TcaUserManager.PutDocGroupData procedure TcaUserManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56C428E4014A_var* //#UC END# *479731C50290_56C428E4014A_var* begin //#UC START# *479731C50290_56C428E4014A_impl* f_HTManager := nil; f_PGManager := nil; f_PriorityCalculator := nil; inherited; //#UC END# *479731C50290_56C428E4014A_impl* end;//TcaUserManager.Cleanup {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC 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. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.LomontFFT; // FFT implementation by Chris Lomont (http://www.lomont.org/Software/). {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Def, CP.FFT; type { TFFTLomont } TFFTLomont = class(TFFTLib) private FInput: TDoubleArray; ForwardCos: TDoubleArray; ForwardSin: TDoubleArray; procedure ComputeTable(size: integer); procedure FFT(var Data: TDoubleArray); procedure RealFFT(var Data: TDoubleArray); public constructor Create(frame_size: integer; window: TDoubleArray); destructor Destroy; override; procedure ComputeFrame(input: TSmallintArray; var frame: TFFTFrame); override; end; implementation uses CP.Utils; { TFFTLomont } // Call this with the size before using the FFT // Fills in tables for speed procedure TFFTLomont.ComputeTable(size: integer); var i, n, mmax, istep, m: integer; theta, wr, wpr, wpi, wi, t: double; begin SetLength(ForwardCos, size); SetLength(ForwardSin, size); // forward pass i := 0; n := size; mmax := 1; while (n > mmax) do begin istep := 2 * mmax; theta := Math_Pi / mmax; wr := 1; wi := 0; wpr := Cos(theta); wpi := Sin(theta); m := 0; while m < istep do begin ForwardCos[i] := wr; ForwardSin[i] := wi; Inc(i); t := wr; wr := wr * wpr - wi * wpi; wi := wi * wpr + t * wpi; m := m + 2; end; mmax := istep; end; end; constructor TFFTLomont.Create(frame_size: integer; window: TDoubleArray); begin FFrameSize := frame_size; FFrameSizeH := frame_size div 2; FWindow := window; SetLength(FInput, frame_size); ComputeTable(frame_size); end; destructor TFFTLomont.Destroy; begin SetLength(FInput, 0); SetLength(FWindow, 0); SetLength(ForwardCos, 0); SetLength(ForwardSin, 0); inherited Destroy; end; // Compute the forward or inverse FFT of data, which is // complex valued items, stored in alternating real and // imaginary real numbers. The length must be a power of 2. procedure TFFTLomont.FFT(var Data: TDoubleArray); var n, j, top, k, h: integer; t: double; mmax, tptr, istep, m: integer; theta, wr, wi, tempr, tempi: double; begin n := Length(Data); // check all are valid // checks n is a power of 2 in 2's complement format if ((n and (n - 1)) <> 0) then begin // throw new Exception("data length " + n + " in FFT is not a power of 2"); Exit; end; n := n div 2; // bit reverse the indices. This is exercise 5 in section 7.2.1.1 of Knuth's TAOCP // the idea is a binary counter in k and one with bits reversed in j // see also Alan H. Karp, "Bit Reversals on Uniprocessors", SIAM Review, vol. 38, #1, 1--26, March (1996) // nn = number of samples, 2* this is length of data? j := 0; k := 0; // Knuth R1: initialize top := n div 2; // this is Knuth's 2^(n-1) while (True) do begin // Knuth R2: swap // swap j+1 and k+2^(n-1) - both have two entries t := Data[j + 2]; Data[j + 2] := Data[k + n]; Data[k + n] := t; t := Data[j + 3]; Data[j + 3] := Data[k + n + 1]; Data[k + n + 1] := t; if (j > k) then begin // swap two more // j and k t := Data[j]; Data[j] := Data[k]; Data[k] := t; t := Data[j + 1]; Data[j + 1] := Data[k + 1]; Data[k + 1] := t; // j + top + 1 and k+top + 1 t := Data[j + n + 2]; Data[j + n + 2] := Data[k + n + 2]; Data[k + n + 2] := t; t := Data[j + n + 3]; Data[j + n + 3] := Data[k + n + 3]; Data[k + n + 3] := t; end; // Knuth R3: advance k k := k + 4; if (k >= n) then break; // Knuth R4: advance j h := top; while (j >= h) do begin j := j - h; h := h div 2; end; j := j + h; end; // bit reverse loop // do transform by doing single point transforms, then doubles, fours, etc. mmax := 1; tptr := 0; while (n > mmax) do begin istep := 2 * mmax; theta := Math_Pi / mmax; m := 0; while m < istep do // for m := 0 to istep-1 do m += 2) begin wr := ForwardCos[tptr]; wi := ForwardSin[tptr]; Inc(tptr); k := m; // for (k = m; k < 2 * n; k += 2 * istep) while (k < 2 * n) do begin j := k + istep; tempr := wr * Data[j] - wi * Data[j + 1]; tempi := wi * Data[j] + wr * Data[j + 1]; Data[j] := Data[k] - tempr; Data[j + 1] := Data[k + 1] - tempi; Data[k] := Data[k] + tempr; Data[k + 1] := Data[k + 1] + tempi; k := k + 2 * istep; end; Inc(m, 2); end; mmax := istep; end; end; // Computes the real FFT. procedure TFFTLomont.RealFFT(var Data: TDoubleArray); var n, j, k: integer; temp, theta, wpr, wpi, wjr, wji: double; tnr, tni, tjr, tji: double; a, b, c, d, e, f: double; begin FFT(Data); // do packed FFT n := Length(Data); // number of real input points, which is 1/2 the complex length theta := 2 * Math_Pi / n; wpr := Cos(theta); wpi := Sin(theta); wjr := wpr; wji := wpi; for j := 1 to (n div 4) do begin k := n div 2 - j; tnr := Data[2 * k]; tni := Data[2 * k + 1]; tjr := Data[2 * j]; tji := Data[2 * j + 1]; e := (tjr + tnr); f := (tji - tni); a := (tjr - tnr) * wji; d := (tji + tni) * wji; b := (tji + tni) * wjr; c := (tjr - tnr) * wjr; // compute entry y[j] Data[2 * j] := 0.5 * (e + (a + b)); Data[2 * j + 1] := 0.5 * (f - (c - d)); // compute entry y[k] Data[2 * k] := 0.5 * (e - (a + b)); Data[2 * k + 1] := 0.5 * ((-c + d) - f); temp := wjr; wjr := wjr * wpr - wji * wpi; wji := temp * wpi + wji * wpr; end; // compute final y0 and y_{N/2} ones, place into data[0] and data[1] temp := Data[0]; Data[0] := Data[0] + Data[1]; Data[1] := temp - Data[1]; end; procedure TFFTLomont.ComputeFrame(input: TSmallintArray; var frame: TFFTFrame); var i: integer; begin for i := 0 to FFrameSize - 1 do begin FInput[i] := input[i] * FWindow[i] * 1.0; end; RealFFT(FInput); // FInput will now contain the FFT values // r0, r(n/2), r1, i1, r2, i2 ... // Compute energy frame.Data[0] := FInput[0] * FInput[0]; frame.Data[FFrameSizeH] := FInput[1] * FInput[1]; for i := 1 to FFrameSizeH - 1 do begin frame.Data[i] := FInput[2 * i] * FInput[2 * i] + FInput[2 * i + 1] * FInput[2 * i + 1]; end; end; end.
$TITLE TIMUTL.PAS, last modified 2/28/84, zw MODULE timutl; $HEADER TIMUTL.HDR TIMUTL.HDR, lst modified 2/28/84, zw Day times are represented in three formats: 1) packed format, "dt_pak": number of days since day zero (17-Nov-1858) number of seconds since midnight 2) record format, "dt_rcd": year, month, day, hour, minute, second 3) string format, "dt_str": DD-Mmm-YY HH:MM:SS Use the packed format for storing, the record format for manipulation and the string format for input/output. Note that the packed format is an undiscriminated union which is mapped to an integer for ease of manipulation. TYM-Pascal time functions are: DATE() returns current date string: DD-Mmm-YY TIME() returns number of milliseconds since midnight RUNTIME() returns cpu milliseconds value The "daytim" function returns the current date/time in record format. Conversion functions are: unpack day time to record: "pakdt" pack day time from record: "unpakdt" make up date string from record: "daystr" make up time string from record: "timstr" make up day time string from record: "dtstr" parse date string to record: "parday" parse time string to record: "partim" parse day time string to record: "pardt" convert date string to record: "strday" convert time string to record; "strtim" convert day time string to record; "strdt" Note: Check "timerr" boolean after any parse or convert! Manipulation functions are: increment year: "incyy" increment month: "addmm" increment day: "addday" increment hour: "addhr" increment minute: "addmin" increment second: "addsec" $INCLUDE TIMUTL.TYP $PAGE TIMUTL.TYP, last modified 2/28/84, zw $IFNOT timutltyp (*day zero is Nov 17, 1858*) TYPE time_pak = RECORD CASE BOOLEAN OF TRUE: (number: INTEGER); FALSE: (date: (1900 - 1858) * 365 .. (2000 - 1858) * 365; time: 0 .. (60 * 60 * 24)) END; time_rcd = RECORD year: 1900 .. 2000; month: 1 .. 12; day: 1 .. 31; hour: 0 .. 23; minute: 0 .. 59; second: 0 .. 59 END; time_str = PACKED ARRAY [1 .. 17]; (*DD-Mmm-YY HH:MM:SS*) months = (january, february, march, april, may, june, july, august, september, october, november, december); days = (sunday, monday, tuesday, wednesday, thursday, friday, saturday); CONST month_str: ARRAY [months] OF STRING[9] = ('JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'); day_str: ARRAY [DAYS] OF STRING[9] = ('SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'); $ENABLE timutltyp $ENDIF $SYSTEM TIMMAC.INC FUNCTION intstr(i: INTEGER ): STRING[11]; BEGIN PUTSTRING(intstr, ABS(i):0); END; FUNCTION digits2(n: -99 .. 99 ): PACKED ARRAY [1 .. 2] OF CHAR; BEGIN PUTSTRING(digits2, ABS(n):2); IF IOSTATUS <> IO_OK THEN digits2 := '**' ELSE IF digits2[1] = ' ' THEN digits2[1] := '0'; END; PUBLIC FUNCTION timsecs(t: time_int ): seconds OPTIONS SPECIAL(WORD); CONST secs_per_day: seconds = 86400; VAR temp: MACHINE_WORD; BEGIN temp := t.t * secs_per_day; temp := temp + #o400000; temp := temp DIV (2**18); timsecs := temp; END; PUBLIC FUNCTION timrcd(t: time_int): time_rcd; VAR time_secs, time_left: seconds; BEGIN WITH timrcd DO BEGIN time_secs := timsecs(t); hours := time_secs DIV 3600; time_left := time_secs MOD 3600; mins := time_left DIV 60; secs := time_left MOD 60 END END; PUBLIC FUNCTION datdays(d: date_int): days; BEGIN datdays := d.d END; PUBLIC FUNCTION datrcd(d: date_int): date_rcd; CONST days_before: ARRAY [1 .. 13] OF -1..367 = (-1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 367); VAR days_left: 0 .. MAXIMUM(INTEGER); quad_centurys: 0 .. 10; centurys: 0 .. 3; quarter_days: 0 .. MAXIMUM(INTEGER); time_temp: 0 .. MAXIMUM(INTEGER); temp_yr: 0 .. 100; mo_found: BOOLEAN; yr: min_year .. max_year; mo: 1 .. 12; da: 1 .. 31; leap_year: BOOLEAN; BEGIN days_left := datdays(d); (*convert day zero from 11/17/1858 to 1/1/1501*) days_left := days_left + ((1857 - 1500) * 365) + ((1857 - 1500) DIV 4) - ((1857 - 1500) DIV 100) + ((1857 -1500) DIV 400) + 31 +28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 17; (*find the number of quadrcenturies since then*) quad_centurys := days_left DIV ((400 * 365) + (400 DIV 4) - (400 DIV 100) + (400 DIV 400)); days_left := days_left MOD ((400 * 365) + (400 DIV 4) - (400 DIV 100) + (400 DIV 400)); (*find quarter days left*) quarter_days := days_left * 4; (*divide that by the average number of quarter days per century*) centurys := quarter_days DIV (((100 * 365) + (100 DIV 4) - (100 DIV 100)) * 4 + (400 DIV 400)); quarter_days := quarter_days MOD (((100 * 365) + (100 DIV 4) - (100 DIV 100)) * 4 + (400 DIV 400)); (*discard any fractions of a day and add in 3/4 of a day to force a leap day into the forth year of each 4 year cycle*) quarter_days := (quarter_days DIV 4) * 4 + 3; temp_yr := quarter_days DIV (365 * 4 + 1); quarter_days := quarter_days MOD (365 * 4 + 1); yr := temp_yr + 1501 + (quad_centurys * 400) + (centurys * 100); days_left := quarter_days DIV 4; (*fake a febuary 29th if its not a leap year and past feb*) leap_year := (yr MOD 4) = 0) AND (((yr MOD 100) <> 0) OR ((yr MOD 400) = 0); IF (NOT leap_year) AND (days_left > (30 + 28)) THEN days_left := days_left + 1; (*which month is it*) mo := 1; mo_found := FALSE; WHILE NOT mo_found DO BEGIN IF days_left <= days_before[mo + 1] THEN mo_found := TRUE ELSE mo := mo + 1 END; da := days_left - days_before[mo]; (*all done, load date record*) datrcd.year := yr; datrcd.month := mo; datrcd.day := da END; PUBLIC FUNCTION dtrcd(dt: day_time_int): day_time_rcd; VAR time_bin: time_rcd; date_bin: date_rcd; BEGIN time_bin := timrcd(dttim(dt)); date_bin := datrcd(dtdat(dt)); WITH dtrcd DO BEGIN year := date_bin.year; month := date_bin.month; day := date_bin.day; hours := time_bin.hours; mins := time_bin.mins; secs := time_bin.secs END END; PUBLIC FUNCTION timext(t: day_time_int): day_time_ext; BEGIN WITH dtrcd(t) DO timext := digits2(day)||'-'||month_name(month)||'-'||SUBSTR(intstr(YEAR),3,2) ||' '||digits2(HOURS)||':'||digits2(MINS)||':'||digits2(SECS); END; PUBLIC PROCEDURE EC_EXT(VAR ERR_CODE: day_time_ERR; DT_EXT: NS_EXT; VAR day_time: day_time_INT); TYPE MONTH_RANGE = 1..12; CURSOR_RANGE = 1..160; POS_INT = 0..MAXIMUM(INTEGER); CONST CENTURY := 1900; (* CENTURY USED FOR 2 DIGIT YEARS *) VAR day_time_BIN: day_timeREC; (*WE FIRST CONVERT TO BINARY *) CURSOR: CURSOR_RANGE; (* CURSOR FOR SCANNING EXTERNAL STRING *) EOS: BOOLEAN; (* END OF STRING FLAG *) CH: CHAR; CASE_IDX: 0..MAXIMUM(INTEGER); (* INDEX FOR MAINLINE CASE *) LA_IDX: CURSOR_RANGE; (* LOOK AHEAD STRING SCAN CURSOR *) TIME_SCANNED: BOOLEAN; (* TRUE IF EXTERNAL TIME SCANNED ALREADY *) $PAGE (* * SCAN_BLANKS - MOVES CURSOR PAST ANY BLANKS; 'EOS' IS * SET TO TRUE IF THE END OF THE STRING IS REACHED BEFORE * A NON-BLANK IS ENCOUNTERED. *) PROCEDURE SCAN_BLANKS(VAR CURSOR: CURSOR_RANGE; VAR EOS: BOOLEAN); BEGIN LOOP EOS := CURSOR > LENGTH(DT_EXT); EXIT IF EOS; EXIT IF DT_EXT[CURSOR] <> ' '; CURSOR := CURSOR + 1 END END; $PAGE (* * SCAN_MONTH - CURSOR SHOULD BE POINTING AT FIRST CHARACTER * OF MONTH. RETURNS INDEX OF MONTH IF ASSUMPTION * HOLDS, OTHERWISE ERROR CODE IS RETURNED. *) PROCEDURE SCAN_MONTH(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE; VAR MONTH_IDX: MONTH_RANGE); TYPE MONTH_TEXT = PACKED ARRAY [1..3] OF CHAR; MTH_NAME_TAB = ARRAY [MONTH_RANGE] OF MONTH_TEXT; CONST MONTH_NAME: MTH_NAME_TAB = ( 'JAN' , 'FEB' , 'MAR' , 'APR' , 'MAY' , 'JUN' , 'JUL' , 'AUG' , 'SEP' , 'OCT' , 'NOV' , 'DEC'); VAR THIS_MONTH: MONTH_TEXT; I: 1..13; BEGIN ERR_CODE := DT_NOERR; IF CURSOR + 2 > LENGTH(DT_EXT) THEN ERR_CODE := DT_ERR ELSE BEGIN THIS_MONTH := UPPERCASE(SUBSTR(DT_EXT,CURSOR,3)); CURSOR := CURSOR + 3; I := 1; WHILE (I <= 12) ANDIF (THIS_MONTH <> MONTH_NAME[I]) DO I := I + 1; IF I = 13 THEN ERR_CODE := DT_ERR ELSE MONTH_IDX := I END END; $PAGE (* * SCAN_INTEGER - CURSOR SHOULD BE POINTING AT FIRST DIGIT * OF AN INTEGER. CONVERTS INTEGER TO BINARY AND RETURNS ITS * VALUE IF ASSUMPTION HOLDS, OTHERWISE ERROR CODE IS RETURNED. *) PROCEDURE SCAN_INTEGER(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE; VAR INT_VAL: POS_INT); TYPE DIGIT_TAB = PACKED ARRAY ['0'..'9'] OF 0..9; SET_OF_CHAR = SET OF CHAR; CONST DIGIT_VAL: DIGIT_TAB := (0,1,2,3,4,5,6,7,8,9); DIGITS_SET: SET_OF_CHAR := ['0'..'9']; BEGIN ERR_CODE := DT_NOERR; INT_VAL := 0; IF (CURSOR > LENGTH(DT_EXT)) ORIF NOT (DT_EXT[CURSOR] IN DIGITS_SET) THEN ERR_CODE := DT_ERR ELSE LOOP EXIT IF CURSOR > LENGTH(DT_EXT); CH := DT_EXT[CURSOR]; EXIT IF NOT (CH IN DIGITS_SET); CURSOR := CURSOR + 1; INT_VAINT_VAL * 10 + DIGIT_VAL[CH] END END; $PAGE (* * SCAN_DATE - PARSES DATE STRING WITH FORMAT: 'DD-MM-YY'. * SETS FIELDS 'YEAR', 'MONTH' AND 'DAY' OF RECORD * 'day_time_BIN'. *) PROCEDURE SCAN_DATE(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE); BEGIN SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.DAY); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP FIRST '-' *) SCAN_MONTH(ERR_CODE,CURSOR,day_time_BIN.MONTH); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP SECOND '-' *) SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.YEAR ); IF ERR_CODE = DT_NOERR THEN day_time_BIN.YEAR := day_time_BIN.YEAR + CENTURY END END END; $PAGE (* * SCAN_NS_D1 - PARSES DATE STRING WITH FORMAT: 'MM/DD/YY'. * SETS FIELDS 'YEAR', 'MONTH' AND 'DAY' OF RECORD 'day_time_BIN'. *) PROCEDURE SCAN_NS_D1(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE); VAR YR: 1858..MAX_YEAR; BEGIN SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.MONTH); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP FIRST '/' *) SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.DAY); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP SECOND '/' *) SCAN_INTEGER(ERR_CODE, CURSOR, YR ); IF ERR_CODE = DT_NOERR THEN day_time_BIN.YEAR := YR + CENTURY END END END; $PAGE (* * SCAN_NS_D2 - PARSES A DATE STRING WITH FORMAT 'MMM DD,YYYY'. * SETS FIELDS 'YEAR', 'MONTH' AND 'DAY' OF RECORD 'day_time_BIN'. *) PROCEDURE SCAN_NS_D2(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE); BEGIN SCAN_MONTH(ERR_CODE, CURSOR, day_time_BIN.MONTH); IF ERR_CODE = DT_NOERR THEN BEGIN SCAN_BLANKS(CURSOR,EOS); SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.DAY); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP ',' *) SCAN_BLANKS(CURSOR,EOS); SCAN_INTEGER(ERR_CODE,CURSOR,day_time_BIN.YEAR) END END END; $PAGE (* * SCAN_TIME - PARSES TIME STRING WITH FORMAT: 'HH:MM:SS [A/P]M', * WHERE FINAL 'AM' OR 'PM' IS OPTIONAL. SETS FIELDS 'HOURS', * 'MINS' AND 'SECS' OF RECORD day_time_BIN. *) PROCEDURE SCAN_TIME(VAR ERR_CODE: day_time_ERR; VAR CURSOR: CURSOR_RANGE); VAR HRS: 0..59; am: packed array [1..2] of char; BEGIN TIME_SCANNED := TRUE; SCAN_INTEGER(ERR_CODE, CURSOR, HRS); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP FIRST ':' *) SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.MINS); IF ERR_CODE = DT_NOERR THEN BEGIN CURSOR := CURSOR + 1; (* SKIP SECOND ':' *) SCAN_INTEGER(ERR_CODE, CURSOR, day_time_BIN.SECS); IF ERR_CODE = DT_NOERR THEN BEGIN SCAN_BLANKS(CURSOR, EOS); IF CURSOR + 1 <= LENGTH(DT_EXT) THEN am := uppercase ( substr ( dt_ext, cursor, 2 ) ); if ( am = 'PM' ) and ( hrs < 12 ) then hrs := hrs + 12 else if ( am = 'AM' ) and (hrs = 12) then hrs := hrs - 12; day_time_BIN.HOURS := HRS END END END END; (* * EC_EXT MAIN ROUTINE. *) BEGIN day_time := BASE_day_time_INTERNAL; ERR_CODE := DT_NOERR; CURSOR := 1; TIME_SCANNED := FALSE; WITH day_time_BIN DO BEGIN YEAR := 1858; MONTH := 11; DAY := 17; HOURS := 0; MINS := 0; SECS := 0 END; SCAN_BLANKS(CURSOR,EOS); (* SCAN PAST ANY INITIAL BLANKS *) IF NOT EOS THEN BEGIN CASE_IDX := 0; LA_IDX := CURSOR; LOOP EXIT IF LENGTH(DT_EXT) <= LA_IDX DO EOS := TRUE; CH := DT_EXT[LA_IDX]; IF CH = '-' THEN CASE_IDX := 1 ELSE IF CH = '/' THEN CASE_IDX := 2 ELSE IF CH = ' ' THEN CASE_IDX := 3 ELSE IF CH = ':' THEN CASE_IDX := 4 ELSE LA_IDX := LA_IDX + 1; EXIT IF CASE_IDX <> 0 END; CASE CASE_IDX OF 0: ERR_CODE := DT_ERR; 1: SCAN_DATE(ERR_CODE, CURSOR); 2: SCAN_NS_D1(ERR_CODE, CURSOR); 3: SCAN_NS_D2(ERR_CODE, CURSOR); 4: SCAN_TIME(ERR_CODE, CURSOR) END; IF NOT TIME_SCANNED THEN BEGIN SCAN_BLANKS(CURSOR, EOS); IF NOT EOS THEN SCAN_TIME(ERR_CODE, CURSOR) END; (* CONVERT BINARY TO INTERNAL FORMAT *) IF ERR_CODE = DT_NOERR THEN EC_day_time(ERR_CODE, day_time_BIN, day_time) END END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC FUNCTION NS_T1(TIME: TIME_INT): NS_TIME1; VAR H: 0..23; AM: PACKED ARRAY [1..2] OF CHAR; BEGIN WITH timrcd(TIME) DO BEGIN H := HOURS; if hours < 12 then begin am := 'AM'; if H = 0 then H := 12; end else begin am := 'PM'; if H > 12 then H := H - 12; end; NS_T1 := digits2(H) || ':' || digits2(MINS) || ':' || digits2(SECS) || ' ' || AM END END; $SYSTEM Iday_time.TYP $SYSTEM Iday_time.TYP VAR DATE_INT); VAR TIME_INT); PUBLIC PROCEDURE EC_day_time(VAR ERR_CODE: day_time_ERR; day_timeBIN: day_timeREC; VAR day_time: day_time_INT); VAR DATE_BIN: DATEREC; TIME_BIN: TIMEREC; DATE: DATE_INT; TIME: TIME_INT; BEGIN WITH day_timeBIN DO BEGIN DATE_BIN.YEAR := YEAR; DATE_BIN.MONTH := MONTH; DATE_BIN.DAY := DAY; EC_DATE(ERR_CODE, DATE_BIN, DATE); IF ERR_CODE = DT_NOERR THEN BEGIN TIME_BIN.HOURS := HOURS; TIME_BIN.MINS := MINS; TIME_BIN.SECS := SECS; EC_TIME(ERR_CODE,TIME_BIN, TIME); IF ERR_CODE = DT_NOERR THEN day_time := DT_COMBINE(DATE,TIME) END END (* WITH *) END; $SYSTEM Iday_time.TYP TIMEREC; VAR TIME_INT); PUBLIC FUNCTION EC_DCTIME(D_TIME: DEC_TIME): TIME_INT; VAR SECS_SINCE: DEC_TIME; (* SECONDS SINCE MIDNIGHT *) SECS_LEFT: DEC_TIME; TIME_BIN: TIMEREC; ERR_CODE: day_time_ERR; TIME: TIME_INT; BEGIN WITH TIME_BIN DO BEGIN SECS_SINCE := D_TIME DIV 1000; HOURS := SECS_SINCE DIV 3600; SECS_LEFT := SECS_SINCE MOD 3600; MINS := SECS_LEFT DIV 60; SECS := SECS_LEFT MOD 60; END; EC_TIME(ERR_CODE, TIME_BIN, TIME ); IF ERR_CODE = DT_NOERR THEN EC_DCTIME := TIME ELSE EC_DCTIME := ( 0, 0 ) END; $SYSTEM Iday_time.TYP DATEREC; VAR DATE_INT); PUBLIC FUNCTION EC_DCDATE(D_DATE: DEC_DATE): DATE_INT; VAR DATE_BIN: DATEREC; DAYS_LEFT: DEC_DATE; ERR_CODE: day_time_ERR; DATE: DATE_INT; BEGIN WITH DATE_BIN DO BEGIN YEAR := D_DATE DIV (12 * 31) + 1964; DAYS_LEFT := D_DATE MOD (12 * 31); MONTH := DAYS_LEFT DIV 31 + 1; DAY := DAYS_LEFT MOD 31 + 1; END; EC_DATE(ERR_CODE, DATE_BIN, DATE); IF ERR_CODE = DT_NOERR THEN EC_DCDATE := DATE ELSE EC_DCDATE := ( 0, 0 ) END; (* EC_TSDATE - converts a standard TYMSHARE date to an internal date. The standard TYMSHARE date is the *exact* number of days since January 1, 1964. *) $SYSTEM iday_time.typ public function ec_tsdate ( ts_date: tym_date ): date_int; begin ec_tsdate.d := ts_date + 112773b; END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC PROCEDURE EC_TIME(VAR ERR_CODE: day_time_ERR; TIME_BIN: TIMEREC; VAR TIME: TIME_INT); CONST SECS_PER_DAY = 86400; VAR TIME_SECS: INTEGER; BEGIN WITH TIME_BIN DO BEGIN IF (HOURS < 0) ORIF (HOURS > 23) ORIF (MINS < 0) ORIF (MINS > 59) ORIF (SECS < 0) ORIF (SECS > 59) THEN ERR_CODE := DT_ERR ELSE BEGIN ERR_CODE := DT_NOERR; TIME_SECS := HOURS * 3600 + MINS * 60 + SECS; TIME := EC_SECS ( TIME_SECS ); END END (* WITH *) END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC FUNCTION NS_D1(DATE: DATE_INT): NS_DATE1; BEGIN WITH datrcd(DATE) DO NS_D1 := digits2(MONTH) || '/' || digits2(DAY) || '/' || SUBSTR(intstr(YEAR),3,2); END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC FUNCTION NS_D2(DATE: DATE_INT): NS_DATE2; BEGIN WITH datrcd(DATE) DO PUTSTRING (NS_D2, month_name(MONTH), ' ', DAY:0, ', ', YEAR:4); END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC PROCEDURE EC_DATE(VAR ERR_CODE: day_time_ERR; DATE_BIN: DATEREC; VAR DATE: DATE_INT); TYPE MONTH_TAB = ARRAY [1..12] OF 0..365; CONST DAYS_IN_MONTH: MONTH_TAB = (31, 29 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); DAYS_BEFORE: MONTH_TAB = (0 , 31, 59, 90, 120, 151,181, 212, 243, 273, 304, 334 ); VAR DAYS_SINCE: 0..MAXIMUM(INTEGER); QUAD_CENT, CENTS, QUAD_YEARS: 0..MAXIMUM(INTEGER); LEAP_YEAR: BOOLEAN; BEGIN WITH DATE_BIN DO BEGIN (* ERROR CHECK DATE PASSED IN *) IF (YEAR < 1858) ORIF (MONTH < 1) ORIF (MONTH > 12) ORIF (DAY < 1) ORIF (DAY > DAYS_IN_MONTH[MONTH]) THEN ERR_CODE := DT_ERR ELSE BEGIN ERR_CODE := DT_NOERR; IF YEAR <> 1858 THEN BEGIN DAYS_SINCE := 44; (*DAYS FROM YEAR 1858 *) DAYS_SINCE := DAYS_SINCE + (YEAR-1859) * 365; (* ADD IN 1 FOR EACH LEAP YEAR. A LEAP YEAR IS ASSUMED TO BE ANY YEAR DIVISIBLE BY 4 BUT NOT DIVISIBLE BY 100, UNLESS DIVISIBLE BY 400 ALSO. THUS 1900 WAS NOT A LEAP YEAR, THE YEAR 2000 WILL BE *) QUAD_CENT := (YEAR-1) DIV 400 - (1858 DIV 400); CENTS := (YEAR-1) DIV 100 - (1858 DIV 100); QUAD_YEARS := (YEAR-1) DIV 4 - (1858 DIV 4); DAYS_SINCE := DAYS_SINCE + QUAD_CENT - CENTS + QUAD_YEARS; (* ADD IN DAYS FOR THE COMPLETED MONTHS OF THIS YEAR *) DAYS_SINCE := DAYS_SINCE + DAYS_BEFORE[MONTH]; IF MONTH > 2 THEN BEGIN LEAP_YEAR := ((YEAR MOD 4) = 0) AND (((YEAR MOD 100) <> 0) OR ((YEAR MOD 400) = 0)); IF LEAP_YEAR THEN DAYS_SINCE := DAYS_SINCE + 1; END; (* NOW ADD IN THE DAYS OF THIS MONTH *) DAYS_SINCE := DAYS_SINCE + DAY; END ELSE (* SPECIAL CASE - DATE IN 1858 *) BEGIN IF MONTH = 12 THEN DAYS_SINCE := DAY + 13 ELSE IF MONTH = 11 THEN DAYS_SINCE := DAY - 17 ELSE ERR_CODE := DT_ERR END; IF ERR_CODE <> DT_ERR THEN DATE := EC_DAYS ( DAYS_SINCE ); END (* FIRST IF STATEMENT *) END (* WITH *) END; $SYSTEM Iday_time.TYP $SYSTEM day_timeI.INC PUBLIC FUNCTION DAY_OF_WEEK(DATE: DATE_INT): WEEK_DAY; VAR NORM_DATE: 0..777777B; DAY_INDEX,I: 0..6; BEGIN NORM_DATE := datdays< ( DATE ); DAY_INDEX := (NORM_DATE + 3) MOD 7; (* DAY ZERO WAS A WED *) DAY_OF_WEEK := SUNDAY; FOR I := 1 TO DAY_INDEX DO DAY_OF_WEEK := SUCC(DAY_OF_WEEK) END; $SYSTEM iday_time.typ $SYSTEM iday_time.typ public function ec_days ( days_since_base: days ): date_int; begin ec_days.d := days_since_base; ec_days.t := 0; END; $SYSTEM iday_time.typ $SYSTEM iday_time.typ public function ec_secs ( secs: seconds ): time_int options special (word); const secs_per_day: seconds = 86400; var temp: machine_word; begin ec_secs.d := 0; temp := secs * (2**18); temp := temp + secs_per_day div 2; (* so following DIV will round *) ec_secs.t := temp div secs_per_day; END. aj<Ú
{ Copyright (c) 2017-18 Pascal Riekenberg VirtualTreeView-Helper-Class See the file COPYING.modifiedLGPL.txt, included in this distribution, for details about the license. 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. **********************************************************************} unit vtvObject; {$mode objfpc}{$H+} interface uses Classes, Generics.Collections, SysUtils, Laz.VirtualTrees; type { TvtvObj } TvtvObj = class; TvtvObjList = specialize TObjectList<TvtvObj>; TvtvObj = class private function GetCheckState: TCheckState; inline; procedure SetNode(pValue: PVirtualNode); protected fLine: Integer; fVst: TBaseVirtualTree; fNode: PVirtualNode; fParent, fRoot: TvtvObj; fChilds: TvtvObjList; procedure SetCheckState(pCheckState: TCheckState); virtual; public constructor Create; destructor Destroy; override; procedure Add(pChild: TvtvObj); function CellText(Column: TColumnIndex; TextType: TVSTTextType): String; virtual; abstract; function InitialStates: TVirtualNodeInitStates; virtual; function InitChildren: Cardinal; virtual; function ImageIndex(pColumn: TColumnIndex): Integer; virtual; procedure InitNode(pVST: TBaseVirtualTree; pNode: PVirtualNode); virtual; procedure UpdateExpanded; virtual; property Node: PVirtualNode read fNode write SetNode; property Childs: TvtvObjList read fChilds; property Parent: TvtvObj read fParent; property Root: TvtvObj read fRoot; property CheckState: TCheckState read GetCheckState write SetCheckState; property Line: Integer read fLine write fLine; end; PvtvObj = ^TvtvObj; implementation { TvtvObj } function TvtvObj.GetCheckState: TCheckState; begin Result := fNode^.CheckState; end; procedure TvtvObj.SetCheckState(pCheckState: TCheckState); var i: Integer; begin fNode^.CheckState := pCheckState; for i := 0 to fChilds.Count - 1 do fChilds[i].CheckState := pCheckState; end; procedure TvtvObj.SetNode(pValue: PVirtualNode); begin if fNode = pValue then Exit; fNode := pValue; end; constructor TvtvObj.Create; begin fChilds := TvtvObjList.Create(True); fParent := nil; fRoot := nil; fNode := nil; end; destructor TvtvObj.Destroy; begin FreeAndNil(fChilds); inherited Destroy; end; procedure TvtvObj.Add(pChild: TvtvObj); begin pChild.fParent := Self; fChilds.Add(pChild); pChild.fRoot := Self; while Assigned(pChild.fRoot.fParent) do pChild.fRoot := pChild.fRoot.fParent; end; function TvtvObj.InitialStates: TVirtualNodeInitStates; begin Result := []; if fChilds.Count > 0 then Result := Result + [ivsHasChildren]; end; function TvtvObj.InitChildren: Cardinal; begin Result := fChilds.Count; end; function TvtvObj.ImageIndex(pColumn: TColumnIndex): Integer; begin Result := -1; end; procedure TvtvObj.InitNode(pVST: TBaseVirtualTree; pNode: PVirtualNode); begin fVst := pVST; fNode := pNode; end; procedure TvtvObj.UpdateExpanded; begin // do nothing end; end.
unit uModel; interface type TUsuario = class private class var FInstance : TUsuario; constructor CreatePrivate(); public constructor Create(); class function GetInstance:TUsuario; end; TConexao = class strict private class var FInstance: TConexao; constructor Create; public class function GetInstance: TConexao; end; implementation uses System.SysUtils; { TUsuario } constructor TUsuario.Create(); begin raise Exception.Create('Para obter uma instância de TUsuario utilize a função TUsuario.GetInstance.'); end; constructor TUsuario.CreatePrivate; begin end; class function TUsuario.GetInstance: TUsuario; begin if not(Assigned(FInstance)) then FInstance := TUsuario.CreatePrivate; Result := FInstance; end; constructor TConexao.Create; begin inherited; end; class function TConexao.GetInstance: TConexao; begin If FInstance = nil Then begin FInstance := TConexao.Create(); end; Result := FInstance; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSocketUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, Windows, SysUtils, {$ELSE} System.Classes, Winapi.Windows, System.SysUtils, {$ENDIF} clUtils; type EclSocketError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; function GetWSAErrorText(AErrorCode: Integer): string; procedure RaiseSocketError(AErrorCode: Integer); overload; procedure RaiseSocketError(const AErrorMessage: string; AErrorCode: Integer); overload; resourcestring TimeoutOccurred = 'Timeout error occured'; InvalidAddress = 'Invalid host address'; InvalidPort = 'Invalid port number'; InvalidBatchSize = 'Invalid Batch Size'; InvalidNetworkStream = 'NetworkStream is required'; ConnectionClosed = 'The connection to the server is not active'; InvalidAddressFamily = 'Invalid address family'; const TimeoutOccurredCode = -1; InvalidAddressCode = -2; InvalidPortCode = -3; InvalidBatchSizeCode = -4; InvalidNetworkStreamCode = -5; ConnectionClosedCode = -6; InvalidAddressFamilyCode = -7; implementation function GetWSAErrorText(AErrorCode: Integer): string; var Buffer: array[0..255] of Char; begin FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, AErrorCode, 0, Buffer, SizeOf(Buffer), nil); Result := Trim(Buffer); end; procedure RaiseSocketError(AErrorCode: Integer); begin raise EclSocketError.Create(GetWSAErrorText(AErrorCode), AErrorCode); end; procedure RaiseSocketError(const AErrorMessage: string; AErrorCode: Integer); begin raise EclSocketError.Create(AErrorMessage, AErrorCode); end; { EclSocketError } constructor EclSocketError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; end.
unit ssExcel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ssWaitForExcel{, VCLUtils}; type TOnProcessEvent = function(Sender: TObject; ProcessID : integer; FWait : TfrmWaitForExcel) : boolean of object; TVertAlignment = (vaTopJustify, vaCenter, vaBottomJustify); type TssExcel = class(TComponent) private { Private declarations } FExcelApp, FWorkBook, FWorkSheet, FCells : Variant; // FCache : TDispInvokeCache; FOnProcess : TOnProcessEvent; FDefFont : TFont; FHorAlign : TAlignment; FVertAlign : TVertAlignment; FAlreadyOpened, //был открыт до нас? FAlreadyVisible, FBeforeFirstSave, FConnected, FShowProgress, FVisible : boolean; FFileName, FInternalVersion, FVersion : string; FRows: Variant; function GetWorkBook : Variant; function GetWorkSheet : Variant; procedure SetConnected(Value : boolean); procedure SetVisible(Value : boolean); procedure SetVersion(Value : string); procedure ClearOleObjects; protected { Protected declarations } function DoConnect : boolean; dynamic; function DoDisconnect : boolean; dynamic; public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; property ExcelApp : Variant read FExcelApp write FExcelApp; property WorkBook : Variant read FWorkBook write FWorkBook; property WorkSheet : Variant read FWorkSheet write FWorkSheet; property Cells : Variant read FCells write FCells; property Rows : Variant read FRows write FRows; property InternalVersion : string read FInternalVersion; procedure OpenWorkBook(FileName : string); procedure CreateWorkBook; procedure SaveWorkBook; //сохран€ет под именем, указанным в FileName procedure SaveWorkBookAs(AFileName : string); procedure CloseWorkBook(WithSave : boolean); { Left €чейка в Top строке } { записывает Value в €чейку с координатами Left, Top с настройками по умолчанию } procedure Put(Left, Top : integer; Value : variant); procedure PutLeft(Left, Top : integer; Value : variant); procedure PutRight(Left, Top : integer; Value : variant); procedure PutCenter(Left, Top : integer; Value : variant); procedure PutW(Left, Top : integer; Value : variant); procedure PutLeftW(Left, Top : integer; Value : variant); procedure PutRightW(Left, Top : integer; Value : variant); procedure PutCenterW(Left, Top : integer; Value : variant); { аналогично Put, только с разворотом на 90 градусов } procedure Put90(Left, Top : integer; Value : variant); { записывает Value в €чейку с координатами Left, Top с указанными параметрами шрифта } procedure PutFont(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontLeft(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontRight(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontCenter(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontLeftW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontRightW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); procedure PutFontCenterW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); { Put с установкой ширины } procedure PutWidth(Left, Top, Width : integer; Value : variant); { Put с установкой ширины и WordWrap } procedure PutWidthW(Left, Top, Width : integer; Value : variant); { сетка/рамка в указанном диапазоне} procedure Frame(Left, Top, Right, Bottom : integer); procedure FrameGrid(Left, Top, Right, Bottom : integer); {включение/выключение переноса слов дл€ указанной €чейки } procedure WordWrap(Left, Top : integer; Value : boolean); procedure RowHeight(Row : integer; Value : integer); procedure ColWidth(Left, Top : integer; Value : integer); //выравнивание в €чейке procedure CellHorAlign(Left, Top : integer; Align : TAlignment); procedure CellVertAlign(Left, Top : integer; Align : TVertAlignment); procedure Preview; function RunProcess(ProcessID : integer) : boolean; published { Published declarations } property Connected : boolean read FConnected write SetConnected; property Visible : boolean read FVisible write SetVisible; property ShowProgress : boolean read FShowProgress write FShowProgress; property Version : string read FVersion write SetVersion; property FileName : string read FFileName write FFileName; property Font : TFont read FDefFont write FDefFont; property HorAlign : TAlignment read FHorAlign write FHorAlign default taLeftJustify; property VertAlign : TVertAlignment read FVertAlign write FVertAlign default vaCenter; property OnProcess : TOnProcessEvent read FOnProcess write FOnProcess; end; implementation uses ComObj, ssExcelConst, Variants; resourcestring rsUnableToStart = 'Unable to start Excel.'; rsExcelNotStarted = 'Excel not started.'; rsWaitForExportInfo = 'Export into Excel in progress...'; rsUnknown = '<unknown>'; constructor TssExcel.Create(AOwner : TComponent); begin inherited Create(AOwner); FExcelApp:=UnAssigned; FWorkBook:=UnAssigned; FWorkSheet:=UnAssigned; FVersion:=rsUnknown; FBeforeFirstSave:=true; FDefFont:=TFont.Create; FHorAlign:=taLeftJustify; FVertAlign:=vaCenter; end; destructor TssExcel.Destroy; begin if not VarIsEmpty(ExcelApp) then try if not VarIsEmpty(WorkBook) then CloseWorkBook(false); if not FAlreadyOpened then ExcelApp.Quit; except end; FDefFont.Free; inherited Destroy; end; function TssExcel.GetWorkBook : Variant; begin if VarIsEmpty(FWorkBook) then begin ExcelApp.WorkBooks.Add; FWorkBook:=ExcelApp.ActiveWorkBook; FBeforeFirstSave:=true; FileName:=WorkBook.Name; end; Result:=FWorkBook; end; procedure TssExcel.SetVersion(Value : string); begin end; function TssExcel.GetWorkSheet : Variant; begin if VarIsEmpty(FWorkSheet) then begin FWorkBook:=GetWorkBook; FWorkSheet:=WorkBook.ActiveSheet; FCells := FWorkSheet.Cells; FRows := FWorkSheet.Rows; end; Result:=FWorkSheet; end; function TssExcel.DoConnect : boolean; begin ExcelApp:=Unassigned; Result:=false; FAlreadyOpened:=false; FAlreadyVisible:=false; try ExcelApp:=GetActiveOleObject(OleClassName); Result:=True; FAlreadyOpened:=true; //был открыт до нас? FAlreadyVisible:=ExcelApp.Visible; except end; if not Result then try ExcelApp:=CreateOLEObject(OleClassName); Result:=True; except MessageDlg(rsUnableToStart, mtError, [mbOK], 0); raise; end; if Result then begin // FCache:=TDispInvokeCache.Create; // FCache.Reset(ExcelApp); if not FAlreadyOpened then ExcelApp.Visible:=Visible; FVersion:=ExcelApp.Version; FInternalVersion:=copy(FVersion, 1, 1); ExcelVersion:=StrToIntDef(FInternalVersion, 8); end; end; function TssExcel.DoDisconnect : boolean; begin try // FCache.Free; CloseWorkBook(false); if not FAlreadyOpened then ExcelApp.Quit else ExcelApp.Visible:=FAlreadyVisible; ExcelApp:=UnAssigned; Result:=true; except raise end; end; procedure TssExcel.SetConnected(Value : boolean); begin if FConnected=Value then exit; if Value then FConnected:=DoConnect else FConnected:=not DoDisconnect; end; procedure TssExcel.SetVisible(Value : boolean); begin if not VarIsEmpty(ExcelApp) then try ExcelApp.Visible:=Value; except end; FVisible:=Value; end; function TssExcel.RunProcess(ProcessID : integer) : boolean; var FWait : TfrmWaitForExcel; DWPtr : pointer; { I1, I2 : string;} begin FWait :=nil; DWPtr :=nil; if ShowProgress then FWait:=TfrmWaitForExcel.Create(Application); try if ShowProgress then begin FWait.Show; FWait.UpDate; DWPtr:=DisableTaskWindows(FWait.Handle); FWait.Info:=rsWaitForExportInfo; FWait.AddInfo:=EmptyStr; end; if Assigned(OnProcess) then if ShowProgress then Result:=OnProcess(Self, ProcessID, FWait) else Result:=OnProcess(Self, ProcessID, Nil) else Result:=false; finally if ShowProgress then begin EnableTaskWindows(DWPtr); FWait.Hide; FWait.Free; end; end; end; procedure TssExcel.CreateWorkBook; begin if not Connected then Connected:=true; GetWorkSheet; end; procedure TssExcel.SaveWorkBookAs(AFileName : string); begin try FileName:=AFileName; WorkBook.SaveAs(FileName); FBeforeFirstSave:=false; except // MessageDlg('Error saving end; end; procedure TssExcel.SaveWorkBook; begin try if FBeforeFirstSave then begin SaveWorkBookAs(FileName); FBeforeFirstSave:=false; end else WorkBook.Save; except raise end; end; procedure TssExcel.ClearOleObjects; begin WorkSheet:=UnAssigned; WorkBook:=UnAssigned; Cells:=UnAssigned; Rows:=UnAssigned; end; procedure TssExcel.CloseWorkBook(WithSave : boolean); begin if not Connected then exit; if VarIsEmpty(WorkBook) then exit; if WithSave then try WorkBook.Save(FileName); except end; try WorkBook.Close; except end; ClearOleObjects; end; procedure TssExcel.OpenWorkBook(FileName : string); begin if not Connected then Connected:=true; FWorkBook := ExcelApp.WorkBooks.Open(FileName, False); // FWorkBook:=ExcelApp.ActiveWorkBook; FWorkSheet:=ExcelApp.ActiveSheet; FCells:=FWorkSheet.Cells; FRows:=FWorkSheet.Rows; end; procedure TssExcel.Put(Left, Top : integer; Value : variant); begin // FWorkSheet.Cells[Top, Left].NumberFormat:='General'; // FWorkSheet.Cells[Top, Left].NumberFormat:='@'; FWorkSheet.Cells[Top, Left].Value:=Value; SetCellsFont(WorkSheet, ExcelRectToStr(Left, Top, Left, Top), Font.Name, Font.Size, Font.Color, Font.Style); CellHorAlign(Left, Top, HorAlign); CellVertAlign(Left, Top, VertAlign); end; procedure TssExcel.PutWidth(Left, Top, Width : integer; Value : variant); begin Put(Left, Top, Value); ColWidth(Left, Top, Width); end; procedure TssExcel.PutWidthW(Left, Top, Width : integer; Value : variant); begin Put(Left, Top, Value); ColWidth(Left, Top, Width); WordWrap(Left, Top, true); end; procedure TssExcel.Put90(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); WorkSheet.Cells[Top, Left].Orientation:=90; end; procedure TssExcel.WordWrap(Left, Top : integer; Value : boolean); begin WorkSheet.Cells[Top, Left].WrapText:=Value; end; procedure TssExcel.PutFont(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin // FWorkSheet.Cells[Top, Left].NumberFormat:='@'; FWorkSheet.Cells[Top, Left].Value:=Value; SetCellsFont(WorkSheet, ExcelRectToStr(Left, Top, Left, Top), FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, HorAlign); CellVertAlign(Left, Top, VertAlign); end; procedure TssExcel.RowHeight(Row : integer; Value : integer); begin WorkSheet.Rows[Row].RowHeight:=Value; end; procedure TssExcel.ColWidth(Left, Top : integer; Value : integer); begin WorkSheet.Cells[Top, Left].ColumnWidth:=Value; end; procedure TssExcel.Frame(Left, Top, Right, Bottom : integer); var Rect : string; begin Rect:=ExcelRectToStr(Left, Top, Right, Bottom); SetCellsBorder(WorkSheet, Rect, xlContinuous, xlThin); end; procedure TssExcel.FrameGrid(Left, Top, Right, Bottom : integer); var Rect : string; begin Rect:=ExcelRectToStr(Left, Top, Right, Bottom); // SetSolidCellsBorder(WorkSheet, Rect, xlContinuous, xlThin); end; procedure TssExcel.Preview; begin try if not Visible then ExcelApp.Visible:=true; WorkBook.PrintPreview; finally if not Visible then ExcelApp.Visible:=false; end; end; procedure TssExcel.CellHorAlign(Left, Top : integer; Align : TAlignment); begin case Align of taLeftJustify : WorkSheet.Cells[Top, Left].HorizontalAlignment:=xlLeft; taRightJustify : WorkSheet.Cells[Top, Left].HorizontalAlignment:=xlRight; taCenter : WorkSheet.Cells[Top, Left].HorizontalAlignment:=xlCenter; end; end; procedure TssExcel.CellVertAlign(Left, Top : integer; Align : TVertAlignment); begin case Align of vaTopJustify : WorkSheet.Cells[Top, Left].VerticalAlignment:=xlVAlignTop; vaBottomJustify : WorkSheet.Cells[Top, Left].VerticalAlignment:=xlVAlignBottom; vaCenter : WorkSheet.Cells[Top, Left].VerticalAlignment:=xlVAlignCenter; end; end; procedure TssExcel.PutLeft(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taLeftJustify); end; procedure TssExcel.PutRight(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taRightJustify); end; procedure TssExcel.PutCenter(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taCenter); end; procedure TssExcel.PutLeftW(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taLeftJustify); WordWrap(Left, Top, true); end; procedure TssExcel.PutRightW(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taRightJustify); WordWrap(Left, Top, true); end; procedure TssExcel.PutCenterW(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); CellHorAlign(Left, Top, taCenter); WordWrap(Left, Top, true); end; procedure TssExcel.PutFontLeft(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFont(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taLeftJustify); end; procedure TssExcel.PutFontRight(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFont(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taRightJustify); end; procedure TssExcel.PutFontCenter(Left, Top : integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFont(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taCenter); end; procedure TssExcel.PutFontLeftW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFont(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taLeftJustify); WordWrap(Left, Top, true); end; procedure TssExcel.PutFontRightW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFontW(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taRightJustify); WordWrap(Left, Top, true); end; procedure TssExcel.PutFontCenterW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFontW(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); CellHorAlign(Left, Top, taCenter); WordWrap(Left, Top, true); end; procedure TssExcel.PutW(Left, Top : integer; Value : variant); begin Put(Left, Top, Value); WordWrap(Left, Top, true); end; procedure TssExcel.PutFontW(Left, Top: integer; Value : variant; FontName : string; FontSize : integer; FontColor : TColor; FontStyle : TFontStyles); begin PutFont(Left, Top, Value, FontName, FontSize, FontColor, FontStyle); WordWrap(Left, Top, true); end; end.
{ Helper functions for easy implementation of TLS communication by means of Windows SChannel. The functions are transport-agnostic so they could be applied to any socket implementation or even other transport. Inspired by [TLS-Sample](http://www.coastrd.com/c-schannel-smtp) Uses [JEDI API units](https://jedi-apilib.sourceforge.net) (c) Fr0sT-Brutal License MIT } unit SChannel.Utils; interface {$IFDEF MSWINDOWS} uses Windows, SysUtils, SChannel.JwaBaseTypes, SChannel.JwaWinError, SChannel.JwaWinCrypt, SChannel.JwaSspi, SChannel.JwaSChannel; const LogPrefix = '[SChannel]: '; // Just a suggested prefix for log output IO_BUFFER_SIZE = $10000; // Size of handshake buffer // Set of used protocols. // Note: TLS 1.0 is not used by default, add `SP_PROT_TLS1_0` if needed USED_PROTOCOLS: DWORD = SP_PROT_TLS1_1 or SP_PROT_TLS1_2; // Set of used algorithms. // `0` means default. Add `CALG_DH_EPHEM`, `CALG_RSA_KEYX`, etc if needed USED_ALGS: ALG_ID = 0; // Default flags used in `InitializeSecurityContextW` call. User can define // alternative value in session data. SSPI_FLAGS = ISC_REQ_SEQUENCE_DETECT or // Detect messages received out of sequence ISC_REQ_REPLAY_DETECT or // Detect replayed messages that have been encoded by using the EncryptMessage or MakeSignature functions ISC_REQ_CONFIDENTIALITY or // Encrypt messages by using the EncryptMessage function ISC_RET_EXTENDED_ERROR or // When errors occur, the remote party will be notified ISC_REQ_ALLOCATE_MEMORY or // The security package allocates output buffers for you. When you have finished using the output buffers, free them by calling the FreeContextBuffer function ISC_REQ_STREAM; // Support a stream-oriented connection type // Stage of handshake THandShakeStage = ( // Initial stage hssNotStarted, // Sending client hello hssSendCliHello, // Reading server hello - general hssReadSrvHello, // Reading server hello - repeat call without reading hssReadSrvHelloNoRead, // Reading server hello - in process, send token hssReadSrvHelloContNeed, // Reading server hello - success, send token hssReadSrvHelloOK, // Final stage hssDone ); // State of secure channel TChannelState = ( // Initial stage chsNotStarted, // Handshaking with server chsHandshake, // Channel established successfully chsEstablished, // Sending shutdown signal and closing connection chsShutdown ); // United state and data for TLS handshake THandShakeData = record // Current stage Stage: THandShakeStage; // Handle of security context. // OUT after hssSendCliHello, IN at hssReadSrvHello* hContext: CtxtHandle; // Buffer with data from server. // IN at hssReadSrvHello* IoBuffer: TBytes; // Size of data in buffer. cbIoBuffer: DWORD; // Array of SChannel-allocated buffers that must be disposed with `g_pSSPI.FreeContextBuffer`. // OUT after hssSendCliHello, hssReadSrvHelloContNeed, hssReadSrvHelloOK OutBuffers: array of SecBuffer; end; // Credentials related to a connection TSessionCreds = record // Handle of credentials, mainly for internal use hCreds: CredHandle; // SChannel credentials, mainly for internal use but could be init-ed by user // to tune specific channel properties. SchannelCred: SCHANNEL_CRED; end; PSessionCreds = ^TSessionCreds; // Interface with session creds for sharing between multiple sessions ISharedSessionCreds = interface // Return pointer to `TSessionCreds` record function GetSessionCredsPtr: PSessionCreds; end; // Session options TSessionFlag = ( // If set, SChannel won't automatically verify server certificate by setting // `ISC_REQ_MANUAL_CRED_VALIDATION` flag in `InitializeSecurityContextW` call. // User has to call manual verification via `CheckServerCert` after handshake // is established (this allows connecting to an IP, domains with custom certs, // expired certs, valid certs if system CRL is expired etc). sfNoServerVerify ); TSessionFlags = set of TSessionFlag; // Logging method that is used by functions to report non-critical errors and // handshake details. TDebugFn = procedure (const Msg: string) of object; // Class with stub debug logging function that reports messages via `OutputDebugString` TDefaultDebugFnHoster = class class procedure Debug(const Msg: string); end; // App-local storage of trusted certs. MT-safe. TTrustedCerts = class strict private FPropCS: TRTLCriticalSection; FCerts: array of record Host: string; Data: TBytes; end; public constructor Create; destructor Destroy; override; procedure Add(const Host: string; const Data: TBytes); function Contains(const Host: string): Boolean; overload; function Contains(const Host: string; pData: Pointer; DataLen: Integer): Boolean; overload; function Contains(const Host: string; const Data: TBytes): Boolean; overload; procedure Clear; end; // Flags to ignore some cert aspects when checking manually via `CheckServerCert`. // Mirror of `SECURITY_FLAG_IGNORE_*` constants TCertCheckIgnoreFlag = ( ignRevokation, // don't check cert revokation (useful if CRL is unavailable) ignUnknownCA, // don't check CA ignWrongUsage, ignCertCNInvalid, // don't check cert name (useful when connecting by IP) ignCertDateInvalid // don't check expiration date ); TCertCheckIgnoreFlags = set of TCertCheckIgnoreFlag; // Data related to a session. Mainly meaningful during handshake and making no // effect when a connection is established. TSessionData = record // Server name that a session is linked to. Must be non-empty. ServerName: string; // Options Flags: TSessionFlags; // User-defined SSPI-specific flags to use in `InitializeSecurityContextW` call. // Default value `SSPI_FLAGS` is used if this value is `0`. \ // **Warning**: `ISC_REQ_ALLOCATE_MEMORY` flag is supposed to be always enabled, // otherwise correct work is not guaranteed SSPIFlags: DWORD; // Pointer to credentials shared between multiple sessions SharedCreds: ISharedSessionCreds; // Non-shared session credentials. It is used if `SharedCreds` is @nil SessionCreds: TSessionCreds; // Pointer to list of trusted certs. The object could be shared or personal to // a client but it has to be created and disposed manually. // If not empty, auto validation of certs is disabled (`sfNoServerVerify` is // included in `Flags` property) at first call to `DoClientHandshake`. TrustedCerts: TTrustedCerts; // Set of cert aspects to ignore when checking manually via `CheckServerCert`. // If not empty, auto validation of certs is disabled (`sfNoServerVerify` is // included in `Flags` property) at first call to `DoClientHandshake`. CertCheckIgnoreFlags: TCertCheckIgnoreFlags; end; PSessionData = ^TSessionData; // Abstract base class for shared TLS options storage TBaseTLSOptions = class // Return pointer to session data record that corresponds to given server name. // @param ServerName - server name // @returns pointer to session data or @nil if there's no entry for the name. function GetSessionDataPtr(const ServerName: string): PSessionData; virtual; abstract; end; // Trivial data storage TBuffer = record Data: TBytes; // Buffer for data DataStartIdx: Integer; // Index in buffer the unprocessed data starts from DataLen: Cardinal; // Length of unprocessed data end; // Specific exception class. Could be created on WinAPI error, SChannel error // or general internal error. // * WinAPI errors are used when a SChannel function returns result code via `GetLastError`. // Non-zero `WinAPIErr` field is set then. // * SChannel errors are used when a SChannel function returns status code of type `SECURITY_STATUS` // OR it succeedes but something went wrong. // Non-zero `SecStatus` field is set then. // * General errors are used in other cases, like incorrect arguments. ESSPIError = class(Exception) public // If not zero, reason of exception is WinAPI and this field contains code of // an error returned by GetLastError WinAPIErr: DWORD; // If not zero, reason of exception is SChannel and this field contains // security status returned by last function call SecStatus: SECURITY_STATUS; // Create WinAPI exception based on Err code constructor CreateWinAPI(const Action, Func: string; Err: DWORD); // Create SChannel exception based on status and, optionally, on custom info message constructor CreateSecStatus(const Action, Func: string; Status: SECURITY_STATUS; const Info: string = ''); overload; end; // Result of `CheckServerCert` function TCertCheckResult = ( ccrValid, // Cert is valid ccrTrusted, // Cert was in trusted list, no check was performed ccrValidWithFlags // Cert is valid with some ignore flags ); var // ~~ Globals that are set/cleared by Init & Fin functions ~~ hMYCertStore: HCERTSTORE = nil; g_pSSPI: PSecurityFunctionTable; const // Set of cert validation ignore flags that has all items set - use it to // ignore everything CertCheckIgnoreAll = [Low(TCertCheckIgnoreFlag)..High(TCertCheckIgnoreFlag)]; // ~~ Init utils - usually not to be called by user ~~ // Mainly for internal use // @raises ESSPIError on error procedure LoadSecurityLibrary; // Mainly for internal use. // @param SchannelCred - [?IN/OUT] If `SchannelCred.dwVersion` = `SCHANNEL_CRED_VERSION`, \ // the parameter is considered "IN/OUT" and won't be modified before `AcquireCredentialsHandle` call.\ // Otherwise the parameter is considered "OUT" and is init-ed with default values. \ // Thus user can pass desired values to `AcquireCredentialsHandle` function. // @raises ESSPIError on error procedure CreateCredentials(const User: string; out hCreds: CredHandle; var SchannelCred: SCHANNEL_CRED); // Validate certificate. Mainly for internal use. Gets called by `CheckServerCert` // @param pServerCert - pointer to cert context // @param szServerName - host name of the server to check. Could be empty but appropriate \ // flags must be set as well, otherwise the function will raise error // @param dwCertFlags - value of `SSL_EXTRA_CERT_CHAIN_POLICY_PARA.fdwChecks` field: \ // flags defining errors to ignore. `0` to ignore nothing // @raises ESSPIError on error procedure VerifyServerCertificate(pServerCert: PCCERT_CONTEXT; const szServerName: string; dwCertFlags: DWORD); // Retrieve server certificate. Mainly for internal use. Gets called by `CheckServerCert`. // Returned result must be freed via `CertFreeCertificateContext`. // @param hContext - current session context // @returns server certificate data // @raises ESSPIError on error function GetCertContext(const hContext: CtxtHandle): PCCERT_CONTEXT; // ~~ Global init and fin ~~ // Load global stuff. Must be called before any other function called. // Could be called multiple times without checks. @br // **Thread-unsafe! Uses global variables** // @raises ESSPIError on error procedure Init; // Dispose and nullify global stuff. // Could be called multiple times without checks. @br // **Thread-unsafe! Uses global variables** procedure Fin; // ~~ Session init and fin ~~ // Init session creds, return data record to be used in calling other functions. // Could be called multiple times (nothing will be done on already init-ed record) // @param SessionCreds - [IN, OUT] record that receives values. On first call \ // must be zeroed. Alternatively, user could fill `SessionCreds.SchannelCred` \ // with desired values to tune channel properties. // @raises ESSPIError on error procedure CreateSessionCreds(var SessionCreds: TSessionCreds); // Shared creds factory function CreateSharedCreds: ISharedSessionCreds; // Finalize session creds procedure FreeSessionCreds(var SessionCreds: TSessionCreds); // Finalize session, free credentials procedure FinSession(var SessionData: TSessionData); // ~~ Start/close connection ~~ // Print debug message either with user-defined function if set or default one // (`TDefaultDebugFnHoster.Debug` method) procedure Debug(DebugLogFn: TDebugFn; const Msg: string); // Function to prepare all necessary handshake data. No transport level actions. // @raises ESSPIError on error function DoClientHandshake(var SessionData: TSessionData; var HandShakeData: THandShakeData; DebugLogFn: TDebugFn = nil): SECURITY_STATUS; // Generate data to send to a server on connection shutdown // @raises ESSPIError on error procedure GetShutdownData(const SessionData: TSessionData; const hContext: CtxtHandle; out OutBuffer: SecBuffer); // Retrieve server certificate linked to current context. More suitable for // userland application than `GetCertContext`, without any SChannel-specific stuff. // @param hContext - current session context // @returns server certificate data // @raises ESSPIError on error function GetCurrentCert(const hContext: CtxtHandle): TBytes; // Check server certificate // @param hContext - current session context // @param ServerName - host name of the server to check. If empty, errors associated // with a certificate that contains a common name that is not valid will be ignored. // (`SECURITY_FLAG_IGNORE_CERT_CN_INVALID` flag will be set calling `CertVerifyCertificateChainPolicy`) // @param TrustedCerts - list of trusted certs. If cert is in this list, it won't be checked by system // @param CertCheckIgnoreFlags - set of cert aspects to ignore when checking. // @returns Result of cert check // @raises ESSPIError on error function CheckServerCert(const hContext: CtxtHandle; const ServerName: string; const TrustedCerts: TTrustedCerts = nil; CertCheckIgnoreFlags: TCertCheckIgnoreFlags = []): TCertCheckResult; overload; // Check server certificate - variant using SessionData only // @returns Result of cert check // @raises ESSPIError on error function CheckServerCert(const hContext: CtxtHandle; const SessionData: TSessionData): TCertCheckResult; overload; // Dispose and nullify security context procedure DeleteContext(var hContext: CtxtHandle); // ~~ Data exchange ~~ // Receive size values for current session and init buffer length to contain // full message including header and trailer // @raises ESSPIError on error procedure InitBuffers(const hContext: CtxtHandle; out pbIoBuffer: TBytes; out Sizes: SecPkgContext_StreamSizes); // Encrypt data (prepare for sending to server). // @param hContext - current session context // @param Sizes - current session sizes // @param pbMessage - input data to encrypt // @param cbMessage - length of input data // @param pbIoBuffer - buffer to receive encrypted data // @param pbIoBufferLength - size of buffer // @param cbWritten - [OUT] size of encrypted data written to buffer // @raises ESSPIError on error procedure EncryptData(const hContext: CtxtHandle; const Sizes: SecPkgContext_StreamSizes; pbMessage: PByte; cbMessage: DWORD; pbIoBuffer: PByte; pbIoBufferLength: DWORD; out cbWritten: DWORD); // Decrypt data received from server. If input data is not processed completely, // unprocessed chunk is copied to beginning of buffer. Thus subsequent call to // Recv could just receive to @Buffer[DataLength] // @param hContext - current session context // @param Sizes - current session sizes // @param pbIoBuffer - input encrypted data to decrypt // @param cbEncData - [IN/OUT] length of encrypted data in buffer. \ // After function call it is set to amount of unprocessed data that \ // is placed from the beginning of the buffer // @param pbDecData - buffer to receive decrypted data // @param cbDecDataLength - size of buffer // @param cbWritten - [OUT] size of decrypted data written to buffer // @returns \ // * `SEC_I_CONTEXT_EXPIRED` - server signaled end of session \ // * `SEC_E_OK` - message processed fully \ // * `SEC_E_INCOMPLETE_MESSAGE` - need more data \ // * `SEC_I_RENEGOTIATE` - server wants to perform another handshake sequence // @raises ESSPIError on error or if Result is not one of above mentioned values function DecryptData(const hContext: CtxtHandle; const Sizes: SecPkgContext_StreamSizes; pbIoBuffer: PByte; var cbEncData: DWORD; pbDecData: PByte; cbDecDataLength: DWORD; out cbWritten: DWORD): SECURITY_STATUS; // ~~ Misc ~~ // Check if handle `x` is null (has both fields equal to zero) function SecIsNullHandle(const x: SecHandle): Boolean; // Returns string representaion of given security status (locale message + constant name + numeric value) function SecStatusErrStr(scRet: SECURITY_STATUS): string; // Returns string representaion of given verify trust error (locale message + constant name + numeric value) function WinVerifyTrustErrorStr(Status: DWORD): string; // Check if status is likely a Windows TLS v1.2 handshake bug (`SEC_E_BUFFER_TOO_SMALL` // or `SEC_E_MESSAGE_ALTERED` status is returned by `InitializeSecurityContext` on handshake). // This function only checks if parameter is one of these two values. function IsWinHandshakeBug(scRet: SECURITY_STATUS): Boolean; // Return effective pointer to session credentials - either personal or shared function GetSessionCredsPtr(const SessionData: TSessionData): PSessionCreds; // Messages that could be written to log by various implementations. None of these // are used in this unit const S_Msg_Received = 'Received %d bytes of encrypted data / %d bytes of payload'; S_Msg_SessionClosed = 'Server closed the session [SEC_I_CONTEXT_EXPIRED]'; S_Msg_Renegotiate = 'Server requested renegotiate'; S_Msg_Sending = 'Sending %d bytes of payload / %d bytes encrypted'; S_Msg_StartingTLS = 'Starting TLS handshake'; S_Msg_HShStageW1Success = 'Handshake @W1 - %d bytes sent'; S_Msg_HShStageW1Incomplete = 'Handshake @W1 - ! incomplete data sent'; S_Msg_HShStageW1Fail = 'Handshake @W1 - ! error sending data ([#%d] %s)'; S_Msg_HShStageRFail = 'Handshake @R - ! no data received or error receiving ([#%d] %s)'; S_Msg_HShStageRSuccess = 'Handshake @R - %d bytes received'; S_Msg_HandshakeBug = 'Handshake bug: "%s", retrying'; S_Msg_HShStageW2Success = 'Handshake @W2 - %d bytes sent'; S_Msg_HShStageW2Incomplete = 'Handshake @W2 - ! incomplete data sent'; S_Msg_HShStageW2Fail = 'Handshake @W2 - ! error sending data ([#%d] %s)'; S_Msg_HShExtraData = 'Handshake: got "%d" bytes of extra data'; S_Msg_Established = 'Handshake established'; S_Msg_SrvCredsAuth = 'Server credentials authenticated'; S_Msg_CredsInited = 'Credentials initialized'; S_Msg_AddrIsIP = 'Address "%s" is IP, verification by name is disabled'; S_Msg_ShuttingDownTLS = 'Shutting down TLS'; S_Msg_SendingShutdown = 'Sending shutdown notify - %d bytes of data'; S_Err_ListeningNotSupported = 'Listening is not supported with SChannel yet'; S_Msg_CertIsTrusted = 'Certificate is in trusted list'; S_Msg_CertIsValidWithFlags = 'Certificate is valid using some ignore flags'; {$ENDIF MSWINDOWS} implementation {$IFDEF MSWINDOWS} type // Interfaced object with session data for sharing credentials TSharedSessionCreds = class(TInterfacedObject, ISharedSessionCreds) strict private FSessionCreds: TSessionCreds; public destructor Destroy; override; function GetSessionCredsPtr: PSessionCreds; end; const // %0s - current action, like 'sending data' or 'at Init' // %1s - WinAPI method, like 'Send' // %2d - error code // %3s - error message for error code S_E_WinAPIErrPatt = 'Error %s calling WinAPI method "%s": [%d] %s'; // %0s - current action, like 'at CreateCredentials' // %1s - SChannel method, like 'AcquireCredentialsHandle' // %2s - error message S_E_SecStatusErrPatt = 'Error %s calling method "%s": %s'; // ~~ Utils ~~ function SecIsNullHandle(const x: SecHandle): Boolean; begin Result := (x.dwLower = 0) and (x.dwUpper = 0); end; function SecStatusErrStr(scRet: SECURITY_STATUS): string; begin // Get name of error constant case scRet of SEC_E_INSUFFICIENT_MEMORY : Result := 'SEC_E_INSUFFICIENT_MEMORY'; SEC_E_INVALID_HANDLE : Result := 'SEC_E_INVALID_HANDLE'; SEC_E_UNSUPPORTED_FUNCTION : Result := 'SEC_E_UNSUPPORTED_FUNCTION'; SEC_E_TARGET_UNKNOWN : Result := 'SEC_E_TARGET_UNKNOWN'; SEC_E_INTERNAL_ERROR : Result := 'SEC_E_INTERNAL_ERROR'; SEC_E_SECPKG_NOT_FOUND : Result := 'SEC_E_SECPKG_NOT_FOUND'; SEC_E_NOT_OWNER : Result := 'SEC_E_NOT_OWNER'; SEC_E_CANNOT_INSTALL : Result := 'SEC_E_CANNOT_INSTALL'; SEC_E_INVALID_TOKEN : Result := 'SEC_E_INVALID_TOKEN'; SEC_E_CANNOT_PACK : Result := 'SEC_E_CANNOT_PACK'; SEC_E_QOP_NOT_SUPPORTED : Result := 'SEC_E_QOP_NOT_SUPPORTED'; SEC_E_NO_IMPERSONATION : Result := 'SEC_E_NO_IMPERSONATION'; SEC_E_LOGON_DENIED : Result := 'SEC_E_LOGON_DENIED'; SEC_E_UNKNOWN_CREDENTIALS : Result := 'SEC_E_UNKNOWN_CREDENTIALS'; SEC_E_NO_CREDENTIALS : Result := 'SEC_E_NO_CREDENTIALS'; SEC_E_MESSAGE_ALTERED : Result := 'SEC_E_MESSAGE_ALTERED'; SEC_E_OUT_OF_SEQUENCE : Result := 'SEC_E_OUT_OF_SEQUENCE'; SEC_E_NO_AUTHENTICATING_AUTHORITY : Result := 'SEC_E_NO_AUTHENTICATING_AUTHORITY'; SEC_I_CONTINUE_NEEDED : Result := 'SEC_I_CONTINUE_NEEDED'; SEC_I_COMPLETE_NEEDED : Result := 'SEC_I_COMPLETE_NEEDED'; SEC_I_COMPLETE_AND_CONTINUE : Result := 'SEC_I_COMPLETE_AND_CONTINUE'; SEC_I_LOCAL_LOGON : Result := 'SEC_I_LOCAL_LOGON'; SEC_E_BAD_PKGID : Result := 'SEC_E_BAD_PKGID'; SEC_E_CONTEXT_EXPIRED : Result := 'SEC_E_CONTEXT_EXPIRED'; SEC_I_CONTEXT_EXPIRED : Result := 'SEC_I_CONTEXT_EXPIRED'; SEC_E_INCOMPLETE_MESSAGE : Result := 'SEC_E_INCOMPLETE_MESSAGE'; SEC_E_INCOMPLETE_CREDENTIALS : Result := 'SEC_E_INCOMPLETE_CREDENTIALS'; SEC_E_BUFFER_TOO_SMALL : Result := 'SEC_E_BUFFER_TOO_SMALL'; SEC_I_INCOMPLETE_CREDENTIALS : Result := 'SEC_I_INCOMPLETE_CREDENTIALS'; SEC_I_RENEGOTIATE : Result := 'SEC_I_RENEGOTIATE'; SEC_E_WRONG_PRINCIPAL : Result := 'SEC_E_WRONG_PRINCIPAL'; SEC_I_NO_LSA_CONTEXT : Result := 'SEC_I_NO_LSA_CONTEXT'; SEC_E_TIME_SKEW : Result := 'SEC_E_TIME_SKEW'; SEC_E_UNTRUSTED_ROOT : Result := 'SEC_E_UNTRUSTED_ROOT'; SEC_E_ILLEGAL_MESSAGE : Result := 'SEC_E_ILLEGAL_MESSAGE'; SEC_E_CERT_UNKNOWN : Result := 'SEC_E_CERT_UNKNOWN'; SEC_E_CERT_EXPIRED : Result := 'SEC_E_CERT_EXPIRED'; SEC_E_ENCRYPT_FAILURE : Result := 'SEC_E_ENCRYPT_FAILURE'; SEC_E_DECRYPT_FAILURE : Result := 'SEC_E_DECRYPT_FAILURE'; SEC_E_ALGORITHM_MISMATCH : Result := 'SEC_E_ALGORITHM_MISMATCH'; SEC_E_SECURITY_QOS_FAILED : Result := 'SEC_E_SECURITY_QOS_FAILED'; SEC_E_UNFINISHED_CONTEXT_DELETED : Result := 'SEC_E_UNFINISHED_CONTEXT_DELETED'; SEC_E_NO_TGT_REPLY : Result := 'SEC_E_NO_TGT_REPLY'; SEC_E_NO_IP_ADDRESSES : Result := 'SEC_E_NO_IP_ADDRESSES'; SEC_E_WRONG_CREDENTIAL_HANDLE : Result := 'SEC_E_WRONG_CREDENTIAL_HANDLE'; SEC_E_CRYPTO_SYSTEM_INVALID : Result := 'SEC_E_CRYPTO_SYSTEM_INVALID'; SEC_E_MAX_REFERRALS_EXCEEDED : Result := 'SEC_E_MAX_REFERRALS_EXCEEDED'; SEC_E_MUST_BE_KDC : Result := 'SEC_E_MUST_BE_KDC'; SEC_E_STRONG_CRYPTO_NOT_SUPPORTED : Result := 'SEC_E_STRONG_CRYPTO_NOT_SUPPORTED'; SEC_E_TOO_MANY_PRINCIPALS : Result := 'SEC_E_TOO_MANY_PRINCIPALS'; SEC_E_NO_PA_DATA : Result := 'SEC_E_NO_PA_DATA'; SEC_E_PKINIT_NAME_MISMATCH : Result := 'SEC_E_PKINIT_NAME_MISMATCH'; SEC_E_SMARTCARD_LOGON_REQUIRED : Result := 'SEC_E_SMARTCARD_LOGON_REQUIRED'; SEC_E_SHUTDOWN_IN_PROGRESS : Result := 'SEC_E_SHUTDOWN_IN_PROGRESS'; SEC_E_KDC_INVALID_REQUEST : Result := 'SEC_E_KDC_INVALID_REQUEST'; SEC_E_KDC_UNABLE_TO_REFER : Result := 'SEC_E_KDC_UNABLE_TO_REFER'; SEC_E_KDC_UNKNOWN_ETYPE : Result := 'SEC_E_KDC_UNKNOWN_ETYPE'; SEC_E_UNSUPPORTED_PREAUTH : Result := 'SEC_E_UNSUPPORTED_PREAUTH'; SEC_E_DELEGATION_REQUIRED : Result := 'SEC_E_DELEGATION_REQUIRED'; SEC_E_BAD_BINDINGS : Result := 'SEC_E_BAD_BINDINGS'; SEC_E_MULTIPLE_ACCOUNTS : Result := 'SEC_E_MULTIPLE_ACCOUNTS'; SEC_E_NO_KERB_KEY : Result := 'SEC_E_NO_KERB_KEY'; SEC_E_CERT_WRONG_USAGE : Result := 'SEC_E_CERT_WRONG_USAGE'; SEC_E_DOWNGRADE_DETECTED : Result := 'SEC_E_DOWNGRADE_DETECTED'; SEC_E_SMARTCARD_CERT_REVOKED : Result := 'SEC_E_SMARTCARD_CERT_REVOKED'; SEC_E_ISSUING_CA_UNTRUSTED : Result := 'SEC_E_ISSUING_CA_UNTRUSTED'; SEC_E_REVOCATION_OFFLINE_C : Result := 'SEC_E_REVOCATION_OFFLINE_C'; SEC_E_PKINIT_CLIENT_FAILURE : Result := 'SEC_E_PKINIT_CLIENT_FAILURE'; SEC_E_SMARTCARD_CERT_EXPIRED : Result := 'SEC_E_SMARTCARD_CERT_EXPIRED'; SEC_E_NO_S4U_PROT_SUPPORT : Result := 'SEC_E_NO_S4U_PROT_SUPPORT'; SEC_E_CROSSREALM_DELEGATION_FAILURE : Result := 'SEC_E_CROSSREALM_DELEGATION_FAILURE'; SEC_E_REVOCATION_OFFLINE_KDC : Result := 'SEC_E_REVOCATION_OFFLINE_KDC'; SEC_E_ISSUING_CA_UNTRUSTED_KDC : Result := 'SEC_E_ISSUING_CA_UNTRUSTED_KDC'; SEC_E_KDC_CERT_EXPIRED : Result := 'SEC_E_KDC_CERT_EXPIRED'; SEC_E_KDC_CERT_REVOKED : Result := 'SEC_E_KDC_CERT_REVOKED'; CRYPT_E_MSG_ERROR : Result := 'CRYPT_E_MSG_ERROR'; CRYPT_E_UNKNOWN_ALGO : Result := 'CRYPT_E_UNKNOWN_ALGO'; CRYPT_E_OID_FORMAT : Result := 'CRYPT_E_OID_FORMAT'; CRYPT_E_INVALID_MSG_TYPE : Result := 'CRYPT_E_INVALID_MSG_TYPE'; CRYPT_E_UNEXPECTED_ENCODING : Result := 'CRYPT_E_UNEXPECTED_ENCODING'; CRYPT_E_AUTH_ATTR_MISSING : Result := 'CRYPT_E_AUTH_ATTR_MISSING'; CRYPT_E_HASH_VALUE : Result := 'CRYPT_E_HASH_VALUE'; CRYPT_E_INVALID_INDEX : Result := 'CRYPT_E_INVALID_INDEX'; CRYPT_E_ALREADY_DECRYPTED : Result := 'CRYPT_E_ALREADY_DECRYPTED'; CRYPT_E_NOT_DECRYPTED : Result := 'CRYPT_E_NOT_DECRYPTED'; CRYPT_E_RECIPIENT_NOT_FOUND : Result := 'CRYPT_E_RECIPIENT_NOT_FOUND'; CRYPT_E_CONTROL_TYPE : Result := 'CRYPT_E_CONTROL_TYPE'; CRYPT_E_ISSUER_SERIALNUMBER : Result := 'CRYPT_E_ISSUER_SERIALNUMBER'; CRYPT_E_SIGNER_NOT_FOUND : Result := 'CRYPT_E_SIGNER_NOT_FOUND'; CRYPT_E_ATTRIBUTES_MISSING : Result := 'CRYPT_E_ATTRIBUTES_MISSING'; CRYPT_E_STREAM_MSG_NOT_READY : Result := 'CRYPT_E_STREAM_MSG_NOT_READY'; CRYPT_E_STREAM_INSUFFICIENT_DATA : Result := 'CRYPT_E_STREAM_INSUFFICIENT_DATA'; CRYPT_E_BAD_LEN : Result := 'CRYPT_E_BAD_LEN'; CRYPT_E_BAD_ENCODE : Result := 'CRYPT_E_BAD_ENCODE'; CRYPT_E_FILE_ERROR : Result := 'CRYPT_E_FILE_ERROR'; CRYPT_E_NOT_FOUND : Result := 'CRYPT_E_NOT_FOUND'; CRYPT_E_EXISTS : Result := 'CRYPT_E_EXISTS'; CRYPT_E_NO_PROVIDER : Result := 'CRYPT_E_NO_PROVIDER'; CRYPT_E_SELF_SIGNED : Result := 'CRYPT_E_SELF_SIGNED'; CRYPT_E_DELETED_PREV : Result := 'CRYPT_E_DELETED_PREV'; CRYPT_E_NO_MATCH : Result := 'CRYPT_E_NO_MATCH'; CRYPT_E_UNEXPECTED_MSG_TYPE : Result := 'CRYPT_E_UNEXPECTED_MSG_TYPE'; CRYPT_E_NO_KEY_PROPERTY : Result := 'CRYPT_E_NO_KEY_PROPERTY'; CRYPT_E_NO_DECRYPT_CERT : Result := 'CRYPT_E_NO_DECRYPT_CERT'; CRYPT_E_BAD_MSG : Result := 'CRYPT_E_BAD_MSG'; CRYPT_E_NO_SIGNER : Result := 'CRYPT_E_NO_SIGNER'; CRYPT_E_PENDING_CLOSE : Result := 'CRYPT_E_PENDING_CLOSE'; CRYPT_E_REVOKED : Result := 'CRYPT_E_REVOKED'; CRYPT_E_NO_REVOCATION_DLL : Result := 'CRYPT_E_NO_REVOCATION_DLL'; CRYPT_E_NO_REVOCATION_CHECK : Result := 'CRYPT_E_NO_REVOCATION_CHECK'; CRYPT_E_REVOCATION_OFFLINE : Result := 'CRYPT_E_REVOCATION_OFFLINE'; CRYPT_E_NOT_IN_REVOCATION_DATABASE : Result := 'CRYPT_E_NOT_IN_REVOCATION_DATABASE'; CRYPT_E_INVALID_NUMERIC_STRING : Result := 'CRYPT_E_INVALID_NUMERIC_STRING'; CRYPT_E_INVALID_PRINTABLE_STRING : Result := 'CRYPT_E_INVALID_PRINTABLE_STRING'; CRYPT_E_INVALID_IA5_STRING : Result := 'CRYPT_E_INVALID_IA5_STRING'; CRYPT_E_INVALID_X500_STRING : Result := 'CRYPT_E_INVALID_X500_STRING'; CRYPT_E_NOT_CHAR_STRING : Result := 'CRYPT_E_NOT_CHAR_STRING'; CRYPT_E_FILERESIZED : Result := 'CRYPT_E_FILERESIZED'; CRYPT_E_SECURITY_SETTINGS : Result := 'CRYPT_E_SECURITY_SETTINGS'; CRYPT_E_NO_VERIFY_USAGE_DLL : Result := 'CRYPT_E_NO_VERIFY_USAGE_DLL'; CRYPT_E_NO_VERIFY_USAGE_CHECK : Result := 'CRYPT_E_NO_VERIFY_USAGE_CHECK'; CRYPT_E_VERIFY_USAGE_OFFLINE : Result := 'CRYPT_E_VERIFY_USAGE_OFFLINE'; CRYPT_E_NOT_IN_CTL : Result := 'CRYPT_E_NOT_IN_CTL'; CRYPT_E_NO_TRUSTED_SIGNER : Result := 'CRYPT_E_NO_TRUSTED_SIGNER'; CRYPT_E_MISSING_PUBKEY_PARA : Result := 'CRYPT_E_MISSING_PUBKEY_PARA'; CRYPT_E_OSS_ERROR : Result := 'CRYPT_E_OSS_ERROR'; CRYPT_E_ASN1_ERROR : Result := 'CRYPT_E_ASN1_ERROR'; CRYPT_E_ASN1_INTERNAL : Result := 'CRYPT_E_ASN1_INTERNAL'; CRYPT_E_ASN1_EOD : Result := 'CRYPT_E_ASN1_EOD'; CRYPT_E_ASN1_CORRUPT : Result := 'CRYPT_E_ASN1_CORRUPT'; CRYPT_E_ASN1_LARGE : Result := 'CRYPT_E_ASN1_LARGE'; CRYPT_E_ASN1_CONSTRAINT : Result := 'CRYPT_E_ASN1_CONSTRAINT'; CRYPT_E_ASN1_MEMORY : Result := 'CRYPT_E_ASN1_MEMORY'; CRYPT_E_ASN1_OVERFLOW : Result := 'CRYPT_E_ASN1_OVERFLOW'; CRYPT_E_ASN1_BADPDU : Result := 'CRYPT_E_ASN1_BADPDU'; CRYPT_E_ASN1_BADARGS : Result := 'CRYPT_E_ASN1_BADARGS'; CRYPT_E_ASN1_BADREAL : Result := 'CRYPT_E_ASN1_BADREAL'; CRYPT_E_ASN1_BADTAG : Result := 'CRYPT_E_ASN1_BADTAG'; CRYPT_E_ASN1_CHOICE : Result := 'CRYPT_E_ASN1_CHOICE'; CRYPT_E_ASN1_RULE : Result := 'CRYPT_E_ASN1_RULE'; CRYPT_E_ASN1_UTF8 : Result := 'CRYPT_E_ASN1_UTF8'; CRYPT_E_ASN1_PDU_TYPE : Result := 'CRYPT_E_ASN1_PDU_TYPE'; CRYPT_E_ASN1_NYI : Result := 'CRYPT_E_ASN1_NYI'; CRYPT_E_ASN1_EXTENDED : Result := 'CRYPT_E_ASN1_EXTENDED'; CRYPT_E_ASN1_NOEOD : Result := 'CRYPT_E_ASN1_NOEOD'; else Result := ''; end; Result := SysErrorMessage(DWORD(scRet)) + Format(' [%s 0x%x]', [Result, scRet]); end; function WinVerifyTrustErrorStr(Status: DWORD): string; begin case HRESULT(Status) of CERT_E_EXPIRED : Result := 'CERT_E_EXPIRED'; CERT_E_VALIDITYPERIODNESTING : Result := 'CERT_E_VALIDITYPERIODNESTING'; CERT_E_ROLE : Result := 'CERT_E_ROLE'; CERT_E_PATHLENCONST : Result := 'CERT_E_PATHLENCONST'; CERT_E_CRITICAL : Result := 'CERT_E_CRITICAL'; CERT_E_PURPOSE : Result := 'CERT_E_PURPOSE'; CERT_E_ISSUERCHAINING : Result := 'CERT_E_ISSUERCHAINING'; CERT_E_MALFORMED : Result := 'CERT_E_MALFORMED'; CERT_E_UNTRUSTEDROOT : Result := 'CERT_E_UNTRUSTEDROOT'; CERT_E_CHAINING : Result := 'CERT_E_CHAINING'; TRUST_E_FAIL : Result := 'TRUST_E_FAIL'; CERT_E_REVOKED : Result := 'CERT_E_REVOKED'; CERT_E_UNTRUSTEDTESTROOT : Result := 'CERT_E_UNTRUSTEDTESTROOT'; CERT_E_REVOCATION_FAILURE : Result := 'CERT_E_REVOCATION_FAILURE'; CERT_E_CN_NO_MATCH : Result := 'CERT_E_CN_NO_MATCH'; CERT_E_WRONG_USAGE : Result := 'CERT_E_WRONG_USAGE'; else Result := ''; end; Result := SysErrorMessage(Status) + Format(' [%s 0x%x]', [Result, Status]); end; function IsWinHandshakeBug(scRet: SECURITY_STATUS): Boolean; begin Result := (scRet = SEC_E_BUFFER_TOO_SMALL) or (scRet = SEC_E_MESSAGE_ALTERED); end; function GetSessionCredsPtr(const SessionData: TSessionData): PSessionCreds; begin if SessionData.SharedCreds <> nil then Result := SessionData.SharedCreds.GetSessionCredsPtr else Result := @SessionData.SessionCreds; end; { ~~ TSharedSessionData ~~ } // Return pointer to `TSessionData` record function TSharedSessionCreds.GetSessionCredsPtr: PSessionCreds; begin Result := @FSessionCreds; end; destructor TSharedSessionCreds.Destroy; begin FreeSessionCreds(FSessionCreds); inherited; end; { ~~ TTrustedCerts ~~ } constructor TTrustedCerts.Create; begin inherited; InitializeCriticalSection(FPropCS); end; destructor TTrustedCerts.Destroy; begin DeleteCriticalSection(FPropCS); inherited; end; // Add a cert to list. // @param Host - cert host. If empty, cert is considered global // @param Data - cert data procedure TTrustedCerts.Add(const Host: string; const Data: TBytes); begin EnterCriticalSection(FPropCS); SetLength(FCerts, Length(FCerts) + 1); FCerts[High(FCerts)].Host := Host; FCerts[High(FCerts)].Data := Data; LeaveCriticalSection(FPropCS); end; // Check if there PROBABLY is a cert in trusted list for the host (i.e., there's // at least one trusted cert either global or host-personal. // @param Host - cert host. If empty, cert is considered global // // @returns @true if there's a cert for the host function TTrustedCerts.Contains(const Host: string): Boolean; var i: Integer; begin EnterCriticalSection(FPropCS); Result := False; for i := Low(FCerts) to High(FCerts) do if (FCerts[i].Host = '') or (FCerts[i].Host = Host) then begin Result := True; Break; end; LeaveCriticalSection(FPropCS); end; // Check if provided cert is in trusted list. Looks for both host-personal and global certs. // @param Host - cert host. If empty, cert is considered global // @param pData - cert data // @param DataLen - length of cert data // // @returns @true if cert is found function TTrustedCerts.Contains(const Host: string; pData: Pointer; DataLen: Integer): Boolean; var i: Integer; begin EnterCriticalSection(FPropCS); Result := False; for i := Low(FCerts) to High(FCerts) do if (FCerts[i].Host = '') or (FCerts[i].Host = Host) then if (DataLen = Length(FCerts[i].Data)) and CompareMem(pData, FCerts[i].Data, DataLen) then begin Result := True; Break; end; LeaveCriticalSection(FPropCS); end; // Check if provided cert is in trusted list. TBytes variant. // @param Host - cert host. If empty, search is performed over all list // @param Data - cert data // // @returns @true if cert is found function TTrustedCerts.Contains(const Host: string; const Data: TBytes): Boolean; begin Result := Contains(Host, Data, Length(Data)); end; // Empty the list procedure TTrustedCerts.Clear; begin EnterCriticalSection(FPropCS); SetLength(FCerts, 0); LeaveCriticalSection(FPropCS); end; { ~~ ESSPIError ~~ } { Create WinAPI exception based on Err code @param Action - current action, like `sending data` or `@ Init` @param Func - WinAPI method, like `Send` @param Err - error code } constructor ESSPIError.CreateWinAPI(const Action, Func: string; Err: DWORD); begin inherited CreateFmt(S_E_WinAPIErrPatt, [Action, Func, Err, SysErrorMessage(Err)]); Self.WinAPIErr := Err; end; { Create SChannel exception based on status and, optionally, on custom info message @param Action - current action, like `@ CreateCredentials` @param Func - SChannel method, like `AcquireCredentialsHandle` @param Status - SChannel status that will be copied to SecStatus field. @param Info - custom info message that will be inserted in exception message. If empty, info message is generated based on Status } constructor ESSPIError.CreateSecStatus(const Action, Func: string; Status: SECURITY_STATUS; const Info: string); begin if Info <> '' then inherited CreateFmt(S_E_SecStatusErrPatt, [Action, Func, Info]) else inherited CreateFmt(S_E_SecStatusErrPatt, [Action, Func, SecStatusErrStr(Status)]); Self.SecStatus := Status; end; // Create general exception function Error(const Msg: string; const Args: array of const): ESSPIError; overload; begin Result := ESSPIError.CreateFmt(Msg, Args); end; function Error(const Msg: string): ESSPIError; overload; begin Result := ESSPIError.Create(Msg); end; // Create security status exception function ErrSecStatus(const Action, Func: string; Status: SECURITY_STATUS; const Info: string = ''): ESSPIError; overload; begin Result := ESSPIError.CreateSecStatus(Action, Func, Status, Info); end; // Create WinAPI exception based on GetLastError function ErrWinAPI(const Action, Func: string): ESSPIError; begin Result := ESSPIError.CreateWinAPI(Action, Func, GetLastError); end; { TDefaultDebugFnHoster } class procedure TDefaultDebugFnHoster.Debug(const Msg: string); begin OutputDebugString(PChar(FormatDateTime('yyyy.mm.dd hh:mm:ss.zzz', Now) + ' ' + LogPrefix + Msg)); end; procedure Debug(DebugLogFn: TDebugFn; const Msg: string); begin if Assigned(DebugLogFn) then DebugLogFn(Msg) else TDefaultDebugFnHoster.Debug(Msg); end; // ~~ Init & fin ~~ procedure LoadSecurityLibrary; begin g_pSSPI := InitSecurityInterface; if g_pSSPI = nil then raise ErrWinAPI('@ LoadSecurityLibrary', 'InitSecurityInterface'); end; procedure CreateCredentials(const User: string; out hCreds: CredHandle; var SchannelCred: SCHANNEL_CRED); var cSupportedAlgs: DWORD; rgbSupportedAlgs: array[0..15] of ALG_ID; pCertContext: PCCERT_CONTEXT; Status: SECURITY_STATUS; begin // If a user name is specified, then attempt to find a client // certificate. Otherwise, just create a NULL credential. if User <> '' then begin // Find client certificate. Note that this sample just searches for a // certificate that contains the user name somewhere in the subject name. // A real application should be a bit less casual. pCertContext := CertFindCertificateInStore(hMyCertStore, // hCertStore X509_ASN_ENCODING, // dwCertEncodingType 0, // dwFindFlags CERT_FIND_SUBJECT_STR_A, // dwFindType Pointer(User), // *pvFindPara nil); // pPrevCertContext if pCertContext = nil then raise ErrWinAPI('@ CreateCredentials', 'CertFindCertificateInStore'); end else pCertContext := nil; // Schannel credential structure not inited yet - fill with default values. // Otherwise let the user pass his own values. if SchannelCred.dwVersion <> SCHANNEL_CRED_VERSION then begin // Build Schannel credential structure. Currently, this sample only // specifies the protocol to be used (and optionally the certificate, // of course). Real applications may wish to specify other parameters as well. SchannelCred := Default(SCHANNEL_CRED); SchannelCred.dwVersion := SCHANNEL_CRED_VERSION; if pCertContext <> nil then begin SchannelCred.cCreds := 1; SchannelCred.paCred := @pCertContext; end; SchannelCred.grbitEnabledProtocols := USED_PROTOCOLS; cSupportedAlgs := 0; if USED_ALGS <> 0 then begin rgbSupportedAlgs[cSupportedAlgs] := USED_ALGS; Inc(cSupportedAlgs); end; if cSupportedAlgs <> 0 then begin SchannelCred.cSupportedAlgs := cSupportedAlgs; SchannelCred.palgSupportedAlgs := @rgbSupportedAlgs; end; SchannelCred.dwFlags := SCH_CRED_REVOCATION_CHECK_CHAIN or // CRL could be offline but we likely want to connect anyway so ignore this error SCH_CRED_IGNORE_REVOCATION_OFFLINE; end; // Create an SSPI credential with SChannel security package Status := g_pSSPI.AcquireCredentialsHandleW(nil, // Name of principal PSecWChar(PChar(UNISP_NAME)), // Name of package SECPKG_CRED_OUTBOUND, // Flags indicating use nil, // Pointer to logon ID @SchannelCred, // Package specific data nil, // Pointer to GetKey() func nil, // Value to pass to GetKey() @hCreds, // (out) Cred Handle nil); // (out) Lifetime (optional) // cleanup: Free the certificate context. Schannel has already made its own copy. if pCertContext <> nil then CertFreeCertificateContext(pCertContext); if Status <> SEC_E_OK then raise ErrSecStatus('@ CreateCredentials', 'AcquireCredentialsHandle', Status); end; procedure Init; begin if g_pSSPI = nil then LoadSecurityLibrary; // Open the "MY" certificate store, where IE stores client certificates. // Windows maintains 4 stores -- MY, CA, ROOT, SPC. if hMYCertStore = nil then begin hMYCertStore := CertOpenSystemStore(0, 'MY'); if hMYCertStore = nil then raise ErrWinAPI('@ Init', 'CertOpenSystemStore'); end; end; procedure Fin; begin // Close "MY" certificate store. if hMYCertStore <> nil then CertCloseStore(hMYCertStore, 0); hMYCertStore := nil; g_pSSPI := nil; end; procedure CreateSessionCreds(var SessionCreds: TSessionCreds); begin if SecIsNullHandle(SessionCreds.hCreds) then begin // Create credentials CreateCredentials('', SessionCreds.hCreds, SessionCreds.SchannelCred); end; end; function CreateSharedCreds: ISharedSessionCreds; begin Result := TSharedSessionCreds.Create; end; procedure FreeSessionCreds(var SessionCreds: TSessionCreds); begin if not SecIsNullHandle(SessionCreds.hCreds) then begin // Free SSPI credentials handle. g_pSSPI.FreeCredentialsHandle(@SessionCreds.hCreds); SessionCreds.hCreds := Default(CredHandle); SessionCreds.SchannelCred := Default(SCHANNEL_CRED); end; end; procedure FinSession(var SessionData: TSessionData); begin SessionData.SharedCreds := nil; FreeSessionCreds(SessionData.SessionCreds); end; // ~~ Connect & close ~~ // Try to get new client credentials, leaving old value on error procedure GetNewClientCredentials(var SessionData: TSessionData; const hContext: CtxtHandle; DebugLogFn: TDebugFn = nil); var pCreds: PSessionCreds; IssuerListInfo: SecPkgContext_IssuerListInfoEx; pChainContext: PCCERT_CHAIN_CONTEXT; Err: LONG; ErrDescr: string; FindByIssuerPara: CERT_CHAIN_FIND_BY_ISSUER_PARA; pCertContext: PCCERT_CONTEXT; SchannelCred: SCHANNEL_CRED; Status: SECURITY_STATUS; hCreds: CredHandle; begin // Read list of trusted issuers from schannel. Status := g_pSSPI.QueryContextAttributesW(@hContext, SECPKG_ATTR_ISSUER_LIST_EX, @IssuerListInfo); if Status <> SEC_E_OK then raise ErrSecStatus('@ GetNewClientCredentials', 'QueryContextAttributesW', Status); // Enumerate the client certificates. FindByIssuerPara := Default(CERT_CHAIN_FIND_BY_ISSUER_PARA); FindByIssuerPara.cbSize := SizeOf(FindByIssuerPara); FindByIssuerPara.pszUsageIdentifier := szOID_PKIX_KP_CLIENT_AUTH; FindByIssuerPara.dwKeySpec := 0; FindByIssuerPara.cIssuer := IssuerListInfo.cIssuers; FindByIssuerPara.rgIssuer := IssuerListInfo.aIssuers; pChainContext := nil; while True do begin // Find a certificate chain. pChainContext := CertFindChainInStore(hMYCertStore, X509_ASN_ENCODING, 0, CERT_CHAIN_FIND_BY_ISSUER, @FindByIssuerPara, pChainContext); if pChainContext = nil then begin ErrDescr := 'GetNewClientCredentials: error in CertFindChainInStore finding cert chain - '; // There's no description of returned codes in MSDN. They're returned via // GetLastError but seem to be SecStatus. Try to determine if that's the // case by extracting facility and comparing it to expected ones: SSPI and // CERT. Others are reported as usual WinAPI errors Err := LONG(GetLastError); if (SCODE_FACILITY(Err) = FACILITY_SSPI) or (SCODE_FACILITY(Err) = FACILITY_CERT) then ErrDescr := ErrDescr + SecStatusErrStr(Err) else ErrDescr := ErrDescr + SysErrorMessage(DWORD(Err)) + Format(' [%d]', [Err]); Debug(DebugLogFn, ErrDescr); Break; end; // Get pointer to leaf certificate context. pCertContext := pChainContext.rgpChain^.rgpElement^.pCertContext; // Create schannel credential. pCreds := GetSessionCredsPtr(SessionData); SchannelCred := Default(SCHANNEL_CRED); SchannelCred.dwVersion := SCHANNEL_CRED_VERSION; SchannelCred.cCreds := 1; SchannelCred.paCred := @pCertContext; Status := g_pSSPI.AcquireCredentialsHandleW(nil, // Name of principal PSecWChar(PChar(UNISP_NAME)), // Name of package SECPKG_CRED_OUTBOUND, // Flags indicating use nil, // Pointer to logon ID @SchannelCred, // Package specific data nil, // Pointer to GetKey() func nil, // Value to pass to GetKey() @hCreds, // (out) Cred Handle nil); // (out) Lifetime (optional) if Status <> SEC_E_OK then Continue; g_pSSPI.FreeCredentialsHandle(@pCreds.hCreds); // Destroy the old credentials. pCreds.hCreds := hCreds; pCreds.SchannelCred := SchannelCred; end; // while end; { Function to prepare all necessary handshake data. No transport level actions. @param SessionData - [IN/OUT] record with session data @param HandShakeData - [IN/OUT] record with handshake data @param DebugLogFn - logging callback, could be @nil @raises ESSPIError on error Function actions and returning data depending on input stage: - `HandShakeData.Stage` = hssNotStarted. Generate client hello. @br *Output stage*: hssSendCliHello. @br *Caller action*: send returned data (client hello) to server @br *Input data*: - ServerName - host we're connecting to *Output data*: - hContext - handle to secure context - OutBuffers - array with single item that must be finally disposed with `g_pSSPI.FreeContextBuffer` - `HandShakeData.Stage` = hssSendCliHello. **Not** handled by @name @br - `HandShakeData.Stage` = hssReadSrvHello, hssReadSrvHelloNoRead, hssReadSrvHelloContNeed. Handle server hello *Output stage*: hssReadSrvHello, hssReadSrvHelloNoRead, hssReadSrvHelloContNeed, hssReadSrvHelloOK. @br *Caller action*: - hssReadSrvHello: read data from server and call @name again - hssReadSrvHelloNoRead: call @name again without reading - hssReadSrvHelloContNeed: send token returned in `OutBuffers` and call @name again - hssReadSrvHelloOK: send token returned in `OutBuffers` and finish *Input data*: - ServerName - host we're connecting to - IoBuffer - buffer with data from server - cbIoBuffer - size of data in buffer *Output data*: - IoBuffer - buffer with unprocessed data from server - cbIoBuffer - length of unprocessed data from server - OutBuffers - array with single item that must be finally disposed with `g_pSSPI.FreeContextBuffer` (hssReadSrvHelloContNeed, hssReadSrvHelloOK) - `HandShakeData.Stage` = hssReadSrvHelloOK. **Not** handled by @name @br - `HandShakeData.Stage` = hssDone. **Not** handled by @name @br } function DoClientHandshake(var SessionData: TSessionData; var HandShakeData: THandShakeData; DebugLogFn: TDebugFn): SECURITY_STATUS; // Process "extra" buffer and modify HandShakeData.cbIoBuffer accordingly. // After the call HandShakeData.IoBuffer will contain HandShakeData.cbIoBuffer // (including zero!) unprocessed data. procedure HandleBuffers(const InBuffer: SecBuffer); begin if InBuffer.BufferType = SECBUFFER_EXTRA then begin Move( (PByte(HandShakeData.IoBuffer) + (HandShakeData.cbIoBuffer - InBuffer.cbBuffer))^, Pointer(HandShakeData.IoBuffer)^, InBuffer.cbBuffer); HandShakeData.cbIoBuffer := InBuffer.cbBuffer; end else HandShakeData.cbIoBuffer := 0; // Prepare for the next recv end; var dwSSPIFlags, dwSSPIOutFlags: DWORD; pCreds: PSessionCreds; InBuffers: array [0..1] of SecBuffer; OutBuffer, InBuffer: SecBufferDesc; begin dwSSPIFlags := SessionData.SSPIFlags; if dwSSPIFlags = 0 then dwSSPIFlags := SSPI_FLAGS; // Check if manual cert validation is required. I haven't found an option to // force SChannel retry handshake stage without auto validation after it had // failed so just turning it off if there's any chance of custom cert check. if ((SessionData.TrustedCerts <> nil) and SessionData.TrustedCerts.Contains(SessionData.ServerName)) or (SessionData.CertCheckIgnoreFlags <> []) then Include(SessionData.Flags, sfNoServerVerify); if sfNoServerVerify in SessionData.Flags then dwSSPIFlags := dwSSPIFlags or ISC_REQ_MANUAL_CRED_VALIDATION; pCreds := GetSessionCredsPtr(SessionData); case HandShakeData.Stage of hssNotStarted: begin // Initiate a ClientHello message and generate a token. SetLength(HandShakeData.OutBuffers, 1); HandShakeData.OutBuffers[0] := Default(SecBuffer); HandShakeData.OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := Length(HandShakeData.OutBuffers); OutBuffer.pBuffers := PSecBuffer(HandShakeData.OutBuffers); Result := g_pSSPI.InitializeSecurityContextW(@pCreds.hCreds, nil, // NULL on the first call PSecWChar(Pointer(SessionData.ServerName)), // ! PChar('') <> nil ! dwSSPIFlags, 0, // Reserved 0, // Not used with Schannel nil, // NULL on the first call 0, // Reserved @HandShakeData.hContext, @OutBuffer, dwSSPIOutFlags, nil); if Result <> SEC_I_CONTINUE_NEEDED then begin DeleteContext(HandShakeData.hContext); raise ErrSecStatus('@ DoClientHandshake @ client hello', 'InitializeSecurityContext', Result); end; if (HandShakeData.OutBuffers[0].cbBuffer = 0) or (HandShakeData.OutBuffers[0].pvBuffer = nil) then raise ErrSecStatus('@ DoClientHandshake @ client hello', 'InitializeSecurityContext', Result, 'generated empty buffer'); HandShakeData.Stage := hssSendCliHello; end; hssReadSrvHello, hssReadSrvHelloNoRead, hssReadSrvHelloContNeed: begin // Set up the input buffers. Buffer 0 is used to pass in data // received from the server. Schannel will consume some or all // of this. Leftover data (if any) will be placed in buffer 1 and // given a buffer type of SECBUFFER_EXTRA. InBuffers[0].cbBuffer := HandShakeData.cbIoBuffer; InBuffers[0].BufferType := SECBUFFER_TOKEN; InBuffers[0].pvBuffer := HandShakeData.IoBuffer; InBuffers[1] := Default(SecBuffer); InBuffers[1].BufferType := SECBUFFER_EMPTY; InBuffer.ulVersion := SECBUFFER_VERSION; InBuffer.cBuffers := Length(InBuffers); InBuffer.pBuffers := @InBuffers; // Set up the output buffers. These are initialized to NULL // so as to make it less likely we'll attempt to free random // garbage later. SetLength(HandShakeData.OutBuffers, 3); HandShakeData.OutBuffers[0] := Default(SecBuffer); HandShakeData.OutBuffers[0].BufferType := SECBUFFER_TOKEN; // ! Usually only one buffer is enough but I experienced rare and random // SEC_E_BUFFER_TOO_SMALL and SEC_E_MESSAGE_ALTERED errors on Windows 7/8. // Retrying a handshake worked well. According to Internet findings, these // errors are caused by SChannel bug with TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 // and TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ciphers. While some advice disabling // these ciphers or not using TLSv1.2 at all or disable revocation checking, // cURL project tries to solve the issue by adding more buffers. This does // NOT fix the error completely but hopefully makes it somewhat less frequent... HandShakeData.OutBuffers[1] := Default(SecBuffer); HandShakeData.OutBuffers[1].BufferType := SECBUFFER_ALERT; HandShakeData.OutBuffers[2] := Default(SecBuffer); HandShakeData.OutBuffers[2].BufferType := SECBUFFER_EMPTY; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := Length(HandShakeData.OutBuffers); OutBuffer.pBuffers := PSecBuffer(HandShakeData.OutBuffers); Result := g_pSSPI.InitializeSecurityContextW(@pCreds.hCreds, @HandShakeData.hContext, PSecWChar(Pointer(SessionData.ServerName)), dwSSPIFlags, 0, // Reserved 0, // Not used with Schannel @InBuffer, 0, // Reserved nil, @OutBuffer, dwSSPIOutFlags, nil); // If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, // then we need to read more data from the server and try again. if Result = SEC_E_INCOMPLETE_MESSAGE then Exit; // Check for fatal error. if Failed(Result) then raise ErrSecStatus('@ DoClientHandshake @ server hello', 'InitializeSecurityContext', Result); case Result of // SEC_I_CONTINUE_NEEDED: // - Not enough data provided (seems it should be SEC_E_INCOMPLETE_MESSAGE // but SChannel returns SEC_I_CONTINUE_NEEDED): // * InBuffers[1] contains length of unread buffer that should be // feed to InitializeSecurityContext next time // * OutBuffers contain nothing // - Token must be sent to server // * OutBuffers[1] contains token to be sent SEC_I_CONTINUE_NEEDED: begin HandShakeData.Stage := hssReadSrvHelloContNeed; end; // SEC_I_INCOMPLETE_CREDENTIALS: // the server just requested client authentication. SEC_I_INCOMPLETE_CREDENTIALS: begin Debug(DebugLogFn, 'DoClientHandshake @ server hello - InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS'); // Busted. The server has requested client authentication and // the credential we supplied didn't contain a client certificate. // This function will read the list of trusted certificate // authorities ("issuers") that was received from the server // and attempt to find a suitable client certificate that // was issued by one of these. If this function is successful, // then we will connect using the new certificate. Otherwise, // we will attempt to connect anonymously (using our current credentials). GetNewClientCredentials(SessionData, HandShakeData.hContext, DebugLogFn); // Go around again HandShakeData.Stage := hssReadSrvHelloNoRead; end; // SEC_E_OK: // handshake completed successfully. // handle extra data if present and finish the process SEC_E_OK: begin HandShakeData.Stage := hssReadSrvHelloOK; end; else // SEC_I_COMPLETE_AND_CONTINUE, SEC_I_COMPLETE_NEEDED raise ErrSecStatus('@ DoClientHandshake @ server hello - don''t know how to handle this', 'InitializeSecurityContext', Result); end; // case HandleBuffers(InBuffers[1]); end; // hssReadServerHello* else raise Error('Error at DoClientHandshake: Stage not handled'); end; // case end; procedure GetShutdownData(const SessionData: TSessionData; const hContext: CtxtHandle; out OutBuffer: SecBuffer); var dwType, dwSSPIFlags, dwSSPIOutFlags, Status: DWORD; OutBufferDesc: SecBufferDesc; OutBuffers: array[0..0] of SecBuffer; tsExpiry: TimeStamp; begin OutBuffer := Default(SecBuffer); dwType := SCHANNEL_SHUTDOWN; // Notify schannel that we are about to close the connection. OutBuffers[0].cbBuffer := SizeOf(dwType); OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := @dwType; OutBufferDesc.ulVersion := SECBUFFER_VERSION; OutBufferDesc.cBuffers := Length(OutBuffers); OutBufferDesc.pBuffers := @OutBuffers; Status := g_pSSPI.ApplyControlToken(@hContext, @OutBufferDesc); if Failed(Status) then raise ErrSecStatus('@ GetShutdownData', 'ApplyControlToken', Status); // Build an SSL close notify message. dwSSPIFlags := SessionData.SSPIFlags; if dwSSPIFlags = 0 then dwSSPIFlags := SSPI_FLAGS; OutBuffers[0] := Default(SecBuffer); OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBufferDesc.ulVersion := SECBUFFER_VERSION; OutBufferDesc.cBuffers := Length(OutBuffers); OutBufferDesc.pBuffers := @OutBuffers; Status := g_pSSPI.InitializeSecurityContextW(@GetSessionCredsPtr(SessionData).hCreds, @hContext, nil, dwSSPIFlags, 0, SECURITY_NATIVE_DREP, nil, 0, @hContext, @OutBufferDesc, dwSSPIOutFlags, @tsExpiry); if Failed(Status) then begin g_pSSPI.FreeContextBuffer(OutBuffers[0].pvBuffer); // Free output buffer. raise ErrSecStatus('@ GetShutdownData', 'InitializeSecurityContext', Status); end; OutBuffer := OutBuffers[0]; end; procedure VerifyServerCertificate(pServerCert: PCCERT_CONTEXT; const szServerName: string; dwCertFlags: DWORD); var polHttps: HTTPSPolicyCallbackData; PolicyPara: CERT_CHAIN_POLICY_PARA; PolicyStatus: CERT_CHAIN_POLICY_STATUS; ChainPara: CERT_CHAIN_PARA; pChainContext: PCCERT_CHAIN_CONTEXT; const rgszUsages: array[0..2] of PAnsiChar = ( szOID_PKIX_KP_SERVER_AUTH, szOID_SERVER_GATED_CRYPTO, szOID_SGC_NETSCAPE ); cUsages: DWORD = SizeOf(rgszUsages) div SizeOf(LPSTR); begin pChainContext := nil; if pServerCert = nil then raise Error('Error @ VerifyServerCertificate - server cert is NULL'); // Build certificate chain. try ChainPara := Default(CERT_CHAIN_PARA); ChainPara.cbSize := SizeOf(ChainPara); ChainPara.RequestedUsage.dwType := USAGE_MATCH_TYPE_OR; ChainPara.RequestedUsage.Usage.cUsageIdentifier := cUsages; ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier := PAnsiChar(@rgszUsages); if not CertGetCertificateChain(0, pServerCert, nil, pServerCert.hCertStore, @ChainPara, 0, nil, @pChainContext) then raise ErrWinAPI('@ VerifyServerCertificate', 'CertGetCertificateChain'); // Validate certificate chain. polHttps := Default(HTTPSPolicyCallbackData); polHttps.cbSize := SizeOf(HTTPSPolicyCallbackData); polHttps.dwAuthType := AUTHTYPE_SERVER; polHttps.fdwChecks := dwCertFlags; polHttps.pwszServerName := PChar(szServerName); PolicyPara := Default(CERT_CHAIN_POLICY_PARA); PolicyPara.cbSize := SizeOf(PolicyPara); PolicyPara.pvExtraPolicyPara := @polHttps; PolicyStatus := Default(CERT_CHAIN_POLICY_STATUS); PolicyStatus.cbSize := SizeOf(PolicyStatus); if not CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, pChainContext, @PolicyPara, @PolicyStatus) then raise ErrWinAPI('@ VerifyServerCertificate', 'CertVerifyCertificateChainPolicy'); // Note dwError is unsigned while SECURITY_STATUS is signed so typecast to suppress Range check error if PolicyStatus.dwError <> NO_ERROR then raise ErrSecStatus('@ VerifyServerCertificate', 'CertVerifyCertificateChainPolicy', SECURITY_STATUS(PolicyStatus.dwError), WinVerifyTrustErrorStr(PolicyStatus.dwError)); finally if pChainContext <> nil then CertFreeCertificateChain(pChainContext); end; end; function GetCertContext(const hContext: CtxtHandle): PCCERT_CONTEXT; var Status: SECURITY_STATUS; begin // Authenticate server's credentials. Get server's certificate. Status := g_pSSPI.QueryContextAttributesW(@hContext, SECPKG_ATTR_REMOTE_CERT_CONTEXT, @Result); if Status <> SEC_E_OK then raise ErrSecStatus('@ GetCertContext', 'QueryContextAttributesW', Status); end; function GetCurrentCert(const hContext: CtxtHandle): TBytes; var pRemoteCertContext: PCCERT_CONTEXT; begin pRemoteCertContext := GetCertContext(hContext); SetLength(Result, pRemoteCertContext.cbCertEncoded); Move(pRemoteCertContext.pbCertEncoded^, Pointer(Result)^, pRemoteCertContext.cbCertEncoded); CertFreeCertificateContext(pRemoteCertContext); end; function CheckServerCert(const hContext: CtxtHandle; const ServerName: string; const TrustedCerts: TTrustedCerts; CertCheckIgnoreFlags: TCertCheckIgnoreFlags): TCertCheckResult; var pRemoteCertContext: PCCERT_CONTEXT; dwCertFlags: DWORD; IgnFlag: TCertCheckIgnoreFlag; begin // Authenticate server's credentials. Get server's certificate. pRemoteCertContext := GetCertContext(hContext); try // Don't check the cert if it's trusted if TrustedCerts <> nil then if TrustedCerts.Contains(ServerName, pRemoteCertContext.pbCertEncoded, pRemoteCertContext.cbCertEncoded) then Exit(ccrTrusted); // Construct flags // If server name is not defined, ignore check for "common name" if ServerName = '' then Include(CertCheckIgnoreFlags, ignCertCNInvalid); dwCertFlags := 0; for IgnFlag in CertCheckIgnoreFlags do case IgnFlag of ignRevokation: dwCertFlags := dwCertFlags or SECURITY_FLAG_IGNORE_REVOCATION; ignUnknownCA: dwCertFlags := dwCertFlags or SECURITY_FLAG_IGNORE_UNKNOWN_CA; ignWrongUsage: dwCertFlags := dwCertFlags or SECURITY_FLAG_IGNORE_WRONG_USAGE; ignCertCNInvalid: dwCertFlags := dwCertFlags or SECURITY_FLAG_IGNORE_CERT_CN_INVALID; ignCertDateInvalid: dwCertFlags := dwCertFlags or SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; end; // Attempt to validate server certificate. VerifyServerCertificate(pRemoteCertContext, ServerName, dwCertFlags); finally // Free the server certificate context. CertFreeCertificateContext(pRemoteCertContext); end; if dwCertFlags <> 0 then Result := ccrValidWithFlags else Result := ccrValid; end; function CheckServerCert(const hContext: CtxtHandle; const SessionData: TSessionData): TCertCheckResult; begin Result := CheckServerCert(hContext, SessionData.ServerName, SessionData.TrustedCerts, SessionData.CertCheckIgnoreFlags); end; procedure DeleteContext(var hContext: CtxtHandle); begin g_pSSPI.DeleteSecurityContext(@hContext); hContext := Default(CtxtHandle); end; // ~~ Data exchange ~~ procedure InitBuffers(const hContext: CtxtHandle; out pbIoBuffer: TBytes; out Sizes: SecPkgContext_StreamSizes); var scRet: SECURITY_STATUS; begin // Read stream encryption properties. scRet := g_pSSPI.QueryContextAttributesW(@hContext, SECPKG_ATTR_STREAM_SIZES, @Sizes); if scRet <> SEC_E_OK then raise ErrSecStatus('@ InitBuffers', 'QueryContextAttributesW', scRet); // Create a buffer. SetLength(pbIoBuffer, Sizes.cbHeader + Sizes.cbMaximumMessage + Sizes.cbTrailer); end; procedure EncryptData(const hContext: CtxtHandle; const Sizes: SecPkgContext_StreamSizes; pbMessage: PByte; cbMessage: DWORD; pbIoBuffer: PByte; pbIoBufferLength: DWORD; out cbWritten: DWORD); var scRet: SECURITY_STATUS; Msg: SecBufferDesc; Buffers: array[0..3] of SecBuffer; begin if cbMessage > Sizes.cbMaximumMessage then raise Error('Message size %d is greater than maximum allowed %d', [cbMessage, Sizes.cbMaximumMessage]); if pbIoBufferLength < Sizes.cbHeader + cbMessage + Sizes.cbTrailer then raise Error('Buffer size %d is lesser than required for message with length %d', [pbIoBufferLength, cbMessage]); Move(pbMessage^, (pbIoBuffer + Sizes.cbHeader)^, cbMessage); // Offset by "header size" pbMessage := (pbIoBuffer + Sizes.cbHeader); // pointer to copy of message // Encrypt the data Buffers[0].cbBuffer := Sizes.cbHeader; // length of header Buffers[0].BufferType := SECBUFFER_STREAM_HEADER; // Type of the buffer Buffers[0].pvBuffer := pbIoBuffer; // Pointer to buffer 1 Buffers[1].cbBuffer := cbMessage; // length of the message Buffers[1].BufferType := SECBUFFER_DATA; // Type of the buffer Buffers[1].pvBuffer := pbMessage; // Pointer to buffer 2 Buffers[2].cbBuffer := Sizes.cbTrailer; // length of the trailer Buffers[2].BufferType := SECBUFFER_STREAM_TRAILER; // Type of the buffer Buffers[2].pvBuffer := pbMessage + cbMessage; // Pointer to buffer 3 Buffers[3] := Default(SecBuffer); Buffers[3].BufferType := SECBUFFER_EMPTY; // Type of the buffer 4 Msg.ulVersion := SECBUFFER_VERSION; // Version number Msg.cBuffers := Length(Buffers); // Number of buffers - must contain four SecBuffer structures. Msg.pBuffers := @Buffers; // Pointer to array of buffers scRet := g_pSSPI.EncryptMessage(@hContext, 0, @Msg, 0); // must contain four SecBuffer structures. if Failed(scRet) then raise ErrSecStatus('@ EncryptData', 'EncryptMessage', scRet); // Resulting Buffers: header, data, trailer cbWritten := Buffers[0].cbBuffer + Buffers[1].cbBuffer + Buffers[2].cbBuffer; if cbWritten = 0 then raise ErrSecStatus('@ EncryptData', 'EncryptMessage', SEC_E_INTERNAL_ERROR, 'zero data'); end; function DecryptData(const hContext: CtxtHandle; const Sizes: SecPkgContext_StreamSizes; pbIoBuffer: PByte; var cbEncData: DWORD; pbDecData: PByte; cbDecDataLength: DWORD; out cbWritten: DWORD): SECURITY_STATUS; var Msg: SecBufferDesc; Buffers: array[0..3] of SecBuffer; i, DataBufferIdx, ExtraBufferIdx: Integer; cbCurrEncData: DWORD; pbCurrIoBuffer: PByte; Dummy: Cardinal; begin cbWritten := 0; cbCurrEncData := cbEncData; pbCurrIoBuffer := pbIoBuffer; // Decrypt the received data. repeat Buffers[0].cbBuffer := cbCurrEncData; Buffers[0].BufferType := SECBUFFER_DATA; // Initial Type of the buffer 1 Buffers[0].pvBuffer := pbCurrIoBuffer; Buffers[1] := Default(SecBuffer); Buffers[1].BufferType := SECBUFFER_EMPTY; // Initial Type of the buffer 2 Buffers[2] := Default(SecBuffer); Buffers[2].BufferType := SECBUFFER_EMPTY; // Initial Type of the buffer 3 Buffers[3] := Default(SecBuffer); Buffers[3].BufferType := SECBUFFER_EMPTY; // Initial Type of the buffer 4 Msg.ulVersion := SECBUFFER_VERSION; // Version number Msg.cBuffers := Length(Buffers); // Number of buffers - must contain four SecBuffer structures. Msg.pBuffers := @Buffers; // Pointer to array of buffers Result := g_pSSPI.DecryptMessage(@hContext, @Msg, 0, Dummy); if Result = SEC_I_CONTEXT_EXPIRED then Break; // Server signaled end of session if (Result <> SEC_E_OK) and (Result <> SEC_E_INCOMPLETE_MESSAGE) and (Result <> SEC_I_RENEGOTIATE) then raise ErrSecStatus('@ DecryptData - unexpected result', 'DecryptMessage', Result); // After DecryptMessage data is still in the Buffers // Buffer with type DATA contains decrypted data // Buffer with type EXTRA contains remaining (unprocessed) data DataBufferIdx := 0; ExtraBufferIdx := 0; for i := Low(Buffers) to High(Buffers) do case Buffers[i].BufferType of SECBUFFER_DATA : DataBufferIdx := i; SECBUFFER_EXTRA: ExtraBufferIdx := i; end; if Result = SEC_E_INCOMPLETE_MESSAGE then begin Assert(DataBufferIdx = 0); Assert(ExtraBufferIdx = 0); // move remaining extra data to the beginning of buffer and exit Move(pbCurrIoBuffer^, pbIoBuffer^, cbCurrEncData); cbEncData := cbCurrEncData; Break; end; // Move received data to destination if present if DataBufferIdx <> 0 then begin // check output buf space remaining if cbDecDataLength < Buffers[DataBufferIdx].cbBuffer then Break; Move(Buffers[DataBufferIdx].pvBuffer^, pbDecData^, Buffers[DataBufferIdx].cbBuffer); Inc(pbDecData, Buffers[DataBufferIdx].cbBuffer); Inc(cbWritten, Buffers[DataBufferIdx].cbBuffer); Dec(cbDecDataLength, Buffers[DataBufferIdx].cbBuffer); end // No data decrypted - move remaining extra data to the beginning of buffer and exit else begin if ExtraBufferIdx <> 0 then begin Move(Buffers[ExtraBufferIdx].pvBuffer^, pbIoBuffer^, Buffers[ExtraBufferIdx].cbBuffer); cbEncData := Buffers[ExtraBufferIdx].cbBuffer; end else cbEncData := 0; // all data processed Break; end; // Move pointers to the extra buffer to process it in the next iteration if ExtraBufferIdx <> 0 then begin pbCurrIoBuffer := Buffers[ExtraBufferIdx].pvBuffer; cbCurrEncData := Buffers[ExtraBufferIdx].cbBuffer; end // No unprocessed data - break the loop else begin cbEncData := 0; // all data processed Break; end; // The server wants to perform another handshake sequence. if Result = SEC_I_RENEGOTIATE then Break; until False; end; initialization finalization Fin; {$ENDIF MSWINDOWS} end.
unit FindUnit.Utils; interface uses IOUtils, Classes, SimpleParser.Lexer.Types, TlHelp32, Windows; type TIncludeHandler = class(TInterfacedObject, IIncludeHandler) private FPath: string; public constructor Create(const Path: string); function GetIncludeFileContent(const FileName: string): string; end; TPathConverter = class(TObject) private const VAR_INIT = '$('; VAR_END = ')'; public class function ConvertPathsToFullPath(Paths: string): string; end; function GetAllFilesFromPath(const Path, Filter: string): TStringList; function GetAllPasFilesFromPath(const Path: string): TStringList; function GetAllDcuFilesFromPath(const Path: string): TStringList; function Fetch(var AInput: string; const ADelim: string = ''; const ADelete: Boolean = True; const ACaseSensitive: Boolean = False): string; inline; function IsProcessRunning(const AExeFileName: string): Boolean; function GetHashCodeFromStr(Str: PChar): Integer; var FindUnitDir: string; FindUnitDirLogger: string; FindUnitDcuDir: string; DirRealeaseWin32: string; implementation uses Types, SysUtils, Log4PAscal; function GetHashCodeFromStr(Str: PChar): Integer; var Off, Len, Skip, I: Integer; begin Result := 0; Off := 1; Len := StrLen(Str); if Len < 16 then for I := (Len - 1) downto 0 do begin Result := (Result * 37) + Ord(Str[Off]); Inc(Off); end else begin { Only sample some characters } Skip := Len div 8; I := Len - 1; while I >= 0 do begin Result := (Result * 39) + Ord(Str[Off]); Dec(I, Skip); Inc(Off, Skip); end; end; end; function IsProcessRunning(const AExeFileName: string): Boolean; var Continuar: BOOL; SnapshotHandle: THandle; Entry: TProcessEntry32; begin Result := False; try SnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); Entry.dwSize := SizeOf(Entry); Continuar := Process32First(SnapshotHandle, Entry); while Integer(Continuar) <> 0 do begin if ((UpperCase(ExtractFileName(Entry.szExeFile)) = UpperCase(AExeFileName)) or (UpperCase(Entry.szExeFile) = UpperCase(AExeFileName))) then begin Result := True; end; Continuar := Process32Next(SnapshotHandle, Entry); end; CloseHandle(SnapshotHandle); except Result := False; end; end; function FetchCaseInsensitive(var AInput: string; const ADelim: string; const ADelete: Boolean): string; inline; var LPos: Integer; begin if ADelim = #0 then begin LPos := Pos(ADelim, AInput); end else begin LPos := Pos(UpperCase(ADelim), UpperCase(AInput)); end; if LPos = 0 then begin Result := AInput; if ADelete then begin AInput := ''; end; end else begin Result := Copy(AInput, 1, LPos - 1); if ADelete then AInput := Copy(AInput, LPos + Length(ADelim), MaxInt); end; end; function Fetch(var AInput: string; const ADelim: string = ''; const ADelete: Boolean = True; const ACaseSensitive: Boolean = False): string; inline; var LPos: Integer; begin if ACaseSensitive then begin LPos := Pos(ADelim, AInput); if LPos = 0 then begin Result := AInput; if ADelete then AInput := ''; end else begin Result := Copy(AInput, 1, LPos - 1); if ADelete then begin // slower Delete(AInput, 1, LPos + Length(ADelim) - 1); because the // remaining part is larger than the deleted AInput := Copy(AInput, LPos + Length(ADelim), MaxInt); end; end; end else begin Result := FetchCaseInsensitive(AInput, ADelim, ADelete); end; end; function GetAllFilesFromPath(const Path, Filter: string): TStringList; var Files: TStringDynArray; FilePath: string; begin Files := IOUtils.TDirectory.GetFiles(Path, Filter, TSearchOption.soTopDirectoryOnly); Result := TStringList.Create; for FilePath in Files do Result.Add(FilePath); end; function GetAllDcuFilesFromPath(const Path: string): TStringList; begin Result := GetAllFilesFromPath(Path, '*.dcu'); end; function GetAllPasFilesFromPath(const Path: string): TStringList; begin Result := GetAllFilesFromPath(Path, '*.pas'); end; { TIncludeHandler } constructor TIncludeHandler.Create(const Path: string); begin inherited Create; FPath := Path; end; function TIncludeHandler.GetIncludeFileContent(const FileName: string): string; var FileContent: TStringList; begin FileContent := TStringList.Create; try FileContent.LoadFromFile(TPath.Combine(FPath, FileName)); Result := FileContent.Text; finally FileContent.Free; end; end; procedure CarregarPaths; begin FindUnitDir := GetEnvironmentVariable('APPDATA') + '\DelphiFindUnit\'; FindUnitDirLogger := FindUnitDir + 'Logger\'; FindUnitDcuDir := FindUnitDir + IntToStr(GetHashCodeFromStr(PChar(ParamStr(0)))) + '\'; FindUnitDcuDir := FindUnitDcuDir + 'DecompiledDcus\'; ForceDirectories(FindUnitDir); ForceDirectories(FindUnitDcuDir); ForceDirectories(FindUnitDirLogger); DirRealeaseWin32 := ExtractFilePath(ParamStr(0)); DirRealeaseWin32 := StringReplace(DirRealeaseWin32,'\bin','\lib\win32\release',[rfReplaceAll, rfIgnoreCase]); end; { TPathConverter } class function TPathConverter.ConvertPathsToFullPath(Paths: string): string; var CurVariable: string; CurPaths: string; FullPath: string; begin while Pos(VAR_INIT, Paths) > 0 do begin CurPaths := Paths; Fetch(CurPaths, VAR_INIT); CurVariable := Fetch(CurPaths, VAR_END, False); Logger.Debug('TPathConverter.ConvertPathsToFullPath: %s', [CurVariable]); FullPath := GetEnvironmentVariable(CurVariable); Paths := StringReplace(Paths, VAR_INIT + CurVariable + VAR_END, FullPath, [rfReplaceAll]); end; Result := Paths; end; initialization CarregarPaths; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Schemas.Swagger; interface uses System.SysUtils, System.Classes, System.JSON, System.Generics.Collections, System.Rtti, WiRL.Core.Application, WiRL.Core.Engine, WiRL.Core.Context, WiRL.Core.Registry, WiRL.Core.Attributes, WiRL.http.Accept.MediaType, WiRL.Rtti.Utils, WiRL.http.Filters; type TSwaggerSchemaCompiler = class public class procedure SetTypeProperties(AType: TRttiObject; AJSON: TJSONObject); static; end; [PreMatching] TSwaggerFilter = class(TInterfacedObject, IWiRLContainerRequestFilter) private const SwaggerVersion = '2.0'; function GetPath(ARttiObject: TRttiObject): string; procedure BuildSwagger(AContext: TWiRLContext; ASwagger: TJSONObject); procedure AddApplicationResource(APaths: TJSONObject; AApplication: TWiRLApplication); procedure AddResource(APaths: TJSONObject; AApplication: TWiRLApplication; LResource: TClass); procedure AddOperation(AJsonPath: TJSONObject; const AMethodName: string; AResourceMethod: TRttiMethod); function CreateParameter(ARttiParameter: TRttiParameter): TJSONObject; public procedure Filter(ARequestContext: TWiRLContainerRequestContext); end; function ExistsInArray(AArray: TJSONArray; const AValue: string): Boolean; function IncludeLeadingSlash(const AValue: string): string; implementation uses System.StrUtils, System.TypInfo, WiRL.http.Server, WiRL.Core.JSON; function ExistsInArray(AArray: TJSONArray; const AValue: string): Boolean; var LValue: TJSONValue; begin for LValue in AArray do begin if LValue.Value.Equals(AValue) then Exit(True); end; Result := False; end; function IncludeLeadingSlash(const AValue: string): string; begin if not AValue.StartsWith('/') then Result := '/' + AValue else Result := AValue; end; { TSwaggerFilter } procedure TSwaggerFilter.AddApplicationResource(APaths: TJSONObject; AApplication: TWiRLApplication); var LResourceName: string; LResource: TClass; begin // Loop on every resource of the application for LResourceName in AApplication.Resources.Keys do begin LResource := AApplication.GetResourceInfo(LResourceName).TypeTClass; AddResource(APaths, AApplication, LResource); end; end; procedure TSwaggerFilter.AddResource(APaths: TJSONObject; AApplication: TWiRLApplication; LResource: TClass); function FindOrCreatePath(APaths: TJSONObject; const AResourcePath: string): TJSONObject; begin Result := APaths.GetValue(AResourcePath) as TJSONObject; if not Assigned(Result) then begin Result := TJSONObject.Create; APaths.AddPair(AResourcePath, Result); end; end; var LMethodPath: string; LResourcePath: string; LResourceType: TRttiType; LResourceMethod: TRttiMethod; LMethodName: string; LResourceMethodPath: string; LJsonPath: TJSONObject; begin LResourceType := TRttiHelper.Context.GetType(LResource); LResourcePath := GetPath(LResourceType); if LResourcePath <> '' then begin // Loop on every method of the current resource object for LResourceMethod in LResourceType.GetMethods do begin LMethodName := ''; TRttiHelper.HasAttribute<HttpMethodAttribute>(LResourceMethod, procedure (AAttr: HttpMethodAttribute) begin LMethodName := AAttr.ToString.ToLower; end ); if LMethodName <> '' then begin LResourceMethodPath := GetPath(LResourceMethod); LMethodPath := IncludeLeadingSlash((AApplication.Engine as TWiRLEngine).BasePath) + IncludeLeadingSlash(AApplication.BasePath) + IncludeLeadingSlash(LResourcePath); if (not LMethodPath.EndsWith('/')) and (not LResourceMethodPath.StartsWith('/')) then LMethodPath := LMethodPath + '/'; LMethodPath := LMethodPath + LResourceMethodPath; // If the resource is already documented add the information on // the same json object LJsonPath := FindOrCreatePath(APaths, LMethodPath); AddOperation(LJsonPath, LMethodName, LResourceMethod); end; end; end; end; procedure TSwaggerFilter.BuildSwagger(AContext: TWiRLContext; ASwagger: TJSONObject); var LInfo: TJSONObject; LPaths: TJSONObject; LServer: TWiRLServer; LEngine: TWiRLCustomEngine; LAppInfo: TWiRLApplicationInfo; begin LServer := AContext.Server as TWiRLServer; // Info object LInfo := TJSONObject.Create; LInfo.AddPair('title', ChangeFileExt(ExtractFileName(ParamStr(0)), '')); LInfo.AddPair('version', '1.0'); // Paths object LPaths := TJSONObject.Create; for LEngine in LServer.Engines do begin if LEngine is TWiRLEngine then begin for LAppInfo in TWiRLEngine(LEngine).Applications do begin AddApplicationResource(LPaths, LAppInfo.Application); end; end; end; // Swagger object (root) ASwagger.AddPair('swagger', SwaggerVersion); ASwagger.AddPair('host', AContext.Request.Host); // ASwagger.AddPair('basePath', LEngine.BasePath); ASwagger.AddPair('info', LInfo); ASwagger.AddPair('paths', LPaths); end; procedure TSwaggerFilter.AddOperation(AJsonPath: TJSONObject; const AMethodName: string; AResourceMethod: TRttiMethod); function CreateResponseSchema(AResourceMethod: TRttiMethod): TJSONObject; begin Result := TJSONObject.Create; TSwaggerSchemaCompiler.SetTypeProperties(AResourceMethod.ReturnType, Result); end; function FindOrCreateOperation(APath: TJSONObject; const AMethodName: string) :TJSONObject; begin Result := APath.GetValue(AMethodName) as TJSONObject; if not Assigned(Result) then begin Result := TJSONObject.Create; AJsonPath.AddPair(AMethodName, Result); end; end; var LOperation: TJSONObject; LResponses: TJSONObject; LParameters: TJSONArray; LParameter: TJSONObject; LProduces: TJSONArray; LConsumes: TJSONArray; LRttiParameter: TRttiParameter; LOkResponse: TJSONObject; begin // Operation = Path+HttpMethod // If more object method use the same operation add info on the // same operation LOperation := FindOrCreateOperation(AJsonPath, AMethodName); if not Assigned(LOperation.GetValue('summary')) then LOperation.AddPair('summary', AResourceMethod.Name); LProduces := LOperation.GetValue('produces') as TJSONArray; TRttiHelper.HasAttribute<ProducesAttribute>(AResourceMethod, procedure (AAttr: ProducesAttribute) begin if not Assigned(LProduces) then begin LProduces := TJSONArray.Create; LOperation.AddPair('produces', LProduces); end; // Check if the produce already exists if not ExistsInArray(LProduces, AAttr.Value) then LProduces.Add(AAttr.Value); end ); LConsumes := LOperation.GetValue('consumes') as TJSONArray; TRttiHelper.HasAttribute<ConsumesAttribute>(AResourceMethod, procedure (AAttr: ConsumesAttribute) begin if not Assigned(LConsumes) then begin LConsumes := TJSONArray.Create; LOperation.AddPair('consumes', LConsumes); end; // Check if the consume already exists if not ExistsInArray(LConsumes, AAttr.Value) then LConsumes.Add(AAttr.Value); end ); if not Assigned(LOperation.GetValue('parameters')) then begin LParameters := nil; for LRttiParameter in AResourceMethod.GetParameters do begin if not Assigned(LParameters) then begin LParameters := TJSONArray.Create; LOperation.AddPair('parameters', LParameters) end; LParameter := CreateParameter(LRttiParameter); if Assigned(LParameter) then LParameters.Add(LParameter); end; end; if not Assigned(LOperation.GetValue('responses')) then begin LResponses := TJSONObject.Create; LOperation.AddPair('responses', LResponses); LOkResponse := TJSONObject.Create(TJSONPair.Create('description', 'Ok')); LResponses.AddPair('200', LOkResponse); LResponses.AddPair('default', TJSONObject.Create(TJSONPair.Create('description', 'Error'))); if Assigned(AResourceMethod.ReturnType) and (AResourceMethod.ReturnType.TypeKind <> tkUnknown) then LOkResponse.AddPair('schema', CreateResponseSchema(AResourceMethod)); end; end; function TSwaggerFilter.CreateParameter(ARttiParameter: TRttiParameter): TJSONObject; function GetParamPosition(ARttiParameter: TRttiParameter): string; begin if TRttiHelper.HasAttribute<PathParamAttribute>(ARttiParameter) then Result := 'path' else if TRttiHelper.HasAttribute<QueryParamAttribute>(ARttiParameter) then Result := 'query' else if TRttiHelper.HasAttribute<FormParamAttribute>(ARttiParameter) then Result := 'formData' else if TRttiHelper.HasAttribute<HeaderParamAttribute>(ARttiParameter) then Result := 'header' else if TRttiHelper.HasAttribute<BodyParamAttribute>(ARttiParameter) then Result := 'body' else Result := '' end; function GetParamName(ARttiParameter: TRttiParameter): string; var LParam: MethodParamAttribute; begin LParam := TRttiHelper.FindAttribute<MethodParamAttribute>(ARttiParameter); if Assigned(LParam) then Result := LParam.Value else Result := ARttiParameter.Name; end; function GetParamSchema(ARttiParameter: TRttiParameter): TJSONObject; begin Result := TJSONObject.Create; Result.AddPair('type', 'string'); Result.AddPair('format', 'byte'); end; var LParameter: TJSONObject; LParamType: string; begin LParamType := GetParamPosition(ARttiParameter); if LParamType <> '' then begin LParameter := TJSONObject.Create; LParameter.AddPair(TJSONPair.Create('name', GetParamName(ARttiParameter))); LParameter.AddPair(TJSONPair.Create('in', LParamType)); if LParamType = 'path' then LParameter.AddPair(TJSONPair.Create('required', TJSONTrue.Create)) else LParameter.AddPair(TJSONPair.Create('required', TJSONFalse.Create)); if LParamType <> 'body' then begin TSwaggerSchemaCompiler.SetTypeProperties(ARttiParameter, LParameter); end else begin LParameter.AddPair(TJSONPair.Create('schema', GetParamSchema(ARttiParameter))); end; end else LParameter := nil; Result := LParameter; end; procedure TSwaggerFilter.Filter(ARequestContext: TWiRLContainerRequestContext); var LSwagger: TJSONObject; begin if ARequestContext.Request.PathInfo.StartsWith('/swagger') then begin LSwagger := TJSONObject.Create; try BuildSwagger(ARequestContext.Context, LSwagger); ARequestContext.Response.ContentType := TMediaType.APPLICATION_JSON; ARequestContext.Response.Content := TJSONHelper.ToJSON(LSwagger); ARequestContext.Abort; finally LSwagger.Free; end; end; end; function TSwaggerFilter.GetPath(ARttiObject: TRttiObject): string; var LPath: string; begin LPath := ''; TRttiHelper.HasAttribute<PathAttribute>(ARttiObject, procedure (AAttr: PathAttribute) begin LPath := AAttr.Value; end ); Result := LPath; end; { TSwaggerSchemaCompiler } class procedure TSwaggerSchemaCompiler.SetTypeProperties(AType: TRttiObject; AJSON: TJSONObject); var LTypeKind: TTypeKind; LPTypeInfo: PTypeInfo; begin LPTypeInfo := PTypeInfo(AType.Handle); LTypeKind := PTypeInfo(AType.Handle)^.Kind; case LTypeKind of tkInteger, tkInt64: begin AJSON.AddPair(TJSONPair.Create('type', 'integer')); end; tkClass, tkRecord: begin AJSON.AddPair(TJSONPair.Create('type', 'object')); end; tkDynArray, tkArray: begin AJSON.AddPair(TJSONPair.Create('type', 'array')); end; tkEnumeration: begin if (LPTypeInfo = System.TypeInfo(Boolean)) then AJSON.AddPair(TJSONPair.Create('type', 'boolean')) else AJSON.AddPair(TJSONPair.Create('type', 'string')); end; tkFloat: begin if (LPTypeInfo = System.TypeInfo(TDateTime)) then begin AJSON.AddPair(TJSONPair.Create('type', 'string')); AJSON.AddPair(TJSONPair.Create('format', 'date-time')); end else if (LPTypeInfo = System.TypeInfo(TDate)) then begin AJSON.AddPair(TJSONPair.Create('type', 'string')); AJSON.AddPair(TJSONPair.Create('format', 'date')); end else if (LPTypeInfo = System.TypeInfo(TTime)) then begin AJSON.AddPair(TJSONPair.Create('type', 'string')); AJSON.AddPair(TJSONPair.Create('format', 'date-time')); end else AJSON.AddPair(TJSONPair.Create('type', 'number')); end; else AJSON.AddPair(TJSONPair.Create('type', 'string')); end; end; initialization TWiRLFilterRegistry.Instance.RegisterFilter<TSwaggerFilter>; end.
{ iOS NOB-designer for the Lazarus IDE Copyright (C) 2012 Joost van der Sluis joost@cnoc.nl 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 iOSNIBDesigner; {$mode objfpc}{$H+} {$typeinfo off} interface uses LCLProc, LCLType, Classes, SysUtils, FormEditingIntf, LCLIntf, Graphics, propedits, CodeToolManager, ProjectIntf, iOS_Views, dom, IDEIntf, IDEWindowIntf, LazIDEIntf, Dialogs, Controls, ComponentReg, typinfo, forms; type { TNSObjectDesignerMediator } TNSObjectDesignerMediator = class(TDesignerMediator,IMyWidgetDesigner) private FMyForm: NSObject; protected // This method is available through IMyWidgetDesigner and is used to // clear the MyForm variable when the form is destroyed. This is necessary // because it could be that this mediator is destroyed somewhat later, // which could lead into problems. procedure ClearMyForm; public function UseRTTIForMethods(aComponent: TComponent): boolean; override; // needed by the lazarus form editor class function CreateMediator(TheOwner, aForm: TComponent): TDesignerMediator; override; class function FormClass: TComponentClass; override; procedure GetBounds(AComponent: TComponent; out CurBounds: TRect); override; procedure SetBounds(AComponent: TComponent; NewBounds: TRect); override; procedure GetClientArea(AComponent: TComponent; out CurClientArea: TRect; out ScrollOffset: TPoint); override; procedure Paint; override; function ComponentIsIcon(AComponent: TComponent): boolean; override; function ParentAcceptsChild(Parent: TComponent; Child: TComponentClass): boolean; override; procedure InitComponent(AComponent, NewParent: TComponent; NewBounds: TRect); override; function CreateComponent(ParentComp: TComponent; TypeClass: TComponentClass; const AUnitName: shortstring; X,Y,W,H: Integer; DisableAutoSize: boolean): TComponent; public // needed by UIView constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InvalidateRect(Sender: TObject; ARect: TRect; Erase: boolean); property MyForm: NSObject read FMyForm; end; { TUIResponderDesignerMediator } TUIResponderDesignerMediator = class(TNSObjectDesignerMediator) public class function FormClass: TComponentClass; override; end; { TiOSMethodPropertyEditor } TiOSMethodPropertyEditor = class(TMethodPropertyEditor) public procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const NewValue: ansistring); override; end; procedure Register; implementation {$R iosdesigner.res} uses ObjInspStrConsts; type { TiOSEventHandlers } TiOSEventHandlers = class private FUpdateVisibleHandlerSet: boolean; FUpdateVisibleHandlerDesignerSet: boolean; public constructor create; destructor destroy; procedure ChangeLookupRoot; procedure HandlerUpdateVisible(AComponent: TRegisteredComponent; var VoteVisible: integer); procedure HandlerUpdateVisibleDesigner(AComponent: TRegisteredComponent; var VoteVisible: integer); end; var GiOSEventHandlers: TiOSEventHandlers = nil; procedure Register; procedure SetFakeUnitname(AClass: TClass); var ATypInfo: PTypeInfo; ATypData: PTypeData; begin ATypInfo:=PTypeInfo(AClass.ClassInfo); ATypData:=GetTypeData(ATypInfo); ATypData^.UnitName[1]:='i'; ATypData^.UnitName[2]:='P'; ATypData^.UnitName[3]:='h'; ATypData^.UnitName[4]:='o'; ATypData^.UnitName[5]:='n'; ATypData^.UnitName[6]:='e'; ATypData^.UnitName[7]:='A'; ATypData^.UnitName[8]:='l'; ATypData^.UnitName[9]:='l'; end; begin FormEditingHook.RegisterDesignerMediator(TNSObjectDesignerMediator); FormEditingHook.RegisterDesignerMediator(TUIResponderDesignerMediator); RegisterComponents('iOS-Windows && Bars',[UIWindow, UISearchBar, UIView, UIxcodePlaceholder]); RegisterComponents('iOS-Data Views',[UITableView, UITextField]); RegisterComponents('iOS-Controls',[UIButton, UILabel, UIProgressView, UISegmentedControl]); RegisterComponents('iOS-Objects & Controllers',[UINavigationController, UIViewController]); GiOSEventHandlers := TiOSEventHandlers.Create; RegisterClass(UINavigationItem); RegisterClass(UIViewController); RegisterClass(UINavigationBar); RegisterPropertyEditor(FindPropInfo(UIButton, 'onTouchDown')^.PropType , tiOSFakeComponent,'onTouchDown',TiOSMethodPropertyEditor); // This is a hack to overwrite the unitname RTTI-information of these objects. // This is to make sure that the Codetools add the right unit-name to the // source when an object is added to the NIB-file. SetFakeUnitname(UIButton); SetFakeUnitname(UILabel); SetFakeUnitname(UITextField); SetFakeUnitname(UITableView); SetFakeUnitname(UISearchBar); SetFakeUnitname(UIWindow); SetFakeUnitname(UIView); SetFakeUnitname(UINavigationController); SetFakeUnitname(UIViewController); SetFakeUnitname(UIProgressView); SetFakeUnitname(UISegmentedControl); SetFakeUnitname(UIxcodePlaceholder); end; { TiOSEventHandlers } constructor TiOSEventHandlers.create; begin GlobalDesignHook.AddHandlerChangeLookupRoot(@ChangeLookupRoot); end; destructor TiOSEventHandlers.destroy; begin GlobalDesignHook.RemoveAllHandlersForObject(self); end; procedure TiOSEventHandlers.ChangeLookupRoot; begin if GlobalDesignHook.LookupRoot is tiOSFakeComponent then begin if not FUpdateVisibleHandlerDesignerSet then begin IDEComponentPalette.AddHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisibleDesigner); FUpdateVisibleHandlerDesignerSet := true; end; if FUpdateVisibleHandlerSet then begin IDEComponentPalette.RemoveHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisible); FUpdateVisibleHandlerSet := false; end; end else if assigned(GlobalDesignHook.LookupRoot) then begin if FUpdateVisibleHandlerDesignerSet then begin IDEComponentPalette.RemoveHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisibleDesigner); FUpdateVisibleHandlerDesignerSet := False; end; if not FUpdateVisibleHandlerSet then begin IDEComponentPalette.AddHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisible); FUpdateVisibleHandlerSet := true; end; end else begin if FUpdateVisibleHandlerDesignerSet then begin IDEComponentPalette.RemoveHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisibleDesigner); FUpdateVisibleHandlerDesignerSet := False; end; if FUpdateVisibleHandlerSet then begin IDEComponentPalette.RemoveHandlerUpdateVisible(@GiOSEventHandlers.HandlerUpdateVisible); FUpdateVisibleHandlerSet := false; end; end; end; procedure TiOSEventHandlers.HandlerUpdateVisible( AComponent: TRegisteredComponent; var VoteVisible: integer); begin if assigned(AComponent) and assigned(AComponent.ComponentClass) and AComponent.ComponentClass.InheritsFrom(tiOSFakeComponent) then dec(VoteVisible); end; procedure TiOSEventHandlers.HandlerUpdateVisibleDesigner( AComponent: TRegisteredComponent; var VoteVisible: integer); begin if not AComponent.ComponentClass.InheritsFrom(tiOSFakeComponent) then dec(VoteVisible); end; { TiOSMethodPropertyEditor } procedure TiOSMethodPropertyEditor.GetValues(Proc: TGetStrProc); begin proc(oisNone); end; procedure TiOSMethodPropertyEditor.SetValue(const NewValue: ansistring); var CreateNewMethod: Boolean; CurValue: string; NewMethodExists, NewMethodIsCompatible, NewMethodIsPublished, NewIdentIsMethod: boolean; IsNil: Boolean; NewMethod: TMethod; begin CurValue := GetValue; if CurValue = NewValue then exit; //DebugLn('### TMethodPropertyEditor.SetValue A OldValue="',CurValue,'" NewValue=',NewValue); IsNil := (NewValue='') or (NewValue=oisNone); if (not IsNil) and (not IsValidIdent(NewValue)) then begin MessageDlg(oisIncompatibleIdentifier, Format(oisIsNotAValidMethodName,['"',NewValue,'"']), mtError, [mbCancel, mbIgnore], 0); exit; end; NewMethodExists := (not IsNil); {and PropertyHook.CompatibleMethodExists(NewValue, GetInstProp, NewMethodIsCompatible, NewMethodIsPublished, NewIdentIsMethod);} //DebugLn('### TMethodPropertyEditor.SetValue B NewMethodExists=',NewMethodExists,' NewMethodIsCompatible=',NewMethodIsCompatible,' ',NewMethodIsPublished,' ',NewIdentIsMethod); { if NewMethodExists then begin if not NewIdentIsMethod then begin if MessageDlg(oisIncompatibleIdentifier, Format(oisTheIdentifierIsNotAMethodPressCancelToUndoPressIgn, ['"', NewValue, '"', LineEnding, LineEnding]), mtWarning, [mbCancel, mbIgnore], 0)<>mrIgnore then exit; end; if not NewMethodIsPublished then begin if MessageDlg(oisIncompatibleMethod, Format(oisTheMethodIsNotPublishedPressCancelToUndoPressIgnor, ['"', NewValue, '"', LineEnding, LineEnding]), mtWarning, [mbCancel, mbIgnore], 0)<>mrIgnore then exit; end; if not NewMethodIsCompatible then begin if MessageDlg(oisIncompatibleMethod, Format(oisTheMethodIsIncompatibleToThisEventPressCancelToUnd, ['"', NewValue, '"', GetName, LineEnding, LineEnding]), mtWarning, [mbCancel, mbIgnore], 0)<>mrIgnore then exit; end; end; } //DebugLn('### TMethodPropertyEditor.SetValue C'); if IsNil then begin NewMethod.Data := nil; NewMethod.Code := nil; SetMethodValue(NewMethod); end else if IsValidIdent(CurValue) and not NewMethodExists and not PropertyHook.MethodFromAncestor(GetMethodValue) then begin // rename the method // Note: // All other not selected properties that use this method, contain just // the TMethod record. So, changing the name in the jitform will change // all other event names in all other components automatically. PropertyHook.RenameMethod(CurValue, NewValue) end else begin //DebugLn('### TMethodPropertyEditor.SetValue E'); CreateNewMethod := not NewMethodExists; SetMethodValue( PropertyHook.CreateMethod(NewValue, GetPropType, GetComponent(0), GetPropertyPath(0))); //DebugLn('### TMethodPropertyEditor.SetValue F NewValue=',GetValue); if CreateNewMethod then begin //DebugLn('### TMethodPropertyEditor.SetValue G'); PropertyHook.ShowMethod(NewValue); end; end; //DebugLn('### TMethodPropertyEditor.SetValue END NewValue=',GetValue); end; { TNSObjectDesignerMediator } constructor TNSObjectDesignerMediator.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TNSObjectDesignerMediator.Destroy; begin if FMyForm<>nil then FMyForm.Designer:=nil; FMyForm:=nil; inherited Destroy; end; function TNSObjectDesignerMediator.UseRTTIForMethods(aComponent: TComponent): boolean; begin if aComponent is tiOSFakeComponent then result := true else Result:=inherited UseRTTIForMethods(aComponent); end; class function TNSObjectDesignerMediator.CreateMediator(TheOwner, aForm: TComponent): TDesignerMediator; var Mediator: TNSObjectDesignerMediator; begin Result:=inherited CreateMediator(TheOwner,aForm); Mediator:=Result as TNSObjectDesignerMediator; if assigned(result) and assigned(aForm) and (aForm is NSObject) then begin Mediator.FMyForm:=aForm as NSObject; Mediator.FMyForm.Designer:=Mediator as IMyWidgetDesigner; end; end; class function TNSObjectDesignerMediator.FormClass: TComponentClass; begin Result:=NSObject; end; procedure TNSObjectDesignerMediator.GetBounds(AComponent: TComponent; out CurBounds: TRect); var w: tiOSFakeComponent; begin if AComponent is tiOSFakeComponent then begin w:=tiOSFakeComponent(AComponent); CurBounds:=Bounds(w.Left,w.Top,w.Width,w.Height); end else inherited GetBounds(AComponent,CurBounds); end; procedure TNSObjectDesignerMediator.InvalidateRect(Sender: TObject; ARect: TRect; Erase: boolean); begin if (LCLForm=nil) or (not LCLForm.HandleAllocated) then exit; LCLIntf.InvalidateRect(LCLForm.Handle,@ARect,Erase); end; procedure TNSObjectDesignerMediator.ClearMyForm; begin FMyForm := nil; end; procedure TNSObjectDesignerMediator.SetBounds(AComponent: TComponent; NewBounds: TRect); begin if AComponent is tiOSFakeComponent then begin tiOSFakeComponent(AComponent).SetBounds(NewBounds.Left,NewBounds.Top, NewBounds.Right-NewBounds.Left,NewBounds.Bottom-NewBounds.Top); end else inherited SetBounds(AComponent,NewBounds); end; procedure TNSObjectDesignerMediator.GetClientArea(AComponent: TComponent; out CurClientArea: TRect; out ScrollOffset: TPoint); var Widget: tiOSFakeComponent; begin if AComponent is tiOSFakeComponent then begin Widget:=tiOSFakeComponent(AComponent); CurClientArea:=Rect(0,0, Widget.Width, Widget.Height); ScrollOffset:=Point(0,0); end else inherited GetClientArea(AComponent, CurClientArea, ScrollOffset); end; procedure TNSObjectDesignerMediator.Paint; procedure PaintWidget(AWidget: tiOSFakeComponent); var i: Integer; Child: tiOSFakeComponent; begin with LCLForm.Canvas do begin SaveHandleState; if AWidget is NSObject then begin Brush.Style:=bsClear; Brush.Color:=clLtGray; Pen.Color:=clMaroon; Rectangle(0,0,AWidget.Width,AWidget.Height); end else begin AWidget.Paint(LCLForm.Canvas); end; RestoreHandleState; // children if AWidget.ChildCount>0 then begin for i:=0 to AWidget.ChildCount-1 do begin SaveHandleState; Child:=AWidget.Children[i]; // clip child area MoveWindowOrgEx(Handle,Child.Left,Child.Top); if IntersectClipRect(Handle,0,0,Child.Width,Child.Height)<>NullRegion then PaintWidget(Child); RestoreHandleState; end; end; end; end; begin PaintWidget(MyForm); inherited Paint; end; function TNSObjectDesignerMediator.ComponentIsIcon(AComponent: TComponent): boolean; begin Result:=not (AComponent is tiOSFakeComponent); end; function TNSObjectDesignerMediator.ParentAcceptsChild(Parent: TComponent; Child: TComponentClass): boolean; begin Result:=(Parent is tiOSFakeComponent) and (Child.InheritsFrom(tiOSFakeComponent)) and (tiOSFakeComponent(Parent).AcceptChildsAtDesignTime); end; procedure TNSObjectDesignerMediator.InitComponent(AComponent, NewParent: TComponent; NewBounds: TRect); begin inherited InitComponent(AComponent, NewParent, NewBounds); if AComponent is tiOSFakeComponent then tiOSFakeComponent(AComponent).InitializeDefaults; end; function TNSObjectDesignerMediator.CreateComponent(ParentComp: TComponent; TypeClass: TComponentClass; const AUnitName: shortstring; X, Y, W, H: Integer; DisableAutoSize: boolean): TComponent; begin result := FormEditingHook.CreateComponent(ParentComp,TypeClass,AUnitName,x,y,w,h,DisableAutoSize); end; { TUIResponderDesignerMediator } class function TUIResponderDesignerMediator.FormClass: TComponentClass; begin Result:=UIResponder; end; end.
//This unit doesn't handle continue records. //I don't know a way to input a formula larger than one record. unit tmsUXlsFormulaParser; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsXlsMessages, tmsXlsFormulaMessages, tmsUFlxStack, tmsUXlsBaseRecords, SysUtils, tmsUXlsBaseRecordLists, tmsUFlxMessages, tmsUXlsReferences, tmsUXlsRowColEntries; //************************************************************ function RPNToString(const RPN: PArrayOfByte; const atPos: integer; const CellList: TCellList): UTF16String; //************************************************************ implementation //Returns an string token function GetString(const Length16Bit: boolean; const RPN: PArrayOfByte; const tpos: integer; var sl: integer): UTF16String; begin GetSimpleString(Length16Bit, RPN, tpos, false, 0, Result, sl); Result:=StringReplace(Result,'"','""', [rfReplaceAll]); end; function GetErrorText(const Err: byte): UTF16String; begin case Err of fmiErrNull: Result:=fmErrNull; $07: Result:=fmErrDiv0; $0F: Result:=fmErrValue; $17: Result:=fmErrRef; $1D: Result:=fmErrName; $24: Result:=fmErrNum; $2A: Result:=fmErrNA; else Result:=fmErrUnknown; end; //case end; function GetBoolText(const Bool: byte): UTF16String; begin if Bool=1 then Result:=fmTrue else Result:=fmFalse; end; function GetDouble(const RPN: PArrayOfByte; const tpos: integer): double; var d: double; begin move(RPN[tpos],d,sizeof(d)); Result:=d; end; function ReadCachedValueTxt(const RPN:PArrayOfByte; var ArrayPos: integer):UTF16String; var ValueType: byte; sl: integer; begin ValueType:=RPN[ArrayPos]; inc(ArrayPos); case ValueType of $01: begin; Result:=FmFloatToStr(GetDouble(RPN, ArrayPos));inc(ArrayPos, SizeOf(Double)); end; $02: begin; Result:=fmStr+GetString(true, RPN, ArrayPos, sl)+fmStr; inc(ArrayPos, sl); end; $04: begin; Result:=GetBoolText(RPN[ArrayPos]);inc(ArrayPos, 8); end; $10: begin; Result:=GetErrorText(RPN[ArrayPos]);inc(ArrayPos, 8); end; else raise Exception.CreateFmt(ErrBadToken,[ValueType]); end; //case end; function GetArrayText(const RPN: PArrayOfByte; const tpos: integer; var ArrayPos: integer):UTF16String; var Columns: integer; Rows: integer; r,c:integer; Sep: UTF16String; begin Columns:= RPN[ArrayPos]+1; Rows:=GetWord(RPN, ArrayPos+1)+1; inc(ArrayPos,3); Result:=fmOpenArray; Sep:=''; for r:=1 to Rows do begin for c:=1 to Columns do begin Result:=Result+Sep+ReadCachedValueTxt(RPN,ArrayPos); Sep:=fmArrayColSep; end; Sep:=fmArrayRowSep; end; Result:=Result+fmCloseArray; end; function Get1Ref(const Row, Col: integer): UTF16String; begin if Col and $4000=0 then Result:=fmAbsoluteRef else Result:=''; //Result:= Result+EncodeColumn(Col and $3FFF ); Result:= Result+EncodeColumn(((Col-1) and $FF)+1); //Error on excel docs!!! This is "and $FF" not "and $3FFF" if Col and $8000=0 then Result:= Result+fmAbsoluteRef; Result:= Result+IntToStr(Row); end; function GetRef(const RPN: PArrayOfByte; const tpos: integer):UTF16String; var Row, Col: integer; begin Row:=GetWord(RPN, tpos)+1; Col:=GetWord(RPN, tpos+2)+1; Result:=Get1Ref(Row, Col); end; function GetRowRange(const Row1, Row2: integer; const Abs1, Abs2: boolean): UTF16String; begin if Abs1 then Result:=fmAbsoluteRef else Result:=''; Result:=Result+IntToStr(Row1)+fmRangeSep; if Abs2 then Result:=Result+fmAbsoluteRef; Result:=Result+IntToStr(Row2); end; function GetColRange(const Col1, Col2: integer): UTF16String; begin if Col1 and $4000=0 then Result:=fmAbsoluteRef else Result:=''; Result:=Result+EncodeColumn(((Col1-1) and $FF)+1)+fmRangeSep; if Col2 and $4000=0 then Result:=Result+fmAbsoluteRef; Result:=Result+EncodeColumn(((Col2-1) and $FF)+1); end; function GetArea(const RPN: PArrayOfByte; const tpos: integer):UTF16String; var Row1, Col1, Row2, Col2: integer; begin Row1:=GetWord(RPN, tpos )+1; Row2:=GetWord(RPN, tpos+2)+1; Col1:=GetWord(RPN, tpos+4)+1; Col2:=GetWord(RPN, tpos+6)+1; if (Col1 and $FF=1) and (Col2 and $FF =Max_Columns+1) then Result:=GetRowRange(Row1, Row2, Col1 and $8000=0, Col2 and $8000=0) else if (Row1=1) and (Row2=Max_Rows+1) then Result:=GetColRange(Col1, Col2) else Result:=Get1Ref(Row1, Col1)+fmRangeSep+Get1Ref(Row2, Col2); end; function GetName(const RPN: PArrayOfByte; const ExternSheet: integer; const tpos: integer; const CellList: TCellList):UTF16String; var Idx: integer; begin Idx:=GetWord(RPN, tPos); Result := CellList.GetName(ExternSheet, Idx - 1); end; function GetNameX(const RPN: PArrayOfByte; const tpos: integer; const CellList: TCellList):UTF16String; var Idx: integer; begin Assert(CellList<>nil,'References must not be nil'); Idx:=GetWord(RPN, tPos); Result:= CellList.GetSheetName(Idx)+GetName(RPN, Idx, tPos+2, CellList); end; procedure ReadMemArea(const RPN: PArrayOfByte; const tpos: integer; var ArrayPos: integer); var Len: integer; begin Len:=GetWord(RPN, ArrayPos); inc(ArrayPos, 2+8*(Len)); end; procedure ReadMemErr(const RPN: PArrayOfByte; const tpos: integer; var ArrayPos: integer); begin //Nothing end; function GetRef3D(const RPN: PArrayOfByte; const tpos: integer; const CellList: TCellList):UTF16String; var Idx: integer; Row, Col: integer; begin Idx:=GetWord(RPN, tPos); Row:=GetWord(RPN, tpos+2)+1; Col:=GetWord(RPN, tpos+4)+1; Result:= CellList.GetSheetName(Idx)+Get1Ref(Row, Col); end; function GetArea3D(const RPN: PArrayOfByte; const tpos: integer; const CellList: TCellList):UTF16String; var Idx: integer; Row1, Col1, Row2, Col2: integer; begin Idx:=GetWord(RPN, tPos); Row1:=GetWord(RPN, tpos+2 )+1; Row2:=GetWord(RPN, tpos+4)+1; Col1:=GetWord(RPN, tpos+6)+1; Col2:=GetWord(RPN, tpos+8)+1; Result:=CellList.GetSheetName(Idx)+Get1Ref(Row1, Col1)+fmRangeSep+Get1Ref(Row2, Col2); end; function GetFuncName(const RPN: PArrayOfByte; const tPos: integer; var minnp, maxnp: integer): UTF16String; var index: integer; begin index:=GetWord(RPN, tPos); if (index<Low(FuncNameArray)) or (index>High(FuncNameArray)) then raise Exception.CreateFmt(ErrIndexOutBounds, [index, 'Function name', Low(FuncNameArray), High(FuncNameArray)]); minnp:=FuncNameArray[index].MinArgCount; maxnp:=FuncNameArray[index].MaxArgCount; Result:=FuncNameArray[index].Name; end; function GetFuncNameVar(const RPN: PArrayOfByte; const tPos: integer; var np: integer; out IsAddIn: boolean): UTF16String; var index: integer; begin index:=GetWord(RPN, tPos+1); IsAddin := index = $FF; if (index<Low(FuncNameArray)) or (index>High(FuncNameArray)) then raise Exception.CreateFmt(ErrIndexOutBounds, [index, 'Function name', Low(FuncNameArray), High(FuncNameArray)]); np:=RPN[tPos]and $7F; if (IsAddIn) then begin Result := ''; dec(np); end else Result:=FuncNameArray[index].Name; end; function GetTableText(const RPN: pArrayOfByte): UTF16String; begin Result:=GetRef(RPN,8)+ fmUnion; //Yes.. Excel leaves an empty comma at the end for one entry tables if RPN[6] and $08= $08 then //two entry table Result:=Result+GetRef(RPN,12); end; function CalcBaseToken(const RealToken: byte): byte; begin if (RealToken and $40)=$40 then Result:= (RealToken or $20) and $3F else Result := RealToken and $3F; end; procedure ProcessAttr(const RPN: PArrayOfByte; const tPos: integer; var AttrLen: integer; const ParsedStack: TFormulaStack); var s: UTF16String; begin AttrLen:=3; if (RPN[tPos] and $04)=$04 then inc(AttrLen, (GetWord(RPN, tPos+1)+1)*2) else if (RPN[tPos] and $10)=$10 then begin //optimized sum ParsedStack.Pop(s); ParsedStack.Push(ParsedStack.FmSpaces+FuncNameArray[4].Name+fmOpenParen+s+fmCloseParen) end else if RPN[tPos] and $40= $40 then //Spaces case RPN[tPos+1] of attr_bitFSpace: ParsedStack.FmSpaces:= StringOfChar(' ', RPN[tPos+2]); attr_bitFEnter: ParsedStack.FmSpaces:= StringOfChar(#13, RPN[tPos+2]); attr_bitFPreSpace: ParsedStack.FmPreSpaces:= StringOfChar(' ', RPN[tPos+2]); attr_bitFPreEnter: ParsedStack.FmPreSpaces:= StringOfChar(#13, RPN[tPos+2]); attr_bitFPostSpace: ParsedStack.FmPostSpaces:= StringOfChar(' ', RPN[tPos+2]); attr_bitFPostEnter: ParsedStack.FmPostSpaces:= StringOfChar(#13, RPN[tPos+2]); attr_bitFPreFmlaSpace: begin end;//not handled; end; //case end; function RPNToString(const RPN: PArrayOfByte; const atPos: integer; const CellList: TCellList): UTF16String; var tPos, fPos, arrayPos: integer; BaseToken, RealToken: byte; ParsedStack: TFormulaStack; s1, s2, s3, s4: UTF16String; IsAddin: boolean; sl, np, i, AttrLen: integer; StartFormula:UTF16String; begin Result:=''; StartFormula:=fmStartFormula; //Formulas do not always begin with "=". Array formulas begin with "{", and they override this var to empty. tPos:=atPos; fPos:=atPos+GetWord(RPN,atPos-2); arrayPos:=fPos; ParsedStack:=TFormulaStack.Create; try while tPos<fPos do begin RealToken:= RPN[tPos]; BaseToken:=CalcBaseToken(RealToken); case BaseToken of {$INCLUDE XlsDoFormula.inc} else raise Exception.CreateFmt(ErrBadToken,[RealToken]); end; //case inc(tPos); end; //while ParsedStack.Pop(Result); Result:=StartFormula+Result; finally FreeAndNil(ParsedStack); end; //finally end; end.
{ Subroutine SST_EXP_USEAGE_CHECK (EXP,RW,DTYPE) * * Check that the attributes of an expression are consistant with its useage. * It is assumed that the expression descriptor is completely filled in and * evaluated. An expression may be evaluated with routine SST_EXP_EVAL. * * EXP - Expression descriptor. * * RW - Indicates the read/write access needed to the expression value. * RW is a SET. The possible element values are: * * SST_RWFLAG_READ_K - Expression value must be readable. * SST_RWFLAG_WRITE_K - Expression value must be writeable. * * DTYPE - A data type descriptor declaring the data type the expression * value must be convertable to/from. The convert direction(s) that are * checked depend on the value of RW. Any expression data type is legal * if DTYPE is set to data type ID of SST_DTYPE_UNDEF_K. } module sst_EXP_USEAGE_CHECK; define sst_exp_useage_check; %include 'sst2.ins.pas'; procedure sst_exp_useage_check ( {check expression attributes for given useage} in exp: sst_exp_t; {expression to check} in rw: sst_rwflag_t; {read/write expression useage} in dtype: sst_dtype_t); {required data type of expression} const max_msg_parms = 1; {max parameters we can pass to a message} var msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; label has_value; begin if rw <> [] then begin {expression must have a value ?} if exp.val_fnd then goto has_value; {expression has known constant value ?} if exp.term1.next_p <> nil then goto has_value; {compound expression ?} case exp.term1.ttype of {what type is the term} sst_term_const_k, {these term types definately have a value} sst_term_func_k, sst_term_ifunc_k, sst_term_type_k, sst_term_set_k: goto has_value; sst_term_var_k: begin {term is a "variable" reference} case exp.term1.var_var_p^.vtype of {what kind of "variable" is this ?} sst_vtype_var_k, {these "variable" types definately have val} sst_vtype_rout_k, sst_vtype_const_k: goto has_value; sst_vtype_dtype_k: begin {variable is a data type} syo_error (exp.str_h, 'sst', 'dtype_useage_bad', nil, 0); end; sst_vtype_com_k: begin {variable is a common block} syo_error (exp.str_h, 'sst', 'common_block_useage_bad', nil, 0); end; end; {end of variable descriptor type cases} end; {end of term is a variable descriptor case} sst_term_exp_k: begin {term is a nested expression} sst_exp_useage_check (exp.term1.exp_exp_p^, rw, dtype); return; end; otherwise sys_msg_parm_int (msg_parm[1], ord(exp.term1.ttype)); syo_error (exp.str_h, 'sst', 'term_type_unknown', msg_parm, 1); end; {end of term type cases} has_value: {jump here if exp definately has a value} end; {done with case where exp needs a value} sst_rwcheck (rw, exp.rwflag, stat); {check read/write permission} syo_error_abort (stat, exp.str_h, '', '', nil, 0); if dtype.dtype = sst_dtype_undef_k {data type indicates universal match ?} then return; if sst_rwflag_read_k in rw then begin {check exp dtype convertable to DTYPE} if not sst_dtype_convertable ( exp.dtype_p^, {input data type} dtype) {data type must be convertable to} then begin syo_error (exp.str_h, 'sst', 'dtype_exp_mismatch', nil, 0); end; end; if sst_rwflag_write_k in rw then begin {check DTYPE convertable to exp dtype} if not sst_dtype_convertable ( dtype, {input data type} exp.dtype_p^) {data type must be convertable to} then begin syo_error (exp.str_h, 'sst', 'dtype_exp_mismatch', nil, 0); end; end; end;
unit CacheServerReportForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, SyncObjs, SocketComp, ImageClient; const MaxTicks = 30; PictureServerPort = 6010; type TCacheServerReport = class(TForm) Panel1: TPanel; Image1: TImage; PageControl1: TPageControl; General: TTabSheet; Label1: TLabel; GlobalPath: TEdit; Browse: TButton; Initialize: TButton; LocalPath: TEdit; Button1: TButton; Label2: TLabel; Label3: TLabel; Port: TEdit; Label4: TLabel; WebSite: TEdit; TabSheet1: TTabSheet; Label5: TLabel; Label6: TLabel; lbCacheObjCount: TLabel; lbCacheItrCount: TLabel; LogTimer: TTimer; procedure InitializeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LogTimerTimer(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure StarPictureServer; procedure OnClientConnect(Sender : TObject; Socket : TCustomWinSocket); procedure OnClientRead(Sender : TObject; Socket : TCustomWinSocket); procedure OnClientClose(Sender : TObject; Socket : TCustomWinSocket); procedure OnClientError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer); function SaveImage(Client : TImageClient) : boolean; private fTickCount : integer; fMaxTTL : TDateTime; fServerSocket : TServerSocket; end; var CacheServerReport : TCacheServerReport; DeleteCache : boolean; RDOCacheObjCount : integer; RDOCacheItrCount : integer; implementation {$IFDEF LOGS} uses Registry, CacheRegistryKeys, FileCtrl, ShellAPI, RDOInterfaces, WinSockRDOConnectionsServer, RDORootServer, CacheCommon, CachedObjectWrap, FolderIteratorWrap, Collection, LogFile; {$ELSE} uses Registry, CacheRegistryKeys, FileCtrl, ShellAPI, RDOInterfaces, WinSockRDOConnectionsServer, RDORootServer, CacheCommon, CachedObjectWrap, FolderIteratorWrap, Collection; {$ENDIF} {$R *.DFM} const MaxPictBufferSize = 1024; type TWorldRegistyServer = class(TRDORootServer) public constructor Create(ConnectionsServer : IRDOConnectionsServer; MaxQueryThreads : integer; QueryCritSection : TCriticalSection; const RootName : string); destructor Destroy; override; private fCachePath : WideString; fWorldURL : WideString; fLivingObjs : TLockableCollection; published function RegisterWorld(const WorldName, ServerName : WideString; ServerPort : integer) : variant; function CreateObject(const WorldName : WideString) : OleVariant; function CreateIterator(const Path : WideString; Options : integer) : OleVariant; procedure CloseObject(Obj : integer); published property CachePath : WideString read fCachePath; property WorldURL : WideString read fWorldURL; public procedure CheckObject(MaxTTL : TDateTime); public property LivingObjs : TLockableCollection read fLivingObjs; end; // TWorldRegistyServer constructor TWorldRegistyServer.Create(ConnectionsServer : IRDOConnectionsServer; MaxQueryThreads : integer; QueryCritSection : TCriticalSection; const RootName : string); begin inherited; fLivingObjs := TLockableCollection.Create(0, rkBelonguer); end; destructor TWorldRegistyServer.Destroy; begin fLivingObjs.Free; inherited; end; function TWorldRegistyServer.RegisterWorld(const WorldName, ServerName : WideString; ServerPort : integer) : variant; var Reg : TRegistry; aux : string; begin try Reg := TRegistry.Create; try aux := WorldsKey + WorldName; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.CreateKey(aux); if Reg.OpenKey(aux, false) then begin Reg.WriteString('Server', ServerName); Reg.WriteInteger('Port', ServerPort); Reg.RegistryConnect(''); result := true; end else result := false; finally Reg.Free; end; except result := false; end; end; function TWorldRegistyServer.CreateObject(const WorldName : WideString) : OleVariant; var CacheObj : TCachedObjectWrap; begin try CacheObj := TCachedObjectWrap.Create; if CacheObj.SetWorld(WorldName) then begin result := integer(CacheObj); fLivingObjs.Insert(CacheObj); end else begin result := integer(0); CacheObj.Free; end; except result := integer(0); end; end; function TWorldRegistyServer.CreateIterator(const Path : WideString; Options : integer) : OleVariant; var Itr : TFolderIteratorWrap; begin try Itr := TFolderIteratorWrap.Create(Path, Options); result := integer(Itr); except result := 0; end; end; procedure TWorldRegistyServer.CloseObject(Obj : integer); begin try fLivingObjs.Delete(TObject(Obj)); except end; end; procedure TWorldRegistyServer.CheckObject(MaxTTL : TDateTime); var CurDate : TDateTime; Obj : TCachedObjectWrap; i : integer; begin CurDate := Now; fLivingObjs.Lock; try i := 0; while i < fLivingObjs.Count do begin Obj := TCachedObjectWrap(fLivingObjs[i]); if CurDate - Obj.LastUpdate > MaxTTL then fLivingObjs.Delete(Obj) else inc(i); end; finally fLivingObjs.Unlock; end; end; // RemoveFullPath function RemoveFullPath(const Path : string) : boolean; var FileOp : TSHFileOpStruct; tmp : array[0..MAX_PATH] of char; begin fillchar(tmp, sizeof(tmp), 0); strpcopy(tmp, Path); // If Path is a folder the last '\' must be removed. if Path[length(Path)] = '\' then tmp[length(Path)-1] := #0; with FileOp do begin wFunc := FO_DELETE; Wnd := 0; pFrom := tmp; pTo := nil; fFlags := FOF_NOCONFIRMATION or FOF_SILENT; hNameMappings := nil; end; result := SHFileOperation(FileOp) = 0; end; var CachePath : string = ''; CacheServer : TWorldRegistyServer = nil; // TCacheServerReport procedure TCacheServerReport.InitializeClick(Sender: TObject); var Reg : TRegistry; ServerConn : IRDOConnectionsServer; begin try fMaxTTL := EncodeTime(0, 5, 0, 0); ServerConn := TWinSockRDOConnectionsServer.Create(StrToInt(Port.Text)); CacheServer := TWorldRegistyServer.Create(ServerConn, 1, nil, WSObjectCacherName); CacheServer.fCachePath := GlobalPath.Text; CacheServer.fWorldURL := WebSite.Text; LogTimer.Enabled := true; if (System.pos('cache', lowercase(LocalPath.Text)) <> 0) and DirectoryExists(LocalPath.Text) and DeleteCache then RemoveFullPath(LocalPath.Text); ForceDirectories(LocalPath.Text); StarPictureServer; Initialize.Enabled := false; {$IFDEF LOGS} SetLogFile(ExtractFilePath(Application.ExeName) + 'CacheServer.log'); {$ENDIF} // Save the path in the registry Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(CacheKey, true) then begin Reg.WriteString('GlobalPath', GlobalPath.Text); Reg.WriteString('RootPath', LocalPath.Text); Reg.WriteString('WebSite', WebSite.Text); Reg.RegistryConnect(''); end finally Reg.Free; end; except Application.MessageBox('Cannot initialize the server', 'Model Server', MB_ICONERROR or MB_OK); end; Application.Minimize; end; procedure TCacheServerReport.FormCreate(Sender: TObject); var Reg : TRegistry; str : string; begin try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(CacheKey, false) then begin LocalPath.Text := Reg.ReadString('RootPath'); GlobalPath.Text := Reg.ReadString('GlobalPath'); str := Reg.ReadString('WebSite'); if str <> '' then WebSite.Text := str; end; finally Reg.Free; end; except end; end; procedure TCacheServerReport.LogTimerTimer(Sender: TObject); begin lbCacheObjCount.Caption := IntToStr(CacheServer.LivingObjs.Count); lbCacheItrCount.Caption := IntToStr(RDOCacheItrCount); if fTickCount > MaxTicks then begin CacheServer.CheckObject(fMaxTTL); fTickCount := 0; end else inc(fTickCount); end; procedure TCacheServerReport.OnClientConnect(Sender : TObject; Socket : TCustomWinSocket); begin Socket.Data := TImageClient.Create; end; procedure TCacheServerReport.OnClientError(Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer); begin ErrorCode := 0; end; procedure TCacheServerReport.OnClientRead(Sender : TObject; Socket : TCustomWinSocket); var Client : TImageClient; logData : TStringList; buffer : array[0..MaxPictBufferSize-1] of byte; size : integer; begin Client := TImageClient(Socket.Data); if Client <> nil then if not Client.Loaded then begin logData := TStringList.Create; logData.Text := Socket.ReceiveText; Client.Name := logData.Values['User']; Client.World := logData.Values['World']; Client.Loaded := true; try Client.Size := StrToInt(logData.Values['Size']); Socket.SendText('SEND'); except Socket.SendText('ERROR'); Socket.Data := nil; Client.Free; end; end else begin size := Socket.ReceiveBuf(buffer, sizeof(buffer)); if size > 0 then if Client.Recieve(buffer, size) then begin if SaveImage(Client) then Socket.SendText('OK') else Socket.SendText('ERROR'); Client.Free; Socket.Data := nil; end; end; end; procedure TCacheServerReport.OnClientClose(Sender : TObject; Socket : TCustomWinSocket); begin if Socket.Data <> nil then TImageClient(Socket.Data).Free; end; function TCacheServerReport.SaveImage(Client : TImageClient) : boolean; var path : string; Stream : TStream; begin path := CacheServer.CachePath; if (path <> '') and (path[length(path)] = '\') then path := ExtractFilePath(copy(path, 1, pred(length(path)))) else path := ExtractFilePath(path); path := path + 'UserInfo\' + Client.World + '\' + Client.Name; ForceDirectories(path); if DirectoryExists(path) then try Stream := TFileStream.Create(path + '\largephoto.jpg', fmCreate); try Client.Stream.Seek(0, 0); Stream.CopyFrom(Client.Stream, Client.Size); result := true; finally Stream.Free; end; except result := false; end else result := false; end; procedure TCacheServerReport.StarPictureServer; begin fServerSocket := TServerSocket.Create(self); fServerSocket.Port := PictureServerPort; fServerSocket.OnClientConnect := OnClientConnect; fServerSocket.OnClientRead := OnClientRead; fServerSocket.OnClientDisconnect := OnClientClose; fServerSocket.OnClientError := OnClientError; fServerSocket.Open; end; procedure TCacheServerReport.FormDestroy(Sender: TObject); begin if fServerSocket <> nil then fServerSocket.Close; fServerSocket.Free; end; end.
unit uFiltroRomaneioIndexadoClass; interface uses Forms, SysUtils, Classes, pcnGerador, pcnLeitor, uMatVars, LibGeral, TypInfo, pcnConversao; type TRotaItem = class; TRotas = class; TCidadeCollection = class; TCidadeCollectionItem = class; TClienteCollection = class; TClienteCollectionItem = class; TShadowedCollection = class; TShadowedCollection = class(TPersistent) private FItemClass: TCollectionItemClass; FItems: TList; end; TRotas = class(TCollection) private FXML: AnsiString; FNomeArq: String; FPathArquivo: string; function GetItem(Index: Integer): TRotaItem; procedure SetItem(Index: Integer; Value: TRotaItem); function GetRotaXML: AnsiString; //(ASalvar: Boolean = False): AnsiString; function StreamToString(Stream: TStream): string; public constructor Create(AOwner: TObject); function Add: TRotaItem; function SaveToFile(APathArquivo: string = ''): boolean; procedure SaveToStream(out AStream: TStream); function LoadFromFile(CaminhoArquivo: string = ''): boolean; function LoadFromStream(Stream: TStream): boolean; function Find(APlaca: string): TRotaItem; function Existe(APlaca: string): Boolean; procedure Excluir(APlaca: string); procedure GerarRota; procedure CopyObject(Source, Dest: TObject); property Items[Index: Integer]: TRotaItem read GetItem write SetItem; default; published property XML: AnsiString read GetRotaXML write FXML; property NomeArq: String read FNomeArq write FNomeArq; property PathArquivo: string read FPathArquivo write FPathArquivo; end; TRotaItem = class(TCollectionItem) private Gerador: TGerador; FXML: string; FNomeArq: string; Fplaca: string; Fsetor: string; Fcidades: TCidadeCollection; Fclientes: TClienteCollection; function GerarXML: string; function GerarCidades: string; function GerarClientes: string; procedure Setcidades(const Value: TCidadeCollection); procedure Setclientes(const Value: TClienteCollection); procedure SetPlaca(const Value: string); public constructor Create; function ClientesToIN: string; function CidadesToIN: string; published property placa: string read Fplaca write SetPlaca; property setor: string read Fsetor write Fsetor; property cidades: TCidadeCollection read Fcidades write Setcidades; property clientes: TClienteCollection read Fclientes write Setclientes; property XML: string read GerarXML write FXML; property NomeArq: String read FNomeArq write FNomeArq; end; TRotaR = class(TPersistent) private FLeitor: TLeitor; FRota: TRotaItem; public constructor Create(AOwner: TRotaItem); destructor Destroy; override; function LerXml: boolean; published property Leitor: TLeitor read FLeitor write FLeitor; property Rota: TRotaItem read FRota write FRota; end; TCidadeCollection = class(TCollection) private function GetItem(Index: Integer): TCidadeCollectionItem; procedure SetItem(Index: Integer; Value: TCidadeCollectionItem); public constructor Create(AOwner: TRotaItem); function Add: TCidadeCollectionItem; procedure Excluir(ACod_IBGE: integer); property Items[Index: Integer]: TCidadeCollectionItem read GetItem write SetItem; default; end; TCidadeCollectionItem = class(TCollectionItem) private FcodigoIBGE: integer; public constructor Create; reintroduce; destructor Destroy; override; published property codigoIBGE: integer read FcodigoIBGE write FcodigoIBGE; end; TClienteCollection = class(TCollection) private function GetItem(Index: Integer): TClienteCollectionItem; procedure SetItem(Index: Integer; Value: TClienteCollectionItem); public constructor Create(AOwner: TRotaItem); function Add: TClienteCollectionItem; procedure Excluir(ACnpj: string); property Items[Index: Integer]: TClienteCollectionItem read GetItem write SetItem; default; end; TClienteCollectionItem = class(TCollectionItem) private Fcnpj: string; public constructor Create; reintroduce; destructor Destroy; override; published property cnpj: string read Fcnpj write Fcnpj; end; { TConfiguracoes = class end;} const ENCODING_ISO8859_1 = '?xml version="1.0" encoding="iso-8859-1"?'; implementation { TRotaItem } constructor TRotaItem.Create; begin Gerador := TGerador.Create; Gerador.Opcoes.TagVaziaNoFormatoResumido := False; Fcidades := TCidadeCollection.Create(Self); Fclientes := TClienteCollection.Create(Self); end; function TRotaItem.GerarClientes: string; var I: Integer; begin Gerador.wGrupo('clientes'); for I := 0 to Fclientes.Count - 1 do begin with Fclientes[I] do begin Gerador.wGrupo('cliente'); Gerador.wCampo(tcStr, '', 'cnpj', 14, 14, 1, Fcnpj, ''); Gerador.wGrupo('/cliente'); end; end; Gerador.wGrupo('/clientes'); end; function TRotaItem.GerarCidades: string; var I: Integer; begin Gerador.wGrupo('cidades'); for I := 0 to Fcidades.Count - 1 do begin with Fcidades[I] do begin Gerador.wGrupo('cidade'); Gerador.wCampo(tcInt, '', 'codigoIBGE', 7, 7, 1, FcodigoIBGE, ''); Gerador.wGrupo('/cidade'); end; end; Gerador.wGrupo('/cidades'); end; function TRotaItem.GerarXML: string; begin Gerador.ArquivoFormatoXML := ''; Gerador.ArquivoFormatoTXT := ''; Gerador.wGrupo('rota'); Gerador.wCampo(tcStr, '', 'placa', 7, 7, 1, Fplaca, ''); Gerador.wCampo(tcStr, '', 'setor', 7, 7, 1, Fsetor, ''); Gerador.wTexto(GerarCidades); Gerador.wTexto(GerarClientes); Gerador.wGrupo('/rota'); result := Gerador.ArquivoFormatoXML; end; procedure TRotaItem.Setcidades(const Value: TCidadeCollection); begin Fcidades := Value; end; procedure TRotaItem.Setclientes(const Value: TClienteCollection); begin Fclientes := Value; end; procedure TRotaItem.SetPlaca(const Value: string); begin Fplaca := Value; end; function TRotaItem.ClientesToIN: string; var I: integer; s: string; begin s := ''; for I := 0 to Fclientes.Count - 1 do s := s + #39 + Formata_CgcCpf(Fclientes[I].cnpj) + #39 + ','; if Length(s) > 0 then s := Copy(s, 1, Length(s) - 1); result := s; end; function TRotaItem.CidadesToIN: string; var I: integer; s: string; begin s := ''; for I := 0 to Fcidades.Count - 1 do s := s + #39 + IntToStr(Fcidades[I].codigoIBGE) + #39 + ','; if Length(s) > 0 then s := Copy(s, 1, Length(s) - 1); result := s; end; { TCidadeCollection } function TCidadeCollection.Add: TCidadeCollectionItem; begin Result := TCidadeCollectionItem(inherited Add); Result.Create; end; constructor TCidadeCollection.Create; begin inherited Create(TCidadeCollectionItem); end; procedure TCidadeCollection.Excluir(ACod_IBGE: integer); var i: Integer; begin for i := 0 to Pred(Self.Count) do begin if TCidadeCollectionItem(Items[i]).codigoIBGE = ACod_IBGE then begin Self.Delete(I); break; end; end; end; function TCidadeCollection.GetItem(Index: Integer): TCidadeCollectionItem; begin Result := TCidadeCollectionItem(inherited GetItem(Index)); end; procedure TCidadeCollection.SetItem(Index: Integer; Value: TCidadeCollectionItem); begin inherited SetItem(Index, Value); end; { TClienteCollection } function TClienteCollection.Add: TClienteCollectionItem; begin Result := TClienteCollectionItem(inherited Add); Result.create; end; constructor TClienteCollection.Create(AOwner: TRotaItem); begin inherited Create(TClienteCollectionItem); end; procedure TClienteCollection.Excluir(ACnpj: string); var i: Integer; begin for i := 0 to Pred(Self.Count) do begin if TClienteCollectionItem(Items[i]).cnpj = ACnpj then begin Self.Delete(I); break; end; end; end; function TClienteCollection.GetItem(Index: Integer): TClienteCollectionItem; begin Result := TClienteCollectionItem(inherited GetItem(Index)); end; procedure TClienteCollection.SetItem(Index: Integer; Value: TClienteCollectionItem); begin inherited SetItem(Index, Value); end; { TCidadeCollectionItem } constructor TCidadeCollectionItem.Create; begin end; destructor TCidadeCollectionItem.Destroy; begin inherited; end; { TClienteCollectionItem } constructor TClienteCollectionItem.Create; begin end; destructor TClienteCollectionItem.Destroy; begin inherited; end; { TRotas } function TRotas.Add: TRotaItem; begin Result := TRotaItem(inherited Add); Result.create; end; constructor TRotas.Create(AOwner: TObject); begin inherited Create(TRotaItem); FNomeArq := 'filtroromaneio.xml'; FPathArquivo := LerInfotecINI('ROTEIRIZACAO', 'CAMINHO DO ARQUIVO', True); end; function TRotas.GetItem(Index: Integer): TRotaItem; begin Result := TRotaItem(inherited GetItem(Index)); end; function TRotas.GetRotaXML: AnsiString; //(ASalvar: Boolean = False): AnsiString; var Gerador : TGerador; i: integer; begin Gerador := TGerador.Create; try Gerador.ArquivoFormatoXML := ''; Gerador.ArquivoFormatoTXT := ''; Gerador.Opcoes.IdentarXML := True; Gerador.wGrupo(ENCODING_ISO8859_1, '', False); Gerador.wGrupo('rotas'); for i := 0 to Self.Count -1 do Gerador.wTexto(Self.Items[i].XML); Gerador.wGrupo('/rotas'); Result := Gerador.ArquivoFormatoXML; // if ASalvar then // Gerador.SalvarArquivo(FPathArquivo + FNomeArq); finally Gerador.Free; end; end; procedure TRotas.GerarRota; var i: Integer; Gerador: TGerador; begin { Gerador := TGerador.Create; Gerador.ArquivoFormatoXML := ''; Gerador.wGrupo(); for i:= 0 to Self.Count-1 do begin LocCTeW := TCTeW.Create(Self.Items[i].CTe); try LocCTeW.GerarXml; Self.Items[i].XML := LocCTeW.Gerador.ArquivoFormatoXML; Self.Items[i].Alertas := LocCTeW.Gerador.ListaDeAlertas.Text; finally LocCTeW.Free; end; end;} end; function TRotas.LoadFromFile(CaminhoArquivo: string): boolean; var LocRotaR : TRotaR; ArquivoXML: TStringList; XML : AnsiString; rotaitem: TRotaItem; sArquivo: string; begin if TemValor(CaminhoArquivo) then sArquivo := CaminhoArquivo else sArquivo := FPathArquivo + NomeArq; if not FileExists(sArquivo) then begin // raise Exception.Create('Arquivo de configuraçao não encontrado.'); exit; end; try ArquivoXML := TStringList.Create; ArquivoXML.LoadFromFile(sArquivo); Result := True; while pos('</rota>',ArquivoXML.Text) > 0 do begin if pos('</cteProc>',ArquivoXML.Text) > 0 then begin XML := copy(ArquivoXML.Text,1,pos('</cteProc>',ArquivoXML.Text)+5); ArquivoXML.Text := Trim(copy(ArquivoXML.Text,pos('</cteProc>',ArquivoXML.Text)+10,length(ArquivoXML.Text))); end else begin XML := copy(ArquivoXML.Text,1,pos('</rota>',ArquivoXML.Text)+6); ArquivoXML.Text := Trim(copy(ArquivoXML.Text,pos('</rota>',ArquivoXML.Text)+7,length(ArquivoXML.Text))); end; rotaitem := Self.Add; LocRotaR := TRotaR.Create(rotaitem); try LocRotaR.Leitor.Arquivo := XML; LocRotaR.LerXml; Items[Self.Count-1].XML := LocRotaR.Leitor.Arquivo; Items[Self.Count-1].NomeArq := sArquivo; // GerarCTe; finally LocRotaR.Free; end; end; ArquivoXML.Free; except raise; Result := False; end; end; function TRotas.LoadFromStream(Stream: TStream): boolean; var LocRotaR : TRotaR; rotaitem: TRotaItem; begin try Result := True; rotaitem := Self.Add; LocRotaR := TRotaR.Create(rotaitem); try LocRotaR.Leitor.CarregarArquivo(StreamToString(Stream)); LocRotaR.LerXml; Items[Self.Count-1].XML := LocRotaR.Leitor.Arquivo; //GerarCTe; finally LocRotaR.Free end; except Result := False; end; end; procedure TRotas.SetItem(Index: Integer; Value: TRotaItem); begin inherited SetItem(Index, Value); end; { TRotasR } constructor TRotaR.Create(AOwner: TRotaItem); begin FLeitor := TLeitor.Create; FRota := AOwner; end; destructor TRotaR.Destroy; begin FLeitor.Free; inherited Destroy; end; function TRotaR.LerXml: boolean; var ok: boolean; i, j, i01, i02, i03: integer; begin I := 0; if Leitor.rExtrai(1, 'rota') <> '' then begin Rota.placa := Leitor.rCampo(tcStr, 'placa'); Rota.setor := Leitor.rCampo(tcStr, 'setor'); end; if Leitor.rExtrai(1, 'rota') <> '' then begin if Leitor.rExtrai(2, 'cidades') <> '' then begin i01 := 0; while Leitor.rExtrai(2, 'cidade', '', i01 + 1) <> '' do begin Rota.cidades.Add.codigoIBGE := Leitor.rCampo(tcInt, 'codigoIBGE'); inc(i01); end; end; end; if Leitor.rExtrai(1, 'rota') <> '' then begin if Leitor.rExtrai(2, 'clientes') <> '' then begin i01 := 0; while Leitor.rExtrai(2, 'cliente', '', i01 + 1) <> '' do begin Rota.clientes.Add.cnpj := Leitor.rCampo(tcStr, 'cnpj'); inc(i01); end; end; end; Result := true; end; function TRotas.SaveToFile(APathArquivo: string): boolean; var Gerador: TGerador; begin try Result := True; Gerador := TGerador.Create; try XML; // if EstaVazio(CaminhoArquivo) or not DirectoryExists(ExtractFilePath(CaminhoArquivo)) then // raise Exception.Create('Caminho Inválido: ' + CaminhoArquivo); Gerador.ArquivoFormatoXML := GetRotaXML; if TemValor(APathArquivo) then Gerador.SalvarArquivo(APathArquivo) else Gerador.SalvarArquivo(FPathArquivo + FNomeArq); finally Gerador.Free; end; except raise; Result := False; end; end; function TRotas.Find(APlaca: string): TRotaItem; var i: Integer; begin Result := nil; for i := 0 to Pred(Self.Count) do begin if TRotaItem(Items[i]).placa = APlaca then begin Result := TRotaItem(Items[i]); break; end; end; //raise; //EItemNotFound.Create; end; function TRotas.Existe(APlaca: string): Boolean; var i: Integer; begin for i := 0 to Pred(Self.Count) do begin if TRotaItem(Items[i]).placa = APlaca then begin Result := True; break; end; end; end; function TRotas.StreamToString(Stream: TStream): string; var ms : TMemoryStream; begin Result := ''; ms := TMemoryStream.Create; try ms.LoadFromStream(Stream); SetString(Result,PChar(ms.memory),ms.Size); finally ms.free; end; end; //procedure retirada do site: http://stackoverflow.com/questions/1082559/string-to-tstream procedure TRotas.SaveToStream(out AStream: TStream); var SS: TStringStream; begin SS := TStringStream.Create(XML); try SS.Position := 0; AStream.CopyFrom(SS, SS.Size); //This is where the "Abstract Error" gets thrown finally SS.Free; end; end; procedure TRotas.CopyObject(Source, Dest: TObject); var TypInfo: PTypeInfo; PropList: TPropList; PropCount, i: integer; Value: variant; begin TypInfo := Source.ClassInfo; PropCount := GetPropList(TypInfo, tkAny, @PropList); for i := 0 to PropCount - 1 do begin try Value := GetPropValue(Source, PropList[i]^.Name); SetPropValue(Dest, PropList[i]^.Name, Value); except // quando encontrar uma read only, gera um except mas não faz nada end; end; end; procedure TRotas.Excluir(APlaca: string); var i: Integer; begin for i := 0 to Pred(Self.Count) do begin if TRotaItem(Items[i]).placa = APlaca then begin Self.Delete(I); break; end; end; end; end.
unit aeMaterial; interface uses types, aeColor, dglOpenGL; type TaeMaterialRenderMode = (AE_MATERIAL_RENDERMODE_TRIANGLES, AE_MATERIAL_RENDERMODE_WIREMESH); type TaeMaterial = class private _color: TaeColor; // opengl mode : GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, // GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLES, // GL_QUAD_STRIP, GL_QUADS, und GL_POLYGON _renderMode: TaeMaterialRenderMode; public property Color: TaeColor read _color write _color; property Rendermode: TaeMaterialRenderMode read _renderMode write _renderMode; constructor Create; end; implementation { TaeMaterial } constructor TaeMaterial.Create; begin self._color := TaeColor.Create(); // start with white default! self._renderMode := AE_MATERIAL_RENDERMODE_TRIANGLES; // default : wiremesh end; end.
unit DAO.Bases; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Bases; type TBasesDAO = class private FConexao : TConexao; public constructor Create; function Inserir(ABase: TBases): Boolean; function Alterar(ABase: TBases): Boolean; function Excluir(ABase: TBases): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; function LocalizarExato(aParam: array of variant): Boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; function SetupModel(FDBases: TFDQuery; ABase: TBases): Boolean; procedure ClearModel(ABase: TBases); end; const TABLENAME = 'tbagentes'; implementation { TBasesDAO } uses Control.Sistema; function TBasesDAO.Alterar(ABase: TBases): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + 'SET COD_AGENTE = :COD_AGENTE, DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL, ' + 'NOM_FANTASIA = :NOM_FANTASIA, DES_TIPO_DOC = :DES_TIPO_DOC, NUM_CNPJ = :NUM_CNPJ, NUM_IE = :NUM_IE, ' + 'NUM_IEST = :NUM_IEST, NUM_IM = :NUM_IM, COD_CNAE = :COD_CNAE, COD_CRT = :COD_CRT, NUM_CNH = :NUM_CNH, ' + 'DES_CATEGORIA_CNH = :DES_CATEGORIA_CNH, DAT_VALIDADE_CNH = :DAT_VALIDADE_CNH, DES_PAGINA = :DES_PAGINA, ' + 'COD_STATUS = :COD_STATUS, DES_OBSERVACAO = :DES_OBSERVACAO, DAT_CADASTRO = :DAT_CADASTRO, ' + 'DAT_ALTERACAO = :DAT_ALTERACAO, VAL_VERBA = :VAL_VERBA, DES_TIPO_CONTA = :DES_TIPO_CONTA, COD_BANCO = :COD_BANCO, ' + 'COD_AGENCIA = :COD_AGENCIA, NUM_CONTA = :NUM_CONTA, NOM_FAVORECIDO = :NOM_FAVORECIDO, ' + 'NUM_CPF_CNPJ_FAVORECIDO = :NUM_CPF_CNPJ_FAVORECIDO, DES_FORMA_PAGAMENTO = :DES_FORMA_PAGAMENTO, ' + 'COD_CENTRO_CUSTO = :COD_CENTRO_CUSTO, COD_GRUPO = :COD_GRUPO WHERE COD_AGENTE = :COD_AGENTE;', [ABase.RazaoSocial, ABase.NomeFantasia, ABase.TipoDoc, ABase.CNPJCPF, ABase.IE, ABase.IEST, ABase.IM, ABase.CNAE, ABase.CRT, ABase.NumeroCNH, ABase.CategoriaCNH, ABase.ValidadeCNH, ABase.PaginaWeb, ABase.Status, ABase.Obs, ABase.DataCadastro, ABase.DataAlteracao, ABase.ValorVerba, ABase.TipoConta, ABase.CodigoBanco, ABase.NumeroAgente, ABase.NumeroConta, ABase.NomeFavorecido, ABase.CNPJCPFFavorecido, ABase.FormaPagamento, ABase.CentroCusto, ABase.Grupo, ABase.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; procedure TBasesDAO.ClearModel; begin ABase.Codigo := 0; ABase.RazaoSocial := ''; ABase.NomeFantasia := ''; ABase.TipoDoc := ''; ABase.CNPJCPF := ''; ABase.IE := ''; ABase.IEST := ''; ABase.IM := ''; ABase.CNAE := ''; ABase.CRT := 0; ABase.NumeroCNH := ''; ABase.CategoriaCNH := ''; ABase.ValidadeCNH := StrToDate('1899-12-31'); ABase.PaginaWeb := ''; ABase.Status := 0; ABase.Obs := ''; ABase.DataCadastro := StrToDate('1899-12-31'); ABase.DataAlteracao := StrToDate('1899-12-31'); ABase.ValorVerba := 0; ABase.TipoConta := ''; ABase.CodigoBanco := ''; ABase.NumeroAgente := ''; ABase.NumeroConta := ''; ABase.NomeFavorecido := ''; ABase.CNPJCPFFavorecido := ''; ABase.FormaPagamento := ''; ABase.CentroCusto := 0; ABase.Grupo := 0; end; constructor TBasesDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TBasesDAO.Excluir(ABase: TBases): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where COD_AGENTE = :COD_AGENTE', [ABase.Codigo]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TBasesDAO.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try 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 TBasesDAO.Inserir(ABase: TBases): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(COD_AGENTE, DES_RAZAO_SOCIAL, NOM_FANTASIA, DES_TIPO_DOC, NUM_CNPJ, NUM_IE, ' + 'NUM_IEST, NUM_IM, COD_CNAE, COD_CRT, NUM_CNH, DES_CATEGORIA_CNH, DAT_VALIDADE_CNH, DES_PAGINA, COD_STATUS, ' + 'DES_OBSERVACAO, DAT_CADASTRO, DAT_ALTERACAO, VAL_VERBA, DES_TIPO_CONTA, COD_BANCO, COD_AGENCIA, NUM_CONTA, ' + 'NOM_FAVORECIDO, NUM_CPF_CNPJ_FAVORECIDO, DES_FORMA_PAGAMENTO, COD_CENTRO_CUSTO, COD_GRUPO) ' + 'VALUES ' + '(:COD_AGENTE, :DES_RAZAO_SOCIAL, :NOM_FANTASIA, :DES_TIPO_DOC, :NUM_CNPJ, :NUM_IE, :NUM_IEST, :NUM_IM, ' + ':COD_CNAE, :COD_CRT, :NUM_CNH, :DES_CATEGORIA_CNH, :DAT_VALIDADE_CNH, :DES_PAGINA, :COD_STATUS, ' + ':DES_OBSERVACAO, :DAT_CADASTRO, :DAT_ALTERACAO, :VAL_VERBA, :DES_TIPO_CONTA, :COD_BANCO, :COD_AGENCIA, ' + ':NUM_CONTA, :NOM_FAVORECIDO, :NUM_CPF_CNPJ_FAVORECIDO, :DES_FORMA_PAGAMENTO, :COD_CENTRO_CUSTO, :COD_GRUPO);', [ABase.Codigo, ABase.RazaoSocial, ABase.NomeFantasia, ABase.TipoDoc, ABase.CNPJCPF, ABase.IE, ABase.IEST, ABase.IM, ABase.CNAE, ABase.CRT, ABase.NumeroCNH, ABase.CategoriaCNH, ABase.ValidadeCNH, ABase.PaginaWeb, ABase.Status, ABase.Obs, ABase.DataCadastro, ABase.DataAlteracao, ABase.ValorVerba, ABase.TipoConta, ABase.CodigoBanco, ABase.NumeroAgente, ABase.NumeroConta, ABase.NomeFavorecido, ABase.CNPJCPFFavorecido, ABase.FormaPagamento, ABase.CentroCusto, ABase.Grupo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBasesDAO.LocalizarExato(aParam: array of variant; ABase: TBases): 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_AGENTE = :COD_AGENTE'); FDQuery.ParamByName('COD_AGENTE').Value := aParam[1]; end; if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ'); FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1]; end; if aParam[0] = 'RAZAO' then begin FDQuery.SQL.Add('WHERE DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL'); FDQuery.ParamByName('DES_RAZAO_SOCIAL').AsString := aParam[1]; end; if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA'); FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1]; end; if aParam[0] = 'IE' then begin FDQuery.SQL.Add('WHERE NUM_IE = :NUM_IE'); FDQuery.ParamByName('NUM_IE').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open; if not FDQuery.IsEmpty then begin FDQuery.First; Result := SetupModel(FDQuery); end else begin ClearModel(); Exit; end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TBasesDAO.Pesquisar(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_AGENTE = :COD_AGENTE'); FDQuery.ParamByName('COD_AGENTE').Value := aParam[1]; end; if aParam[0] = 'CNPJ' then begin FDQuery.SQL.Add('WHERE NUM_CNPJ = :NUM_CNPJ'); FDQuery.ParamByName('NUM_CNPJ').AsString := aParam[1]; end; if aParam[0] = 'RAZAO' then begin FDQuery.SQL.Add('WHERE DES_RAZAO_SOCIAL = :DES_RAZAO_SOCIAL'); FDQuery.ParamByName('DES_RAZAO_SOCIAL').AsString := aParam[1]; end; if aParam[0] = 'FANTASIA' then begin FDQuery.SQL.Add('WHERE NOM_FANTASIA = :NOM_FANTASIA'); FDQuery.ParamByName('NOM_FANTASIA').AsString := aParam[1]; end; if aParam[0] = 'IE' then begin FDQuery.SQL.Add('WHERE NUM_IE = :NUM_IE'); FDQuery.ParamByName('NUM_IE').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 TBasesDAO.SetupModel(FDBases: TFDQuery; ABase: TBases): Boolean; begin try Result := False; ABase.Codigo := FDBases.FieldByName('cod_agente').AsInteger; ABase.RazaoSocial := FDBases.FieldByName('des_razao_social').AsString; ABase.NomeFantasia := FDBases.FieldByName('nom_fantasia').AsString; ABase.TipoDoc := FDBases.FieldByName('des_tipo_doc').AsString; ABase.CNPJCPF := FDBases.FieldByName('num_cnpj').AsString; ABase.IE := FDBases.FieldByName('num_ie').AsString; ABase.IEST := FDBases.FieldByName('num_iest').AsString; ABase.IM := FDBases.FieldByName('num_im').AsString; ABase.CNAE := FDBases.FieldByName('cod_cnae').AsString; ABase.CRT := FDBases.FieldByName('cod_crt').AsInteger; ABase.NumeroCNH := FDBases.FieldByName('num_cnh').AsString; ABase.CategoriaCNH := FDBases.FieldByName('des_categoria_cnh').AsString; ABase.ValidadeCNH := FDBases.FieldByName('dat_validade_cnh').AsDateTime; ABase.PaginaWeb := FDBases.FieldByName('des_pagina').AsString; ABase.Status := FDBases.FieldByName('cod_status').AsInteger; ABase.Obs := FDBases.FieldByName('des_observacao').AsString; ABase.DataCadastro := FDBases.FieldByName('dat_cadastro').AsDateTime; ABase.DataAlteracao := FDBases.FieldByName('dat_alteracao').AsDateTime; ABase.ValorVerba := FDBases.FieldByName('val_verba').AsFloat; ABase.TipoConta := FDBases.FieldByName('des_tipo_conta').AsString; ABase.CodigoBanco := FDBases.FieldByName('cod_banco').AsString; ABase.NumeroAgente := FDBases.FieldByName('cod_agencia').AsString; ABase.NumeroConta := FDBases.FieldByName('num_conta').AsString; ABase.NomeFavorecido := FDBases.FieldByName('nom_favorecido').AsString; ABase.CNPJCPFFavorecido := FDBases.FieldByName('num_cpf_cnpj_favorecido').AsString; ABase.FormaPagamento := FDBases.FieldByName('des_forma_pagamento').AsString; ABase.CentroCusto := FDBases.FieldByName('cod_centro_custo').AsInteger; ABase.Grupo := FDBases.FieldByName('cod_grupo').AsInteger; finally Result := True; end; end; end.
unit FastMM_OSXUtil; interface type LPCSTR = PAnsiChar; LPSTR = PAnsiChar; DWORD = Cardinal; BOOL = Boolean; PSystemTime = ^TSystemTime; _SYSTEMTIME = record wYear: Word; wMonth: Word; wDayOfWeek: Word; wDay: Word; wHour: Word; wMinute: Word; wSecond: Word; wMilliseconds: Word; end; TSystemTime = _SYSTEMTIME; SYSTEMTIME = _SYSTEMTIME; SIZE_T = NativeUInt; PUINT_PTR = ^UIntPtr; const PAGE_NOACCESS = 1; PAGE_READONLY = 2; PAGE_READWRITE = 4; PAGE_WRITECOPY = 8; PAGE_EXECUTE = $10; PAGE_EXECUTE_READ = $20; PAGE_EXECUTE_READWRITE = $40; PAGE_GUARD = $100; PAGE_NOCACHE = $200; MEM_COMMIT = $1000; MEM_RESERVE = $2000; MEM_DECOMMIT = $4000; MEM_RELEASE = $8000; MEM_FREE = $10000; MEM_PRIVATE = $20000; MEM_MAPPED = $40000; MEM_RESET = $80000; MEM_TOP_DOWN = $100000; EXCEPTION_ACCESS_VIOLATION = DWORD($C0000005); //function GetModuleHandleA(lpModuleName: LPCSTR): HMODULE; stdcall; function GetEnvironmentVariableA(lpName: LPCSTR; lpBuffer: LPSTR; nSize: DWORD): DWORD; stdcall; overload; function DeleteFileA(lpFileName: LPCSTR): BOOL; stdcall; function VirtualAlloc(lpvAddress: Pointer; dwSize: SIZE_T; flAllocationType, flProtect: DWORD): Pointer; stdcall; function VirtualFree(lpAddress: Pointer; dwSize, dwFreeType: Cardinal): LongBool; stdcall; procedure RaiseException(dwExceptionCode, dwExceptionFlags, nNumberOfArguments: DWORD; lpArguments: PUINT_PTR); stdcall; type PSecurityAttributes = ^TSecurityAttributes; _SECURITY_ATTRIBUTES = record nLength: DWORD; lpSecurityDescriptor: Pointer; bInheritHandle: BOOL; end; TSecurityAttributes = _SECURITY_ATTRIBUTES; SECURITY_ATTRIBUTES = _SECURITY_ATTRIBUTES; const GENERIC_READ = DWORD($80000000); GENERIC_WRITE = $40000000; OPEN_ALWAYS = 4; FILE_ATTRIBUTE_NORMAL = $00000080; FILE_BEGIN = 0; FILE_CURRENT = 1; FILE_END = 2; INVALID_SET_FILE_POINTER = DWORD(-1); procedure GetLocalTime(var lpSystemTime: TSystemTime); stdcall; function CreateFileA(lpFileName: LPCSTR; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle): THandle; stdcall; function SetFilePointer(hFile: THandle; lDistanceToMove: Longint; lpDistanceToMoveHigh: PLongInt; dwMoveMethod: DWORD): DWORD; stdcall; function CloseHandle(hObject: THandle): BOOL; stdcall; implementation uses Posix.Stdlib, Posix.Unistd, Posix.SysMman, Posix.Fcntl, Posix.SysStat, Posix.SysTime, Posix.Time, Posix.Errno, Posix.Signal; function CreateFileA(lpFileName: LPCSTR; dwDesiredAccess, dwShareMode: DWORD; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD; hTemplateFile: THandle): THandle; stdcall; var Flags: Integer; FileAccessRights: Integer; begin // O_RDONLY open for reading only // O_WRONLY open for writing only // O_RDWR open for reading and writing // O_NONBLOCK do not block on open or for data to become available // O_APPEND append on each write // O_CREAT create file if it does not exist // O_TRUNC truncate size to 0 // O_EXCL error if O_CREAT and the file exists // O_SHLOCK atomically obtain a shared lock // O_EXLOCK atomically obtain an exclusive lock // O_NOFOLLOW do not follow symlinks // O_SYMLINK allow open of symlinks // O_EVTONLY descriptor requested for event notifications only // O_CLOEXEC mark as close-on-exec Flags := 0; FileAccessRights := S_IRUSR or S_IWUSR or S_IRGRP or S_IWGRP or S_IROTH or S_IWOTH; case dwDesiredAccess and (GENERIC_READ or GENERIC_WRITE) of //= (GENERIC_READ or GENERIC_WRITE) then GENERIC_READ or GENERIC_WRITE: Flags := Flags or O_RDWR; GENERIC_READ: Flags := Flags or O_RDONLY; GENERIC_WRITE: Flags := Flags or O_WRONLY; else Exit(THandle(-1)); end; case dwCreationDisposition of // CREATE_NEW: // CREATE_ALWAYS: // OPEN_EXISTING: OPEN_ALWAYS: Flags := Flags or O_CREAT; // TRUNCATE_EXISTING: end; Result := THandle(__open(lpFileName, Flags, FileAccessRights)); // ShareMode // smode := Mode and $F0 shr 4; // if ShareMode[smode] <> 0 then // begin // LockVar.l_whence := SEEK_SET; // LockVar.l_start := 0; // LockVar.l_len := 0; // LockVar.l_type := ShareMode[smode]; // Tvar := fcntl(FileHandle, F_SETLK, LockVar); // Code := errno; // if (Tvar = -1) and (Code <> EINVAL) and (Code <> ENOTSUP) then // EINVAL/ENOTSUP - file doesn't support locking // begin // __close(FileHandle); // Exit; // end; end; type _LARGE_INTEGER = record case Integer of 0: ( LowPart: DWORD; HighPart: Longint); 1: ( QuadPart: Int64); end; function SetFilePointer(hFile: THandle; lDistanceToMove: Longint; lpDistanceToMoveHigh: PLongInt; dwMoveMethod: DWORD): DWORD; stdcall; var dist: _LARGE_INTEGER; begin dist.LowPart := lDistanceToMove; if Assigned(lpDistanceToMoveHigh) then dist.HighPart := lpDistanceToMoveHigh^ else dist.HighPart := 0; dist.QuadPart := lseek(hFile, dist.QuadPart, dwMoveMethod); // dwMoveMethod = same as in windows if dist.QuadPart = -1 then Result := DWORD(-1) else begin Result := dist.LowPart; if Assigned(lpDistanceToMoveHigh) then lpDistanceToMoveHigh^ := dist.HighPart; end; end; procedure GetLocalTime(var lpSystemTime: TSystemTime); stdcall; var T: time_t; TV: timeval; UT: tm; begin gettimeofday(TV, nil); T := TV.tv_sec; localtime_r(T, UT); lpSystemTime.wYear := UT.tm_year; lpSystemTime.wMonth := UT.tm_mon; lpSystemTime.wDayOfWeek := UT.tm_wday; lpSystemTime.wDay := UT.tm_mday; lpSystemTime.wHour := UT.tm_hour; lpSystemTime.wMinute := UT.tm_min; lpSystemTime.wSecond := UT.tm_sec; lpSystemTime.wMilliseconds := 0; end; function CloseHandle(hObject: THandle): BOOL; stdcall; begin Result := __close(hObject) = 0; end; function StrLen(const Str: PAnsiChar): Cardinal; begin Result := Length(Str); end; function StrLCopy(Dest: PAnsiChar; const Source: PAnsiChar; MaxLen: Cardinal): PAnsiChar; var Len: Cardinal; begin Result := Dest; Len := StrLen(Source); if Len > MaxLen then Len := MaxLen; Move(Source^, Dest^, Len * SizeOf(AnsiChar)); Dest[Len] := #0; end; function StrPLCopy(Dest: PAnsiChar; const Source: AnsiString; MaxLen: Cardinal): PAnsiChar; begin Result := StrLCopy(Dest, PAnsiChar(Source), MaxLen); end; function GetModuleHandle(lpModuleName: PWideChar): HMODULE; begin Result := 0; if lpModuleName = 'kernel32' then Result := 1; end; function GetModuleHandleA(lpModuleName: LPCSTR): HMODULE; stdcall; begin Result := GetModuleHandle(PChar(string(lpModuleName))); end; function GetEnvironmentVariableA(lpName: LPCSTR; lpBuffer: LPSTR; nSize: DWORD): DWORD; stdcall; overload; var Len: Integer; Env: string; begin env := string(getenv(lpName)); Len := Length(env); Result := Len; if nSize < Result then Result := nSize; StrPLCopy(lpBuffer, env, Result); if Len > nSize then SetLastError(122) //ERROR_INSUFFICIENT_BUFFER) else SetLastError(0); end; function DeleteFileA(lpFileName: LPCSTR): BOOL; stdcall; begin Result := unlink(lpFileName) <> -1; end; // ReservedBlock := VirtualAlloc(Pointer(DebugReservedAddress), 65536, MEM_RESERVE, PAGE_NOACCESS); function VirtualAlloc(lpvAddress: Pointer; dwSize: SIZE_T; flAllocationType, flProtect: DWORD): Pointer; stdcall; var PageSize: LongInt; AllocSize: LongInt; Protect: Integer; begin if lpvAddress <> nil then begin if flAllocationType <> MEM_RESERVE then Exit(0); if flProtect <> PAGE_NOACCESS then Exit(0); PageSize := sysconf(_SC_PAGESIZE); AllocSize := dwSize - (dwSize mod PageSize) + PageSize; Result := mmap(lpvAddress, AllocSize, PROT_NONE, MAP_PRIVATE or MAP_ANON, -1, 0); Exit; end; Result := malloc(dwSize); FillChar(Result^, dwSize, 0); //Result := valloc(dwSize); // FreeItem.Addr := mmap(nil, PageSize, PROT_WRITE or PROT_EXEC, // MAP_PRIVATE or MAP_ANON, -1, 0); end; function VirtualFree(lpAddress: Pointer; dwSize, dwFreeType: Cardinal): LongBool; stdcall; begin Result := True; if dwFreetype = MEM_RELEASE then begin if lpAddress = Pointer($80800000) then munmap(lpAddress, dwSize) else free(lpAddress); end; end; procedure RaiseException(dwExceptionCode, dwExceptionFlags, nNumberOfArguments: DWORD; lpArguments: PUINT_PTR); stdcall; begin WriteLN('ACCESS VIOLATION (set breakpoint in FastMM_OSXUtil: RaiseException for easier debugging)'); kill(getppid, SIGSEGV); asm int 3; end; end; end.
unit MFichas.Controller.Usuario.Operacoes.Interfaces; interface uses MFichas.Controller.Types; type iControllerUsuarioOperacoes = interface; iControllerUsuarioOperacoesPedirSenha = interface; iControllerUsuarioOperacoes = interface ['{2E1ADF5A-9BC9-4297-9625-FB95253ACC9C}'] function PedirSenha: iControllerUsuarioOperacoesPedirSenha; end; iControllerUsuarioOperacoesPedirSenha = interface ['{00484B27-FD89-4980-8B5C-E6FCCD58836C}'] function SetTitle(ATitle: String) : iControllerUsuarioOperacoesPedirSenha; function SetTextConfirm(ATextConfirm: String) : iControllerUsuarioOperacoesPedirSenha; function SetTextCancel(ATextCancel: String) : iControllerUsuarioOperacoesPedirSenha; function SetChamada(AChamada: TTypeTipoUsuario): iControllerUsuarioOperacoesPedirSenha; function SetOperacao(AOperacao: TTypePermissoesUsuario): iControllerUsuarioOperacoesPedirSenha; function &End : iControllerUsuarioOperacoesPedirSenha; end; implementation end.
unit liMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, ComCtrls, l3Types; type TMainForm = class(TForm) feFilename: TFilenameEdit; Label1: TLabel; ProgressBar: TProgressBar; btnStart: TButton; procedure feFilenameChange(Sender: TObject); procedure btnStartClick(Sender: TObject); private procedure OnProgressProc(aState: Byte; aValue: Long; const aMsg : String = ''); { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses l3Base, l3Interfaces, liEngine; {$R *.dfm} procedure TMainForm.feFilenameChange(Sender: TObject); begin btnStart.Enabled := FileExists(feFilename.FileName); end; procedure TMainForm.btnStartClick(Sender: TObject); var l_LI: TListImporter; begin l_LI := TListImporter.Create(feFilename.FileName); try l_LI.OnProgress := OnProgressProc; l_LI.Process; finally l3Free(l_LI); btnStart.Enabled := True; end; end; procedure TMainForm.OnProgressProc(aState: Byte; aValue: Long; const aMsg : String = ''); begin case aState of piStart: begin btnStart.Enabled := False; ProgressBar.Max := aValue; ProgressBar.Position := 0; end; piCurrent: begin ProgressBar.Position := aValue; end; piEnd: begin ProgressBar.Position := ProgressBar.Max; feFilenameChange(nil); end; end; Application.ProcessMessages; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_WAVE * Implements a WAV file loader/decoder *********************************************************************************************************************** } Unit TERRA_WAVE; {$I terra.inc} Interface Uses TERRA_Stream, TERRA_Sound; Function ValidateWAV(Source:Stream):Boolean; Function WAVLoad(Source:Stream; MySound:Sound):Boolean; Implementation Uses TERRA_Error, TERRA_Utils, TERRA_FileStream, TERRA_FileUtils, TERRA_Log, TERRA_Application; Const PCM_FORMAT = 1; // Chunks IDs RIFF_ID = $46464952; // "RIFF" WAVE_ID = $45564157; // "WAVE" FMT_ID = $20746D66; // " fmt" DATA_ID = $61746164; // "data" Type TWaveHeader=Packed Record Format:Word; Channels:Word; Frequency:Cardinal; AvgBytes:Cardinal; BlockAlign:Word; Bits:Word; End; TWaveChunk=Packed Record ID:Cardinal; Size:Cardinal; End; Function FindChunk(Source:Stream; ID:Cardinal; Var Chunk:TWaveChunk):Boolean; Var Pos:Cardinal; Begin Result:=False; Pos:=Source.Position; Repeat Source.Read(@Chunk, SizeOf(Chunk)); If Chunk.ID<>ID Then Begin Inc(Pos,SizeOf(Chunk)+Chunk.Size); Source.Seek(Pos); End Else Result:=True; Until (Result) Or (Source.Position>=Source.Size); End; Function WAVLoad(Source:Stream; MySound:Sound):Boolean; Var Chunk:TWaveChunk; Header:TWaveHeader; Pos,Id :Cardinal; Size:Cardinal; Begin Result := False; Source.Read(@Chunk, SizeOf(Chunk)); Source.Read(@Id,4); If (Chunk.ID<>RIFF_ID) Or (Id<> WAVE_ID) Then Begin RaiseError('Invalid wave file.'); Exit; End; If Not FindChunk(Source, FMT_ID, Chunk ) Then Begin RaiseError('Cannot find header chunk.'); Exit; End; Pos:=Source.Position; Source.Read(@Header, SizeOf(Header)); If Header.Format<>PCM_FORMAT Then Begin RaiseError('Wave format not supported.'); Exit; End; Source.Seek(Pos+Chunk.Size); If Not FindChunk(Source, DATA_ID, Chunk ) Then Begin RaiseError('Cannot find wave data chunk.'); Exit; End; MySound.New(Chunk.Size, Header.Channels, Header.Bits, Header.Frequency); Source.Read(MySound.Data, Chunk.Size); Result := True; End; Function ValidateWAV(Source:Stream):Boolean; Var ID:FileHeader; Begin Source.Read(@ID,4); Result := CompareFileHeader(ID, 'RIFF'); End; Begin Log(logDebug, 'WAV', 'Initializing'); RegisterSoundFormat('WAV',ValidateWAV,WAVLoad); Log(logDebug, 'WAV', 'WAVE sound format registered!'); End.
{$include lem_directives.inc} unit LemRendering; {------------------------------------------------------------------------------- Some notes on the rendering here... Levels consist of terrains and objects. 1) Objects kan animate and terrain can be changed. 2) Lemmings only have collisions with terrain The alpha channel of the pixels is used to put information about the pixels in the bitmap: Bit0 = there is terrain in this pixel Bit1 = there is interactive object in this pixel (maybe this makes no sense) This is done to optimize the drawing of (funny enough) static and triggered objects. mmm how are we going to do that???? (Other ideas: pixel builder-brick, pixel erased by basher/miner/digger, triggerarea) -------------------------------------------------------------------------------} interface uses Classes, Contnrs, GR32, GR32_LowLevel, UMisc, LemTypes, LemMetaObject, LemTerrain, LemInteractiveObject, LemGraphicSet, LemLevel; // we could maybe use the alpha channel for rendering, ok thats working! // create gamerenderlist in order of rendering type TDrawItem = class private protected fOriginal: TBitmap32; // reference public constructor Create(aOriginal: TBitmap32); destructor Destroy; override; property Original: TBitmap32 read fOriginal; end; TDrawList = class(TObjectList) private function GetItem(Index: Integer): TDrawItem; protected public function Add(Item: TDrawItem): Integer; procedure Insert(Index: Integer; Item: TDrawItem); property Items[Index: Integer]: TDrawItem read GetItem; default; published end; TAnimation = class(TDrawItem) private procedure Check; procedure CheckFrame(Bmp: TBitmap32); protected fFrameHeight: Integer; fFrameCount: Integer; fFrameWidth: Integer; public constructor Create(aOriginal: TBitmap32; aFrameCount, aFrameWidth, aFrameHeight: Integer); function CalcFrameRect(aFrameIndex: Integer): TRect; function CalcTop(aFrameIndex: Integer): Integer; procedure InsertFrame(Bmp: TBitmap32; aFrameIndex: Integer); procedure GetFrame(Bmp: TBitmap32; aFrameIndex: Integer); property FrameCount: Integer read fFrameCount default 1; property FrameWidth: Integer read fFrameWidth; property FrameHeight: Integer read fFrameHeight; end; TObjectAnimation = class(TAnimation) private protected fInverted: TBitmap32; // copy of original procedure Flip; public constructor Create(aOriginal: TBitmap32; aFrameCount, aFrameWidth, aFrameHeight: Integer); destructor Destroy; override; property Inverted: TBitmap32 read fInverted; end; type // temp solution TRenderInfoRec = record // World : TBitmap32; // the actual bitmap TargetBitmap : TBitmap32; // the visual bitmap Level : TLevel; GraphicSet : TBaseGraphicSet; end; TRenderer = class private TempBitmap : TBitmap32; ObjectRenderList : TDrawList; // list to accelerate object drawing Inf : TRenderInfoRec; //Prepared: Boolean; fWorld: TBitmap32; procedure CombineTerrainDefault(F: TColor32; var B: TColor32; M: TColor32); procedure CombineTerrainNoOverwrite(F: TColor32; var B: TColor32; M: TColor32); procedure CombineTerrainErase(F: TColor32; var B: TColor32; M: TColor32); procedure CombineObjectDefault(F: TColor32; var B: TColor32; M: TColor32); procedure CombineObjectNoOverwrite(F: TColor32; var B: TColor32; M: TColor32); procedure CombineObjectOnlyOnTerrain(F: TColor32; var B: TColor32; M: TColor32); procedure PrepareTerrainBitmap(Bmp: TBitmap32; DrawingFlags: Byte); procedure PrepareObjectBitmap(Bmp: TBitmap32; DrawingFlags: Byte); protected public constructor Create; destructor Destroy; override; procedure PrepareGameRendering(const Info: TRenderInfoRec); procedure DrawTerrain(Dst: TBitmap32; T: TTerrain); procedure DrawObject(Dst: TBitmap32; O: TInteractiveObject; aFrame: Integer; aOriginal: TBitmap32 = nil); procedure EraseObject(Dst: TBitmap32; O: TInteractiveObject; aOriginal: TBitmap32 = nil); procedure DrawSpecialBitmap(Dst, Spec: TBitmap32); procedure RenderMinimap(Dst, World: TBitmap32; aColor: TColor32); procedure DrawObjects(Dst: TBitmap32); // procedure Restore(Original, Target) procedure RenderAnimatedObject(O: TInteractiveObject; aFrame: Integer); function HasPixelAt(X, Y: Integer): Boolean; // procedure DrawMask(Dst: TBitmap32; Mask: TBitmap32; X, Y: Integer); // drawmask to: world, targetbitmap, minimap procedure RenderWorld(World: TBitmap32; DoObjects: Boolean); procedure Highlight(World: TBitmap32; M: TColor32); end; const COLOR_MASK = $80FFFFFF; // transparent black flag is included! ALPHA_MASK = $FF000000; ALPHA_TERRAIN = $01000000; ALPHA_OBJECT = $02000000; // not really needed, but used // to enable black terrain. bitmaps with transparent black should include // this bit ALPHA_TRANSPARENTBLACK = $80000000; implementation uses UTools; { TDrawItem } constructor TDrawItem.Create(aOriginal: TBitmap32); begin inherited Create; fOriginal := aOriginal; end; destructor TDrawItem.Destroy; begin inherited Destroy; end; { TDrawList } function TDrawList.Add(Item: TDrawItem): Integer; begin Result := inherited Add(Item); end; function TDrawList.GetItem(Index: Integer): TDrawItem; begin Result := inherited Get(Index); end; procedure TDrawList.Insert(Index: Integer; Item: TDrawItem); begin inherited Insert(Index, Item); end; { TAnimation } function TAnimation.CalcFrameRect(aFrameIndex: Integer): TRect; begin with Result do begin Left := 0; Top := aFrameIndex * fFrameHeight; Right := Left + fFrameWidth; Bottom := Top + fFrameHeight; end; end; function TAnimation.CalcTop(aFrameIndex: Integer): Integer; begin Result := aFrameIndex * fFrameHeight; end; procedure TAnimation.Check; begin Assert(fFrameCount <> 0); Assert(Original.Width = fFrameWidth); Assert(fFrameHeight * fFrameCount = Original.Height); end; procedure TAnimation.CheckFrame(Bmp: TBitmap32); begin Assert(Bmp.Width = Original.Width); Assert(Bmp.Height * fFrameCount = Original.Height); end; constructor TAnimation.Create(aOriginal: TBitmap32; aFrameCount, aFrameWidth, aFrameHeight: Integer); begin inherited Create(aOriginal); fFrameCount := aFrameCount; fFrameWidth := aFrameWidth; fFrameHeight := aFrameHeight; Check; end; procedure TAnimation.GetFrame(Bmp: TBitmap32; aFrameIndex: Integer); // unsafe var Y, W: Integer; SrcP, DstP: PColor32; begin Check; Bmp.SetSize(fFrameWidth, fFrameHeight); DstP := Bmp.PixelPtr[0, 0]; SrcP := Original.PixelPtr[0, CalcTop(aFrameIndex)]; W := fFrameWidth; for Y := 0 to fFrameHeight - 1 do begin MoveLongWord(SrcP^, DstP^, W); Inc(SrcP, W); Inc(DstP, W); end; end; procedure TAnimation.InsertFrame(Bmp: TBitmap32; aFrameIndex: Integer); // unsafe var Y, W: Integer; SrcP, DstP: PColor32; begin Check; CheckFrame(Bmp); SrcP := Bmp.PixelPtr[0, 0]; DstP := Original.PixelPtr[0, CalcTop(aFrameIndex)]; W := fFrameWidth; for Y := 0 to fFrameHeight - 1 do begin MoveLongWord(SrcP^, DstP^, W); Inc(SrcP, W); Inc(DstP, W); end; end; { TObjectAnimation } constructor TObjectAnimation.Create(aOriginal: TBitmap32; aFrameCount, aFrameWidth, aFrameHeight: Integer); begin inherited; fInverted := TBitmap32.Create; fInverted.Assign(aOriginal); Flip; end; destructor TObjectAnimation.Destroy; begin fInverted.Free; inherited; end; procedure TObjectAnimation.Flip; //unsafe, can be optimized by making a algorithm var Temp: TBitmap32; i: Integer; procedure Ins(aFrameIndex: Integer); var Y, W: Integer; SrcP, DstP: PColor32; begin // Check; //CheckFrame(TEBmp); SrcP := Temp.PixelPtr[0, 0]; DstP := Inverted.PixelPtr[0, CalcTop(aFrameIndex)]; W := fFrameWidth; for Y := 0 to fFrameHeight - 1 do begin MoveLongWord(SrcP^, DstP^, W); Inc(SrcP, W); Inc(DstP, W); end; end; begin if fFrameCount = 0 then Exit; Temp := TBitmap32.Create; try for i := 0 to fFrameCount - 1 do begin GetFrame(Temp, i); Temp.FlipVert; Ins(i); end; finally Temp.Free; end; end; { TRenderer } procedure TRenderer.CombineTerrainDefault(F: TColor32; var B: TColor32; M: TColor32); begin if F <> 0 then begin //B := F ; B := B and not COLOR_MASK; // erase color B := B or ALPHA_TERRAIN; // put terrain bit B := B or (F and COLOR_MASK) // copy color end; end; procedure TRenderer.CombineTerrainNoOverwrite(F: TColor32; var B: TColor32; M: TColor32); begin if (F <> 0) and (B and ALPHA_TERRAIN = 0) then begin //B := F; B := B and not COLOR_MASK; // erase color B := B or ALPHA_TERRAIN; // put terrain bit B := B or (F and COLOR_MASK) // copy color end; end; procedure TRenderer.CombineTerrainErase(F: TColor32; var B: TColor32; M: TColor32); begin if F <> 0 then B := 0; end; procedure TRenderer.CombineObjectDefault(F: TColor32; var B: TColor32; M: TColor32); begin if F <> 0 then begin //B := F; B := B and not COLOR_MASK; // erase color B := B or ALPHA_OBJECT; // put object bit B := B or (F and COLOR_MASK) // copy color end; end; procedure TRenderer.CombineObjectNoOverwrite(F: TColor32; var B: TColor32; M: TColor32); begin if (F <> 0) and (B and ALPHA_MASK = 0) then begin B := B and not COLOR_MASK; // erase color B := B or ALPHA_OBJECT; // put object bit B := B or (F and COLOR_MASK) // copy color end; end; procedure TRenderer.CombineObjectOnlyOnTerrain(F: TColor32; var B: TColor32; M: TColor32); begin if (F <> 0) and (B and ALPHA_TERRAIN <> 0) then begin //B := F; B := B and not COLOR_MASK; // erase color B := B or ALPHA_OBJECT; // put object bit B := B or (F and COLOR_MASK) // copy color end; end; procedure TRenderer.PrepareTerrainBitmap(Bmp: TBitmap32; DrawingFlags: Byte); begin if DrawingFlags and tdf_NoOverwrite <> 0 then begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineTerrainNoOverwrite; end else if DrawingFlags and tdf_Erase <> 0 then begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineTerrainErase; end else begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineTerrainDefault; end; end; procedure TRenderer.PrepareObjectBitmap(Bmp: TBitmap32; DrawingFlags: Byte); begin if DrawingFlags and odf_OnlyOnTerrain <> 0 then begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineObjectOnlyOnTerrain; end else if DrawingFlags and odf_NoOverwrite <> 0 then begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineObjectNoOverwrite; end else begin Bmp.DrawMode := dmCustom; Bmp.OnPixelCombine := CombineObjectDefault; end; end; procedure TRenderer.DrawTerrain(Dst: TBitmap32; T: TTerrain); var Src: TBitmap32; begin if T.Identifier >= Inf.GraphicSet.MetaTerrains.Count then Exit; Src := Inf.GraphicSet.TerrainBitmaps.List^[T.Identifier]; if T.DrawingFlags and tdf_Invert = 0 then begin PrepareTerrainBitmap(Src, T.DrawingFlags); Src.DrawTo(Dst, T.Left, T.Top) end else begin Src.FlipVert(TempBitmap); PrepareTerrainBitmap(TempBitmap, T.DrawingFlags); TempBitmap.DrawTo(Dst, T.Left, T.Top); end; end; procedure TRenderer.DrawSpecialBitmap(Dst, Spec: TBitmap32); begin Spec.DrawMode := dmCustom; Spec.OnPixelCombine := CombineTerrainDefault; Spec.DrawTo(Dst, (784 - (Spec.Width div 2)), 80 - (Spec.Height div 2)); end; procedure TRenderer.DrawObject(Dst: TBitmap32; O: TInteractiveObject; aFrame: Integer; aOriginal: TBitmap32 = nil); {------------------------------------------------------------------------------- Draws a interactive object • Dst = the targetbitmap • O = the object • aOriginal = if specified then first a part of this bitmap (world when playing) is copied to Dst to restore -------------------------------------------------------------------------------} var SrcRect, DstRect, R: TRect; Item: TObjectAnimation;// TDrawItem; Src: TBitmap32; begin if O.Identifier >= Inf.GraphicSet.MetaObjects.Count then Exit; Assert(ObjectRenderList[O.Identifier] is TObjectAnimation); Item := TObjectAnimation(ObjectRenderList[O.Identifier]); //ObjectBitmapItems.List^[O.Identifier]; if odf_UpsideDown and O.DrawingFlags = 0 then Src := Item.Original else Src := Item.Inverted; PrepareObjectBitmap(Src, O.DrawingFlags); SrcRect := Item.CalcFrameRect(aFrame); DstRect := SrcRect; DstRect := ZeroTopLeftRect(DstRect); OffsetRect(DstRect, O.Left, O.Top); if aOriginal <> nil then begin IntersectRect(R, DstRect, aOriginal.BoundsRect); // oops important! aOriginal.DrawTo(Dst, R, R); end; Src.DrawTo(Dst, DstRect, SrcRect); end; procedure TRenderer.EraseObject(Dst: TBitmap32; O: TInteractiveObject; aOriginal: TBitmap32); {------------------------------------------------------------------------------- Draws a interactive object o Dst = the targetbitmap o O = the object o aOriginal = if specified then first a part of this bitmap (world when playing) is copied to Dst to restore -------------------------------------------------------------------------------} var SrcRect, DstRect, R: TRect; Item: TObjectAnimation;// TDrawItem; Src: TBitmap32; begin if aOriginal = nil then Exit; Assert(ObjectRenderList[O.Identifier] is TObjectAnimation); Item := TObjectAnimation(ObjectRenderList[O.Identifier]); //ObjectBitmapItems.List^[O.Identifier]; SrcRect := Item.CalcFrameRect(0); DstRect := SrcRect; DstRect := ZeroTopLeftRect(DstRect); OffsetRect(DstRect, O.Left, O.Top); IntersectRect(R, DstRect, aOriginal.BoundsRect); // oops important! aOriginal.DrawTo(Dst, R, R); end; constructor TRenderer.Create; begin inherited Create; TempBitmap := TBitmap32.Create; ObjectRenderList := TDrawList.Create; end; destructor TRenderer.Destroy; begin TempBitmap.Free; ObjectRenderList.Free; inherited Destroy; end; procedure TRenderer.RenderWorld(World: TBitmap32; DoObjects: Boolean); var i: Integer; Ter: TTerrain; Bmp: TBitmap32; Obj: TInteractiveObject; // Bmp: TBitmap32; // Item : TObjectBitmapItem; MO: TMetaObject; // tid: Integer; begin // windlg([bit32str(alpha_terrain), bit32str(alpha_object)]); //windlg([alpha_terrain shr 24, alpha_object shr 24]); World.Clear(0); if inf.level=nil then exit; if inf.graphicset=nil then exit; with Inf do begin if Inf.GraphicSet.GraphicSetIdExt > 0 then begin Bmp := Inf.GraphicSet.SpecialBitmap; DrawSpecialBitmap(World, Bmp); end else begin with Level.Terrains.HackedList do for i := 0 to Count - 1 do begin Ter := List^[i]; DrawTerrain(World, Ter); end; end; if DoObjects then with Level.InteractiveObjects.HackedList do begin for i := 0 to Count - 1 do begin Obj := List^[i]; MO := Inf.GraphicSet.MetaObjects[obj.identifier]; if odf_OnlyOnTerrain and Obj.DrawingFlags <> 0 then DrawObject(World, Obj, MO.PreviewFrameIndex); end; for i := 0 to Count - 1 do begin Obj := List^[i]; MO := Inf.GraphicSet.MetaObjects[obj.identifier]; if odf_OnlyOnTerrain and Obj.DrawingFlags = 0 then DrawObject(World, Obj, MO.PreviewFrameIndex); end; end; end; end; procedure TRenderer.PrepareGameRendering(const Info: TRenderInfoRec); var i: Integer; Item: TObjectAnimation; Bmp: TBitmap32; MO: TMetaObject; // R: TRect; begin Inf := Info; // create cache to draw from ObjectRenderList.Clear; with Inf, GraphicSet do for i := 0 to ObjectBitmaps.Count - 1 do begin MO := MetaObjects[i]; Bmp := ObjectBitmaps.List^[i]; //ReplaceColor(Bmp, 0, clBlue32); Item := TObjectAnimation.Create(Bmp, MO.AnimationFrameCount, MO.Width, MO.Height); ObjectRenderList.Add(Item); // Item.Normal.SetSizes(MO.AnimationFrameCount, MO.Width, MO.Height); // Item.Inverted.SetSizes(MO.AnimationFrameCount, MO.Width, MO.Height); // Item.Normal.Assign(Bmp); // Item.Inverted.Assign(Bmp); //Item.Inverted.FlipVertFrames; end; end; procedure TRenderer.Highlight(World: TBitmap32; M: TColor32); var i: Integer; P: PColor32; begin with World do begin P := PixelPtr[0, 0]; for i := 0 to Width * Height - 1 do begin if P^ and M <> 0 then P^ := clRed32 else P^ := 0; Inc(P); end; end; end; function TRenderer.HasPixelAt(X, Y: Integer): Boolean; begin Result := fWorld.PixelS[X, Y] and ALPHA_TERRAIN = 0; end; procedure TRenderer.RenderAnimatedObject(O: TInteractiveObject; aFrame: Integer); begin // windlg('renderobject') end; procedure TRenderer.DrawObjects; begin { with Level.InteractiveObjects.HackedList do begin for i := 0 to Count - 1 do begin Obj := List^[i]; MO := Inf.GraphicSet.MetaObjects[obj.identifier]; if odf_OnlyOnTerrain and Obj.DrawingFlags <> 0 then DrawObject(World, Obj, MO.PreviewFrameIndex); end; for i := 0 to Count - 1 do begin Obj := List^[i]; MO := Inf.GraphicSet.MetaObjects[obj.identifier]; if odf_OnlyOnTerrain and Obj.DrawingFlags = 0 then DrawObject(World, Obj, MO.PreviewFrameIndex); end; end; } end; procedure TRenderer.RenderMinimap(Dst, World: TBitmap32; aColor: TColor32); var dx, dy, sx, sy: Integer; begin (* sx := 0; sy := 0; dy := 0; dx := 0; repeat Inc(sx); if sx > until False; *) end; end.
unit fmuBillAcceptor; interface uses // VCL Windows, Forms, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Messages, Buttons, Dialogs, // This untPages, untUtil, untDriver; type { TfmBillAcceptor } TfmBillAcceptor = class(TPage) Memo: TMemo; btnGetCashBillStatus: TButton; btnGetBillAcceptorRegisters: TButton; btnBillAcceptorReport: TButton; cbRegisterNumber: TComboBox; lblRegisterNumber: TLabel; procedure btnGetCashBillStatusClick(Sender: TObject); procedure btnGetBillAcceptorRegistersClick(Sender: TObject); procedure btnBillAcceptorReportClick(Sender: TObject); private procedure AddSeparator; procedure AddLineWidth(V1, V2: Variant; TextWidth: Integer); procedure AddMemoLine(const S: string); end; implementation {$R *.DFM} { TfmECRStatus } const DescriptionWidth = 33; procedure TfmBillAcceptor.AddMemoLine(const S: string); begin Memo.Lines.Add(' ' + S); end; procedure TfmBillAcceptor.AddLineWidth(V1, V2: Variant; TextWidth: Integer); begin AddMemoLine(Format('%-*s: %s', [TextWidth, String(V1), String(V2)])); end; procedure TfmBillAcceptor.AddSeparator; begin AddMemoLine(StringOfChar('-', 40)); end; function CAModeTostr(ACAMode: Integer): string; begin case ACAMode of 0: Result := 'не ведется'; 1: Result := 'ведется'; else Result := IntToStr(ACAMode); end; end; procedure TfmBillAcceptor.btnGetCashBillStatusClick(Sender: TObject); begin EnableButtons(False); Memo.Lines.BeginUpdate; try Memo.Clear; if Driver.GetCashAcceptorStatus <> 0 then Exit; Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Запрос состояния купюроприемника:'); AddSeparator; AddLineWidth('Режим опроса купюроприемника', CAModeTostr(Driver.CashAcceptorPollingMode), 29); AddLineWidth('Poll1', Driver.Poll1, 29); AddLineWidth('Poll2', Driver.poll2, 29); Memo.Lines.Add(' Описание: ' + Driver.PollDescription); AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; finally Memo.Lines.EndUpdate; EnableButtons(True); end; end; procedure TfmBillAcceptor.btnGetBillAcceptorRegistersClick(Sender: TObject); var i: Integer; begin EnableButtons(False); Memo.Lines.BeginUpdate; try Memo.Clear; Driver.RegisterNumber := cbRegisterNumber.ItemIndex; if Driver.GetCashAcceptorRegisters <> 0 then Exit; Memo.Lines.Add(''); AddSeparator; Memo.Lines.Add(' Запрос регистров купюроприемника:'); AddSeparator; AddLineWidth('Номер набора регистров', IntToStr(Driver.RegisterNumber), 23); for i := 0 to 23 do begin Driver.BanknoteType := i; if Driver.ReadBanknoteCount <> 0 then Exit; AddLineWidth(Format('Кол-во купюр типа %.2d', [i]), Driver.BanknoteCount, 23); end; AddSeparator; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; finally Memo.Lines.EndUpdate; EnableButtons(True); end; end; procedure TfmBillAcceptor.btnBillAcceptorReportClick(Sender: TObject); begin EnableButtons(False); try Driver.CashAcceptorReport; finally EnableButtons(True); end; end; end.
unit StockDayDataAccess; interface uses define_dealItem, BaseDataSet, define_price, define_datasrc, QuickList_DayData, define_stock_quotes; type { 行情日线数据访问 } TStockDayData = record DealItem : PRT_DealItem; IsDataChangedStatus: Byte; WeightMode : Byte; DayDealData : TDayDataList; FirstDealDate : Word; // 2 LastDealDate : Word; // 2 最后记录交易时间 DataSource : TDealDataSource; end; TStockDayDataAccess = class(TBaseDataSetAccess) protected fStockDayData: TStockDayData; function GetFirstDealDate: Word; procedure SetFirstDealDate(const Value: Word); function GetLastDealDate: Word; procedure SetLastDealDate(const Value: Word); function GetEndDealDate: Word; procedure SetEndDealDate(const Value: Word); procedure SetStockItem(AStockItem: PRT_DealItem); function GetWeightMode: TRT_WeightMode; procedure SetWeightMode(value: TRT_WeightMode); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode); reintroduce; destructor Destroy; override; class function DataTypeDefine: integer; override; function FindRecord(ADate: Integer): PRT_Quote_Day; function CheckOutRecord(ADate: Word): PRT_Quote_Day; procedure DeleteRecord(ARecord: PRT_Quote_Day); function DayDataByIndex(AIndex: integer): PRT_Quote_Day; function DoGetRecords: integer; function DoGetStockOpenPrice(AIndex: integer): double; function DoGetStockClosePrice(AIndex: integer): double; function DoGetStockHighPrice(AIndex: integer): double; function DoGetStockLowPrice(AIndex: integer): double; procedure Sort; override; procedure Clear; override; property FirstDealDate: Word read GetFirstDealDate; property LastDealDate: Word read GetLastDealDate; property EndDealDate: Word read GetEndDealDate write SetEndDealDate; property StockItem: PRT_DealItem read fStockDayData.DealItem write SetStockItem; property DataSource: TDealDataSource read fStockDayData.DataSource write fStockDayData.DataSource; property WeightMode: TRT_WeightMode read GetWeightMode write SetWeightMode; end; procedure AddDealDayData(ADataAccess: TStockDayDataAccess; ATempDealDayData: PRT_Quote_Day); implementation uses QuickSortList, define_dealstore_file, SysUtils; { TStockDayDataAccess } procedure AddDealDayData(ADataAccess: TStockDayDataAccess; ATempDealDayData: PRT_Quote_Day); var tmpAddDealDayData: PRT_Quote_Day; // tmpDate: string; begin if (nil = ATempDealDayData) then exit; if (ATempDealDayData.DealDate.Value > 0) and (ATempDealDayData.PriceRange.PriceOpen.Value > 0) and (ATempDealDayData.PriceRange.PriceClose.Value > 0) and (ATempDealDayData.DealVolume > 0) and (ATempDealDayData.DealAmount > 0) then begin // tmpDate := FormatDateTime('', ATempDealDayData.DealDateTime.Value); // if '' <> tmpDate then // begin // end; tmpAddDealDayData := ADataAccess.CheckOutRecord(ATempDealDayData.DealDate.Value); tmpAddDealDayData.PriceRange.PriceHigh := ATempDealDayData.PriceRange.PriceHigh; tmpAddDealDayData.PriceRange.PriceLow := ATempDealDayData.PriceRange.PriceLow; tmpAddDealDayData.PriceRange.PriceOpen := ATempDealDayData.PriceRange.PriceOpen; tmpAddDealDayData.PriceRange.PriceClose := ATempDealDayData.PriceRange.PriceClose; tmpAddDealDayData.DealVolume := ATempDealDayData.DealVolume; tmpAddDealDayData.DealAmount := ATempDealDayData.DealAmount; tmpAddDealDayData.Weight := ATempDealDayData.Weight; end; end; constructor TStockDayDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode); begin inherited Create(AStockItem.DBType, GetDealDataSourceCode(ADataSrc)); FillChar(fStockDayData, SizeOf(fStockDayData), 0); fStockDayData.DealItem := AStockItem; fStockDayData.DayDealData := TDayDataList.Create; fStockDayData.DayDealData.Clear; fStockDayData.DayDealData.Duplicates := QuickSortList.lstDupIgnore; fStockDayData.FirstDealDate := 0; // 2 fStockDayData.LastDealDate := 0; // 2 最后记录交易时间 fStockDayData.DataSource := ADataSrc; fStockDayData.WeightMode := Byte(AWeightMode); end; destructor TStockDayDataAccess.Destroy; begin Clear; FreeAndNil(fStockDayData.DayDealData); inherited; end; class function TStockDayDataAccess.DataTypeDefine: integer; begin Result := DataType_DayData; end; procedure TStockDayDataAccess.Clear; var i: integer; tmpQuoteDay: PRT_Quote_Day; begin if nil <> fStockDayData.DayDealData then begin for i := fStockDayData.DayDealData.Count - 1 downto 0 do begin tmpQuoteDay := fStockDayData.DayDealData.DayData[i]; FreeMem(tmpQuoteDay); end; fStockDayData.DayDealData.Clear; end; end; procedure TStockDayDataAccess.SetStockItem(AStockItem: PRT_DealItem); begin if nil <> AStockItem then begin if fStockDayData.DealItem <> AStockItem then begin end; end; fStockDayData.DealItem := AStockItem; if nil <> fStockDayData.DealItem then begin end; end; function TStockDayDataAccess.GetFirstDealDate: Word; begin Result := fStockDayData.FirstDealDate; end; function TStockDayDataAccess.GetWeightMode: TRT_WeightMode; begin Result := TRT_WeightMode(fStockDayData.WeightMode); end; procedure TStockDayDataAccess.SetWeightMode(value: TRT_WeightMode); begin fStockDayData.WeightMode := Byte(value); end; procedure TStockDayDataAccess.SetFirstDealDate(const Value: Word); begin fStockDayData.FirstDealDate := Value; end; function TStockDayDataAccess.GetLastDealDate: Word; begin Result := fStockDayData.LastDealDate; end; procedure TStockDayDataAccess.SetLastDealDate(const Value: Word); begin fStockDayData.LastDealDate := Value; end; function TStockDayDataAccess.GetEndDealDate: Word; begin Result := 0; end; procedure TStockDayDataAccess.SetEndDealDate(const Value: Word); begin end; function TStockDayDataAccess.GetRecordCount: Integer; begin Result := fStockDayData.DayDealData.Count; end; function TStockDayDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := fStockDayData.DayDealData.DayData[AIndex]; end; procedure TStockDayDataAccess.Sort; begin fStockDayData.DayDealData.Sort; end; function TStockDayDataAccess.CheckOutRecord(ADate: Word): PRT_Quote_Day; begin Result := nil; if ADate < 1 then exit; Result := FindRecord(ADate); if nil = Result then begin if fStockDayData.FirstDealDate = 0 then fStockDayData.FirstDealDate := ADate; if fStockDayData.FirstDealDate > ADate then fStockDayData.FirstDealDate := ADate; if fStockDayData.LastDealDate < ADate then fStockDayData.LastDealDate := ADate; Result := System.New(PRT_Quote_Day); FillChar(Result^, SizeOf(TRT_Quote_Day), 0); Result.DealDate.Value := ADate; fStockDayData.DayDealData.AddDayData(ADate, Result); end; end; function TStockDayDataAccess.DayDataByIndex(AIndex: integer): PRT_Quote_Day; begin Result := GetRecordItem(AIndex); end; function TStockDayDataAccess.FindRecord(ADate: Integer): PRT_Quote_Day; var tmpPos: integer; begin Result := nil; tmpPos := fStockDayData.DayDealData.IndexOf(ADate); if 0 <= tmpPos then Result := fStockDayData.DayDealData.DayData[tmpPos]; end; procedure TStockDayDataAccess.DeleteRecord(ARecord: PRT_Quote_Day); var tmpPos: integer; begin if nil = ARecord then exit; tmpPos := fStockDayData.DayDealData.IndexOf(ARecord.DealDate.Value); if 0 <= tmpPos then begin fStockDayData.DayDealData.Delete(tmpPos); end; end; function TStockDayDataAccess.DoGetStockOpenPrice(AIndex: integer): double; begin Result := DayDataByIndex(AIndex).PriceRange.PriceOpen.Value; end; function TStockDayDataAccess.DoGetStockClosePrice(AIndex: integer): double; begin Result := DayDataByIndex(AIndex).PriceRange.PriceClose.Value; end; function TStockDayDataAccess.DoGetStockHighPrice(AIndex: integer): double; begin Result := DayDataByIndex(AIndex).PriceRange.PriceHigh.Value; end; function TStockDayDataAccess.DoGetStockLowPrice(AIndex: integer): double; begin Result := DayDataByIndex(AIndex).PriceRange.PriceLow.Value; end; function TStockDayDataAccess.DoGetRecords: integer; begin Result := Self.RecordCount; end; end.
{ CSI 1101-X, Winter, 1999 } { Assignment 8 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Jensen Boire } program a8 (input,output); const maxIDsize = 4 ; { maximum length of identifiers (labels, etc.) } maxStatements = 400 ; { maximum number of statements in the assembly language program, not counting comments and empty lines } null = '' ; { it is easier to distinguish the empty string from a } space = ' ' ; { one-space string when labels are used for them } type str = string[maxIDsize] ; markfile = text ; { type for text files } {********* YOU MAY CHANGE THE FOLLOWING TYPE DEFINITIONS ********} {********* The following type definitions can be used ********} {********* but you are free to change them providing: ********} {********* (1) the Symbol Table and Opcode Table must ********} {********* both be type "table" (they cannot be ********} {********* different types), and ********} {********* (2) the type "table" is a linked data type ********} {********* that uses dynamically allocated memory. ********} { The data type "table" is used for both the Symbol Table and the Opcode Table. A table is a linked list in which each node contains a next pointer and two values, called "key" and "data". The key is a string - in the Opcode Table it will be a symbolic mnemonic (e.g. 'ADD'), in the Symbol Table it will be a statement label (e.g. '[1]' or 'X'). The data value is the numerical value that corresponds to the symbolic key - e.g. in the Opcode Table the node that has key='ADD' will have data=99 (99 is the opcode for ADD). In the Symbol Table, data will be the numerical memory address that corresponds to the label (e.g. if the instruction with statement label '[1]' starts at memory location 4213, then the Symbol Table node that has key='[1]' will have data=4213. } pointer = ^node ; node = record key: str ; data: str ; { data changed from 'integer' to 'str' } next: pointer end ; table = pointer ; var memory_count: integer; infile, outfile : markfile ; ASMfile, Machinefile : string ; continue : char ; { *************** MEMORY MANAGEMENT ************************************ } { get_node - Returns a pointer to a new node. } procedure get_node(var P: pointer) ; BEGIN memory_count := memory_count + 1 ; new(P) END; { proc get_node } { return_node - Make the node pointed at by P "free" (available to get_node). } procedure return_node(var P: pointer) ; BEGIN memory_count := memory_count - 1 ; dispose(P) END; { proc return_node } { ************************************************************************* } { destroy - returns all dynamic memory associated with T } procedure destroy(var T: table) ; BEGIN if T <> nil then BEGIN destroy(T^.next) ; return_node(T) END END; { proc destroy } { create_empty - create an empty table } procedure create_empty(var T: table) ; BEGIN T := nil END; { proc create_empty } procedure chop(var S: string) ; var Slen: integer ; BEGIN if (s <> null) then BEGIN Slen := length(S) ; while (S[Slen] = space) do BEGIN delete(S, Slen, 1) ; dec(Slen) ; END { while } END { if } END; { proc chop } procedure write_table_line(var F: markfile; var T: table) ; var num_add : integer ; BEGIN if T = Nil then writeln('ERROR: Cannot write: Table is empty.') else BEGIN write(F, T^.key:4) ; if ( T^.data <> null ) then BEGIN { Need Val() instead of ReadString() for TurboPascal } ReadString(T^.data, num_add) ; write(F, (num_add div 100):3) ; write(F, (num_add mod 100):3) ; END; { if } writeln(F) END { else } END; { proc write_table_line } { update - given values for "T", "k", and "d", this procedure adds an entry to "T" that has "k" as its key part and "d" as its data part. This procedure may assume that "T" does not already contain an entry with key "k" - it does not have to check that (however, it might be useful for debugging purposes to handle this error condition). } procedure update(var T: table; k, d: str) ; var p: pointer ; BEGIN if T = Nil then BEGIN get_node(p) ; p^.key := k ; p^.data := d ; p^.next := Nil ; T := p END { if } else update(T^.next, k, d) END; { proc update } { lookup - given values for "T" and "k", this procedure searches through "T" for an entry that has a key equal to "k" and returns in "answer" the data field (integer value) for that entry. This procedure may assume an entry with key "k" will be found in table "T" - it does not have to check that (however, it might be useful for debugging purposes to handle this error condition). } procedure lookup(T: table; k: str; var answer: str) ; BEGIN if T = Nil then writeln('Lookup ERROR: Could not find value ', k, ' in table!') else if T^.key = k then answer := T^.data else lookup(T^.next, k, answer) END; { proc lookup } { create_opcode_table - reads "opcode_table" from the file whose DOS/Windows name is 'opcodes.dat'. Each line of opcodes.dat contains: a mnemonic (string of maxIDsize or fewer non-blank characters) starting in column 1, followed by one or more blanks, followed by the integer opcode corresponding to the mnemonic. } procedure create_opcode_table(var opcode_table: table) ; var opfile: markfile ; s: string ; opkey, opdata : str ; space_posn: integer ; BEGIN assign(opfile, 'opcodes.dat') ; reset(opfile) ; create_empty(opcode_table) ; while not EOF(opfile) do BEGIN readln(opfile, S) ; space_posn := pos(space, S) ; opkey := copy(S, 1, (space_posn -1)) ; opdata := copy(S, (length(S) - 1), 2) ; update(opcode_table, opkey, opdata) END; { while } close(opfile) END; { proc create_opcode_table } { read_asm_line - reads the next line of input (keyboard), and extracts from the input line values for "labl", "mnemonic", and "operand". Each input line is assumed to be an empty line or a correctly formatted line of an assembly language program. You are NOT REQUIRED to do any input checking. If the input line is empty, or is a comment ('/' in column 1), "labl", "mnemonic", and "operand" are all set to be the empty string (''). If there is a blank (' ') in column 1, "labl" is set to the empty string; otherwise "labl" is set to contain the sequence of non-blank characters starting in column 1 up to (but not including) the first blank. "mnemonic" is set to be the first sequence of non-blank characters beginning after the first blank on the line. "operand" is set to be the first sequence of non-blank characters beginning after the first blank after the end of "mnemonic". If there is no non-blank character after the end of "mnemonic", "operand" is set to the empty string (''). NOTE: "label" is a keyword in Pascal, so it cannot be used as a variable name. } procedure read_asm_line(var F: markfile; var labl, mnemonic, operand: str) ; var S, first: string ; S_len, mnem, op : integer ; BEGIN repeat if EOF(F) then BEGIN mnemonic := null ; exit END ; readln(F, S) ; first := S[1] ; S_len := length(S) ; until ( S_len > 0 ) & ( first <> '/' ) ; if first = space then labl := null else labl := copy(S, 1, 4) ; chop(labl) ; mnem := length(labl) + 2 ; while (S[mnem] = space) do inc(mnem) ; mnemonic := copy(S, mnem, 3) ; if ( S_len > (mnem + 2) ) & (S[mnem + 3] <> space) then mnemonic := mnemonic + S[mnem + 3] ; chop(mnemonic) ; op := mnem + length(mnemonic) ; while ( op <= S_len ) & ( S[op] = space ) do inc(op) ; if ( op > S_len ) then operand := null else operand := copy(S, op, (S_len - op + 1)) ; chop(operand) END; { proc read_asm_line } { assemble - This procedure reads an assembly language program and writes out the corresponding machine language program. For each non-empty, non-comment line of assembly language there must be one line of output containing its machine language equivalent. The machine language produced should be in a format that can be read by the simulator program (a8sim.pas). You must follow the two-pass algorithm shown in class. The main task of the first pass is to create a "symbol table" - this is a list that contains: - the symbolic statement labels that have occurred in the assembly language program, and, for each label, - the numerical memory address that corresponds to that label (assuming the program starts at location 0). Conversion of each symbolic mnemonic to the corresponding numerical opcode (by looking it up in the opcode table) can be done in the first pass (as in class) or on the second pass. The first pass does nothing with the symbolic operands in the assembly language program. The main task of the second pass is to convert these to addresses by looking them up in the symbol table. The second pass also prints out the machine language program line by line. } procedure assemble(var infile, outfile : markfile; name: string) ; var address, lines : integer ; labl, mnemonic, operand, answer, A : str ; SymbolTable, OpcodeTable, MachineLang, Surf_ML : table ; BEGIN address := 0 ; { starting address for the program } create_opcode_table(OpcodeTable) ; create_empty(SymbolTable) ; create_empty(MachineLang) ; lines := 0 ; {* FIRST PASS: convert mnemonics, build symbol table - need to process differently three types of input line: (1) empty lines and comments (2) lines whose mnemonic is 'BYTE' (3) lines whose mnemonic is in the opcode table. *} while ( not EOF(infile) ) & ( lines < maxStatements ) do BEGIN read_asm_line(infile, labl, mnemonic, operand ) ; if ( mnemonic = null ) then break ; {testing} writeln('Line read. labl: ', labl, ' mnem: ', mnemonic, ' op: ', operand) ; if ( labl <> null ) then BEGIN {testing} writeln('updating SymbolTable: labl = ', labl, ' / address = ', address) ; update(SymbolTable, labl, StringOf(address:4)) ; END; { if } if ( mnemonic = 'BYTE' ) then update(MachineLang, operand, null) else BEGIN lookup(OpcodeTable, mnemonic, answer) ; update(MachineLang, answer, operand) ; if (operand <> null) then address := address + 2 END; { else } inc(address) ; inc(lines) END; { while not EOF } if ( lines = maxStatements ) & ( not EOF(infile) ) then BEGIN writeln('ERROR: ASM program was truncated: # of code lines exceeds maximum: ', maxStatements) ; writeln(outfile, '/ ERROR: Processing was terminated: # of lines exceeds maximum: ', maxStatements, ' /') ; writeln(outfile) END; { if } {testing} writeln('End of first pass.') ; {* SECOND PASS: look up symbolic operands in the Symbol Table (unless the mnemonic is 'BYTE' - the operand for 'BYTE' is not a symbol, it is an integer that is to be directly used) and write out the machine language program line by line. *} writeln(outfile, '/ CSI 1101-X, Winter 1999, Assignment #8 /') ; writeln(outfile, '/ Mark Sattolo, student# 428500 /') ; writeln(outfile, '/ tutorial section DGD-4, t.a. = Jensen Boire /'); writeln(outfile, '/ Machine language file written by assembler a8 /') ; writeln(outfile, '/ Produced from ASM file ''', name, ''' /') ; Surf_ML := MachineLang ; while Surf_ML <> Nil do BEGIN A := Surf_ML^.data ; if A <> null then BEGIN lookup(SymbolTable, A, answer) ; Surf_ML^.data := answer ; END; { if } write_table_line(outfile, Surf_ML) ; Surf_ML := Surf_ML^.next END; { while } destroy(OpcodeTable) ; destroy(SymbolTable) ; destroy(MachineLang) END; { procedure assemble } procedure identify_myself ; BEGIN writeln ; writeln('CSI 1101-X (winter,1999). Assignment #8.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Jensen Boire'); writeln END ; BEGIN { main program } repeat writeln('Please enter the name of the file with the ASM code.') ; readln(ASMfile) ; assign(infile, ASMfile) ; reset(infile) ; writeln('Please enter a name to give the machine code file.') ; readln(Machinefile) ; assign(outfile, Machinefile) ; rewrite(outfile) ; identify_myself ; memory_count := 0 ; assemble(infile, outfile, ASMfile) ; writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; close(infile) ; close(outfile) ; writeln('Do you wish to process another file [ y or n ] ?') ; readln(continue) ; if ( continue in ['n', 'N'] ) then writeln('PROGRAM ENDED - have a nice day!') else writeln('========================================') until continue in ['n', 'N'] END.
unit Model.EntityGenerate; interface uses System.StrUtils, System.SysUtils, Data.DB, Model.Interfaces, Model.DAO.Interfaces, Model.DAO.Connection.FireDac, Model.FileControl, Model.Util; type TModelEntityGenerate = class(TInterfacedObject, iModelEntityGenerate) private [weak] FParent : iModelGenerator; [weak] FConnection : iModelDAOConnection; FTabela : String; function PrefixoProjeto : String; function FormataNome( aValue : String) : String; function GetFieldType( aClassName : String) : String; public constructor Create( aParent : iModelGenerator); Destructor Destroy; override; class function New( aParent : iModelGenerator) : iModelEntityGenerate; function Connection( aConnection : iModelDAOConnection) : iModelEntityGenerate; function Tabela( aValue : String) : iModelEntityGenerate; function Generate : iModelEntityGenerate; function &End :iModelGenerator; end; implementation { TModelEntityGenerate } function TModelEntityGenerate.Connection( aConnection : iModelDAOConnection) : iModelEntityGenerate; begin Result := Self; FConnection := aConnection; end; constructor TModelEntityGenerate.Create( aParent : iModelGenerator); begin FParent := aParent; end; destructor TModelEntityGenerate.Destroy; begin inherited; end; function TModelEntityGenerate.FormataNome(aValue: String): String; begin Result := Capitaliza(RemoveAcento(aValue) , FParent.Params.Captalizar, FParent.Params.RemoverCaracter); end; function TModelEntityGenerate.Generate: iModelEntityGenerate; var i: Integer; campo: string; FQuery: iModelDAOConnectionQuery; mUnit: iModelFileControl; begin Result := Self; FQuery := TModelDAOConnectionQuery.New(FConnection); FQuery .SQLClear .SQL('select * from '+ FTabela) .SQL('where 1 > 1 ') .Open; mUnit := TModelFileControl.New; mUnit .Clear .Add('unit ' + PrefixoProjeto + FParent.Params.Prefixo + '.' + FormataNome(FTabela) + ';') .Add('') .Add('interface') .Add('') .Add('uses') .Add(' System.Generics.Collections,') .Add(' System.Classes,') .Add(' Data.DB,') .Add(' Rest.Json,') .Add(' System.JSON,') .Add(' SimpleAttributes;') .Add('') .Add('type') .Add(' [Tabela(' + QuotedStr(RemoveAcento(FTabela)) + ')]') .Add(' T' + FormataNome(FTabela) + ' = class') .Add(' private'); for I := 0 to FQuery.DataSet.FieldCount - 1 do begin campo := GetFieldType(FQuery.DataSet.Fields[i].ClassName) + ';'; mUnit.Add(' F' + FormataNome(FQuery.DataSet.Fields[i].FieldName) + ': ' + campo); end; mUnit .Add('') .Add(' public') .Add(' constructor Create;') .Add(' destructor Destroy; override;') .Add('') .Add(' published') .Add('{verificar os atributos do campo de chave primária}') .Add('{Exemplo: [Campo(' + QuotedStr('NOME_CAMPO') + '), PK, AutoInc] }'); for I := 0 to FQuery.DataSet.FieldCount - 1 do begin campo := GetFieldType(FQuery.DataSet.Fields[i].ClassName); if I = 0 then mUnit.Add(' [Campo(' + quotedstr(RemoveAcento(FQuery.DataSet.Fields[i].FieldName)) + '), PK, AutoInc]') else mUnit.Add(' [Campo(' + quotedstr(RemoveAcento(FQuery.DataSet.Fields[i].FieldName)) + ')]'); mUnit.Add(' property ' + FormataNome(FQuery.DataSet.Fields[i].FieldName) + ': ' + campo + ' read F' + FormataNome(FQuery.DataSet.Fields[i].FieldName) + ' write F' + FormataNome(FQuery.DataSet.Fields[i].FieldName) + ';'); end; mUnit .Add('') .Add(' function ToJSONObject: TJsonObject;') .Add(' function ToJsonString: string;') .Add('') .Add(' end;') .Add('') .Add('implementation') .Add('') .Add('constructor T' + FormataNome(FTabela) + '.Create;') .Add('begin') .Add('') .Add('end;') .Add('') .Add('destructor T' + FormataNome(FTabela) + '.Destroy;') .Add('begin') .Add('') .Add(' inherited;') .Add('end;') .Add('') .Add('function T' + FormataNome(FTabela) + '.ToJSONObject: TJsonObject;') .Add('begin') .Add(' Result := TJson.ObjectToJsonObject(Self);') .Add('end;') .Add('') .Add('function T' + FormataNome(FTabela) + '.ToJsonString: string;') .Add('begin') .Add(' result := TJson.ObjectToJsonString(self);') .Add('end;') .Add('') .Add('end.') .SaveToFile(FParent.Params.Diretorio+'\Model\Entity\'+PrefixoProjeto + FParent.Params.Prefixo+'.'+FormataNome(FTabela)+'.pas'); FParent.Params.Display(mUnit.Text); end; function TModelEntityGenerate.GetFieldType(aClassName: String): String; const _Real = 'double'; _Integer = 'integer'; _string = 'string'; _Date = 'TDate'; _DateTime= 'TDateTime'; _Blob = 'string'; begin if aClassName = 'TIntegerField' then Result := _Integer else if aClassName = 'TSmallintField' then Result := _Integer else if aClassName = 'TLargeintField' then Result := _Integer else if aClassName = 'TIBStringField' then Result := _string else if aClassName = 'TDateField' then Result := _Date else if aClassName = 'TSQLTimeStampField' then Result := _DateTime else if aClassName = 'TBCDField' then Result := _Real else if aClassName = 'TIBBCDField' then Result := _Real else if aClassName = 'TFMTBCDField' then Result := _Real else if aClassName = 'TCurrencyField' then Result := _Real else if aClassName = 'TSingleField' then Result := _Real else if aClassName = 'TStringField' then Result := _string else if aClassName = 'TFloatField' then Result := _Real else if aClassName = 'TBlobField' then Result := _Blob else Result := _string+ ' {'+aClassName+'}'; end; class function TModelEntityGenerate.New( aParent : iModelGenerator) : iModelEntityGenerate; begin Result := Self.Create( aParent); end; function TModelEntityGenerate.PrefixoProjeto: String; begin Result := ifThen(FParent.Params.Projeto.Trim.IsEmpty, '', FParent.Params.Projeto.Trim+'.'); end; function TModelEntityGenerate.Tabela( aValue : String) : iModelEntityGenerate; begin Result := Self; FTabela := aValue; end; function TModelEntityGenerate.&End: iModelGenerator; begin Result := FParent; end; end.
program V_AV; const DEFAULT_CAP_SIZE = 16; type intArray = array[1..1] of integer; Vector = ^VectorObj; VectorObj = OBJECT PRIVATE arrPtr : ^intArray; capacityCount : integer; top : integer; //equals size initCapacity : integer; PUBLIC constructor init(userCapacity : integer); destructor done; procedure add(val : integer); virtual; procedure insertElementAt(pos : integer; val : integer); virtual; procedure getElementAt(pos : integer; var val : integer; var ok : boolean); function size : integer; function capacity : integer; procedure clear; PRIVATE procedure realloc; function isOutOfRange(pos : integer) : boolean; end; NaturalVector = ^NaturalVectorObj; NaturalVectorObj = OBJECT(VectorObj) PUBLIC procedure add(val : integer); virtual; procedure insertElementAt(pos : integer; val : integer); virtual; PRIVATE function isNatural(val : integer) : boolean; end; PrimeVector = ^PrimeVectorObj; PrimeVectorObj = OBJECT(VectorObj) PUBLIC procedure add(val : integer); virtual; procedure insertElementAt(pos : integer; val : integer); virtual; PRIVATE function isPrime(val : integer) : boolean; end; constructor VectorObj.init(userCapacity : integer); begin if(arrPtr <> NIL) then begin writeln('Can''t initialize non-empty stack!'); halt; end; if(userCapacity <= 0) then begin writeLn('No capacity given. Creating with default size ', DEFAULT_CAP_SIZE); initCapacity := DEFAULT_CAP_SIZE; end else initCapacity := userCapacity; new(arrPtr); top := 0; capacityCount := initCapacity; GetMem(arrPtr, SIZEOF(integer) * capacityCount); end; destructor VectorObj.done; begin freeMem(arrPtr, SIZEOF(integer) * capacityCount); arrPtr := NIL; end; procedure VectorObj.add(val : integer); begin if top >= capacityCount then begin realloc; end; inc(top); (*$R-*) arrPtr^[top] := val; (*$R+*) end; procedure VectorObj.insertElementAt(pos : integer; val : integer); var i : integer; begin inc(top); if(isOutOfRange(pos)) then pos := top else if pos < 0 then pos := 0; i := top; while (i > pos) do begin (*$R-*) arrPtr^[i] := arrPtr^[i-1]; (*$R+*) dec(i); end; (*$R-*) arrPtr^[pos] := val; (*$R+*) end; procedure VectorObj.getElementAt(pos : integer; var val : integer; var ok : boolean); begin ok := TRUE; if(isOutOfRange(pos)) then begin ok := FALSE; val := -1; exit; end; (*$R-*) val := arrPtr^[pos]; (*$R+*) end; function VectorObj.size : integer; begin size := top; end; function VectorObj.capacity : integer; begin capacity := capacityCount; end; procedure VectorObj.clear; begin if arrPtr = NIL then begin writeLn('Cannot dispose uninitialized vector!'); halt; end; freeMem(arrPtr, SIZEOF(integer) * capacityCount); arrPtr := NIL; init(initCapacity); end; procedure VectorObj.realloc; var newArray : ^intArray; i : integer; begin getMem(newArray, SIZEOF(INTEGER) * 2 * capacityCount); for i := 1 to top do begin (*$R-*) newArray^[i] := arrPtr^[i]; (*$R+*) end; freeMem(arrPtr, SIZEOF(integer) * capacityCount); capacityCount := 2 * capacityCount; arrPtr := newArray; end; function VectorObj.isOutOfRange(pos : integer) : boolean; begin if pos > top then isOutOfRange := TRUE else isOutOfRange := FALSE end; procedure NaturalVectorObj.add(val : integer); begin if NOT isNatural(val) then begin writeln('Given value is not a natural number!'); exit; end; inherited add(val); end; procedure NaturalVectorObj.insertElementAt(pos : integer; val : integer); begin if NOT isNatural(val) then begin writeln('Given value is not a natural number!'); exit; end; inherited insertElementAt(pos, val); end; function NaturalVectorObj.isNatural(val : integer) : boolean; begin if(val >= 0) then isNatural := TRUE else isNatural := FALSE; end; procedure PrimeVectorObj.add(val : integer); begin if NOT isPrime(val) then begin writeln('Given value is not a prime number!'); exit; end; inherited add(val); end; procedure PrimeVectorObj.insertElementAt(pos : integer; val : integer); begin if NOT isPrime(val) then begin writeln('Given value is not a prime number!'); exit; end; inherited insertElementAt(pos, val); end; function PrimeVectorObj.isPrime(val : integer) : boolean; var i : integer; begin isPrime := TRUE; if(val <= 1) then begin isPrime := FALSE; exit; end; for i := 2 to val div 2-1 do if val mod i = 0 then isPrime := FALSE; end; var intVector : vector; natVector : NaturalVector; priVector : PrimeVector; i : integer; tVal : integer; ok : boolean; begin New(intVector, init(4)); New(natVector, init(20)); New(priVector, init(17)); for i := -20 to 20 do begin intVector^.add(i); natVector^.add(i); priVector^.add(i); end; writeLn('Current size intVec: ', intVector^.size); writeLn('Current size natVector: ', natVector^.size); writeLn('Current size priVector: ', priVector^.size); write('intVec=['); for i := 1 to intVector^.capacity do begin intVector^.getElementAt(i, tVal, ok); if(ok) then write(tVal,',') end; write(']'); writeln; write('natVec=['); for i := 1 to natVector^.capacity do begin natVector^.getElementAt(i, tVal, ok); if(ok) then write(tVal,',') end; write(']'); writeln; write('priVec=['); for i := 1 to priVector^.capacity do begin priVector^.getElementAt(i, tVal, ok); if(ok) then write(tVal,',') end; write(']'); writeln; end.
unit frmContacts; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListBox, FMX.StdCtrls, FMX.ListView, CommonHeader, strutils, FmxJabberTools, FMX.TabControl, FMX.Layouts, FMX.Memo, FMX.Objects, frmAddContact; type TFormContacts = class(TForm) ListViewContacts: TListView; lbDisplayName: TLabel; cmbAvailability: TComboBox; btnAddcontact: TButton; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabControl2: TTabControl; lbContactsList: TLabel; ImgUserstatus: TImage; procedure FormCreate(Sender: TObject); procedure btnAddcontactClick(Sender: TObject); procedure cmbAvailabilityChange(Sender: TObject); procedure ListViewContactsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ListViewContactsDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); private procedure OnNewContactProc(AJID : string); procedure OnMessageReceivedProc(AFrom, AMessage : string); procedure OnAskTosendMessageProc(ATo, AMessage : string); function GetTabIndex(ATagString : string ) : integer; procedure CreateConversation(AContact : PContact); overload; procedure OnPResenceCallBack(AJid : String); procedure UpdateContactDisplay(AIdx : integer); procedure ContactAskToAddProc(Jid : string; var AAccept : Boolean); procedure OnAddContactStatusProc(AJid : string; AAccepted : Boolean); public procedure ShowContacts; end; var FormContacts: TFormContacts; implementation {$R *.fmx} uses frmConversation, frmConnect; procedure TFormContacts.btnAddcontactClick(Sender: TObject); var wID : string; begin if InputQuery('Add new contact', 'Set user ID',wID) then GJabberClient.AddContact(wID,wID,''); end; procedure TFormContacts.cmbAvailabilityChange(Sender: TObject); begin case cmbAvailability.ItemIndex of 0 : GJabberClient.SetPresence(usOnline, ''); 1 : GJabberClient.SetPresence(usAway, ''); 2 : GJabberClient.SetPresence(usInVisible, ''); end; end; procedure TFormContacts.ContactAskToAddProc(Jid : string; var AAccept: Boolean); var wContactName : String; begin AAccept := False; wContactName := jid; if MessageDlg(wContactName + ' want to add you to it''s contacts list, ok ?',TMsgDlgType.mtConfirmation,mbYesNo,0) = mrYes then AAccept := True; end; procedure TFormContacts.CreateConversation(AContact : PContact); var wNewTab : TTabItem; wFrame : TFrameConversation; begin try wNewTab := TTabItem.Create(TabControl2); wNewTab.Text := AContact.Jid; wNewTab.TagString := AContact.Jid; wFrame := TFrameConversation.Create(Self); wFrame.Name := 'Frame_' + inttostr(TabControl2.TabCount); wFrame.Parent := wNewTab; wFrame.MessageTo :=AContact.Jid; wFrame.OnSendMessage := OnAskTosendMessageProc; wFrame.Initialize(AContact.Jid); TabControl2.AddObject(wNewTab); wFrame.Align := TAlignLayout.alClient; except On E:Exception do Raise Exception.create('[TFormContacts.CreateConversation] : '+E.message); end; end; procedure TFormContacts.FormClose(Sender: TObject; var Action: TCloseAction); begin if GJabberClient.Connected then GJabberClient.Disconnect; FormConnect.Close; end; procedure TFormContacts.FormCreate(Sender: TObject); begin Caption := GJabberClient.Login; GJabberClient.OnNewContact := OnNewContactProc; GJabberClient.OnMessageReceived := OnMessageReceivedProc; GJabberClient.OnUpdatePresence := OnPResenceCallBack; GJabberClient.OnContactAskToAdd := ContactAskToAddProc; GJabberClient.OnAddContactStatus := OnAddContactStatusProc; end; function TFormContacts.GetTabIndex(ATagString: string): integer; var i : integer; begin Result := -1; for i := 0 to TabControl2.TabCount -1 do if Pos(uppercase(TabControl2.Tabs[i].TagString) , UpperCase(ATagString)) > 0 then begin Result := i; Break; end; end; procedure TFormContacts.ListViewContactsClick(Sender: TObject); var wTabID : integer; wContact : PContact; begin if ListViewContacts.ItemIndex <> -1 then begin wContact := GJabberClient.Contacts[ListViewContacts.ItemIndex]; wTabID := GetTabIndex( wContact.Jid ); if wTabID = -1 then begin CreateConversation(wContact); wTabID := TabControl2.TabCount -1; end; TabControl1.ActiveTab := TabItem2; TabControl2.TabIndex := wTabID; end; end; procedure TFormContacts.ListViewContactsDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); begin if MessageDlg('Are you sure you want to delete the user ' + ListViewContacts.Items[AIndex].Text + '?',TMsgDlgType.mtConfirmation, mbYesNo,0) = mrYes then begin ACanDelete := True; GJabberClient.RemoveContact(AIndex); end else ACanDelete := False; end; procedure TFormContacts.OnAddContactStatusProc(AJid: string; AAccepted: Boolean); begin // if AAccepted then // showmessage(AJid + ' accepted your request.') // else // showmessage(AJid + ' refused your request.'); end; procedure TFormContacts.OnAskTosendMessageProc(ATo, AMessage: string); begin GJabberClient.SendMessage(ATo, AMessage); end; procedure TFormContacts.OnMessageReceivedProc(AFrom, AMessage: string); var i, wTabID : Integer; wFrame : TFrameConversation; wContact : PContact; wUnreadMsgColor : TAlphaColorRec; begin ListViewContacts.BeginUpdate; try wTabID := GetTabIndex(AFrom); if wTabID <> -1 then begin wFrame := TFrameConversation(FindComponent('Frame_' + inttostr(wTabID))); if wFrame <> nil then begin wFrame.TalkComp.AddMessageFromPeople2( AMessage ); wFrame.MemText2Send.SetFocus; end; end else begin for i := 0 to GJabberClient.ContactsCount -1 do begin wContact := GJabberClient.Contacts[i]; if Pos(uppercase(wContact.Jid), uppercase(AFrom)) > 0 then begin CreateConversation(GJabberClient.Contacts[i]); wTabID := GetTabIndex(AFrom); if wTabID <> -1 then begin wFrame := TFrameConversation(FindComponent('Frame_' + inttostr(wTabID))); if wFrame <> nil then begin wFrame.TalkComp.AddMessageFromPeople2( AMessage ); wFrame.MemText2Send.SetFocus; end; end; ListViewContacts.Items[i].Detail := '! New message !'; ListViewContacts.Repaint; Break; end; end; end; finally ListViewContacts.EndUpdate; end; end; procedure TFormContacts.OnNewContactProc(AJID : string); begin ShowContacts; end; procedure TFormContacts.OnPResenceCallBack(AJid: String); var i : integer; begin if AJid = '-2' then begin case GJabberClient.UserStatus of usOnline : begin cmbAvailability.ItemIndex := 0; ImgUserstatus.Bitmap.Assign(FormConnect.OnlineImage.Bitmap); //LoadFromFile(GetImageFilename('online.png')); end; usAway : begin cmbAvailability.ItemIndex := 1; ImgUserstatus.Bitmap.Assign(FormConnect.BusyImage.Bitmap); //LoadFromFile(GetImageFilename('busy.png')); end; usInVisible : begin cmbAvailability.ItemIndex := 2; ImgUserstatus.Bitmap.Assign(FormConnect.OfflineImage.Bitmap); //LoadFromFile(GetImageFilename('offline.png')); end; end; end else begin for i := 0 to GJabberClient.ContactsCount -1 do begin if CompareText(AJid,GJabberClient.Contacts[i].Jid) = 0 then UpdateContactDisplay(i); end; end; end; procedure TFormContacts.ShowContacts; var i : integer; wContact : PContact; wTListViewItem : TListViewItem; begin ListViewContacts.ClearItems; FormContacts.ListViewContacts.BeginUpdate; try for i := 0 to GJabberClient.ContactsCount -1 do begin wTListViewItem := ListViewContacts.Items.Add; wContact := GJabberClient.Contacts[i]; wTListViewItem.Text := IFTHEN(wContact.Name = '', wContact.Jid, wContact.Name); wTListViewItem.Detail := wContact.ADisplayMessage; wTListViewItem.Bitmap.Assign(FormConnect.OfflineImage.Bitmap); //LoadFromFile(GetImageFilename('offline.png')); end; finally FormContacts.ListViewContacts.EndUpdate; end; end; procedure TFormContacts.UpdateContactDisplay(AIdx: integer); begin ListViewContacts.Items[Aidx].Detail := GJabberClient.Contacts[AIdx].ADisplayMessage; case GJabberClient.Contacts[AIdx].AStatus of usOnline : ListViewContacts.Items[Aidx].Bitmap.Assign(FormConnect.OnlineImage.Bitmap); //LoadFromFile(GetImageFilename('online.png')); usAway : ListViewContacts.Items[Aidx].Bitmap.Assign(FormConnect.BusyImage.Bitmap); //LoadFromFile(GetImageFilename('busy.png')); usInVisible : ListViewContacts.Items[Aidx].Bitmap.Assign(FormConnect.OfflineImage.Bitmap); //LoadFromFile(GetImageFilename('offline.png')); end; end; end.
{ //************************************************************// } { // // } { // Código gerado pelo assistente // } { // // } { // Projeto MVCBr // } { // tireideletra.com.br / amarildo lacerda // } { //************************************************************// } { // Data: 16/04/2017 22:28:42 // } { //************************************************************// } unit masterDetail.Controller.Interf; /// /// <summary> /// ImaterDetailController /// Interaface de acesso ao object factory do controller /// </summary> /// interface uses System.SysUtils, {$IFDEF LINUX} {$ELSE} {$IFDEF FMX} FMX.Forms, {$ELSE}VCL.Forms, {$ENDIF} {$ENDIF} System.Classes, MVCBr.Interf; type ImaterDetailController = interface(IController) ['{CEB04DF6-3891-40A5-BA0B-7CF7A8E9909F}'] // incluir especializações aqui end; Implementation end.
program Median (input, output); { bestimmt den Median einer einzugebenden Buchstabenfolge aus mindestens zweich verschiedenen Kleinbuchstaben } type tBuchst = 'a'..'z'; tNatZahl = 0..maxint; tFeld = array [tBuchst] of boolean; var vorhanden : tFeld; gesamt, i, MedianPos : tNatZahl; Buchstabe : tBuchst; Zeichen : char; begin { Eingabe anfordern } writeln('Geben Sie eine Kleinbuchstaben-Folge ein.'); writeln('Eingabe-Ende durch ein anderes Zeichen'); { Initialisierung } for Buchstabe := 'a' to 'z' do vorhanden[Buchstabe] := false; gesamt := 0; { Einlesen und Markierungen setzen } read (Zeichen); while (Zeichen >= 'a') and (Zeichen <= 'z') do begin if not vorhanden[Zeichen] then begin vorhanden[Zeichen] := true; gesamt := gesamt + 1 end; read (Zeichen) end; writeln; { Alle Buchstaben und Marken ausgeben } for Buchstabe := 'a' to 'z' do write (Buchstabe); writeln; for Buchstabe := 'a' to 'z' do if vorhanden[Buchstabe] then write ('*') else write (' '); writeln; { Median suchen } MedianPos := (gesamt +1) div 2; Buchstabe := 'a'; i := 0; repeat if vorhanden[Buchstabe] then i := i + 1; Buchstabe := succ (Buchstabe) until i = MedianPos; writeln ('Der Median ist: ', pred (Buchstabe), '.') end. { Median }
unit MemoForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FormOperations, StdCtrls, SaveStatusForms; type TFormMemo = class(TSaveStatusForm, IFormOperations) Memo1: TMemo; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; private { Private declarations } public procedure Load; procedure Save; end; var FormMemo: TFormMemo; implementation {$R *.DFM} { TForm2 } procedure TFormMemo.Load; begin if OpenDialog1.Execute then Memo1.Lines.LoadFromFile(OpenDialog1.FileName); end; procedure TFormMemo.Save; begin if SaveDialog1.Execute then Memo1.Lines.SaveToFile(SaveDialog1.FileName); end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSTransportTypes.pas } { File version: 5.01 } { Description: TLS Transport Types } { } { Copyright: Copyright (c) 2008-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: } { } { 2020/05/01 5.01 Initial version: Options. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSTransportTypes; interface type TTLSLogType = ( tlsltDebug, tlsltParameter, tlsltInfo, tlsltWarning, tlsltError ); type TTLSVersionOption = ( tlsvoSSL3, tlsvoTLS10, tlsvoTLS11, tlsvoTLS12 ); TTLSVersionOptions = set of TTLSVersionOption; const AllTLSVersionOptions = [ tlsvoSSL3, tlsvoTLS10, tlsvoTLS11, tlsvoTLS12 ]; type TTLSKeyExchangeOption = ( tlskeoRSA, tlskeoDH_Anon, tlskeoDH_RSA, tlskeoDHE_RSA, tlskeoECDH_RSA, tlskeoECDHE_RSA ); TTLSKeyExchangeOptions = set of TTLSKeyExchangeOption; const AllTLSKeyExchangeOptions = [ tlskeoRSA, tlskeoDH_Anon, tlskeoDH_RSA, tlskeoDHE_RSA, tlskeoECDH_RSA, tlskeoECDHE_RSA ]; type TTLSCipherOption = ( tlscoRC4, tlscoDES, tlsco3DES, tlscoAES128, tlscoAES256 ); TTLSCipherOptions = set of TTLSCipherOption; const AllTLSCipherOptions = [ tlscoRC4, tlscoDES, tlsco3DES, tlscoAES128, tlscoAES256 ]; type TTLSHashOption = ( tlshoMD5, tlshoSHA1, tlshoSHA256, tlshoSHA384 ); TTLSHashOptions = set of TTLSHashOption; const AllTLSHashOptions = [ tlshoMD5, tlshoSHA1, tlshoSHA256, tlshoSHA384 ]; implementation end.
{$IFDEF VER1_0} {$IFDEF ENDIAN_LITTLE} {$DEFINE FPC_LITTLE_ENDIAN} {$ENDIF ENDIAN_LITTLE} {$IFDEF ENDIAN_BIG} {$DEFINE FPC_BIG_ENDIAN} {$ENDIF ENDIAN_BIG} {$ENDIF VER1_0} {$IFDEF FPC_LITTLE_ENDIAN} {$IFDEF FPC_BIG_ENDIAN} {$FATAL Both FPC_LITTLE_ENDIAN and FPC_BIG_ENDIAN defined?!} {$ENDIF FPC_BIG_ENDIAN} {$ELSE FPC_LITTLE_ENDIAN} {$IFNDEF FPC_BIG_ENDIAN} {$FATAL Neither FPC_LITTLE_ENDIAN, nor FPC_BIG_ENDIAN defined?!} {$ENDIF FPC_BIG_ENDIAN} {$ENDIF FPC_LITTLE_ENDIAN} {$IFDEF FPC_LITTLE_ENDIAN} {$INFO FPC_LITTLE_ENDIAN} {$ENDIF FPC_LITTLE_ENDIAN} {$IFDEF FPC_BIG_ENDIAN} {$INFO FPC_BIG_ENDIAN} {$ENDIF FPC_BIG_ENDIAN}
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StVArr.pas 4.04 *} {*********************************************************} {* SysTools: Virtual matrix class *} {*********************************************************} {$I StDefine.inc} {$I+} {trap I/O exceptions here} {Notes: - The virtual matrix uses a disk file for the main storage of a two-dimensional array. A specified number of rows from the matrix can be stored in a memory cache. - The cache must be large enough to hold at least 2 rows. In 16-bit mode, the cache can hold at most about 5460 rows. In 32-bit mode, the number of cached rows is essentially unlimited. - Normally the disk file is treated as a pure file of rows, where each row is composed of cell columns. By overriding the HeaderSize, WriteHeader, and ReadHeader methods, the application can use a file that has a header prior to the array data. - By defining a matrix of one column, the TStVMatrix class can be used as a cache manager for any file of record. } unit StVArr; interface uses Windows, Classes, SysUtils, StConst, StBase, StUtils; {used for ExchangeStructs} type {.Z-} TStCacheRec = record crRow : Cardinal; {row number in cache} crRowData : Pointer; {pointer to row buffer} crTime : Integer; {quasi-time last used} crDirty : Integer; {non-zero if Row changed in memory} end; TStCacheArray = array[0..(StMaxBlockSize div SizeOf(TStCacheRec))-1] of TStCacheRec; PStCacheArray = ^TStCacheArray; {.Z-} TStVMatrix = class(TStContainer) {.Z+} protected {property instance variables} FRows : Cardinal; {number of rows} FCacheRows: Integer; {number of cached rows} FCols : Cardinal; {number of columns} FElSize : Integer; {size of each array element} {private instance variables} vmRowSize : Integer; {number of bytes in a row} vmCacheCnt : Integer; {number of used rows in cache} vmCacheTime: Integer; {quasi-time for LRU} vmCache : PStCacheArray; {sorted collection of cached rows} vmDataF : Integer; {data file} {protected undocumented methods} procedure ForEachUntypedVar(Action : TIterateUntypedFunc; OtherData : pointer); override; procedure GetArraySizes(var RowCount, ColCount, ElSize : Cardinal); override; procedure SetArraySizes(RowCount, ColCount, ElSize : Cardinal); override; function StoresUntypedVars : boolean; override; procedure vmSetCacheRows(CacheRows : Integer); procedure vmAllocateCache; procedure vmDeallocateCache; procedure vmInvalidateCache; procedure vmFlushCacheNode(CacheIndex : Integer); function vmIncCacheTime : Integer; function vmSearchCache(Row : Cardinal; var CacheIndex : Integer) : Boolean; function vmGetRowData(Row : Cardinal; MakeDirty : Boolean) : Pointer; procedure vmWriteRow(Row : Cardinal; Data : Pointer; Seek : Boolean); procedure vmSetRows(Rows : Cardinal); {.Z-} public constructor Create(Rows, Cols, ElementSize : Cardinal; CacheRows : Integer; const DataFile : string; OpenMode : Word); virtual; {-Initialize a virtual 2D matrix} destructor Destroy; override; {-Free a virtual 2D matrix} procedure FlushCache; {-Write any dirty cache rows to disk} function HeaderSize : Integer; virtual; {-Return the header size of the array file, default 0} procedure WriteHeader; virtual; {-Write a header to the array file, default none} procedure ReadHeader; virtual; {-Read a header from the array file, default none} procedure Assign(Source: TPersistent); override; {-Assign another container's contents to this one} procedure Clear; override; {-Fill the matrix with zeros} procedure Fill(const Value); {-Fill matrix with specified element value} procedure Put(Row, Col : Cardinal; const Value); {-Set an element} procedure Get(Row, Col : Cardinal; var Value); {-Return an element} procedure PutRow(Row : Cardinal; const RowValue); {-Set an entire row} procedure GetRow(Row : Cardinal; var RowValue); {-Return an entire row} procedure ExchangeRows(Row1, Row2 : Cardinal); {-Exchange the specified rows} procedure SortRows(KeyCol : Cardinal; Compare : TUntypedCompareFunc); {-Sort the array rows using the given comparison function and the elements in the given column} property Rows : Cardinal {-Read or write the number of rows in the array} read FRows write vmSetRows; property CacheRows : Integer {-Read or write the number of cache rows in the array} read FCacheRows write vmSetCacheRows; property Cols : Cardinal {-Read the number of columns in the array} read FCols; property ElementSize : Integer {-Read the size of each element in the array} read FElSize; end; implementation function AssignMatrixData(Container : TStContainer; var Data; OtherData : Pointer) : Boolean; far; var OurMatrix : TStVMatrix absolute OtherData; RD : TAssignRowData absolute Data; begin OurMatrix.PutRow(RD.RowNum, RD.Data); Result := true; end; procedure TStVMatrix.Assign(Source: TPersistent); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {The only containers that we allow to be assigned to a large matrix are: - a SysTools large array (TStLArray) - a SysTools large matrix (TStLMatrix) - another SysTools virtual matrix (TStVMatrix)} if not AssignUntypedVars(Source, AssignMatrixData) then inherited Assign(Source); {$IFDEF ThreadSafe} finally LeaveCS; end;{try..finally} {$ENDIF} end; procedure TStVMatrix.Clear; var Row : Cardinal; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} vmInvalidateCache; vmCacheCnt := 1; with vmCache^[0] do begin FillChar(crRowData^, vmRowSize, 0); crRow := 0; crTime := vmIncCacheTime; crDirty := 0; FileSeek(vmDataF, 0, 0); WriteHeader; for Row := 0 to FRows-1 do vmWriteRow(Row, crRowData, False); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.ForEachUntypedVar(Action : TIterateUntypedFunc; OtherData : pointer); var FullRow : ^TAssignRowData; i : Cardinal; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} GetMem(FullRow, sizeof(Cardinal) + vmRowSize); try for i := 0 to pred(Rows) do begin FullRow^.RowNum := i; GetRow(i, FullRow^.Data); Action(Self, FullRow^, OtherData); end; finally FreeMem(FullRow, sizeof(Cardinal) + vmRowSize); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.GetArraySizes(var RowCount, ColCount, ElSize : Cardinal); begin RowCount := Rows; ColCount := Cols; ElSize := ElementSize; end; procedure TStVMatrix.SetArraySizes(RowCount, ColCount, ElSize : Cardinal); begin if (ColCount <> Cols) then RaiseContainerError(stscBadColCount); if (Integer(ElSize) <> ElementSize) then RaiseContainerError(stscBadElSize); if (RowCount <> Rows) then begin Rows := RowCount; end; end; function TStVMatrix.StoresUntypedVars : boolean; begin Result := true; end; constructor TStVMatrix.Create(Rows, Cols, ElementSize : Cardinal; CacheRows : Integer; const DataFile : string; OpenMode : Word); begin FElSize := ElementSize; FRows := Rows; FCols := Cols; FCount := Integer(Rows)*Integer(Cols); vmRowSize := Integer(Cols)*Integer(ElementSize); FCacheRows := CacheRows; vmDataF := -1; CreateContainer(TStNode, 0); if (Rows = 0) or (Cols = 0) or (ElementSize = 0) or (CacheRows < 2) or ProductOverflow(Cols, ElementSize) or ProductOverflow(Integer(Cols)*Integer(ElementSize), Rows) or (Integer(Cols)*Integer(ElementSize)*Integer(Rows) > MaxLongInt-HeaderSize) or (CacheRows > StMaxBlockSize div SizeOf(TStCacheRec)) then RaiseContainerError(stscBadSize); vmAllocateCache; {open the data file} vmDataF := FileOpen(DataFile, OpenMode); if vmDataF < 0 then begin {file not found, create it} vmDataF := FileCreate(DataFile); if vmDataF < 0 then RaiseContainerError(stscFileCreate) else begin FileClose(vmDataF); vmDataF := FileOpen(DataFile, OpenMode); if vmDataF < 0 then RaiseContainerError(stscFileOpen); {write user defined header to file} WriteHeader; FileSeek(vmDataF, 0, 0); end; end; {read user defined header from file} ReadHeader; end; destructor TStVMatrix.Destroy; begin if Assigned(vmCache) then begin if vmDataF > 0 then FlushCache; vmDeallocateCache; end; if vmDataF > 0 then begin {write user defined header to file} FileSeek(vmDataF, 0, 0); WriteHeader; FileClose(vmDataF); end; IncNodeProtection; inherited Destroy; end; procedure TStVMatrix.ExchangeRows(Row1, Row2 : Cardinal); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {$IFOPT R+} if (Row1 >= Rows) or (Row2 >= Rows) then RaiseContainerError(stscBadIndex); {$ENDIF} ExchangeStructs(vmGetRowData(Row1, True)^, vmGetRowData(Row2, True)^, vmRowSize); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.Fill(const Value); var Row : Cardinal; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} vmInvalidateCache; vmCacheCnt := 1; with vmCache^[0] do begin HugeFillStruc(crRowData^, FCols, Value, FElSize); crRow := 0; crTime := vmIncCacheTime; crDirty := 0; FileSeek(vmDataF, 0, 0); WriteHeader; for Row := 0 to FRows-1 do vmWriteRow(Row, crRowData, False); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.FlushCache; var I : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} for I := 0 to vmCacheCnt-1 do vmFlushCacheNode(I); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.Get(Row, Col : Cardinal; var Value); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {$IFOPT R+} if (Row >= Rows) or (Col >= Cols) then RaiseContainerError(stscBadIndex); {$ENDIF} Move(PAnsiChar(vmGetRowData(Row, False))[Integer(Col)*FElSize], Value, FElSize); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.GetRow(Row : Cardinal; var RowValue); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {$IFOPT R+} if Row >= Rows then RaiseContainerError(stscBadIndex); {$ENDIF} Move(vmGetRowData(Row, False)^, RowValue, vmRowSize); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStVMatrix.HeaderSize : Integer; begin Result := 0; end; procedure TStVMatrix.ReadHeader; begin {does nothing by default} {can assume that FilePos = 0 when this is called} end; procedure TStVMatrix.Put(Row, Col : Cardinal; const Value); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {$IFOPT R+} if (Row >= Rows) or (Col >= Cols) then RaiseContainerError(stscBadIndex); {$ENDIF} Move(Value, PAnsiChar(vmGetRowData(Row, True))[Integer(Col)*FElSize], FElSize); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.PutRow(Row : Cardinal; const RowValue); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {$IFOPT R+} if Row >= Rows then RaiseContainerError(stscBadIndex); {$ENDIF} Move(RowValue, vmGetRowData(Row, True)^, vmRowSize); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.SortRows(KeyCol : Cardinal; Compare : TUntypedCompareFunc); const StackSize = 32; type Stack = array[0..StackSize-1] of Integer; var L : Integer; R : Integer; PL : Integer; PR : Integer; CurEl : Pointer; PivEl : Pointer; StackP : Integer; LStack : Stack; RStack : Stack; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if KeyCol >= Cols then RaiseContainerError(stscBadIndex); {Need at least 2 rows to sort} if FRows <= 1 then Exit; GetMem(CurEl, FElSize); try GetMem(PivEl, FElSize); {Initialize the stacks} StackP := 0; LStack[0] := 0; RStack[0] := FRows-1; {Repeatedly take top partition from stack} repeat {Pop the stack} L := LStack[StackP]; R := RStack[StackP]; Dec(StackP); {Sort current partition} repeat {Load the pivot element} Get((L+R) div 2, KeyCol, PivEl^); PL := L; PR := R; {Swap items in sort order around the pivot index} repeat Get(PL, KeyCol, CurEl^); while Compare(CurEl^, PivEl^) < 0 do begin Inc(PL); Get(PL, KeyCol, CurEl^); end; Get(PR, KeyCol, CurEl^); while Compare(PivEl^, CurEl^) < 0 do begin Dec(PR); Get(PR, KeyCol, CurEl^); end; if PL <= PR then begin if PL <> PR then {Swap the two elements} ExchangeRows(PL, PR); Inc(PL); {assume we'll never sort 2 billion elements} Dec(PR); end; until PL > PR; {Decide which partition to sort next} if (PR-L) < (R-PL) then begin {Right partition is bigger} if PL < R then begin {Stack the request for sorting right partition} Inc(StackP); LStack[StackP] := PL; RStack[StackP] := R; end; {Continue sorting left partition} R := PR; end else begin {Left partition is bigger} if L < PR then begin {Stack the request for sorting left partition} Inc(StackP); LStack[StackP] := L; RStack[StackP] := PR; end; {Continue sorting right partition} L := PL; end; until L >= R; until StackP < 0; FreeMem(PivEl, FElSize); finally FreeMem(CurEl, FElSize); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.vmAllocateCache; var I : Integer; begin GetMem(vmCache, FCacheRows*SizeOf(TStCacheRec)); FillChar(vmCache^, FCacheRows*SizeOf(TStCacheRec), 0); try for I := 0 to FCacheRows-1 do with vmCache^[I] do GetMem(crRowData, vmRowSize); except vmDeallocateCache; raise; end; vmInvalidateCache; end; procedure TStVMatrix.vmDeallocateCache; var I : Integer; begin if Assigned(vmCache) then begin for I := FCacheRows-1 downto 0 do HugeFreeMem(vmCache^[I].crRowData, vmRowSize); if Assigned(vmCache) then FreeMem(vmCache, FCacheRows*SizeOf(TStCacheRec)); vmCache := nil; end; FCacheRows := 0; end; procedure TStVMatrix.vmFlushCacheNode(CacheIndex : Integer); begin with vmCache^[CacheIndex] do if crDirty > 0 then begin vmWriteRow(crRow, crRowData, True); crDirty := 0; end; end; function TStVMatrix.vmGetRowData(Row : Cardinal; MakeDirty : Boolean) : Pointer; var CacheIndex, OldestIndex : Integer; OldestTime, Bytes : Integer; TmpRowData : Pointer; begin if not vmSearchCache(Row, CacheIndex) then begin {row not found in cache} if vmCacheCnt = FCacheRows then begin {cache full, must throw out oldest row in cache} OldestTime := MaxLongInt; OldestIndex := 0; {prevent D32 from generating a warning} for CacheIndex := 0 to vmCacheCnt-1 do with vmCache^[CacheIndex] do if crTime < OldestTime then begin OldestIndex := CacheIndex; OldestTime := crTime; end; vmFlushCacheNode(OldestIndex); dec(vmCacheCnt); TmpRowData := vmCache^[OldestIndex].crRowData; Move(vmCache^[OldestIndex+1], vmCache^[OldestIndex], (vmCacheCnt-OldestIndex)*SizeOf(TStCacheRec)); vmCache^[vmCacheCnt].crRowData := TmpRowData; {find spot where row should now be inserted} vmSearchCache(Row, CacheIndex); end; {add row to cache} TmpRowData := vmCache^[vmCacheCnt].crRowData; Move(vmCache^[CacheIndex], vmCache^[CacheIndex+1], (vmCacheCnt-CacheIndex)*SizeOf(TStCacheRec)); inc(vmCacheCnt); with vmCache^[CacheIndex] do begin crRowData := TmpRowData; crRow := Row; Bytes := FileSeek(vmDataF, HeaderSize+Integer(Row)*vmRowSize, 0); if Bytes >= 0 then Bytes := FileRead(vmDataF, crRowData^, vmRowSize); if Bytes < 0 then RaiseContainerError(stscFileRead); {else if Bytes = 0 then} {row hasn't been written to yet} {HugeFillChar(crRowData^, vmRowSize, 0);} crDirty := 0; end; end; with vmCache^[CacheIndex] do begin Result := crRowData; if MakeDirty then crDirty := 1; crTime := vmIncCacheTime; end; end; function TStVMatrix.vmIncCacheTime : Integer; var I : Integer; begin if vmCacheTime = MaxLongInt-1 then begin {reset time for all buffers} for I := 0 to vmCacheCnt-1 do vmCache^[I].crTime := 0; vmCacheTime := 0; end; inc(vmCacheTime); Result := vmCacheTime; end; procedure TStVMatrix.vmInvalidateCache; begin vmCacheCnt := 0; vmCacheTime := 0; end; function TStVMatrix.vmSearchCache(Row : Cardinal; var CacheIndex : Integer) : Boolean; var L, R, M : Integer; Comp : Integer; begin if vmCacheCnt = 0 then begin Result := False; CacheIndex := 0; Exit; end; {search cache for row using binary search} L := 0; R := vmCacheCnt-1; repeat M := (L+R) div 2; with vmCache^[M] do begin Comp := Integer(Row)-Integer(crRow); if Comp = 0 then begin {found row in cache} Result := True; CacheIndex := M; Exit; end else if Comp < 0 then R := M-1 else L := M+1; end; until L > R; {not found, return where it should be inserted} Result := False; CacheIndex := M; if Comp > 0 then inc(CacheIndex); end; procedure TStVMatrix.vmSetCacheRows(CacheRows : Integer); var I : Integer; NewCache : PStCacheArray; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if CacheRows = FCacheRows then Exit; if (CacheRows < 2) or (CacheRows > StMaxBlockSize div SizeOf(TStCacheRec)) then RaiseContainerError(stscBadSize); {allocate new cache descriptor array} GetMem(NewCache, CacheRows*SizeOf(TStCacheRec)); FillChar(NewCache^, CacheRows*SizeOf(TStCacheRec), 0); try {allocate new buffers if any} for I := FCacheRows to CacheRows-1 do with NewCache^[I] do GetMem(crRowData, vmRowSize); {transfer old cache buffers to new array} for I := 0 to FCacheRows-1 do if I < CacheRows then NewCache^[I] := vmCache^[I] else begin {number of buffers shrunk, get rid of excess buffers} if I < vmCacheCnt then vmFlushCacheNode(I); HugeFreeMem(vmCache^[I].crRowData, vmRowSize); end; except for I := CacheRows-1 downto 0 do HugeFreeMem(NewCache^[I].crRowData, vmRowSize); FreeMem(NewCache, CacheRows*SizeOf(TStCacheRec)); end; {update cache in-use count} if vmCacheCnt > CacheRows then vmCacheCnt := CacheRows; {deallocate old cache} FreeMem(vmCache, FCacheRows*SizeOf(TStCacheRec)); vmCache := NewCache; FCacheRows := CacheRows; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.vmSetRows(Rows : Cardinal); var I : Integer; NewSize : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Rows = FRows then Exit; {validate new size} if (Rows = 0) or ProductOverflow(Rows, Cols) or ProductOverflow(Integer(Rows)*Integer(Cols), FElSize) then RaiseContainerError(stscBadSize); if Rows < FRows then begin {dump now-irrelevant rows from cache} for I := 0 to vmCacheCnt-1 do if vmCache^[I].crRow >= Rows then begin vmCacheCnt := I; break; end; {truncate data file} NewSize := HeaderSize+Integer(Rows)*Integer(Cols)*FElSize; if FileSeek(vmDataF, 0, 2) > NewSize then begin FileSeek(vmDataF, NewSize, 0); if not SetEndOfFile(vmDataF) then RaiseContainerError(stscFileWrite); end; end; FRows := Rows; FileSeek(vmDataF, 0, 0); WriteHeader; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStVMatrix.vmWriteRow(Row : Cardinal; Data : Pointer; Seek : Boolean); var Bytes : Integer; begin if Seek then FileSeek(vmDataF, HeaderSize+Integer(Row)*vmRowSize, 0); Bytes := FileWrite(vmDataF, Data^, vmRowSize); if (Bytes < 0) or (Bytes <> vmRowSize) then RaiseContainerError(stscFileWrite); end; procedure TStVMatrix.WriteHeader; begin {does nothing by default} {can assume that FilePos = 0 when this is called} end; end.
unit glr_gamescreens; interface uses glr_core, glr_utils; type // Usual lifecycle: // Hidden -> Loading -> Ready -> Paused/Unpaused -> Unloading -> Hidden TglrGameScreenState = ( gssHidden = 0, gssLoading, gssReady, gssPaused, gssUnloading ); // GameScreen is something like a form, internal window. // Main menu is a GameScreen, pause menu is a GameScreen, even a game itself // is a GameScreen. Game level could be descendant of GameScreen { TglrGameScreen } TglrGameScreen = class abstract private procedure InternalUpdate(const DeltaTime: Double); protected fState: TglrGameScreenState; procedure SetState(NewState: TglrGameScreenState); virtual; procedure LoadCompleted(); virtual; procedure UnloadCompleted(); virtual; public Name: UnicodeString; constructor Create(ScreenName: UnicodeString); virtual; property State: TglrGameScreenState read fState write SetState; procedure OnUpdate (const DeltaTime: Double); virtual; abstract; procedure OnLoadStarted (); virtual; procedure OnUnloadStarted (); virtual; procedure OnRender (); virtual; abstract; procedure OnInput(Event: PglrInputEvent); virtual; abstract; end; TglrGameScreenList = TglrObjectList<TglrGameScreen>; TglrGameScreenStack = TglrStack<TglrGameScreen>; { TglrGameScreenManager } TglrGameScreenManager = class (TglrGameScreenList) protected fUnloadingScreen: TglrGameScreen; function GetScreenIndex(ScreenName: UnicodeString): Integer; overload; function GetScreenIndex(Screen: TglrGameScreen): Integer; overload; public ScreenStack: TglrGameScreenStack; constructor Create(aCapacity: LongInt = 4); override; destructor Destroy(); override; procedure ShowModal(const Index : Integer); overload; procedure ShowModal(const Name : UnicodeString); overload; procedure ShowModal(const Screen: TglrGameScreen); overload; procedure SwitchTo(const Index : Integer); overload; procedure SwitchTo(const Name : UnicodeString); overload; procedure SwitchTo(const Screen: TglrGameScreen); overload; procedure Back(); procedure Update(const DeltaTime: Double); procedure Input(Event: PglrInputEvent); procedure Render(); end; implementation { TglrGameScreen } procedure TglrGameScreen.SetState(NewState: TglrGameScreenState); begin case fState of gssHidden: case NewState of gssUnloading: Exit(); gssReady: NewState := gssLoading; end; gssLoading: case NewState of gssHidden: NewState := gssUnloading; gssReady, gssPaused: Exit(); end; gssReady, gssPaused: case NewState of gssHidden: NewState := gssUnloading; gssLoading: NewState := gssReady; end; gssUnloading: case NewState of gssHidden, gssPaused: Exit(); gssReady: NewState := gssLoading; end; end; if (fState <> NewState) then begin fState := NewState; case fState of gssLoading: OnLoadStarted(); gssUnloading: OnUnloadStarted(); end; end; end; procedure TglrGameScreen.LoadCompleted; begin // Load ended fState := gssReady; end; procedure TglrGameScreen.UnloadCompleted; begin // Unload ended fState := gssHidden; end; procedure TglrGameScreen.InternalUpdate(const DeltaTime: Double); begin case fState of gssHidden, gssPaused: ; gssLoading, gssReady, gssUnloading: OnUpdate(DeltaTime); end; end; constructor TglrGameScreen.Create(ScreenName: UnicodeString); begin inherited Create(); Name := ScreenName; end; procedure TglrGameScreen.OnLoadStarted; begin LoadCompleted(); end; procedure TglrGameScreen.OnUnloadStarted; begin UnloadCompleted(); end; { TglrGameScreenManager } function TglrGameScreenManager.GetScreenIndex(ScreenName: UnicodeString ): Integer; var i: Integer; begin Result := -1; for i := 0 to FCount - 1 do if (FItems[i].Name = ScreenName) then Exit(i); end; function TglrGameScreenManager.GetScreenIndex(Screen: TglrGameScreen): Integer; var i: Integer; begin Result := -1; for i := 0 to FCount - 1 do if (FItems[i] = Screen) then Exit(i); end; constructor TglrGameScreenManager.Create(aCapacity: LongInt); begin inherited Create(aCapacity); ScreenStack := TglrGameScreenStack.Create(aCapacity); fUnloadingScreen := nil; end; destructor TglrGameScreenManager.Destroy; begin ScreenStack.Free(); inherited Destroy; end; procedure TglrGameScreenManager.ShowModal(const Index: Integer); begin if (index < 0) or (index >= FCount) then Log.Write(lCritical, 'GameScreenManager.ShowModal(index): index is out of range'); // Pause current game screen if (not ScreenStack.IsEmpty()) then ScreenStack.Head().State := gssPaused; // Push new screen as current ScreenStack.Push(FItems[index]); // Start loading FItems[index].State := gssLoading; end; procedure TglrGameScreenManager.ShowModal(const Name: UnicodeString); var index: Integer; begin index := GetScreenIndex(Name); if (index = -1) then Log.Write(lCritical, 'GameScreenManager: can not find screen with name "' + Name + '"'); ShowModal(index); end; procedure TglrGameScreenManager.ShowModal(const Screen: TglrGameScreen); var index: Integer; begin index := GetScreenIndex(Screen); if (index = -1) then Log.Write(lCritical, 'GameScreenManager: can not find screen by ref'); ShowModal(index); end; procedure TglrGameScreenManager.SwitchTo(const Index: Integer); begin if (index < 0) or (index >= FCount) then Log.Write(lCritical, 'GameScreenManager.ShowModal(index): index is out of range'); // Unload current game screen if (not ScreenStack.IsEmpty()) then begin fUnloadingScreen := ScreenStack.Head(); fUnloadingScreen.State := gssUnloading; end // If there is no current screen - start loading else FItems[index].State := gssLoading; // Push new screen as current ScreenStack.Push(FItems[index]); end; procedure TglrGameScreenManager.SwitchTo(const Name: UnicodeString); var index: Integer; begin index := GetScreenIndex(Name); if (index = -1) then Log.Write(lCritical, 'GameScreenManager: can not find screen with name "' + Name + '"'); SwitchTo(index); end; procedure TglrGameScreenManager.SwitchTo(const Screen: TglrGameScreen); var index: Integer; begin index := GetScreenIndex(Screen); if (index = -1) then Log.Write(lCritical, 'GameScreenManager: can not find screen by ref'); SwitchTo(index); end; procedure TglrGameScreenManager.Back(); begin // Pop current and unload it if (not ScreenStack.IsEmpty()) then begin fUnloadingScreen := ScreenStack.Pop(); fUnloadingScreen.State := gssUnloading; end; end; procedure TglrGameScreenManager.Update(const DeltaTime: Double); var i: Integer; begin for i := 0 to FCount - 1 do FItems[i].InternalUpdate(DeltaTime); // if previous screen is unloaded (state = hidden) if (fUnloadingScreen <> nil) and (fUnloadingScreen.State = gssHidden) then begin fUnloadingScreen := nil; // Make current screen loading // If it is already loaded and paused, state will be automatically set to Ready // ( check GameScreen.SetState() ) if (not ScreenStack.IsEmpty()) then ScreenStack.Head().State := gssLoading; end; end; procedure TglrGameScreenManager.Input(Event: PglrInputEvent); begin // Process input only for current screen if it is ready or paused if (not ScreenStack.IsEmpty()) and (ScreenStack.Head().State in [gssReady, gssPaused]) then ScreenStack.Head().OnInput(Event); end; procedure TglrGameScreenManager.Render; var i: Integer; begin // Render all screens except of hidden for i := 0 to FCount - 1 do if (FItems[i].State <> gssHidden) then FItems[i].OnRender(); end; end.
{$include lem_directives.inc} unit AppController; interface uses Classes, SysUtils, UMisc, //typinfo, Forms, LemTypes, LemRendering, LemLevel, LemDosStyle, LemDosGraphicSet, {$ifdef flexi}LemDosMainDAT,{$endif} FBaseDosForm, GameControl; type {------------------------------------------------------------------------------- The main application screen logic is handled by this class. it's a kind of simple statemachine, which shows the appropriate screens. These screens must change the GameParams.NextScreen property, when closing. -------------------------------------------------------------------------------} TAppController = class(TComponent) private //fCurrentScreen: TBaseDosForm; fGameParams: TDosGameParams; // instance protected public constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure ShowMenuScreen; procedure ShowPreviewScreen; procedure ShowPlayScreen; procedure ShowPostviewScreen; procedure ShowLevelCodeScreen; procedure ShowOptionsScreen; procedure Execute; end; implementation uses GameMenuScreen, GameLevelCodeScreen, GamePreviewScreen, GamePostviewScreen, GameConfigScreen, GameWindow; { TAppController } constructor TAppController.Create(aOwner: TComponent); var Fn: string; {$ifdef flexi}fMainDatExtractor : TMainDatExtractor;{$endif} tsx: byte; begin inherited; fGameParams := TDosGameParams.Create; fGameParams.Directory := LemmingsPath; fGameParams.MainDatFile := LemmingsPath + 'main.dat'; fGameParams.Renderer := TRenderer.Create; fGameParams.Level := Tlevel.Create(nil); {$ifdef flexi}fMainDatExtractor := TMainDatExtractor.Create; fMainDatExtractor.FileName := LemmingsPath + 'main.dat'; fGameParams.SysDat := fMainDatExtractor.GetSysData; fMainDatExtractor.free; {$endif} fGameParams.Style := AutoCreateStyle(fGameParams.Directory{$ifdef flexi}, fGameParams.SysDat{$endif}); // fGameParams.Style.LevelSystem as TBaseDosLevelSystem fGameParams.GraphicSet := fGameParams.Style.CreateGraphicSet as TBaseDosGraphicSet; fGameParams.NextScreen := gstMenu; {$ifdef testmode} if ParamStr(1) = 'testmode' then begin fGameParams.fTestMode := true; fGameParams.fTestLevelFile := ExtractFilePath(Application.ExeName) + ParamStr(2); fGameParams.fTestGroundFile := ExtractFilePath(Application.ExeName) + ParamStr(3); fGameParams.fTestVgagrFile := ExtractFilePath(Application.ExeName) + ParamStr(4); fGameParams.fTestVgaspecFile := ExtractFilePath(Application.ExeName) + ParamStr(5); fGameParams.NextScreen := gstPreview; end; {$endif} fGameParams.SoundOptions := [gsoSound, gsoMusic]; Fn := ReplaceFileExt(Application.Exename, '.ini');//' AppPath + 'LemmixPlayer.ini'; if FileExists(Fn) then fGameParams.LoadFromIniFile(Fn); if fGameParams.Style.LevelSystem is TBaseDosLevelSystem then begin TBaseDosLevelSystem(fGameParams.Style.LevelSystem).LookForLVL := fGameParams.LookForLVLFiles; TBaseDosLevelSystem(fGameParams.Style.LevelSystem).LevelPack := fGameParams.LevelPack; {$ifdef testmode}TBaseDosLevelSystem(fGameParams.Style.LevelSystem).fTestMode := fGameParams.fTestMode; TBaseDosLevelSystem(fGameParams.Style.LevelSystem).fTestLevel := fGameParams.fTestLevelFile;{$endif} {$ifdef flexi}TBaseDosLevelSystem(fGameParams.Style.LevelSystem).SysDat := fGameParams.SysDat; TDosCustLevelSystem(fGameParams.Style.LevelSystem).SysDat := fGameParams.SysDat; TDosCustMusicSystem(fGameParams.Style.MusicSystem).MusicCount := fGameParams.SysDat.TrackCount;{$endif} end; {$ifdef flexi} tsx := fGameParams.SysDat.Options; if tsx and 1 = 0 then fGameParams.LookForLVLFiles := false; if tsx and 2 = 0 then fGameParams.CheatCodesEnabled := false; {if tsx and 32 = 0 then begin fGameParams.DebugSteel := false; fGameParams.ChallengeMode := false; fGameParams.TimerMode := false; fGameParams.GimmickMusic := true; fGameParams.ForceGimmick := '0000'; end;} {$endif} end; destructor TAppController.Destroy; var Fn: string; begin Fn := ReplaceFileExt(Application.Exename, '.ini');//' AppPath + 'LemmixPlayer.ini'; // Fn := AppPath + 'LemmixPlayer.ini'; fGameParams.SaveToIniFile(Fn); fGameParams.Renderer.Free; fGameParams.Level.Free; fGameParams.Style.Free; fGameParams.GraphicSet.Free; fGameParams.Free; inherited; end; procedure TAppController.Execute; {------------------------------------------------------------------------------- Main screen-loop. Every screen returns its nextscreen (if he knows) in the GameParams -------------------------------------------------------------------------------} var NewScreen: TGameScreenType; begin while fGameParams.NextScreen <> gstExit do begin NewScreen := fGameParams.NextScreen; // save fGameParams.NextScreen := gstUnknown; // reset case NewScreen of gstMenu : ShowMenuScreen; gstPreview : ShowPreviewScreen; gstPlay : ShowPlayScreen; gstPostview : ShowPostviewScreen; gstNavigation: ShowOptionsScreen; gstLevelCode : ShowLevelCodeScreen; else Exit; end; end; end; procedure TAppController.ShowLevelCodeScreen; var F: TGameLevelCodeScreen; begin F := TGameLevelCodeScreen.Create(nil); try F.ShowScreen(fGameParams); finally F.Free; end; end; procedure TAppController.ShowMenuScreen; var F: TGameMenuScreen; begin F := TGameMenuScreen.Create(nil); try F.ShowScreen(fGameParams); finally F.Free; end; end; procedure TAppController.ShowOptionsScreen; var F: TGameConfigScreen; begin F := TGameConfigScreen.Create(nil); try F.ShowScreen(fGameParams); finally F.Free; end; end; procedure TAppController.ShowPlayScreen; var F: TGameWindow; begin F := TGameWindow.Create(nil); try F.ShowScreen(fGameParams); finally F.Free; end; end; procedure TAppController.ShowPostviewScreen; var F: TGamePostviewScreen; begin F := TGamePostviewScreen.Create(nil); try F.ShowScreen(fGameParams); finally F.Free; end; end; procedure TAppController.ShowPreviewScreen; var F: TGamePreviewScreen; dS, dL: Integer; begin F := TGamePreviewScreen.Create(nil); try {$ifdef testmode} if (fGameParams.fTestMode and (fGameParams.QuickTestMode <> 0)) then begin F.PrepareGameParams(fGameParams); F.BuildScreenInvis; fGameParams.NextScreen := gstPlay; end else{$endif} if fGameParams.DumpMode then begin for dS := 0 to TBaseDosLevelSystem(fGameParams.Style.LevelSystem).fDefaultSectionCount - 1 do for dL := 0 to TBaseDosLevelSystem(fGameParams.Style.LevelSystem).GetLevelCount(dS) - 1 {$ifdef cust}- 1{$endif} do begin fGameParams.WhichLevel := wlSame; fGameParams.Info.dSection := dS; fGameParams.Info.dLevel := dL; F.PrepareGameParams(fGameParams); F.BuildScreenInvis; end; fGameParams.WhichLevel := wlFirst; fGameParams.NextScreen := gstMenu; fGameParams.DumpMode := false; end else F.ShowScreen(fGameParams); finally F.Free; end; end; end. (* procedure TGameMenuScreen.ShowLevelCodeScreen; var F: TGameLevelCodeScreen; begin F := TGameLevelCodeScreen.Create(nil); try // F.MainDatFile := Self.MainDatFile; F.BuildScreen; F.ShowModal; finally F.Free; end; end;
unit ElToolbarDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ElPanel, ElToolBar, ElPopBtn, ElBtnCtl, ElCheckCtl, StdCtrls, ElACtrls, ElClrCmb, Buttons, ElImgFrm, ElVCLUtils, ElSpin, ElImgLst, ElXPThemedControl, ImgList, ElEdits, ElBtnEdit, ElCombos; type TElToolbarDemoMainForm = class(TForm) SampleElToolbar: TElToolBar; ElToolbarImageForm: TElImageForm; SmallImages: TElImageList; LargeImages: TElImageList; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; ElToolbarAddButtonButton: TElPopupButton; ElToolbarAddSeparatorButton: TElPopupButton; ElToolbarAddDividerButton: TElPopupButton; ElToolbarClearButton: TElPopupButton; ElToolbarLargeButtonsCB: TElCheckBox; ElToolbarFlatCB: TElCheckBox; ElToolbarButtonColorCombo: TElColorCombo; ElToolbarGlyphLayoutCombo: TElComboBox; ElToolbarAlignCombo: TElComboBox; ElToolbarUseBackgroundCB: TElCheckBox; ElToolbarTransparentButtonsCB: TElCheckBox; EltoolbarThinButtonsCB: TElCheckBox; ElToolbarUseImageFormCB: TElCheckBox; ElToolbarAutosizeCB: TElCheckBox; ElToolbarResizableCB: TElCheckBox; ElToolbarAutoWrapCB: TElCheckBox; ElToolbarShowGlyphsCB: TElCheckBox; ElToolbarShowTextCB: TElCheckBox; ElToolbarSmallButtonWidthSpinEdit: TElSpinEdit; ElToolbarSmallButtonHeightSpinEdit: TElSpinEdit; ElToolbarLargeButtonWidthSpinEdit: TElSpinEdit; ElToolbarLargeButtonHeightSpinEdit: TElSpinEdit; procedure FormActivate(Sender: TObject); procedure ElToolbarAddButtonButtonClick(Sender: TObject); procedure ElToolbarAddSeparatorButtonClick(Sender: TObject); procedure ElToolbarAddDividerButtonClick(Sender: TObject); procedure ElToolbarClearButtonClick(Sender: TObject); procedure ElToolbarLargeButtonsCBClick(Sender: TObject); procedure ElToolbarFlatCBClick(Sender: TObject); procedure ElToolbarGlyphLayoutComboChange(Sender: TObject); procedure ElToolbarAlignComboChange(Sender: TObject); procedure ElToolbarUseBackgroundCBClick(Sender: TObject); procedure ElToolbarButtonColorComboChange(Sender: TObject); procedure ElToolbarTransparentButtonsCBClick(Sender: TObject); procedure EltoolbarThinButtonsCBClick(Sender: TObject); procedure ElToolbarUseImageFormCBClick(Sender: TObject); procedure ElToolbarAutosizeCBClick(Sender: TObject); procedure ElToolbarResizableCBClick(Sender: TObject); procedure ElToolbarAutoWrapCBClick(Sender: TObject); procedure ElToolbarShowGlyphsCBClick(Sender: TObject); procedure ElToolbarShowTextCBClick(Sender: TObject); procedure ElToolbarSmallButtonWidthSpinEditChange(Sender: TObject); procedure ElToolbarSmallButtonHeightSpinEditChange(Sender: TObject); procedure ElToolbarLargeButtonWidthSpinEditChange(Sender: TObject); procedure ElToolbarLargeButtonHeightSpinEditChange(Sender: TObject); private { Private declarations } public NotFirstTime : boolean; end; var ElToolbarDemoMainForm: TElToolbarDemoMainForm; implementation {$R *.DFM} procedure TElToolbarDemoMainForm.FormActivate(Sender: TObject); begin if not NotFirstTime then begin ElToolbarGlyphLayoutCombo.ItemIndex := 0; ElToolbarAlignCombo.ItemIndex := 2; end; NotFirstTime := true; end; procedure TElToolbarDemoMainForm.ElToolbarAddButtonButtonClick( Sender: TObject); begin with SampleElToolbar.AddButton(ebtButton) do begin Caption := 'Button ' + IntToStr(SampleElToolbar.ControlCount - 1); ImageIndex := SampleElToolbar.ControlCount - 1; end; end; procedure TElToolbarDemoMainForm.ElToolbarAddSeparatorButtonClick( Sender: TObject); begin SampleElToolbar.AddButton(ebtSeparator); end; procedure TElToolbarDemoMainForm.ElToolbarAddDividerButtonClick( Sender: TObject); begin SampleElToolbar.AddButton(ebtDivider); end; procedure TElToolbarDemoMainForm.ElToolbarClearButtonClick( Sender: TObject); var AControl : TControl; begin while sampleEltoolbar.ControlCount > 0 do begin AControl := sampleEltoolbar.Controls[0]; AControl.Free; end; end; procedure TElToolbarDemoMainForm.ElToolbarLargeButtonsCBClick( Sender: TObject); begin sampleElToolbar.LargeSize := ElToolbarLargeButtonsCB.Checked; if sampleElToolbar.LargeSize then sampleElToolbar.Images := LargeImages else sampleElToolbar.Images := SmallImages; end; procedure TElToolbarDemoMainForm.ElToolbarFlatCBClick(Sender: TObject); begin sampleElToolbar.Flat := ElToolbarFlatCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarGlyphLayoutComboChange( Sender: TObject); begin sampleElToolbar.GlyphLayout := TButtonLayout(ElToolbarGlyphLayoutCombo.ItemIndex); end; procedure TElToolbarDemoMainForm.ElToolbarAlignComboChange( Sender: TObject); begin case ElToolbarAlignCombo.ItemIndex of 0: sampleElToolbar.Align := alLeft; 1: sampleElToolbar.Align := alRight; 2: sampleElToolbar.Align := alTop; 3: sampleElToolbar.Align := alBottom; end; end; procedure TElToolbarDemoMainForm.ElToolbarUseBackgroundCBClick( Sender: TObject); begin if ElToolbarUseBackgroundCB.Checked then begin sampleElToolbar.ImageForm := nil; sampleElToolbar.ButtonImageForm := nil; sampleElToolbar.BackgroundType := bgtTileBitmap; end else begin if ElToolbarUseImageFormCB.Checked then begin sampleElToolbar.ImageForm := ElToolbarImageForm; sampleElToolbar.ButtonImageForm := ElToolbarImageForm; end; sampleElToolbar.BackgroundType := bgtColorFill; end; end; procedure TElToolbarDemoMainForm.ElToolbarButtonColorComboChange( Sender: TObject); begin sampleElToolbar.ButtonColor := ElToolbarButtonColorCombo.SelectedColor; end; procedure TElToolbarDemoMainForm.ElToolbarTransparentButtonsCBClick( Sender: TObject); begin sampleElToolbar.TransparentButtons := ElToolbarTransparentButtonsCB.Checked; end; procedure TElToolbarDemoMainForm.EltoolbarThinButtonsCBClick( Sender: TObject); begin sampleElToolbar.ThinButtons := EltoolbarThinButtonsCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarUseImageFormCBClick( Sender: TObject); begin if ElToolbarUseImageFormCB.Checked then begin sampleElToolbar.ImageForm := ElToolbarImageForm; sampleElToolbar.ButtonImageForm := ElToolbarImageForm; ElToolbarImageForm.BackgroundType := bgtTileBitmap end else begin sampleElToolbar.ImageForm := nil; sampleElToolbar.ButtonImageForm := nil; ElToolbarImageForm.BackgroundType := bgtColorFill; end; end; procedure TElToolbarDemoMainForm.ElToolbarAutosizeCBClick(Sender: TObject); begin sampleElToolbar.Autosize := ElToolbarAutosizeCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarResizableCBClick( Sender: TObject); begin sampleElToolbar.Resizable := ElToolbarResizableCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarAutoWrapCBClick(Sender: TObject); begin sampleElToolbar.AutoWrap := ElToolbarAutoWrapCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarShowGlyphsCBClick( Sender: TObject); begin sampleElToolbar.ShowGlyph := ElToolbarShowGlyphsCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarShowTextCBClick(Sender: TObject); begin sampleElToolbar.ShowCaption := ElToolbarShowTextCB.Checked; end; procedure TElToolbarDemoMainForm.ElToolbarSmallButtonWidthSpinEditChange( Sender: TObject); begin sampleElToolbar.BtnWidth := ElToolbarSmallButtonWidthSpinEdit.Value; end; procedure TElToolbarDemoMainForm.ElToolbarSmallButtonHeightSpinEditChange( Sender: TObject); begin sampleElToolbar.BtnHeight := ElToolbarSmallButtonHeightSpinEdit.Value; end; procedure TElToolbarDemoMainForm.ElToolbarLargeButtonWidthSpinEditChange( Sender: TObject); begin sampleElToolbar.LargeBtnWidth := ElToolbarLargeButtonWidthSpinEdit.Value; end; procedure TElToolbarDemoMainForm.ElToolbarLargeButtonHeightSpinEditChange( Sender: TObject); begin sampleElToolbar.LargeBtnHeight := ElToolbarLargeButtonHeightSpinEdit.Value; end; end.
unit DelphiUp.View.Components.Card001; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Layouts, DelphiUp.View.Components.Cards.Interfaces; type TComponentCard001 = class(TForm) Layout1: TLayout; Rectangle1: TRectangle; Layout2: TLayout; Rectangle2: TRectangle; Label1: TLabel; Layout3: TLayout; procedure FormCreate(Sender: TObject); private { Private declarations } FAttributes : iComponentCardAttributes<TComponentCard001>; FCountItem : Integer; public { Public declarations } function Component : TFMXObject; function Attributes : iComponentCardAttributes<TComponentCard001>; function AddItem( aValue : TFMXObject ) : TComponentCard001; end; var ComponentCard001: TComponentCard001; implementation uses DelphiUp.View.Components.Cards.Attributes; {$R *.fmx} { TComponentCard001 } function TComponentCard001.AddItem(aValue: TFMXObject): TComponentCard001; begin Result := Self; Layout3.AddObject(aValue); Inc(FCountItem); Layout1.Height := 48 + (TLayout(aValue).Height * FCountItem); end; function TComponentCard001.Attributes: iComponentCardAttributes<TComponentCard001>; begin Result := FAttributes; end; function TComponentCard001.Component: TFMXObject; begin Result := Layout1; Rectangle1.Fill.Color := FAttributes.Background; Rectangle2.Fill.Color := FAttributes.DestBackground; Label1.Text := FAttributes.Title; Label1.FontColor := FAttributes.FontTitleColor; Label1.TextSettings.Font.Size := FAttributes.FontTitleSize; end; procedure TComponentCard001.FormCreate(Sender: TObject); begin FAttributes := TCardsAttributes<TComponentCard001>.New(Self); FCountItem := 0; Layout1.Height := 33; end; end.
unit Cabeleireiro_u; interface uses System.Classes, Vcl.CheckLst, System.SysUtils, Vcl.StdCtrls, System.SyncObjs, Winapi.Messages, Vcl.Forms; type Cabeleireiro = class(TThread) private FilaClientes: TCheckListBox; QuantidadeCadeiras: Integer; CadeiraCabeleireiro: TCheckBox; SecaoCritica: TCriticalSection; FTempoParaCorte: Integer; FTempoParaDormir: Integer; FProgramaExecutando: Boolean; procedure setTempoParaCorte(const Value: Integer); procedure setTempoParaDormir(const Value: Integer); procedure setProgramaExecutando(const Value: Boolean); procedure AtualizaStatus; function ExisteClienteEsperando: Boolean; function BuscaProximoCliente: Integer; procedure DesocuparCadeiraCliente(Const ANumeroCadeira: Integer); procedure AtenderCliente; procedure Dormir; protected procedure Execute; override; public constructor Create(const ACreateSuspended: Boolean; const AProgramaExecutando: boolean; Var AFilaClientes: TCheckListBox; const AQuantidadeCadeiras: Integer; Var ACadeiraCabeleireiro: TCheckBox; Var ASecaoCritica: TCriticalSection); property TempoParaCorte: Integer read FTempoParaCorte write setTempoParaCorte; property TempoParaDormir: Integer read FTempoParaDormir write setTempoParaDormir; property ProgramaExecutando: Boolean read FProgramaExecutando write setProgramaExecutando; end; implementation { Cabeleireiro } procedure Cabeleireiro.AtenderCliente; begin Sleep(TempoParaCorte * 1000); end; procedure Cabeleireiro.AtualizaStatus; begin FilaClientes.Update; CadeiraCabeleireiro.Update; end; function Cabeleireiro.BuscaProximoCliente: Integer; var i, vMenor, vCadeira: Integer; begin vMenor := 0; vCadeira := -1; for i := 0 to QuantidadeCadeiras - 1 do begin if FilaClientes.Checked[i] then begin if (vMenor = 0) or (StrToIntDef(FilaClientes.Items[i], 0) < vMenor) then begin vMenor := StrToIntDef(FilaClientes.Items[i], 0); vCadeira := i; end; end; end; Result := vCadeira; end; constructor Cabeleireiro.Create(const ACreateSuspended, AProgramaExecutando: boolean; Var AFilaClientes: TCheckListBox; const AQuantidadeCadeiras: Integer; Var ACadeiraCabeleireiro: TCheckBox; Var ASecaoCritica: TCriticalSection); begin Self.ProgramaExecutando := AProgramaExecutando; Self.FilaClientes := AFilaClientes; Self.QuantidadeCadeiras := AQuantidadeCadeiras; Self.CadeiraCabeleireiro := ACadeiraCabeleireiro; Self.SecaoCritica := ASecaoCritica; inherited Create(ACreateSuspended); end; procedure Cabeleireiro.Dormir; begin Sleep(TempoParaDormir * 1000); end; procedure Cabeleireiro.Execute; var vProximoCliente: Integer; begin while ProgramaExecutando do begin AtualizaStatus; if ExisteClienteEsperando then begin SecaoCritica.Acquire; try CadeiraCabeleireiro.Checked := True; CadeiraCabeleireiro.Caption := 'Ocupada por Cliente'; vProximoCliente := BuscaProximoCliente; DesocuparCadeiraCliente(vProximoCliente); AtenderCliente; finally SecaoCritica.Release; end; end else if CadeiraCabeleireiro.Checked then begin SecaoCritica.Acquire; try AtenderCliente; finally SecaoCritica.Release; end; end else begin SecaoCritica.Acquire; try CadeiraCabeleireiro.Checked := True; CadeiraCabeleireiro.Caption := 'Ocupada pelo Cabeleireiro'; finally SecaoCritica.Release; end; //Caso o caption não seja o que foi tentado setar a cima, significa que alguém estava usando a seção crítica //e por isso não foi possível acessá-la, neste caso se não estiver Ocupada pelo Cabeleireiro estará //sendo ocupada por Cliente, assim sendo atende o mesmo, senão o cabeleireiro irá Dormir if CadeiraCabeleireiro.Caption <> 'Ocupada pelo Cabeleireiro' then begin SecaoCritica.Acquire; try AtenderCliente; finally SecaoCritica.Release; end; end else begin SecaoCritica.Acquire; try Dormir; finally SecaoCritica.Release; end; end; end; CadeiraCabeleireiro.Checked := False; CadeiraCabeleireiro.Caption := 'Cadeira Livre'; AtualizaStatus; end; end; function Cabeleireiro.ExisteClienteEsperando: Boolean; var i: Integer; vExisteCliente: Boolean; begin vExisteCliente := False; for i := 0 to QuantidadeCadeiras - 1 do begin if FilaClientes.Checked[i] then begin vExisteCliente := True; break; end; end; Result := vExisteCliente; end; procedure Cabeleireiro.setProgramaExecutando(const Value: Boolean); begin FProgramaExecutando := Value; end; procedure Cabeleireiro.setTempoParaCorte(const Value: Integer); begin FTempoParaCorte := Value; end; procedure Cabeleireiro.setTempoParaDormir(const Value: Integer); begin FTempoParaDormir := Value; end; procedure Cabeleireiro.DesocuparCadeiraCliente(const ANumeroCadeira: Integer); begin FilaClientes.Items[ANumeroCadeira] := '0'; FilaClientes.Checked[ANumeroCadeira] := False; end; end.
unit MFichas.Model.Empresa.Metodos.Buscar.View; interface uses System.SysUtils, MFichas.Model.Empresa.Interfaces, FireDAC.Comp.Client, FireDAC.Comp.DataSet; type TModelEmpresaMetodosBuscarView = class(TInterfacedObject, iModelEmpresaMetodosBuscarView) private [weak] FParent : iModelEmpresa; FFDMemTable: TFDMemTable; constructor Create(AParent: iModelEmpresa); procedure Validacao; procedure CopiarDataSet; public destructor Destroy; override; class function New(AParent: iModelEmpresa): iModelEmpresaMetodosBuscarView; function FDMemTable(AFDMemTable: TFDMemTable): iModelEmpresaMetodosBuscarView; function BuscarEmpresa : iModelEmpresaMetodosBuscarView; function &End : iModelEmpresaMetodos; end; implementation { TModelEmpresaMetodosBuscarView } function TModelEmpresaMetodosBuscarView.BuscarEmpresa: iModelEmpresaMetodosBuscarView; begin Result := Self; FParent.DAODataSet.Open; Validacao; CopiarDataSet; end; function TModelEmpresaMetodosBuscarView.&End: iModelEmpresaMetodos; begin Result := FParent.Metodos; end; procedure TModelEmpresaMetodosBuscarView.CopiarDataSet; begin FFDMemTable.CopyDataSet(FParent.DAODataSet.DataSet, [coStructure, coRestart, coAppend]); end; constructor TModelEmpresaMetodosBuscarView.Create(AParent: iModelEmpresa); begin FParent := AParent; end; destructor TModelEmpresaMetodosBuscarView.Destroy; begin inherited; end; function TModelEmpresaMetodosBuscarView.FDMemTable( AFDMemTable: TFDMemTable): iModelEmpresaMetodosBuscarView; begin Result := Self; FFDMemTable := AFDMemTable; end; class function TModelEmpresaMetodosBuscarView.New(AParent: iModelEmpresa): iModelEmpresaMetodosBuscarView; begin Result := Self.Create(AParent); end; procedure TModelEmpresaMetodosBuscarView.Validacao; begin if FParent.DAODataSet.DataSet.RecordCount = 0 then raise Exception.Create( 'Nenhuma empresa encontrada.' ); if not Assigned(FFDMemTable) then raise Exception.Create( 'Para prosseguir, você deve vincular um FDMemTable ao encadeamento' + ' de funcões do método de Empresa.Metodos.BuscarView .' ); end; end.
unit hcQueryQueue; // Назначение : Очередь необработанных запросов; // Автор : М. Морозов; // Версия : $Id: hcQueryQueue.pas,v 1.3 2008/02/20 06:47:56 oman Exp $ {------------------------------------------------------------------------------- $Log: hcQueryQueue.pas,v $ Revision 1.3 2008/02/20 06:47:56 oman Не собиралось Revision 1.2 2008/02/06 09:04:21 oman Не собирались Revision 1.1 2007/09/04 08:07:39 mmorozov - new: возможность устанавливаться задержку перед отправкой ответа\уведомления (CQ: OIT5-24653); -------------------------------------------------------------------------------} interface {$Include hcDefine.inc} uses l3Base, l3ObjectRefList, hcInterfaces ; type ThcQueryQueueItem = class(Tl3Base) private // fields f_Answer : ThcAnswerType; f_Id : ThcConsultationId; f_Time : TDateTime; public // methods constructor Create(const aAnswer : ThcAnswerType; const aId : ThcConsultationId); reintroduce; {-} public // properties property Answer: ThcAnswerType read f_Answer; {-} property Id: ThcConsultationId read f_Id; {-} property Time: TDateTime read f_Time; {-} end;//ThcQueryQueueItem ThcQueryQueue = class(Tl3ObjectRefList) public // methods procedure Pop(const aAnswer : ThcAnswerType; const aId : ThcConsultationId); {* - добавить запрос в очередь. } function Push(const aDelay: Integer): ThcQueryQueueItem; {* - выгружает первый загруженный элемент, если с момента его получения прошло время aDelay в миллисекундах. } end;//ThcQueryQueue implementation uses SysUtils, DateUtils; { ThcQueryQueueItem } constructor ThcQueryQueueItem.Create(const aAnswer : ThcAnswerType; const aId : ThcConsultationId); begin inherited Create; f_Answer := aAnswer; f_Id := aId; f_Time := Now; end;//Create { ThcQueryQueue } procedure ThcQueryQueue.Pop(const aAnswer : ThcAnswerType; const aId : ThcConsultationId); var l_Class: ThcQueryQueueItem; begin l_Class := ThcQueryQueueItem.Create(aAnswer, aId); try Add(l_Class); finally FreeAndNil(l_Class); end;//try..finally end;//Pop function ThcQueryQueue.Push(const aDelay: Integer): ThcQueryQueueItem; begin if (Count > 0) and (MilliSecondsBetween(Now, ThcQueryQueueItem(Items[0]).Time) >= aDelay) then begin ThcQueryQueueItem(Items[0]).Use; Result := ThcQueryQueueItem(Items[0]); Delete(0); end//if (Count > 0) and else Result := nil; end;//Push end.
{******************************************************************************* 作者: dmzn@163.com 2009-11-3 描述: USB头文件 *******************************************************************************} unit UUSBLib; interface const cMachine = '.'; const USB_SUBMIT_URB = 0; USB_RESET_PORT = 1; USB_GET_ROOTHUB_PDO = 3; USB_GET_PORT_STATUS = 4; USB_ENABLE_PORT = 5; USB_GET_HUB_COUNT = 6; USB_CYCLE_PORT = 7; USB_GET_HUB_NAME = 8; USB_IDLE_NOTIFICATION = 9; USB_GET_BUS_INFO = 264; USB_GET_CONTROLLER_NAME = 265; USB_GET_BUSGUID_INFO = 266; USB_GET_PARENT_HUB_INFO = 267; USB_GET_DEVICE_HANDLE = 268; HCD_GET_STATS_1 = 255; HCD_DIAGNOSTIC_MODE_ON = 256; HCD_DIAGNOSTIC_MODE_OFF = 257; HCD_GET_ROOT_HUB_NAME = 258; HCD_GET_DRIVERKEY_NAME = 265; HCD_GET_STATS_2 = 266; HCD_DISABLE_PORT = 268; HCD_ENABLE_PORT = 269; HCD_USER_REQUEST = 270; USB_GET_NODE_INFORMATION = 258; USB_GET_NODE_CONNECTION_INFORMATION = 259; USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION = 260; USB_GET_NODE_CONNECTION_NAME = 261; USB_DIAG_IGNORE_HUBS_ON = 262; USB_DIAG_IGNORE_HUBS_OFF = 263; USB_GET_NODE_CONNECTION_DRIVERKEY_NAME = 264; USB_GET_HUB_CAPABILITIES = 271; USB_GET_NODE_CONNECTION_ATTRIBUTES = 272; METHOD_BUFFERED = 0; METHOD_IN_DIRECT = 1; {+} METHOD_OUT_DIRECT = 2; {+} METHOD_NEITHER = 3; FILE_ANY_ACCESS = 0; FILE_SPECIAL_ACCESS = (FILE_ANY_ACCESS); {+} FILE_READ_ACCESS = ( $0001 ); // file & pipe {+} FILE_WRITE_ACCESS = ( $0002 ); // file & pipe {+} FILE_DEVICE_UNKNOWN = $00000022; FILE_DEVICE_USB = FILE_DEVICE_UNKNOWN; USB_CTL_BASE = (FILE_DEVICE_USB shl 16) or (FILE_ANY_ACCESS shl 14); USB_CTL_CONST = USB_CTL_BASE or METHOD_BUFFERED; USB_KERNEL_CTL_CONST = USB_CTL_BASE or METHOD_NEITHER; IOCTL_USB_DIAG_IGNORE_HUBS_ON = USB_CTL_CONST or (USB_DIAG_IGNORE_HUBS_ON shl 2); IOCTL_USB_DIAG_IGNORE_HUBS_OFF = USB_CTL_CONST or (USB_DIAG_IGNORE_HUBS_OFF shl 2); IOCTL_USB_DIAGNOSTIC_MODE_OFF = USB_CTL_CONST or (HCD_DIAGNOSTIC_MODE_OFF shl 2); IOCTL_USB_DIAGNOSTIC_MODE_ON = USB_CTL_CONST or (HCD_DIAGNOSTIC_MODE_ON shl 2); IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION = USB_CTL_CONST or (USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION shl 2); IOCTL_USB_GET_HUB_CAPABILITIES = USB_CTL_CONST or (USB_GET_HUB_CAPABILITIES shl 2); IOCTL_USB_GET_ROOT_HUB_NAME = USB_CTL_CONST or (HCD_GET_ROOT_HUB_NAME shl 2); IOCTL_GET_HCD_DRIVERKEY_NAME = USB_CTL_CONST or (HCD_GET_DRIVERKEY_NAME shl 2); IOCTL_USB_GET_NODE_INFORMATION = USB_CTL_CONST or (USB_GET_NODE_INFORMATION shl 2); IOCTL_USB_GET_NODE_CONNECTION_INFORMATION = USB_CTL_CONST or (USB_GET_NODE_CONNECTION_INFORMATION shl 2); IOCTL_USB_GET_NODE_CONNECTION_ATTRIBUTES = USB_CTL_CONST or (USB_GET_NODE_CONNECTION_ATTRIBUTES shl 2); IOCTL_USB_GET_NODE_CONNECTION_NAME = USB_CTL_CONST or (USB_GET_NODE_CONNECTION_NAME shl 2); IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME = USB_CTL_CONST or (USB_GET_NODE_CONNECTION_DRIVERKEY_NAME shl 2); IOCTL_USB_HCD_DISABLE_PORT = USB_CTL_CONST or (HCD_DISABLE_PORT shl 2); IOCTL_USB_HCD_ENABLE_PORT = USB_CTL_CONST or (HCD_ENABLE_PORT shl 2); IOCTL_USB_HCD_GET_STATS_1 = USB_CTL_CONST or (HCD_GET_STATS_1 shl 2); IOCTL_USB_HCD_GET_STATS_2 = USB_CTL_CONST or (HCD_GET_STATS_2 shl 2); const MAXIMUM_USB_STRING_LENGTH = 255; USB_DEVICE_CLASS_RESERVED = $00; USB_DEVICE_CLASS_AUDIO = $01; USB_DEVICE_CLASS_COMMUNICATIONS = $02; USB_DEVICE_CLASS_HUMAN_INTERFACE = $03; USB_DEVICE_CLASS_MONITOR = $04; USB_DEVICE_CLASS_PHYSICAL_INTERFACE = $05; USB_DEVICE_CLASS_POWER = $06; USB_DEVICE_CLASS_PRINTER = $07; USB_DEVICE_CLASS_STORAGE = $08; USB_DEVICE_CLASS_HUB = $09; USB_DEVICE_CLASS_VENDOR_SPECIFIC = $FF; USB_RESERVED_DESCRIPTOR_TYPE = $06; USB_CONFIG_POWER_DESCRIPTOR_TYPE = $07; USB_INTERFACE_POWER_DESCRIPTOR_TYPE = $08; USB_REQUEST_GET_STATUS = $00; USB_REQUEST_CLEAR_FEATURE = $01; USB_REQUEST_SET_FEATURE = $03; USB_REQUEST_SET_ADDRESS = $05; USB_REQUEST_GET_DESCRIPTOR = $06; USB_REQUEST_SET_DESCRIPTOR = $07; USB_REQUEST_GET_CONFIGURATION = $08; USB_REQUEST_SET_CONFIGURATION = $09; USB_REQUEST_GET_INTERFACE = $0A; USB_REQUEST_SET_INTERFACE = $0B; USB_REQUEST_SYNC_FRAME = $0C; USB_GETSTATUS_SELF_POWERED = $01; USB_GETSTATUS_REMOTE_WAKEUP_ENABLED = $02; BMREQUEST_HOST_TO_DEVICE = 0; BMREQUEST_DEVICE_TO_HOST = 1; BMREQUEST_STANDARD = 0; BMREQUEST_CLASS = 1; BMREQUEST_VENDOR = 2; BMREQUEST_TO_DEVICE = 0; BMREQUEST_TO_INTERFACE = 1; BMREQUEST_TO_ENDPOINT = 2; BMREQUEST_TO_OTHER = 3; // USB_COMMON_DESCRIPTOR.bDescriptorType constants USB_DEVICE_DESCRIPTOR_TYPE = $01; USB_CONFIGURATION_DESCRIPTOR_TYPE = $02; USB_STRING_DESCRIPTOR_TYPE = $03; USB_INTERFACE_DESCRIPTOR_TYPE = $04; USB_ENDPOINT_DESCRIPTOR_TYPE = $05; type TUnicodeName = array[0..MAXIMUM_USB_STRING_LENGTH] of WideChar; THCDDriverKeyName = record Length: Cardinal; UnicodeName: TUnicodeName; end; TNodeConnectionDriveKeyName = record ConnectionIndex: Cardinal; Length: Cardinal; UnicodeName: TUnicodeName; end; THubDescriptor = record Length: Byte; HubType: Byte; PortCount: Byte; Characteristics: array[0..1] of Byte; PowerOnToPowerGood: Byte; HubControlCurrent: Byte; RemoveAndPowerMask: array[0..63] of Byte; end; TEndPointDescriptor = record Length: Byte; DescriptorType: Byte; EndpointAddress: Byte; Attributes: Byte; MaxPacketSize: WORD; PollingInterval: Byte; end; TNodeInformation = record NodeType: Cardinal; NodeDescriptor: THubDescriptor; HubIsBusPowered: Byte; end; TDeviceDescriptor = record Length: Byte; DescriptorType: Byte; USBSpec: array[0..1] of Byte; DeviceClass: Byte; DeviceSubClass: Byte; DeviceProtocol: Byte; MaxPacketSize0: Byte; VendorID: Word;//array[0..1] of Byte; ProductID: Word; //array[0..1] of Byte; DeviceRevision: array[0..1] of byte; ManufacturerStringIndex: byte; ProductStringIndex: Byte; SerialNumberStringIndex: Byte; ConfigurationCount: Byte; end; TUSBPipeInfo = record EndPointDescriptor: TEndpointDescriptor; ScheduleOffset: Cardinal; end; TNodeConnectionInformation = record ConnectionIndex: Cardinal; ThisDevice: TDeviceDescriptor; CurrentConfiguration: Byte; LowSpeed: Byte; DeviceIsHub: Byte; DeviceAddress: array[0..1] of Byte; NumberOfOpenEndPoints: array[0..3] of Byte; ThisConnectionStatus: array[0..3] of Byte; PipeList: array[0..31] of TUSBPipeInfo; end; TSetupPacket = record bmRequest: Byte; bRequest: Byte; wValue: array[0..1] of Byte; wIndex: array[0..1] of Byte; wLength: array[0..1] of Byte; end; TDescriptorRequest = record ConnectionIndex: Cardinal; SetupPacket: TSetupPacket; ConfigurationDescriptor: array[0..2047] of Byte; end; type TUSBClass = (usbReserved, usbAudio, usbCommunications, usbHID, usbMonitor, usbPhysicalIntf, usbPower, usbPrinter, usbStorage, usbHub, usbVendorSpec, // illegal values usbExternalHub, usbHostController, usbUnknown, usbError); TRegistryRecord = record Name, USBClass, DeviceClass: shortstring; IntfGUID: shortstring; Drive: shortstring; Timestamp: TDateTime; end; TRegistrySet = array of TRegistryRecord; TUSBDevice = record Port: Cardinal; DeviceAddress: Cardinal; Manufacturer, Product, Serial: Shortstring; ConnectionStatus: Byte; MaxPower: WORD; MajorVersion, MinorVersion: Byte; ProductID, VendorID: Word; USBClassname: string; Registry: TRegistrySet; end; TUSBNode = record ConnectionName: Shortstring; Keyname: ShortString; USBClass: TUSBClass; ParentIndex: Integer; Level: Integer; TimeStamp: TDateTime; USBDevice: TUSBDevice; end; TUSBNodes = array of TUSBNode; implementation end.
unit kwPopFormActiveMDIChild; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopFormActiveMDIChild.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::FormsProcessing::pop_form_ActiveMDIChild // // *Формат:* aForm pop:form:ActiveMDIChild // *Описание:* Складывает в стек указатель на активную дочернюю форму, если есть. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses Forms, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} TkwPopFormActiveMDIChild = {final} class(_kwFormFromStackWord_) {* *Формат:* aForm pop:form:ActiveMDIChild *Описание:* Складывает в стек указатель на активную дочернюю форму, если есть. } protected // realized methods procedure DoForm(aForm: TForm; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopFormActiveMDIChild {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopFormActiveMDIChild; {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} // start class TkwPopFormActiveMDIChild procedure TkwPopFormActiveMDIChild.DoForm(aForm: TForm; const aCtx: TtfwContext); //#UC START# *4F2145550317_512F082300F1_var* //#UC END# *4F2145550317_512F082300F1_var* begin //#UC START# *4F2145550317_512F082300F1_impl* aCtx.rEngine.PushObj(aForm.ActiveMDIChild); //#UC END# *4F2145550317_512F082300F1_impl* end;//TkwPopFormActiveMDIChild.DoForm class function TkwPopFormActiveMDIChild.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:form:ActiveMDIChild'; end;//TkwPopFormActiveMDIChild.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwFormFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit EMSHosting.RequestHandler; interface uses System.SysUtils, System.Classes, System.Generics.Collections, EMSHosting.RequestTypes, EMS.ResourceAPI, EMSHosting.Endpoints; type TEMSHostRequestProps = record public type THeaderNames = record public const ApiVersion = 'X-Embarcadero-Api-Version'; ApplicationId = 'X-Embarcadero-Application-Id'; SessionToken = 'X-Embarcadero-Session-Token'; MasterSecret = 'X-Embarcadero-Master-Secret'; AppSecret = 'X-Embarcadero-App-Secret'; end; private FApplicationId: string; FApiVersion: string; FApiMajorVersion: string; FApiMinorVersion: string; FSessionToken: string; FResourceURL: string; FAppSecret: string; FMasterSecret: string; public property ApiVersion: string read FApiVersion; property ApiMajorVersion: string read FApiMajorVersion; property ApiMinorVersion: string read FApiMinorVersion; property ApplicationID: string read FApplicationID; property ResourceURL: string read FResourceURL; property SessionToken: string read FSessionToken; property AppSecret: string read FAppSecret; property MasterSecret: string read FMasterSecret; end; TEMSHostRequestHandler = class abstract private function GetRequestProps( const Request: IEMSHostRequest): TEMSHostRequestProps; function GetGroups(const AContext: IEMSHostContext; const AUserID: string; var AGroups: TEndpointContext.TGroups): TEndpointContext.TGroups; function GetUserID(const AContext: IEMSHostContext; const ASessionToken: string; var AUserID: string): string; function GetUserName(const AContext: IEMSHostContext; const AUserID: string; var AUserName: string): string; protected function UserIDOfSession(const AContext: IEMSHostContext; const ASessionToken: string; out AUserID: string): Boolean; virtual; abstract; function UserNameOfID(const AContext: IEMSHostContext; const AUserID: string; out AUserName: string): Boolean; virtual; abstract; function GetGroupsByUser(const AContext: IEMSHostContext; const AUserID: string): TArray<string>; virtual; procedure CheckForbiddenRequest(const AResourceName, AOriginalResourceName: string); virtual; abstract; procedure AuthenticateRequest(const AResources: TArray<TEMSResource>; const AResourceRequest: TEMSHostRequestProps; var AAuthenticated: TEndpointContext.TAuthenticated); virtual; abstract; procedure LogEndpoint(const AResource, AEndpointName, AMethod, AUserID, ACustom: string); virtual; abstract; procedure RedirectResource(const AContext: TEndpointContext; var AResource: TEMSResource; var AEndpointName: string); virtual; abstract; public { Public declarations } procedure HandleRequest(const Context: IEMSHostContext; const Request: IEMSHostRequest; const Response: IEMSHostResponse; var Handled: Boolean); procedure HandleException(const E: Exception; const Response: IEMSHostResponse; var Handled: Boolean); end; implementation uses System.JSON, EMSHosting.Utility, EMSHosting.Helpers, EMSHosting.ResourceManager, EMSHosting.Consts; function TEMSHostRequestHandler.GetRequestProps(const Request: IEMSHostRequest): TEMSHostRequestProps; function GetField(const AName: string; const ADefault: string = ''): string; begin Result := Request.Headers[AName]; if Result = '' then Result := ADefault; end; var LPathInfo: string; LStrings: TStrings; I: Integer; begin LPathInfo := String(Request.PathInfo); LStrings := ParseURLPath(LPathInfo); try if LStrings.Count > 0 then begin if LStrings[0] = '/' then if LStrings.Count > 1 then Result.FResourceURL := '/' + LStrings[1] else Result.FResourceURL := LStrings[0] else Result.FResourceURL := LStrings[0]; end; Result.FApplicationId := GetField(TEMSHostRequestProps.THeaderNames.ApplicationId); Result.FApiVersion := GetField(TEMSHostRequestProps.THeaderNames.ApiVersion); I := Result.FApiVersion.IndexOf('.'); if I > 0 then begin Result.FApiMinorVersion := Result.FApiVersion.Substring(I+1); Result.FApiMajorVersion := Result.FApiVersion.Substring(0, I); end else Result.FApiMajorVersion := Result.FApiVersion; Result.FMasterSecret := GetField(TEMSHostRequestProps.THeaderNames.MasterSecret); Result.FAppSecret := GetField(TEMSHostRequestProps.THeaderNames.AppSecret); Result.FSessionToken := GetField(TEMSHostRequestProps.THeaderNames.SessionToken); if Result.FResourceURL = '' then Result.FResourceURL := '/'; finally LStrings.Free; end; end; type TUser = class(TEndpointContextImpl.TUser) private type TGroups = TEndpointContext.TGroups; private FGetGroups: TFunc<TGroups>; FGetUserName: TFunc<string>; FGetUserID: TFunc<string>; protected function GetUserName: string; override; function GetUserID: string; override; function GetGroups: TEndpointContext.TGroups; override; end; TEdgemodule = class(TEndpointContextImpl.TEdgemodule) private FGetModuleName: TFunc<string>; FGetModuleVersion: TFunc<string>; protected function GetModuleName: string; override; function GetModuleVersion: string; override; end; TGroups = class(TEndpointContextImpl.TGroups) private FRequestHandler: TEMSHostRequestHandler; FUserID: string; FGroups: TList<string>; FContext: IEMSHostContext; procedure CheckGroups; protected function GetCount: Integer; override; public constructor Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AUserID: string); destructor Destroy; override; function Contains(const AGroup: string): Boolean; override; end; { TUser } function TUser.GetUserName: string; begin Assert(Assigned(FGetUserName)); Result := FGetUserName; end; function TUser.GetUserID: string; begin Assert(Assigned(FGetUserID)); Result := FGetUserID; end; function TUser.GetGroups: TEndpointContext.TGroups; begin Assert(Assigned(FGetGroups)); Result := FGetGroups; end; { TEdgemodule } function TEdgemodule.GetModuleName: string; begin Assert(Assigned(FGetModuleName)); Result := FGetModuleName; end; function TEdgemodule.GetModuleVersion: string; begin Assert(Assigned(FGetModuleVersion)); Result := FGetModuleVersion; end; function TEMSHostRequestHandler.GetUserID(const AContext: IEMSHostContext; const ASessionToken: string; var AUserID: string): string; begin Result := AUserID; if Result = '' then begin if not Self.UserIDOfSession(AContext, ASessionToken, Result) then EEMSHTTPError.RaiseUnauthorized; // No user end; AUserID := Result; end; function TEMSHostRequestHandler.GetGroups(const AContext: IEMSHostContext; const AUserID: string; var AGroups: TEndpointContext.TGroups): TEndpointContext.TGroups; begin Result := AGroups; if Result = nil then Result := TGroups.Create(AContext, Self, AUserID); AGroups := Result; end; function TEMSHostRequestHandler.GetUserName(const AContext: IEMSHostContext; const AUserID: string; var AUserName: string): string; begin Result := AUserName; if Result = '' then begin if not Self.UserNameOfID(AContext, AUserID, Result) then EEMSHTTPError.RaiseNotFound; end; AUserName := Result; end; function TEMSHostRequestHandler.GetGroupsByUser(const AContext: IEMSHostContext; const AUserID: string): TArray<string>; begin Result := nil; end; procedure TEMSHostRequestHandler.HandleRequest(const Context: IEMSHostContext; const Request: IEMSHostRequest; const Response: IEMSHostResponse; var Handled: Boolean); var LResources: TArray<TEMSResource>; function IsVersionResource: Boolean; begin Result := (Length(LResources) = 1) and SameText(LResources[0].Name, 'version'); end; type TUserGroups = TUser.TGroups; var LPathInfo: string; LResource: TEMSResource; R: TEMSResource; LContext: TEndpointContextImpl; LRequest: TEndpointRequest; LResponse: TEndpointResponseImpl; LAuthenticated: TEndpointContext.TAuthenticated; LEndpointName: string; LCustom: string; LResourceRequest: TEMSHostRequestProps; LUserID: string; LUserName: string; LGroups: TEndpointContext.TGroups; LGetGroups: TFunc<TUserGroups>; LGetUserName: TFunc<string>; LGetUserID: TFunc<string>; LOriginalResourceName: string; LOriginalEndpointName: string; begin LGroups := nil; LAuthenticated := []; LRequest := nil; LResponse := nil; try LPathInfo := String(Request.PathInfo); LResourceRequest := GetRequestProps(Request); LResources := TEMSEndpointManagerImpl.Instance.FindByBaseURL(LResourceRequest.ResourceURL); Self.AuthenticateRequest(LResources, LResourceRequest, LAuthenticated); LResource := nil; if LResources = nil then begin if LResourceRequest.ResourceURL = '/' then begin // Blank page Response.StatusCode := 200; Exit; // EXIT end else if SameText(LResourceRequest.ResourceURL, '/favicon.ico') then begin // Silent failure Response.StatusCode := EEMSHTTPError.TCodes.NotFound; Exit; // EXIT end; EEMSHTTPError.RaiseNotFound(Format(sResourceNotFound, [LResourceRequest.ResourceURL])); end; LRequest := TEndpointRequestImpl.Create(Request); LContext := TEndpointContextImpl.Create; LContext.OnGetAuthenticated := function: TEndpointContext.TAuthenticated begin Result := LAuthenticated; if LContext.User <> nil then Include(Result, TEndpointContext.TAuthenticate.User); end; LContext.OnGetEndpointName := function: string begin Result := LEndpointName; end; LContext.OnGetRequest := function: TEndpointRequest begin Result := LRequest; end; LContext.OnGetResponse := function: TEndpointResponse begin Result := LResponse; end; LGetGroups := function: TUserGroups begin Result := Self.GetGroups(Context, Self.GetUserID(Context, LResourceRequest.SessionToken, LUserID), LGroups); end; LGetUserName := function: string begin Result := Self.GetUserName(Context, Self.GetUserID(Context, LResourceRequest.SessionToken, LUserID), LUserName); end; LGetUserID := function: string begin Result := Self.GetUserID(Context, LResourceRequest.SessionToken, LUserID); end; LContext.OnCreateUser := procedure(const AContext: TEndpointContextImpl; out AUser: TEndpointContextImpl.TUser) begin AUser := nil; if LResourceRequest.SessionToken <> '' then begin AUser := TUser.Create; TUser(AUser).FGetGroups := LGetGroups; TUser(AUser).FGetUserName := LGetUserName; TUser(AUser).FGetUserID := LGetUserID; end; end; LContext.OnCreateEdgemodule := procedure(const AContext: TEndpointContextImpl; out AEdgemodule: TEndpointContextImpl.TEdgemodule) var LIntf: IEMSEdgeHostContext; begin AEdgemodule := nil; if Supports(Context, IEMSEdgeHostContext, LIntf) then begin AEdgemodule := TEdgemodule.Create; TEdgemodule(AEdgemodule).FGetModuleName := function: string begin Result := LIntf.ModuleName end; TEdgemodule(AEdgemodule).FGetModuleVersion := function: string begin Result := LIntf.ModuleVersion end; end; end; for R in LResources do if R.CanHandleRequest(LContext, LEndpointName) then begin if LResource = nil then LResource := R else EEMSHTTPError.RaiseError(500, sResourceErrorMessage, Format(sResourceMultipleEndpoints, [LEndpointName])); end; if LResource <> nil then begin LOriginalResourceName := LResource.Name; LOriginalEndpointName := LEndpointName; RedirectResource(LContext, LResource, LEndpointName); end; if LResource <> nil then begin CheckForbiddenRequest(LResource.Name, LOriginalResourceName); if LContext.User <> nil then LUserID := LContext.User.UserID else LUserID := ''; if TLogHelpers.LoggingEnabled then TLogHelpers.LogRequest(LResource.Name, LEndpointName, LRequest.MethodString, LUserID); LResponse := TEndpointResponseImpl.Create(Response); Handled := True; LResource.HandleRequest(LContext); LResponse.Write; case LContext.EndpointDataType of // In the case of AddUser/DeleteUser, the userid being added or deleted should be passed to ACustom TEndpointContextImpl.TEndpointDataType.AddUser, TEndpointContextImpl.TEndpointDataType.DeletedUser: LCustom := LContext.EndpointDataValue; end; case LContext.EndpointDataType of // In the case of AddUser/Login, log the userid TEndpointContextImpl.TEndpointDataType.AddUser, TEndpointContextImpl.TEndpointDataType.LoginUser: if LUserID = '' then LUserID := LContext.EndpointDataValue; end; // Analytics log Self.LogEndpoint(LResource.Name, LEndpointName, LRequest.MethodString, LUserID, LCustom); end else EEMSHTTPError.RaiseNotFound('', Format(sResourceNotFound, [LResourceRequest.ResourceURL])); finally LRequest.Free; LResponse.Free; LContext.Free; end; end; procedure TEMSHostRequestHandler.HandleException(const E: Exception; const Response: IEMSHostResponse; var Handled: Boolean); var LHTTPError: EEMSHTTPError; LJSONObject: TJSONObject; LBody: TEndpointResponseBodyImpl; LError: string; LDescription: string; begin Handled := True; if E is EEMSHTTPError then begin LHTTPError := EEMSHTTPError(E); Response.StatusCode := LHTTPError.Code; if LHTTPError.Error <> '' then LError := LHTTPError.Error; if LHTTPError.Description <> '' then LDescription := LHTTPError.Description; end else begin Response.StatusCode := 500; LDescription := E.Message; end; // Write JSONObject with error description LJSONObject := TErrorHelpers.CreateJSONError(string(Response.ReasonString), LError, LDescription); try if TLogHelpers.LoggingEnabled then TLogHelpers.LogHTTPError(REsponse.StatusCode, String(Response.ReasonString), LError, LDescription); LBody := TEndpointResponseBodyImpl.Create( Response); try // Write to response LBody.SetValue(LJSONObject, False); finally LBody.Free; end; finally LJSONObject.Free; end; end; { TGroups } procedure TGroups.CheckGroups; begin if FGroups = nil then begin FGroups := TList<string>.Create; FGroups.AddRange(FRequestHandler.GetGroupsByUser(FContext, FUserID)); end; end; function TGroups.Contains(const AGroup: string): Boolean; begin CheckGroups; Result := FGroups.Contains(AGroup); end; constructor TGroups.Create(const AContext: IEMSHostContext; const ARequestHandler: TEMSHostRequestHandler; const AUserID: string); begin FContext := AContext; FRequestHandler := ARequestHandler; FUserID := AUserID; end; destructor TGroups.Destroy; begin FGroups.Free; inherited; end; function TGroups.GetCount: Integer; begin CheckGroups; Result := FGroups.Count; end; end.
unit MFichas.Model.Configuracao.Interfaces; interface uses System.Generics.Collections, MFichas.Model.Entidade.CONFIGURACOES, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.DataSet.Interfaces, FireDAC.Comp.Client; type iModelConfiguracao = interface; iModelConfiguracaoMetodos = interface; iModelConfiguracaoMetodosEditarView = interface; iModelConfiguracaoMetodosBuscarModel = interface; iModelConfiguracaoMetodosBuscarView = interface; iModelConfiguracao = interface ['{CCD68DC9-037A-4D2E-A58C-E4CEB5349B60}'] function Metodos : iModelConfiguracaoMetodos; function DAO : iContainerObjectSet<TCONFIGURACOES>; function DAODataSet: iContainerDataSet<TCONFIGURACOES>; end; iModelConfiguracaoMetodos = interface ['{F4145C48-8209-43E8-A388-C0359E62558F}'] function BuscarModel: iModelConfiguracaoMetodosBuscarModel; function EditarView : iModelConfiguracaoMetodosEditarView; function BuscarView : iModelConfiguracaoMetodosBuscarView; function &End : iModelConfiguracao; end; iModelConfiguracaoMetodosBuscarModel = interface ['{070A5592-6D5D-41CC-884F-2757C8E7C9FE}'] function Impressora: String; function &End : iModelConfiguracaoMetodos; end; iModelConfiguracaoMetodosEditarView = interface ['{3FD6FD21-EF3A-4D8F-9785-7FCC7B097311}'] function Impressora(AImpressora: String): iModelConfiguracaoMetodosEditarView; function &End : iModelConfiguracaoMetodos; end; iModelConfiguracaoMetodosBuscarView = interface ['{09CFFA6C-2D8F-4F2E-8D5F-5951BA2209F4}'] function FDMemTable(AFDMemTable: TFDMemTable): iModelConfiguracaoMetodosBuscarView; function BuscarConfiguracao : iModelConfiguracaoMetodosBuscarView; function &End : iModelConfiguracaoMetodos; end; implementation end.
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Bytecode interpreter unit unit interpreter; {$IFDEF fpc} {$MODE objfpc} {$ENDIF} interface uses typedefs, variable, bytecode, SysUtils; type islip_stack = class public constructor create(size : size_t); destructor destroy; override; procedure push(pv : pislip_var); procedure pop(pv : pislip_var); function peek : pislip_var; private m_stack : array of islip_var; m_top : integer; end; islip_interpreter = class public constructor create(stack_size : size_t; var c : islip_bytecode; var d : islip_data); destructor destroy; override; procedure run; private m_stack : islip_stack; m_code : pislip_bytecode; m_data : pislip_data; end; implementation // ==================================================== // interpreter implementation // ==================================================== constructor islip_interpreter.create(stack_size : size_t; var c : islip_bytecode; var d : islip_data); begin m_stack := islip_stack.create(stack_size); m_code := @c; m_data := @d; end; destructor islip_interpreter.destroy; begin m_stack.destroy; end; procedure islip_interpreter.run; var i : size_t; pv : pislip_var; v : islip_var; s : string; begin i := 1; v := islip_var.create; while i < size_t(length(m_code^)) do begin case m_code^[i].inst of OP_STOP: break; OP_PUSH: if m_code^[i].arg = ARG_NULL then m_stack.push(nil) else m_stack.push(@m_data^[m_code^[i].arg]); OP_POP: if m_code^[i].arg = ARG_NULL then m_stack.pop(nil) else m_stack.pop(@m_data^[m_code^[i].arg]); OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD, OP_MIN, OP_MAX: // pop the top-most value off the stack, write the result // into the second one begin m_stack.pop(@v); pv := m_stack.peek; if not pv^.math(@v, m_code^[i].inst) then begin writeln('RUNTIME ERROR: Invalid operands to ', 'arithmetic operator at 0x', IntToHex(i, 8)); v.destroy; exit; end; end; OP_NEG: begin pv := m_stack.peek; pv^.logic(nil, OP_NEG); end; OP_AND, OP_OR, OP_XOR, OP_EQ, OP_NEQ: // pop the top-most value off the stack, write the result // into the second one begin m_stack.pop(@v); pv := m_stack.peek; if not pv^.logic(@v, m_code^[i].inst) then begin writeln('RUNTIME ERROR: Invalid operands to ', 'logical operator at 0x', IntToHex(i, 8)); v.destroy; exit; end; end; OP_CONCAT: begin m_stack.pop(@v); pv := m_stack.peek; pv^.concat(@v); end; OP_PRINT: begin m_stack.pop(@v); if m_code^[i].arg = 1 then begin v.echo(true); writeln(stderr); end else begin v.echo(false); writeln; end; end; OP_READ: begin readln(s); new(pv); pv^ := islip_var.create(s); m_stack.push(pv); end; OP_CAST: (m_stack.peek)^.cast(islip_type(m_code^[i].arg)); OP_JMP: begin i := m_code^[i].arg; continue; end; OP_CNDJMP: begin m_stack.pop(@v); // NOTE: jump occurs if the top of the stack variable is // FALSE! this is because the success block follows // immediately, while the "else" block (or further code, if // there is no "else") appears after the success block if not v.get_bool then begin i := m_code^[i].arg; continue; end; end; OP_INCR: begin pv := m_stack.peek; v.destroy; if m_code^[i].arg = 0 then v := islip_var.create(-1) else v := islip_var.create(1); pv^.math(@v, OP_ADD); v.reset_value; end; else begin writeln('ERROR: Invalid instruction 0x', IntToHex(m_code^[i].inst, 2), ', possibly corrupt bytecode ', 'or unimplemented instruction'); v.destroy; exit; end; end; inc(i); end; v.destroy; end; // ==================================================== // stack implementation // ==================================================== constructor islip_stack.create(size : size_t); var i : size_t; begin setlength(m_stack, size); for i := 1 to size do m_stack[i] := islip_var.create; m_top := 0; end; destructor islip_stack.destroy; var i : size_t; begin for i := 1 to length(m_stack) do m_stack[i].destroy; end; procedure islip_stack.push(pv : pislip_var); var i : size_t; begin if m_top = length(m_stack) then begin //writeln('ERROR: Stack overflow'); //exit; setlength(m_stack, length(m_stack) * 2); // initialize the new part of the stack for i := length(m_stack) div 2 + 1 to length(m_stack) do m_stack[i] := islip_var.create; end; inc(m_top); if pv <> nil then m_stack[m_top].copy(pv) else m_stack[m_top] := islip_var.create; end; procedure islip_stack.pop(pv : pislip_var); begin if m_top <= 0 then begin writeln('RUNTIME ERROR: Stack underflow'); exit; end; if pv <> nil then begin pv^.copy(@m_stack[m_top]); end; dec(m_top); end; function islip_stack.peek : pislip_var; begin if m_top <= 0 then begin writeln('RUNTIME ERROR: Peeking into an empty stack'); exit; end; peek := @m_stack[m_top]; end; end.
unit main; interface uses System.SysUtils, System.Types, System.UITypes, System.Generics.Collections, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Calendar, RegularPolygon, FMX.Menus, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo; type SGameInput = record LeftButtonPressed: boolean; RightButtonPressed: boolean; UpButtonPressed: boolean; DownButtonPressed: boolean; end; TMainForm = class(TForm) gameLoopTimer: TTimer; FrameLayout: TLayout; MenuPanel: TPanel; StatusPanel: TPanel; chk_IsDoubleBuffered: TCheckBox; lblFPS_Counter: TLabel; GameViewPort: TPanel; menuBar: TMenuBar; mnitemData: TMenuItem; mnitemLoad: TMenuItem; memStatus: TMemo; pnlPlayArea: TPanel; PlayAreaBck: TRectangle; Ship: TRectangle; procedure OnGameLoopTick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure chk_IsDoubleBufferedChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure GameViewPortMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure mnitemLoadClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure PlayAreaBckMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ShipClick(Sender: TObject); private { Private-Deklarationen } FObjList: TList<TRectangle>; FCurrSelObj: TRectangle; public { Public-Deklarationen } end; const FPS_HISTORY_SIZE = 50; RotationSpeed = 10; velocity_x = 20; { means 20 Pixels per second } velocity_y = 20; var MainForm: TMainForm; currGameInput: SGameInput; fps: Double; fpsHistory: array[0..FPS_HISTORY_SIZE] of Double; fpsIdx: Integer; lastTime, currentTime, elapsedTime, lastFPSDisplayTime: System.Cardinal; GameObjList: TObjectList<TRectangle>; { module procs and functions since they are app-wide unique anyway } { if they should be obj-bound, a kind of Main-Class-Obj have to be invented } procedure startGame(); procedure stopGame(); implementation {$R *.fmx} {$R *.Windows.fmx MSWINDOWS} uses frmHousingUseCase; var IsGameRunning: Boolean; procedure InitGame; begin { ameObjList := TObjectList<TRectangle>.Create; (check if they are contigous in memory layout) } end; function getMeanFPS: Double; var i: Integer; sum: Double; begin sum := 0; for i := 0 to FPS_HISTORY_SIZE-1 do begin sum := sum + fpsHistory[i]; end; Result := sum / FPS_HISTORY_SIZE; end; procedure startGame(); begin IsGameRunning := True; lastTime := TThread.GetTickCount; end; procedure stopGame(); begin IsGameRunning := False; end; {--- START Win event handlers ---} procedure TMainForm.chk_IsDoubleBufferedChange(Sender: TObject); begin {if chk_IsDoubleBuffered.IsChecked then DoubleBuffered := True else DoubleBuffered := False;} end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin FObjList.Clear; FObjList.Free; Application.Terminate; end; procedure TMainForm.FormCreate(Sender: TObject); begin lastTime := TThread.GetTickCount; Fillchar(fpsHistory, SizeOf(fpsHistory), 0); fpsIdx := 0; lastFPSDisplayTime := TThread.GetTickCount; FObjList := TList<TRectangle>.Create; InitGame; end; procedure TMainForm.FormDestroy(Sender: TObject); begin { GameObjList.Clear; GameObjList.Free; } end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case Key of vkLeft: begin currGameInput.LeftButtonPressed := True; currGameInput.RightButtonPressed := False; end; vkRight: begin currGameInput.LeftButtonPressed := False; currGameInput.RightButtonPressed := True; end; vkUp: begin currGameInput.UpButtonPressed := True; currGameInput.DownButtonPressed := False; end; vkDown: begin currGameInput.UpButtonPressed := False; currGameInput.DownButtonPressed := True; end; end; case KeyChar of 'P', 'p': if IsGameRunning then IsGameRunning := False else IsGameRunning := True; end; end; procedure TMainForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin case Key of vkLeft: currGameInput.LeftButtonPressed := False; vkRight: currGameInput.RightButtonPressed := False; vkUp: currGameInput.UpButtonPressed := False; vkDown: currGameInput.DownButtonPressed := False; end; end; procedure TMainForm.GameViewPortMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); Var newObject: TRectangle; begin newObject := TRectangle.Create(MainForm.GameViewPort); newObject.Opacity := 0.3; { GameObjList.Add(newObject); } MainForm.AddObject(newObject); newObject.Position.X := X; newObject.Position.Y := Y; end; procedure TMainForm.mnitemLoadClick(Sender: TObject); var dummy: string; modalHouseUC: THousingForm; begin modalHouseUC := THousingForm.Create(Self); try modalHouseUC.showModal(); finally modalHouseUC.Free; end; end; procedure TMainForm.OnGameLoopTick(Sender: TObject); begin if IsGameRunning then begin currentTime := TThread.GetTickCount; elapsedTime := currentTime - lastTime; { will be used for update() } if fpsIdx > FPS_HISTORY_SIZE - 1 then fpsIdx := 0 else fpsIdx := fpsIdx + 1; fpsHistory[fpsIdx] := (1000.0 / Double(elapsedTime)); lastTime := currentTime; GameViewPort.BeginUpdate; { if its time to update our fps-Display Counter } if currentTime > lastFPSDisplayTime + 1000 then begin lblFPS_Counter.Text := Format('%.2f', [getMeanFPS]); lastFPSDisplayTime := currentTime; end; { process the Input-Info for actions/changed settings } { if currGameInput.LeftButtonPressed = True then Player.RotationAngle := Player.RotationAngle - RotationSpeed; if currGameInput.RightButtonPressed = True then Player.RotationAngle := Player.RotationAngle + RotationSpeed; } { change state because of game rules, physics = moving... } { Player.Position.X := Player.Position.X + (elapsedTime * velocity_x / 1000.0); Player.Position.Y := Player.Position.Y + (elapsedTime * velocity_y / 1000.0); if Player.Position.X >= pnlPlayArea.Size.Width then Player.Position.X := pnlPlayArea.Size.Width - 1; if Player.Position.Y >= pnlPlayArea.Size.Height then Player.Position.Y := pnlPlayArea.Size.Height - 1; } { render ?? implicit } GameViewPort.EndUpdate; end else lastTime := TThread.GetTickCount; end; procedure TMainForm.PlayAreaBckMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); Var newObject: TRectangle; begin memStatus.Lines.Add('X: ' + FloatToStr(X) + '; Y: ' + FloatToStr(Y)); newObject := TRectangle.Create(MainForm.PlayAreaBck); { GameObjList.Add(newObject); } newObject.Position.X := X; newObject.Position.Y := Y; newObject.Stroke.Kind := TBrushKind.Solid; newObject.Fill.Kind := TBrushKind.Bitmap; newObject.Fill.Bitmap.WrapMode := TWrapMode.TileStretch; newObject.Fill.Bitmap.Bitmap.LoadFromFile('ship.png'); newObject.OnClick := ShipClick; PlayAreaBck.AddObject(newObject); FObjList.Add(newObject); end; procedure TMainForm.ShipClick(Sender: TObject); begin if Assigned(FCurrSelObj) then FCurrSelObj.Stroke.Color := TAlphaColorRec.Black; FCurrSelObj := Sender as TRectangle; FCurrSelObj.Stroke.Color := TAlphaColorRec.Red; end; initialization begin IsGameRunning := True; end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPPNG; interface uses Classes, QGraphics, uGraphics, QDialogs, QTypes, Types, Sysutils; type TXPPNG=class(TGraphic) private FBackground: TBitmap; FAlphaMask: TBitmap; FSelectedMask: TBitmap; FCached: TBitmap; original: TBitmap; Fdone: boolean; FBackgroundColor: TColor; FUseBackground: boolean; ox: integer; oy: integer; FSelected: boolean; procedure createAlphaMask(original: TBitmap); procedure createSelectedMask; procedure SetBackground(const Value: TBitmap); procedure SetBackgroundColor(const Value: TColor); procedure SetUseBackground(const Value: boolean); procedure SetSelected(const Value: boolean); protected function GetEmpty: Boolean; override; function GetHeight: Integer; override; function GetWidth: Integer; override; procedure SetHeight(Value: Integer); override; procedure SetWidth(Value: Integer); override; public cache: boolean; procedure LoadFromMimeSource(MimeSource: TMimeSource); override; procedure SaveToMimeSource(MimeSource: TClxMimeSource); override; procedure Assign(source:TPersistent);override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; property Selected:boolean read FSelected write SetSelected; procedure paintToCanvas(ACanvas:TCanvas; const x,y:integer; dens:integer=0); constructor Create;override; destructor Destroy;override; property Background:TBitmap read FBackground write SetBackground; property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor; property UseBackground: boolean read FUseBackground write SetUseBackground; end; implementation { TXPPNG } //Constructor constructor TXPPNG.Create; begin inherited; cache:=true; //Store previous draw values to improve a bit drawing ox:=-1; oy:=-1; FSelected:=false; FCached:=TBitmap.create; FSelectedMask:=TBitmap.create; FUseBackground:=false; FBackgroundColor:=clBtnFace; Fdone:=false; original:=TBitmap.create; FAlphaMask:=TBitmap.create; FBackground:=TBitmap.create; end; destructor TXPPNG.Destroy; begin FCached.free; original.free; FSelectedMask.free; FBackground.free; FAlphaMask.free; inherited; end; //Creates the alpha mask used to draw the png with alpha channel procedure TXPPNG.createAlphaMask(original:TBitmap); var x,y:integer; points: Pointer; alpha: Pointer; a,r,g,b: byte; begin falphamask.Canvas.brush.color:=clWhite; falphamask.Canvas.FillRect(rect(0,0,32,32)); for y:=0 to original.height-1 do begin points:=original.ScanLine[y]; alpha:=falphamask.ScanLine[y]; for x:=0 to original.width-1 do begin r:=byte(points^); inc(PChar(points),1); g:=byte(points^); inc(PChar(points),1); b:=byte(points^); inc(PChar(points),1); a:=byte(points^); inc(PChar(points),1); if a<>0 then begin if a=255 then integer(alpha^):=(0 shl 24)+(b shl 16)+(g shl 8)+r else integer(alpha^):=((31-(a div 8)) shl 24)+(b shl 16)+(g shl 8)+r; end else integer(alpha^):=integer($FFFFFFFF); inc(PChar(alpha),4); end; end; end; //Sets the background procedure TXPPNG.SetBackground(const Value: TBitmap); begin FBackground.assign(Value); end; //Paint the png to a canvas procedure TXPPNG.paintToCanvas(ACanvas: TCanvas; const x, y: integer; dens:integer=0); var s: TBitmap; begin //Use a previous value if (x<>ox) or (y<>oy) or (not cache) then begin s:=TBitmap.create; try s.Width:=falphamask.width; s.height:=falphamask.height; //Depending on the png state if not fselected then begin bitblt(falphamask,s,0,0,falphamask.width,falphamask.height); end else begin bitblt(fselectedmask,s,0,0,falphamask.width,falphamask.height); end; //Merges the alpha channel with the background AlphaBitmap(s,fbackground,fcached,dens); ox:=x; oy:=y; //Draws the bitmap ACanvas.Draw(x,y,fcached); finally s.free; end; end else begin ACanvas.Draw(x,y,fcached); end; end; procedure TXPPNG.LoadFromStream(Stream: TStream); begin original.LoadFromStream(stream); falphamask.width:=original.width; falphamask.height:=original.height; fbackground.width:=falphamask.width; fbackground.height:=falphamask.height; fbackground.Canvas.brush.color:=clBtnFace; fbackground.Canvas.FillRect(types.rect(0,0,falphamask.width,falphamask.height)); createAlphaMask(original); createSelectedMask; end; procedure TXPPNG.Draw(ACanvas: TCanvas; const Rect: TRect); begin paintToCanvas(ACanvas, rect.left, rect.top); end; function TXPPNG.GetEmpty: Boolean; begin result:=falphamask.empty; end; function TXPPNG.GetHeight: Integer; begin result:=falphamask.height; end; function TXPPNG.GetWidth: Integer; begin result:=falphamask.width; end; procedure TXPPNG.SetHeight(Value: Integer); begin end; procedure TXPPNG.SetWidth(Value: Integer); begin end; procedure TXPPNG.Assign(source: TPersistent); var m: TMemoryStream; begin if source is TXPPNG then begin falphamask.width:=(source as TXPPNG).falphamask.width; falphamask.height:=(source as TXPPNG).falphamask.height; bitblt((source as TXPPNG).falphamask,falphamask,0,0,falphamask.width,falphamask.height); end else if source is TBitmap then begin m:=TMemorystream.create; try (source as TBitmap).SaveToStream(m); m.position:=0; LoadFromStream(m); finally m.free; end; end else inherited; end; procedure TXPPNG.SaveToStream(Stream: TStream); begin original.SaveToStream(stream); end; procedure TXPPNG.SetBackgroundColor(const Value: TColor); begin if value<>FBackgroundColor then begin FBackgroundColor := Value; ox:=ox-1; FBackground.Width:=original.Width; FBackground.height:=original.height; FBackground.Canvas.Brush.Color:=FBackgroundColor; FBackground.Canvas.FillRect(rect(0,0,original.width,original.height)); end; end; procedure TXPPNG.SetUseBackground(const Value: boolean); begin if Value<>FUseBackground then begin FUseBackground := Value; createSelectedMask; end; end; procedure TXPPNG.createSelectedMask; var c: TBitmap; s: TBitmap; b: TBitmap; d: TBitmap; begin c:=TBitmap.create; s:=TBitmap.create; b:=TBitmap.create; d:=TBitmap.create; try fselectedmask.Width:=falphamask.width; fselectedmask.height:=falphamask.height; c.Width:=falphamask.width; c.height:=falphamask.height; s.Width:=falphamask.width; s.height:=falphamask.height; b.Width:=falphamask.width; b.height:=falphamask.height; d.Width:=falphamask.width; d.height:=falphamask.height; if fusebackground then begin b.Assign(fbackground); end else begin b.Canvas.Brush.color:=FBackgroundColor; b.Canvas.FillRect(rect(0,0,falphamask.width,falphamask.height)); end; bitblt(falphamask,s,0,0,falphamask.width,falphamask.height); b.Canvas.Brush.color:=clHighlight; b.Canvas.FillRect(rect(0,0,falphamask.width,falphamask.height)); SelectedBitmap(s,b,c,16); bitblt(c,FSelectedMask,0,0,falphamask.width,falphamask.height); finally d.free; b.free; s.free; c.free; end; end; procedure TXPPNG.SetSelected(const Value: boolean); begin if FSelected<>Value then begin FSelected := Value; ox:=ox-1; end; end; procedure TXPPNG.LoadFromMimeSource(MimeSource: TMimeSource); begin inherited; end; procedure TXPPNG.SaveToMimeSource(MimeSource: TClxMimeSource); begin inherited; end; initialization //Removed until the desktop is ready for alpha channel //TPicture.RegisterFileFormat('PNG','PNG Alpha', TXPPNG); finalization //Removed until the desktop is ready for alpha channel //TPicture.UnregisterGraphicClass(TXPPNG); end.
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Buttons, CsvDocument, dnssend, tlntsend; type { TfrmMain } TfrmMain = class(TForm) btnLoadCSV: TButton; btnVerifyAll: TButton; CSV_OpenDialog: TOpenDialog; lvEmails: TListView; mmoLog: TMemo; ProgressBar1: TProgressBar; procedure btnLoadCSVClick(Sender: TObject); procedure btnVerifyAllClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FDoc: TCSVDocument; procedure PopulateData(dataStrings: TStringList); function GetDataCSV(CSVFilename: String): TStringList; procedure VerifyAllEmails; function VerifyEmail(EmailAddress: String): boolean; public { public declarations } end; var frmMain: TfrmMain; implementation {$R *.lfm} { TfrmMain } procedure TfrmMain.btnLoadCSVClick(Sender: TObject); var dataStrings: TStringList; begin if CSV_OpenDialog.Execute then begin FDoc.LoadFromFile(CSV_OpenDialog.FileName); dataStrings := GetDataCSV(CSV_OpenDialog.FileName); try PopulateData(dataStrings); finally dataStrings.Free; end; end; end; procedure TfrmMain.btnVerifyAllClick(Sender: TObject); begin VerifyAllEmails; end; procedure TfrmMain.FormCreate(Sender: TObject); begin FDoc := TCSVDocument.Create; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FDoc.Free; end; procedure TfrmMain.PopulateData(dataStrings: TStringList); var I: Integer; emailItem: TListItem; begin lvEmails.BeginUpdate; progressBar1.Position:=0; progressBar1.Max:= dataStrings.Count; for I:= 0 to dataStrings.Count - 1 do begin emailItem := lvEmails.Items.Add; emailItem.Caption:= dataStrings[I]; progressBar1.Position:= i; end; lvEmails.EndUpdate; end; function TfrmMain.GetDataCSV(CSVFilename: String): TStringList; var i: Integer; begin Result := TStringList.Create; for i := 0 to FDoc.RowCount - 1 do begin Result.Add(FDoc.Cells[0, i]); end; end; procedure TfrmMain.VerifyAllEmails; var i : Integer; emailAddress: String; item: TListItem; begin lvEmails.BeginUpdate; try ProgressBar1.Position:= 0; ProgressBar1.Max:=lvEmails.Items.Count - 1; for i:= 0 to lvEmails.Items.Count - 1 do begin item := lvEmails.Items[i]; ProgressBar1.Position:= i; emailAddress := item.Caption; try if VerifyEmail(emailAddress) then item.SubItems.Add('Verified') else item.SubItems.Add('Fail'); except on E:Exception do item.SubItems.Add('Fail'); end; application.ProcessMessages; end; finally lvEmails.EndUpdate; end; end; function TfrmMain.VerifyEmail(EmailAddress: String): boolean; var dnsList: TStringList; domainParser: TStringList; domainName: String; telnet: TTelnetSend; i: Integer; function Read: String; procedure Strip0; var I : Integer; begin i:=1; while i<=Length(Result) do begin if (Result[i]=#0)and (Result[i-1]=#13) then System.Delete(Result,i-1,2) else Inc(i); end; end; begin Result := telnet.RecvString; while Result <> '' do begin Strip0; mmoLog.Lines.Add(Result); Result:=telnet.RecvString; end; end; begin dnsList := TStringList.Create; domainParser:= TStringList.Create; try domainParser.delimiter := '@'; domainParser.delimitedText := EmailAddress; if domainParser.count = 0 then begin Result := False; exit; end; domainName := domainParser[1]; GetMailServers('gmail.org', domainName, dnsList); if dnsList.count = 0 then begin Result := False; Exit; end; if dnsList.Count = 0 then begin Result := False; mmoLog.Lines.Add('Name server not found for email address: '+EmailAddress); Exit; end; for i:= 0 to dnsList.Count - 1 do begin mmoLog.Lines.add(dnsList[i]); end; telnet := TTelnetSend.Create; try try telnet.TargetHost := dnsList[0]; telnet.TargetPort := '25'; telnet.Timeout := 1000; telnet.TermType:= 'dumb'; telnet.Login; Read; telnet.Send('HELO gmail.com'#13#10); Read; telnet.Send('MAIL FROM:<untuk.cek.subscriber@gmail.com>'#13#10); Read; telnet.Send('RCPT TO:<'+EmailAddress+'>'); if Pos( Read, 'OK') >= 1 then Result := True else Result := False; telnet.Logout; except on E:Exception do mmoLog.Lines.Add('Error connecting to nameserver: '+dnsList[0]); end; finally telnet.Free; end; Result := True; finally dnsList.Free; domainParser.free; end; end; end.
unit fmuCustomerAttributes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AtrPages, ToolCtrlsEh, ComCtrls, ToolWin, GridsEh, DBGridEh, DB, FIBDataSet, pFIBDataSet, ActnList, DBGridEhToolCtrls, DBAxisGridsEh, System.Actions, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, FIBDatabase, pFIBDatabase; type TapgCustomerAttributes = class(TA4onPage) dsCustAttributes: TpFIBDataSet; srcCustAttributes: TDataSource; dbgCustAttr: TDBGridEh; tbAttributes: TToolBar; btnAdd: TToolButton; btnEdit: TToolButton; btnDel: TToolButton; ActListCustomers: TActionList; actAdd: TAction; actEdit: TAction; actDel: TAction; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDelExecute(Sender: TObject); procedure dbgCustAttrDblClick(Sender: TObject); private { Private declarations } procedure EnableControls; public procedure InitForm; override; procedure OpenData; override; procedure CloseData; override; class function GetPageName: string; override; end; implementation {$R *.dfm} uses MAIN, AtrCommon, DM, EditAttributeForma; class function TapgCustomerAttributes.GetPageName: string; begin Result := rsClmnAttributes; end; procedure TapgCustomerAttributes.InitForm; var FullAccess: Boolean; begin FullAccess := (dmMain.AllowedAction(rght_Customer_full)); // Полный доступ // атрибуты tbAttributes.Visible := (dmMain.AllowedAction(rght_Customer_Attribute)) or (dmMain.AllowedAction(rght_Customer_edit)) or FullAccess; actAdd.Visible := tbAttributes.Visible; actDel.Visible := tbAttributes.Visible; actEdit.Visible := tbAttributes.Visible; dsCustAttributes.DataSource := FDataSource; end; procedure TapgCustomerAttributes.EnableControls; begin actEdit.Enabled := dsCustAttributes.RecordCount > 0; actDel.Enabled := dsCustAttributes.RecordCount > 0; end; procedure TapgCustomerAttributes.OpenData; begin if dsCustAttributes.Active then dsCustAttributes.Close; dsCustAttributes.OrderClause := GetOrderClause(dbgCustAttr); dsCustAttributes.Open; EnableControls; end; procedure TapgCustomerAttributes.actAddExecute(Sender: TObject); begin // dsCustAttributes.append; if EditAttribute(FDataSource.DataSet['CUSTOMER_ID'], '') then begin // dsCustAttributes.Post; dsCustAttributes.CloseOpen(true); EnableControls; UpdatePage; end end; procedure TapgCustomerAttributes.actDelExecute(Sender: TObject); begin if srcCustAttributes.DataSet.State in [dsInsert, dsEdit] then srcCustAttributes.DataSet.Cancel else begin if ((not dsCustAttributes.Active) or (dsCustAttributes.RecordCount = 0)) then Exit; if (not srcCustAttributes.DataSet.FieldByName('O_NAME').IsNull) then begin if (MessageDlg(Format(rsDeleteWithName, [srcCustAttributes.DataSet['O_NAME']]), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin srcCustAttributes.DataSet.Delete; EnableControls; UpdatePage; end; end; end; end; procedure TapgCustomerAttributes.actEditExecute(Sender: TObject); begin // dsCustAttributes.Edit; if ((not dsCustAttributes.Active) or (dsCustAttributes.RecordCount = 0)) then Exit; if (dsCustAttributes.FieldByName('O_NAME').IsNull) or (dsCustAttributes.FieldByName('CA_ID').IsNull) or (FDataSource.DataSet.FieldByName('CUSTOMER_ID').IsNull) then Exit; if EditAttribute(FDataSource.DataSet['CUSTOMER_ID'], dsCustAttributes['O_NAME'], dsCustAttributes['CA_ID']) then begin // dsCustAttributes.Post; dsCustAttributes.Refresh; EnableControls; UpdatePage; end // else dsCustAttributes.Cancel; end; procedure TapgCustomerAttributes.CloseData; begin dsCustAttributes.Close; end; procedure TapgCustomerAttributes.dbgCustAttrDblClick(Sender: TObject); begin if (Sender as TDBGridEh).DataSource.DataSet.RecordCount > 0 then begin if actEdit.Enabled then actEdit.Execute; end else begin if actAdd.Enabled then actAdd.Execute; end; end; end.
unit ClientTrain; interface uses Classes, StateEngine, DistributedStates, ActorTypes, ActorPool, Automaton, Train, Vehicles; const HighResFreqMult = 10; type TClientCar = class; TClientCarModification = (ccmInserted, ccmDeleted); TOnClientCarModified = procedure( Car : TClientCar; Modification : TClientCarModification ) of object; TClientCar = class( TCar, IVehicle ) public destructor Destroy; override; private fHigResX : single; fHigResY : single; fHigResAngle : single; fHigResSpeedX : single; fHigResSpeedY : single; fNoSynchAct : boolean; fLastAngle : single; protected procedure Act( State : TStateId; Mode : TActMode ); override; function HandleEvent( anEvent : TDistributedEvent ) : boolean; override; procedure Load( Stream : TStream ); override; private fOnClientTrainModified : TOnClientCarModified; public property OnClientTrainModified : TOnClientCarModified read fOnClientTrainModified write fOnClientTrainModified; // IVehicle private function getX : single; function getY : single; function getAngle : single; function getDir : TVehicleDirection; function getNextDir : TVehicleDirection; function getGroupId : integer; function getVisualClass : word; function getCustomData : pointer; procedure setCustomData( data : pointer; datasize : integer ); procedure Deleted; override; private fCustomData : pointer; fDataSize : integer; protected procedure MsgAnswerVehicle( var Msg : TMsgAnswerVehicle ); message msgAnswerVehicle; end; implementation uses LogFile, SysUtils, MathUtils; // TClientCar destructor TClientCar.Destroy; begin if fCustomData <> nil then freemem( fCustomData, fDataSize ); inherited; end; procedure TClientCar.Act( State : TStateId; Mode : TActMode ); var HRAngleSpeed : single; begin if not fNoSynchAct then inherited else fNoSynchAct := false; case Mode of amdSynchronized : begin fHigResAngle := fLastAngle; fLastAngle := Angle; end; amdHighRes : case State of carstRunning : begin fHigResSpeedX := (x - fHigResX)/HighResFreqMult; fHigResSpeedY := (y - fHigResY)/HighResFreqMult; if round(100*fHigResSpeedX) <> 0 then fHigResX := fHigResX + fHigResSpeedX else fHigResX := x; if round(100*fHigResSpeedY) <> 0 then fHigResY := fHigResY + fHigResSpeedY else fHigResY := y; HRAngleSpeed := (Angle - fHigResAngle)/HighResFreqMult; if round(100*HRAngleSpeed) <> 0 then fHigResAngle := fHigResAngle + HRAngleSpeed else fHigResAngle := Angle; { fHigResAngle := fLastAngle; fLastAngle := Angle; } { HRAngleSpeed := (Angle - fHigResAngle)/HighResFreqMult; fHigResAngle := fHigResAngle + HRAngleSpeed; } end; end; end; end; function TClientCar.HandleEvent( anEvent : TDistributedEvent ) : boolean; begin result := true; case anEvent.Id of evnAccelerationChange : Acceleration := single(anEvent.Data^); evnSpeedChange : Speed := single(anEvent.Data^); evnVisualStageChange : VisualStage := integer(anEvent.Data^); evnDirectionChange : begin { if (abs(fHigResX - x) > 1) or (abs(fHigResY - y) > 1) then case Direction of cdirN : fHigResY := y + 1; cdirE : fHigResX := x - 1; cdirS : fHigResY := y - 1; cdirW : fHigResX := x + 1; end; } Direction := TCarDirection(anEvent.Data^); case Direction of cdirN, cdirS : x := round(x); else y := round(y); end; end; evnNextDirectionChange : NextDirection := TCarDirection(anEvent.Data^); evnSyncInfo : begin x := TSyncInfo(anEvent.Data^).x; y := TSyncInfo(anEvent.Data^).y; Acceleration := TSyncInfo(anEvent.Data^).accel; Speed := TSyncInfo(anEvent.Data^).speed; Angle := TSyncInfo(anEvent.Data^).angle; { if abs(fHigResX - x) > 1.5 then fHigResX := x; if abs(fHigResY - y) > 1.5 then fHigResY := y; } LogThis( 'Synchronizing angle: ' + IntToStr(round(180*Angle/pi)) + ' and position (x: ' + FloatToStr(x) + ', y: ' + FloatToStr(y) + ')' ); fNoSynchAct := true; end; else result := inherited HandleEvent( anEvent ); end; end; procedure TClientCar.Load( Stream : TStream ); begin inherited; fHigResX := x; fHigResY := y; fLastAngle := Angle; fHigResAngle := fLastAngle; end; function TClientCar.getX : single; begin result := fHigResX; //X // end; function TClientCar.getY : single; begin result := fHigResY; //Y // end; function TClientCar.getAngle : single; begin result := fHigResAngle; //result := Angle; end; function TClientCar.getDir : TVehicleDirection; begin case Direction of cdirN : result := vdirN; cdirS : result := vdirS; cdirE : result := vdirE; else result := vdirW; end; end; function TClientCar.getNextDir : TVehicleDirection; begin case NextDirection of cdirN : result := vdirN; cdirS : result := vdirS; cdirE : result := vdirE; else result := vdirW; end; end; function TClientCar.getGroupId : integer; begin result := 1; end; function TClientCar.getVisualClass : word; begin result := VisualClass; end; function TClientCar.getCustomData : pointer; begin result := fCustomData; end; procedure TClientCar.setCustomData( data : pointer; datasize : integer ); begin fCustomData := data; fDataSize := datasize; end; procedure TClientCar.Deleted; begin if assigned(fOnClientTrainModified) then fOnClientTrainModified( self, ccmDeleted ); end; procedure TClientCar.MsgAnswerVehicle( var Msg : TMsgAnswerVehicle ); begin Msg.Vehicle := self; end; end.
{ Subroutine SST_R_PAS_SMENT_VAR * * Process the Pascal VAR_STATEMENT syntax. This will also involve processing * any number of VAR_SUBSTATEMENT syntaxes. These will be invoked explicitly * with the syntax subroutine SSR_R_PAS_SYN_VAR. } module sst_r_pas_SMENT_VAR; define sst_r_pas_sment_var; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_sment_var; {process VAR_STATEMENT syntax} var tag: sys_int_machine_t; {syntax tag from .syn file} str_h: syo_string_t; {handle to string for a tag} sym_p: sst_symbol_p_t; {scratch pointer to symbol table entry} chain_p: sst_symbol_p_t; {points to symbols declared here} dtype_p: sst_dtype_p_t; {points to data type for curr set of vars} com_p: sst_symbol_p_t; {points to common block symbol, if any} com_chain_pp: sst_symbol_pp_t; {points to end of common block names chain} exp_p: sst_exp_p_t; {points to initial value for variables} new_chain: boolean; {TRUE if next name start new chain} charcase: syo_charcase_k_t; {name character upper/lower case flag} mflag: syo_mflag_k_t; {syntaxed matched yes/no flag} stat: sys_err_t; label loop_statement, loop_tag; begin syo_level_down; {down into VAR_STATEMENT syntax} { * Process optional common block name for all the variables of this VAR statement. } syo_get_tag_msg {get common block name tag} (tag, str_h, 'sst_pas_read', 'var_sment_bad', nil, 0); case tag of 1: begin {no common block name} com_p := nil; com_chain_pp := nil; end; 2: begin {common block name present} sst_symbol_new ( {create and init common block name symbol} str_h, syo_charcase_asis_k, com_p, stat); syo_error_abort (stat, str_h, '', '', nil, 0); com_p^.symtype := sst_symtype_com_k; {set up common block symbol descriptor} if not (sst_symflag_global_k in com_p^.flags) then begin {not in DEFINE ?} com_p^.flags := com_p^.flags + {init to common block defined elsewhere} [sst_symflag_global_k, sst_symflag_extern_k]; end; if sst_config.os = sys_os_domain_k then begin {target machine is Apollo ?} com_p^.flags := com_p^.flags + {common blocks are always "defined"} [sst_symflag_global_k]; com_p^.flags := com_p^.flags - [sst_symflag_extern_k]; end; com_p^.com_first_p := nil; com_p^.com_size := 0; com_chain_pp := addr(com_p^.com_first_p); {init pointer to com names chain end} end; otherwise syo_error_tag_unexp (tag, str_h); end; new_chain := true; {next symbol name starts new chain of vars} { * Back here each new VAR_SUBSTATEMENT syntaxes. } loop_statement: syo_tree_clear; {set up for parsing} sst_r_pas_syn_var (mflag); {try to parse next VAR_SUBSTATEMENT syntax} if mflag = syo_mflag_yes_k then begin {syntax matched} error_syo_found := false; {indicate no syntax error} end else begin {syntax did not match} return; {no more VAR_SUBSTATMENTS here} end ; syo_tree_setup; {set up syntax tree for getting tags} syo_level_down; {down into VAR_SUBSTATEMENT syntax level} { * Determine whether the variable name cases should be preserved or not. * The variable names are always converted to lower case unless they are * globally known symbols. This is only true if the EXTERN keyword is present. } charcase := syo_charcase_down_k; {init to assume conversion to lower case} syo_push_pos; {save state of syntax tree traversal} repeat {loop over all the variable name tags} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'var_sment_bad', nil, 0); until tag <> 1; if tag = 2 then begin {found EXTERN keyword ?} charcase := syo_charcase_asis_k; {preserve character upper/lower case} end; syo_pop_pos; {restore syntax tree traversal state} { * Back here each new tag. } loop_tag: {back here for next syntax tag} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'var_sment_bad', nil, 0); case tag of { * Tag is name of new symbol being declared as a variable. } 1: begin if new_chain then begin {this symbol starts a new chain of var names} sst_symbol_new ( {add new symbol to current scope} str_h, charcase, sym_p, stat); chain_p := sym_p; {init start of chain} new_chain := false; {next symbol adds to this chain} end else begin {this symbol will be added to existing chain} sst_symbol_new ( {add new symbol to current scope} str_h, charcase, sym_p^.next_p, stat); sym_p := sym_p^.next_p; {update current symbol to new symbol} end ; syo_error_abort (stat, str_h, '', '', nil, 0); sym_p^.symtype := sst_symtype_var_k; {new symbol is a variable} sym_p^.flags := [ {init flags for this symbol} sst_symflag_def_k]; {symbol will be defined} if {this variable is in static storage ?} (com_p <> nil) or {variable is in a common block ?} (nest_level <= 1) {variable is at PROGRAM or MODULE level ?} then begin sym_p^.flags := sym_p^.flags + [sst_symflag_static_k]; end; end; { * All the variable names of the current chain were flagged with the EXTERN * keyword. } 2: begin sym_p := chain_p; {init current symbol to first symbol in chain} while sym_p <> nil do begin {once for each symbol in chain} if com_p <> nil then begin {symbols are in a common block ?} syo_error (str_h, 'sst_pas_read', 'common_and_extern', nil, 0); end; sym_p^.flags := sym_p^.flags + [sst_symflag_global_k, sst_symflag_extern_k]; sym_p := sym_p^.next_p; {advance to next symbol in chain} end; {back and process this new symbol} end; { * Tag is data type definition for the variables currently on the chain. } 3: begin new_chain := true; {next variable name starts a new chain} dtype_p := nil; {indicate to create new data type descriptor} sst_r_pas_data_type (dtype_p); {get pointer to data type for vars on chain} sym_p := chain_p; {init to first symbol in chain} while sym_p <> nil do begin {once for each var name in chain} sym_p^.var_dtype_p := dtype_p; {set data type for this var name} sym_p^.var_val_p := nil; {init to no initializer value here} sym_p^.var_arg_p := nil; {this variable is not a dummy argument} sym_p^.var_proc_p := nil; sym_p^.var_com_p := com_p; {point to common block symbol, if any} sym_p^.var_next_p := nil; {init to this is last symbol in common block} if com_p <> nil then begin {this variable is in a common block ?} com_chain_pp^ := sym_p; {add variable to common block chain} com_chain_pp := addr(sym_p^.var_next_p); {update pointer to end of chain} if dtype_p^.align > 0 then begin com_p^.com_size := {pad size for this var's alignment} ((com_p^.com_size + dtype_p^.align - 1) div dtype_p^.align) * dtype_p^.align; end; com_p^.com_size := com_p^.com_size + {add size of this variable} dtype_p^.size_used; end; {done handling var is in common block} sym_p := sym_p^.next_p; {advance to next symbol in chain} end; {back to process new symbol in chain} end; { * No tag was found. This is the normal way to indicate end of VAR_SUBSTATEMENT. } syo_tag_end_k: begin goto loop_statement; {back for next VAR_SUBSTATEMENT syntax} end; { * Tag is initial value for all the variables in the chain. } 4: begin sst_r_pas_var_init (dtype_p^, exp_p); {get expression for initial var value} sym_p := chain_p; {init current symbol to first in chain} while sym_p <> nil do begin {once for each symbol in chain} if not (sst_symflag_static_k in sym_p^.flags) then begin {variable not static ?} syo_error (str_h, 'sst', 'var_init_not_static', nil, 0); end; sym_p^.var_val_p := exp_p; {indicate this var has initial value} sym_p := sym_p^.next_p; {to next var symbol with same initial value} end; {back and process this new var} end; { * Tag is STATIC keyword. This explicitly makes all the variables on the * chain allocated in static storage (not on the routine stack frame). } 5: begin sym_p := chain_p; {init current symbol to first in chain} while sym_p <> nil do begin {once for each symbol in chain} sym_p^.flags := sym_p^.flags + [sst_symflag_static_k]; {flag this var as static} sym_p := sym_p^.next_p; {advance to next var in chain} end; {back and process this new var} end; { * Unexpected tag value } otherwise syo_error_tag_unexp (tag, str_h); end; {end of tag cases} goto loop_tag; {back for next tag in VAR_SUBSTATEMENT} end;