text
stringlengths
14
6.51M
unit ValidationRules.TDataTypeValidationRule; interface uses System.SysUtils, System.Variants, Framework.Interfaces, EnumClasses.TDataType, DataValidators.TBooleanDataValidator, DataValidators.TCurrencyDataValidator, DataValidators.TDateTimeDataValidator, DataValidators.TIntegerDataValidator, DataValidators.TNumericDataValidator, DataValidators.TStringDataValidator; type TDataTypeValidationRule = class(TInterfacedObject, IValidationRule) const INVALID_DATATYPE_MESSAGE = 'Invalid data type'; private FDataValidator: IDataValidator; FDataType: String; FAcceptEmpty: Boolean; function GetDataValidatorInstance(const ADataType: String; const ADateFormat: String; const ADateSeparator: Char): IDataValidator; function IsEmpty(const AValue: Variant): Boolean; public constructor Create(const AAcceptEmpty: Boolean; const ADataType: String; const ADateFormat: String; const ADateSeparator: Char); destructor Destroy; override; function Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; end; implementation { TDataTypeValidationRule } constructor TDataTypeValidationRule.Create(const AAcceptEmpty: Boolean; const ADataType: String; const ADateFormat: String; const ADateSeparator: Char); begin inherited Create; FAcceptEmpty := AAcceptEmpty; FDataType := ADataType; FDataValidator := GetDataValidatorInstance(FDataType, ADateFormat, ADateSeparator); end; destructor TDataTypeValidationRule.Destroy; begin inherited; end; function TDataTypeValidationRule.GetDataValidatorInstance( const ADataType: String; const ADateFormat: String; const ADateSeparator: Char): IDataValidator; var AuxDataType: String; begin AuxDataType := UpperCase(Trim(ADataType)); if AuxDataType = UpperCase(Trim(TDataType.dtBoolean)) then Result := TBooleanDataValidator.Create else if AuxDataType = UpperCase(Trim(TDataType.dtCurrency)) then Result := TCurrencyDataValidator.Create else if AuxDataType = UpperCase(Trim(TDataType.dtDateTime)) then Result := TDateTimeDataValidator.Create(ADateFormat, ADateSeparator) else if AuxDataType = UpperCase(Trim(TDataType.dtInteger)) then Result := TIntegerDataValidator.Create else if AuxDataType = UpperCase(Trim(TDataType.dtNumeric)) then Result := TNumericDataValidator.Create else if AuxDataType = UpperCase(Trim(TDataType.dtString)) then Result := TStringDataValidator.Create; end; function TDataTypeValidationRule.IsEmpty(const AValue: Variant): Boolean; begin Result := (Trim(AValue) = ''); end; function TDataTypeValidationRule.Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; begin Result := (FAcceptEmpty and IsEmpty(AValue)); if not Result then Result := FDataValidator.Parse(AValue); if not Result then AReasonForRejection := Self.INVALID_DATATYPE_MESSAGE + ' [' + FDataType + ']'; end; end.
unit uGraph; interface uses Windows, SysUtils, Graphics, JPEG, GIFImage, PNGImage, // Own units UCommon; type TGraph = class(THODObject) private FJPG: TJpegImage; FGIF: TGIFImage; FPNG: TPNGObject; FFilePath: string; FBasePath: string; procedure SetBasePath(const Value: string); function FileExt: string; public function LoadImage(const APath: string; Bitmap: TBitmap): Boolean; procedure DrawText(const Text: string; Bitmap: TBitmap; AX, AY: Integer; FName: string; FSize, FColor: Integer; FBold: Boolean = False); property BasePath: string read FBasePath; function TakeScreenShot(): string; //** Конструктор. constructor Create(const ABasePath: string); //** Деструктор. destructor Destroy; override; end; implementation uses uSCR, uBox; { TGraph } constructor TGraph.Create(const ABasePath: string); begin FBasePath := ABasePath; end; destructor TGraph.Destroy; begin inherited; end; procedure TGraph.DrawText(const Text: string; Bitmap: TBitmap; AX, AY: Integer; FName: string; FSize, FColor: Integer; FBold: Boolean = False); begin with Bitmap.Canvas do begin Font.Size := FSize; Font.Name := FName; Font.Color := FColor; Font.Style := []; if FBold then Font.Style := [fsBold]; TextOut(AX, AY, Text); end; end; function TGraph.FileExt: string; begin Result := Copy(FFilePath, Length(FFilePath) - 3, Length(FFilePath)); end; function TGraph.LoadImage(const APath: string; Bitmap: TBitmap): Boolean; begin Result := False; FFilePath := BasePath + APath; if FileExists(FFilePath) then begin if (LowerCase(FileExt) = '.bmp') then begin Result := True; Bitmap.LoadFromFile(FFilePath); end else if (LowerCase(FileExt) = '.png') then begin Result := True; FPNG := TPNGObject.Create; try FPNG.LoadFromFile(FFilePath); Bitmap.Assign(FPNG); finally FPNG.Free; end; end else if (LowerCase(FileExt) = '.jpg') then begin Result := True; FJPG := TJpegImage.Create; try FJPG.LoadFromFile(FFilePath); Bitmap.Assign(FJPG); finally FJPG.Free; end; end else if (LowerCase(FileExt) = '.gif') then begin Result := True; FGIF := TGIFImage.Create; try FGIF.LoadFromFile(FFilePath); Bitmap.Assign(FGIF); finally FGIF.Free; end; end; end else begin MessageBox(0, PChar(Format('File "%s" not found!', [FFilePath])), 'Error', MB_OK or MB_ICONERROR); Halt; end; end; procedure TGraph.SetBasePath(const Value: string); begin FBasePath := Value; end; function TGraph.TakeScreenShot(): string; var T: TSystemTime; P: TPNGObject; begin GetSystemTime(T); Result := IntToStr(T.wYear) + IntToStr(T.wMonth) + IntToStr(T.wDay) + IntToStr(T.wHour) + IntToStr(T.wMinute) + IntToStr(T.wSecond) + '.png'; P := TPNGObject.Create; P.Assign(SCR.BG); P.SaveToFile(Result); P.Free; end; end.
unit StockDetailData_Save; interface uses BaseApp, StockDetailDataAccess; procedure SaveStockDetailData(App: TBaseApp; ADataAccess: TStockDetailDataAccess); procedure SaveStockDetailData2File(App: TBaseApp; ADataAccess: TStockDetailDataAccess; AFileUrl: string); implementation uses Windows, Sysutils, BaseWinFile, //UtilsLog, define_datasrc, define_dealstore_file, define_stock_quotes, define_dealstore_header, Define_Price; {$IFNDEF RELEASE} const LOGTAG = 'StockDetailData_Save.pas'; {$ENDIF} procedure SaveStockDetailDataToBuffer(App: TBaseApp; ADataAccess: TStockDetailDataAccess; AMemory: pointer); forward; procedure SaveStockDetailData(App: TBaseApp; ADataAccess: TStockDetailDataAccess); var tmpFileUrl: string; begin tmpFileUrl := App.Path.GetFileUrl(ADataAccess.DBType, ADataAccess.DataType, GetDealDataSourceCode(ADataAccess.DataSource), ADataAccess.FirstDealDate, ADataAccess.StockItem); //Log(LOGTAG, 'SaveStockDetailData:' + tmpFileUrl); SaveStockDetailData2File(App, ADataAccess, tmpFileUrl); end; procedure SaveStockDetailData2File(App: TBaseApp; ADataAccess: TStockDetailDataAccess; AFileUrl: string); var tmpWinFile: TWinFile; tmpFileMapView: Pointer; tmpFileNewSize: integer; begin if '' = AFileUrl then exit; ForceDirectories(ExtractFilePath(AFileUrl)); tmpWinFile := TWinFile.Create; try if tmpWinFile.OpenFile(AFileUrl, true) then begin tmpFileNewSize := SizeOf(define_dealstore_header.TStore_Quote_M2_Detail_Header_V1Rec) + ADataAccess.RecordCount * SizeOf(define_stock_quotes.TStore_Quote32_Detail); //400k tmpFileNewSize := ((tmpFileNewSize div (1 * 1024)) + 1) * 1 * 1024; tmpWinFile.FileSize := tmpFileNewSize; tmpFileMapView := tmpWinFile.OpenFileMap; if nil <> tmpFileMapView then begin SaveStockDetailDataToBuffer(App, ADataAccess, tmpFileMapView); end; end; finally tmpWinFile.Free; end; end; procedure SaveStockDetailDataToBuffer(App: TBaseApp; ADataAccess: TStockDetailDataAccess; AMemory: pointer); var tmpHead: PStore_Quote_M2_Detail_Header_V1Rec; tmpStoreDetailData: PStore_Quote32_Detail; tmpRTDetailData: PRT_Quote_Detail; i: integer; begin tmpHead := AMemory; tmpHead.Header.BaseHeader.CommonHeader.Signature.Signature := 7784; // 6 tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer1 := 1; tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer2 := 0; tmpHead.Header.BaseHeader.CommonHeader.Signature.DataVer3 := 0; // 字节存储顺序 java 和 delphi 不同 // 00 // 01 tmpHead.Header.BaseHeader.CommonHeader.Signature.BytesOrder:= 1; tmpHead.Header.BaseHeader.CommonHeader.HeadSize := SizeOf(TStore_Quote_M2_Detail_Header_V1Rec); // 1 -- 7 tmpHead.Header.BaseHeader.CommonHeader.StoreSizeMode.Value := 16; // 1 -- 8 page size mode { 表明是什么数据 } tmpHead.Header.BaseHeader.CommonHeader.DataType := DataType_Stock; // 2 -- 10 tmpHead.Header.BaseHeader.CommonHeader.DataMode := DataMode_DayDetailDataM2; // 1 -- 11 tmpHead.Header.BaseHeader.CommonHeader.RecordSizeMode.Value:= 6; // 1 -- 12 tmpHead.Header.BaseHeader.CommonHeader.RecordCount := ADataAccess.RecordCount; // 4 -- 16 tmpHead.Header.BaseHeader.CommonHeader.CompressFlag := 0; // 1 -- 17 tmpHead.Header.BaseHeader.CommonHeader.EncryptFlag := 0; // 1 -- 18 tmpHead.Header.BaseHeader.CommonHeader.DataSourceId := GetDealDataSourceCode(ADataAccess.DataSource); // 2 -- 20 CopyMemory(@tmpHead.Header.BaseHeader.Code[0], @ADataAccess.StockItem.sCode[1], Length(ADataAccess.StockItem.sCode)); //Move(ADataAccess.StockItem.Code, tmpHead.Header.BaseHeader.Code[0], Length(ADataAccess.StockItem.Code)); // 12 - 32 // ---------------------------------------------------- tmpHead.Header.BaseHeader.StorePriceFactor := 1000; // 2 - 34 tmpHead.Header.BaseHeader.FirstDealDate := ADataAccess.FirstDealDate; // 2 - 36 tmpHead.Header.BaseHeader.LastDealDate := ADataAccess.LastDealDate; // 2 - 36 Inc(tmpHead); tmpStoreDetailData := PStore_Quote32_Detail(tmpHead); ADataAccess.Sort; for i := 0 to ADataAccess.RecordCount - 1 do begin tmpRTDetailData := ADataAccess.RecordItem[i]; if nil <> tmpRTDetailData then begin RTPricePack2StorePrice(@tmpStoreDetailData.Quote.Price, @tmpRTDetailData.Price); tmpStoreDetailData.Quote.DealVolume := tmpRTDetailData.DealVolume; // 8 - 24 成交量 tmpStoreDetailData.Quote.DealAmount := tmpRTDetailData.DealAmount; // 8 - 32 成交金额 tmpStoreDetailData.Quote.QuoteDealTime := tmpRTDetailData.DealDateTime.Time.Value; // 4 - 36 交易日期 tmpStoreDetailData.Quote.QuoteDealDate := tmpRTDetailData.DealDateTime.Date.Value; tmpStoreDetailData.Quote.DealType := tmpRTDetailData.DealType; Inc(tmpStoreDetailData); end; end; end; end.
// Dialog to select a macro template unit GX_MacroSelect; interface uses Classes, Controls, Forms, ExtCtrls, StdCtrls, ComCtrls, CommCtrl, GX_MacroFile, GX_BaseForm; type TfmMacroSelect = class(TfmBaseForm) pnlMain: TPanel; lvMacros: TListView; pnlHeader: TPanel; lblFilter: TLabel; tbEnter: TMemo; pnlButtonsRight: TPanel; btnConfiguration: TButton; procedure tbEnterChange(Sender: TObject); procedure lstMacrosDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tbEnterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure btnConfigurationClick(Sender: TObject); private FMacroFile: TMacroFile; procedure SelectTemplate(Index: Integer); procedure LoadFormLayout; procedure SaveFormLayout; procedure SizeColumns; function WindowPosKey: string; public function GetSelectedMacroCode: Integer; procedure LoadTemplates(AMacroFile: TMacroFile; Filter: string = ''); end; // Returns the index of the selected macro function GetTemplateFromUser(const ATemplateName: string; MacroFile: TMacroFile): Integer; implementation uses Messages, Windows, GX_MacroTemplates, GX_MacroTemplatesExpert, GX_ConfigurationInfo, GX_GenericUtils, GX_GxUtils; {$R *.dfm} function GetTemplateFromUser(const ATemplateName: string; MacroFile: TMacroFile): Integer; begin Assert(Assigned(MacroFile)); with TfmMacroSelect.Create(Application) do try LoadTemplates(MacroFile); tbEnter.Text := ATemplateName; tbEnter.SelStart := Length(ATemplateName); if ShowModal = mrOk then Result := GetSelectedMacroCode else Result := -1; finally Free; end; end; procedure TfmMacroSelect.SelectTemplate(Index: Integer); begin lvMacros.Selected := lvMacros.Items[Index]; lvMacros.ItemFocused := lvMacros.Selected; lvMacros.Selected.MakeVisible(False); end; procedure TfmMacroSelect.tbEnterChange(Sender: TObject); begin LoadTemplates(GetExpandMacroExpert.MacroFile, tbEnter.Text); end; procedure TfmMacroSelect.lstMacrosDblClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TfmMacroSelect.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then ModalResult := mrOk; if Key = VK_ESCAPE then ModalResult := mrCancel; end; function TfmMacroSelect.GetSelectedMacroCode: Integer; var MacroName: string; begin Result := -1; if lvMacros.Selected <> nil then begin MacroName := lvMacros.Selected.Caption; if Assigned(FMacroFile) then Result := FMacroFile.IndexOf(MacroName); end; end; procedure TfmMacroSelect.LoadTemplates(AMacroFile: TMacroFile; Filter: string = ''); procedure AddMacroToList(const AMacroName, AMacroDesc: string); var ListItem: TListItem; begin if (Filter = '') or StrContains(Filter, AMacroName, False) or StrContains(Filter, AMacroDesc, False) then begin ListItem := lvMacros.Items.Add; ListItem.Caption := AMacroName; ListItem.SubItems.Add(AMacroDesc); end; end; procedure FocusAndSelectFirstItem; begin if lvMacros.Items.Count > 0 then SelectTemplate(0); end; var i: Integer; begin FMacroFile := AMacroFile; lvMacros.Items.BeginUpdate; try lvMacros.Items.Clear; for i := 0 to AMacroFile.MacroCount - 1 do AddMacroToList(AMacroFile.MacroItems[i].Name, AMacroFile.MacroItems[i].Desc); FocusAndSelectFirstItem; SizeColumns; finally lvMacros.Items.EndUpdate; end; end; procedure TfmMacroSelect.tbEnterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DOWN) or (Key = VK_UP) or (Key = VK_NEXT) or (Key = VK_PRIOR) or (Key = VK_HOME) or (Key = VK_END) then begin SendMessage(lvMacros.Handle, WM_KEYDOWN, Key, 0); Key := 0; end; end; procedure TfmMacroSelect.LoadFormLayout; begin // do not localize with TGExpertsSettings.Create(MacroTemplatesBaseKey) do try LoadForm(Self, WindowPosKey, [fsSize]); lvMacros.Columns[0].Width := ReadInteger(WindowPosKey, 'NameWidth', lvMacros.Columns[0].Width); finally Free; end; end; procedure TfmMacroSelect.SaveFormLayout; begin // do not localize with TGExpertsSettings.Create(MacroTemplatesBaseKey) do try if WindowState = wsNormal then // save only if not maximized/minimized SaveForm(Self, WindowPosKey, [fsSize]); WriteInteger(WindowPosKey, 'NameWidth', lvMacros.Columns[0].Width); finally Free; end; end; procedure TfmMacroSelect.FormCreate(Sender: TObject); begin LoadFormLayout; end; procedure TfmMacroSelect.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveFormLayout; end; procedure TfmMacroSelect.FormResize(Sender: TObject); begin SizeColumns; end; procedure TfmMacroSelect.SizeColumns; begin if lvMacros.Items.Count > 0 then ListView_SetColumnWidth(lvMacros.Handle, 1, ColumnTextWidth) else lvMacros.Columns[1].Width := 200; end; procedure TfmMacroSelect.btnConfigurationClick(Sender: TObject); begin Assert(Assigned(FMacroFile)); GetExpandMacroExpertReq.Configure; LoadTemplates(GetExpandMacroExpertReq.MacroFile); end; function TfmMacroSelect.WindowPosKey: string; begin Result := 'SelectWindow'; end; end.
{$include lem_directives.inc} unit LemLevelSystem; interface uses Classes, UMisc, UTools, UClasses, {$ifdef flexi}LemDosStructures,{$endif} LemLevel; {------------------------------------------------------------------------------- Nested classes for levelpack system: system levelpack (DosOrig=Default: only for multi levelpacks like Lemmini) section (FUN) levelinfo (just dig) levelpack section levelinfo -------------------------------------------------------------------------------} type TPackSection = class; TLevelPack = class; TLevelInfo = class(TCollectionItem) private function GetOwnerSection: TPackSection; protected fTrimmedTitle : string; // the title: this is only for display purposes. fDosLevelPackFileName : string; // dos file where we can find this level (levelxxx.dat) fDosLevelPackIndex : Integer; // dos file position in doslevelpackfilename(in fact: which decompression section) fDosIsOddTableClone : Boolean; // true if this is a cloned level with other title and skills fDosOddTableFileName : string; // only dosorig: oddtable.dat fDosOddTableIndex : Integer; // were can we find this other title and skills in the dosoddtable file fOwnerFile : string; // lemmini: lemmini ini file containing this level public property OwnerSection: TPackSection read GetOwnerSection; published property TrimmedTitle: string read fTrimmedTitle write fTrimmedTitle; property DosLevelPackFileName: string read fDosLevelPackFileName write fDosLevelPackFileName; property DosLevelPackIndex: Integer read fDosLevelPackIndex write fDosLevelPackIndex; property DosIsOddTableClone: Boolean read fDosIsOddTableClone write fDosIsOddTableClone; property DosOddTableFileName: string read fDosOddTableFileName write fDosOddTableFileName; property DosOddTableIndex: Integer read fDosOddTableIndex write fDosOddTableIndex; property OwnerFile: string read fOwnerFile write fOwnerFile; end; TLevelInfos = class(TOwnedCollectionEx) private function GetItem(Index: Integer): TLevelInfo; procedure SetItem(Index: Integer; const Value: TLevelInfo); protected public constructor Create(aOwner: TPersistent); // owner = TPackSection function Add: TLevelInfo; function Insert(Index: Integer): TLevelInfo; property Items[Index: Integer]: TLevelInfo read GetItem write SetItem; default; published end; TPackSection = class(TCollectionItem) private fLevelInfos: TLevelInfos; fSectionName: string; fSourceFileName: string; function GetOwnerPack: TLevelPack; protected public constructor Create(Collection: TCollection); override; destructor Destroy; override; property OwnerPack: TLevelPack read GetOwnerPack; published property SourceFileName: string read fSourceFileName write fSourceFileName; property SectionName: string read fSectionName write fSectionName; property LevelInfos: TLevelInfos read fLevelInfos write fLevelInfos; // tricky? end; TPackSections = class(TOwnedCollectionEx) private function GetItem(Index: Integer): TPackSection; procedure SetItem(Index: Integer; const Value: TPackSection); protected public constructor Create(aOwner: TPersistent); // owner = TLevelPack function Add: TPackSection; function Insert(Index: Integer): TPackSection; property Items[Index: Integer]: TPackSection read GetItem write SetItem; default; published end; TLevelPack = class(TCollectionItem) private fPackSections: TPackSections; fLevelPackName: string; fSourceFileName: string; function GetPackSection(Index: Integer): TPackSection; protected public constructor Create(Collection: TCollection); override; destructor Destroy; override; property PackSection[Index: Integer]: TPackSection read GetPackSection; default; published property SourceFileName: string read fSourceFileName write fSourceFileName stored True; // only lemmini property LevelPackName: string read fLevelPackName write fLevelPackName; property PackSections: TPackSections read fPackSections write fPackSections; // tricky? end; TLevelPacks = class(TCollectionEx) private function GetItem(Index: Integer): TLevelPack; procedure SetItem(Index: Integer; const Value: TLevelPack); protected public constructor Create; function Add: TLevelPack; function Insert(Index: Integer): TLevelPack; procedure SaveToStream(S: TStream); procedure SaveToTxtFile(const aFileName: string); property Items[Index: Integer]: TLevelPack read GetItem write SetItem; default; published end; TLevelPacksWrapper = class(TComponent) private fLevelPacks: TLevelPacks; public procedure SaveToTxtFile(const aFileName: string); procedure SaveToStream(S: TStream); published property LevelPacks: TLevelPacks read fLevelPacks write fLevelPacks; end; {------------------------------------------------------------------------------- This record is used as parameter for retrieving levels. TBaseDosLevelSystem provides the mechanism. -------------------------------------------------------------------------------} TDosGamePlayInfoRec = record dValid : Boolean; dPack : Integer; // this is a dummy for dos dSection : Integer; dLevel : Integer; // zero based! dSectionName : string; end; TBaseLevelSystemClass = class of TBaseLevelSystem; TBaseLevelSystem = class(TOwnedPersistent) private function GetLevelPackCount: Integer; protected fLevelPacks : TLevelPacks; fPrepared : Boolean; procedure InternalPrepare; virtual; abstract; // function InternalGetLevelInfo(aPack, aSection, aLevel: Integer): TLevelInfo; virtual; abstract; procedure InternalLoadLevel(aInfo: TLevelInfo; aLevel: TLevel; OddLoad: Boolean = false); virtual; abstract; procedure InternalLoadSingleLevel(aPack, aSection, aLevelIndex: Integer; aLevel: TLevel; OddLoad: Boolean = false); virtual; abstract; public {$ifdef flexi}SysDat : TSysDatRec;{$endif} constructor Create(aOwner: TPersistent); destructor Destroy; override; procedure Prepare; procedure LoadLevel(aInfo: TLevelInfo; aLevel: TLevel); procedure LoadSingleLevel(aPack, aSection, aLevelIndex: Integer; aLevel: TLevel); function FindFirstLevel(var Rec: TDosGamePlayInfoRec): Boolean; virtual; abstract; function FindNextLevel(var Rec : TDosGamePlayInfoRec): Boolean; virtual; abstract; function FindLevel(var Rec : TDosGamePlayInfoRec): Boolean; virtual; abstract; function GetLevelCode(const Rec : TDosGamePlayInfoRec): string; virtual; abstract; function FindLevelCode(const aCode: string; var Rec : TDosGamePlayInfoRec): Boolean; virtual; abstract; function FindCheatCode(const aCode: string; var Rec : TDosGamePlayInfoRec): Boolean; virtual; abstract; property LevelPacks: TLevelPacks read fLevelPacks; property LevelPackCount: Integer read GetLevelPackCount; end; implementation { TLevelInfo } function TLevelInfo.GetOwnerSection: TPackSection; begin Result := TPackSection(Collection.Owner); end; { TLevelInfos } function TLevelInfos.Add: TLevelInfo; begin Result := TLevelInfo(inherited Add); end; constructor TLevelInfos.Create(aOwner: TPersistent); begin inherited Create(aOwner, TLevelInfo); end; function TLevelInfos.GetItem(Index: Integer): TLevelInfo; begin Result := TLevelInfo(inherited GetItem(Index)) end; function TLevelInfos.Insert(Index: Integer): TLevelInfo; begin Result := TLevelInfo(inherited Insert(Index)) end; procedure TLevelInfos.SetItem(Index: Integer; const Value: TLevelInfo); begin inherited SetItem(Index, Value); end; { TPackSection } constructor TPackSection.Create(Collection: TCollection); begin inherited; fLevelInfos := TLevelInfos.Create(Self); end; destructor TPackSection.Destroy; begin fLevelInfos.Free; inherited; end; function TPackSection.GetOwnerPack: TLevelPack; begin Result := TLevelPack(Collection.Owner); end; { TPackSections } function TPackSections.Add: TPackSection; begin Result := TPackSection(inherited Add); end; constructor TPackSections.Create(aOwner: TPersistent); begin inherited Create(aOwner, TPackSection); end; function TPackSections.GetItem(Index: Integer): TPackSection; begin Result := TPackSection(inherited GetItem(Index)) end; function TPackSections.Insert(Index: Integer): TPackSection; begin Result := TPackSection(inherited Insert(Index)) end; procedure TPackSections.SetItem(Index: Integer; const Value: TPackSection); begin inherited SetItem(Index, Value); end; { TLevelPack } constructor TLevelPack.Create(Collection: TCollection); begin inherited; fPackSections := TPackSections.Create(Self); end; destructor TLevelPack.Destroy; begin fPackSections.Free; inherited; end; (*function TLevelPack.GetPackSection(Index: Integer): TPackSection; begin Result := fPackSections[Index]; end;*) function TLevelPack.GetPackSection(Index: Integer): TPackSection; begin Result := fPackSections[Index]; end; { TLevelPacks } function TLevelPacks.Add: TLevelPack; begin Result := TLevelPack(inherited Add); end; constructor TLevelPacks.Create; begin inherited Create(TLevelPack); end; function TLevelPacks.GetItem(Index: Integer): TLevelPack; begin Result := TLevelPack(inherited GetItem(Index)) end; function TLevelPacks.Insert(Index: Integer): TLevelPack; begin Result := TLevelPack(inherited Insert(Index)) end; procedure TLevelPacks.SaveToStream(S: TStream); var Wrapper: TLevelPacksWrapper; begin Wrapper := TLevelPacksWrapper.Create(nil); try Wrapper.LevelPacks := Self; Wrapper.SaveToStream(S); finally Wrapper.Free; end; end; procedure TLevelPacks.SaveToTxtFile(const aFileName: string); var Wrapper: TLevelPacksWrapper; begin Wrapper := TLevelPacksWrapper.Create(nil); try Wrapper.LevelPacks := Self; Wrapper.SaveToTxtFile(aFileName); finally Wrapper.Free; end; end; procedure TLevelPacks.SetItem(Index: Integer; const Value: TLevelPack); begin inherited SetItem(Index, Value); end; { TLevelPacksWrapper } procedure TLevelPacksWrapper.SaveToStream(S: TStream); begin S.WriteComponent(Self); end; procedure TLevelPacksWrapper.SaveToTxtFile(const aFileName: string); begin ComponentToTextFile(Self, aFileName); end; { TBaseLevelSystem } constructor TBaseLevelSystem.Create(aOwner: TPersistent); begin inherited Create(aOwner); fLevelPacks := TLevelPacks.Create; end; destructor TBaseLevelSystem.Destroy; begin fLevelPacks.Free; inherited; end; function TBaseLevelSystem.GetLevelPackCount: Integer; begin Result := fLevelPacks.Count end; procedure TBaseLevelSystem.LoadLevel(aInfo: TLevelInfo; aLevel: TLevel); begin InternalLoadLevel(aInfo, aLevel); end; procedure TBaseLevelSystem.LoadSingleLevel(aPack, aSection, aLevelIndex: Integer; aLevel: TLevel); begin InternalLoadSingleLevel(aPack, aSection, aLevelIndex, aLevel); end; procedure TBaseLevelSystem.Prepare; begin if not fPrepared then begin InternalPrepare; fPrepared := True; end; end; end.
{******************************************************************************} {* This software is provided 'as-is', without any express or *} {* implied warranty. In no event will the author be held liable *} {* for any damages arising from the use of this software. *} {* *} {* Permission is granted to anyone to use this software for any *} {* purpose, including commercial applications, and to alter it *} {* and redistribute it freely, subject to the following *} {* restrictions: *} {* *} {* 1. The origin of this software must not be misrepresented, *} {* you must not claim that you wrote the original software. *} {* If you use this software in a product, an acknowledgment *} {* in the product documentation would be appreciated but is *} {* not required. *} {* *} {* 2. Altered source versions must be plainly marked as such, and *} {* must not be misrepresented as being the original software. *} {* *} {* 3. This notice may not be removed or altered from any source *} {* distribution. *} {* *} {* *} {* The initial developer is Andreas Hausladen (Andreas.Hausladen@gmx.de) *} {* *} {******************************************************************************} {.$A+,B-,C+,D+,E-,F-,G+,H+,I+,J+,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1} {$IFDEF LINUX} {.$DEFINE USE_WHITE_RADIOMASK} {$ENDIF LINUX} unit QThemed; interface uses {$IFDEF MSWINDOWS} Windows, QThemeSrv, {$ENDIF MSWINDOWS} {$IFDEF LINUX} Libc, Xlib, QThemeSrvLinux, {$ENDIF LINUX} Qt, QTypes, SysUtils, Classes, Types, Math, QGraphics, QControls, QForms, QStdCtrls, QExtCtrls, QComCtrls, QButtons, QMenus, QImgList, QGrids, QStyle; type TRedirectCode = packed record Jump: Byte; Offset: Integer; RealProc: Pointer; end; TEventFilter = function(Sender: QObjectH; Event: QEventH): Boolean of object; QClxStyle_drawToolButton_Event = procedure (p: QPainterH; x: Integer; y: Integer; w: Integer; h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH) of object cdecl; QClxStyle_drawToolButton2_Event = procedure (btn: QToolButtonH; p: QPainterH) of object cdecl; TThemedStyleNotify = class(TComponent) protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; end; TThemedStyle = class(TApplicationStyle) private FOldAppIdle: TNotifyEvent; FCodeQFrame_drawFrame, FCodeDrawButtonFace, FCodeDrawEdge, FCodeDrawShadePanel, FCodeCustomTabControlDoHotTrack, FCodeDrawTab, FCodeProgressBarPaint, FCodeWidgetControlPainting, FCodeToolButtonPaint, {FCodeToolBarPaint,} FCodeSpeedButtonPaint, FCodeControlMouseMove, FCodeListViewHeaderEventFilters: TRedirectCode; FOrgListViewHeaderEventFilter: Pointer; FDoHotTrack: Pointer; // address of TCustomTabControl.DoHotTrack FMenusEnabled: Boolean; FControlInfo: TStrings; FNotifyObject: TThemedStyleNotify; function GetActive: Boolean; procedure SetActive(const Value: Boolean); procedure InternalDrawTab(Index: Integer); protected procedure DrawPushButtonHook(btn: QPushButtonH; p: QPainterH; var Stage: Integer); cdecl; procedure DrawPopupMenuItemHook(p: QPainterH; checkable: Boolean; maxpmw, tab: Integer; mi: QMenuItemH; itemID: Integer; act, enabled: Boolean; x, y, w, h: Integer; var Stage: Integer); cdecl; {$IFDEF LINUX} procedure DoDrawToolButtonHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH); cdecl; procedure DoDrawToolButton2Hook(btn: QToolButtonH; p: QPainterH); cdecl; {$ENDIF LINUX} procedure DoDrawMenuItemObject(Item: QMenuItemH; Canvas: TCanvas; Highlighted, Enabled: Boolean; const Rect: TRect; Checkable: Boolean; CheckMaxWidth, LabelWidth: Integer; var Stage: Integer); protected {$IFDEF LINUX} procedure DrawQToolButton(Canvas: TCanvas; R: TRect; Down, Focused: Boolean); virtual; {$ENDIF LINUX} procedure EvAfterDrawButton(Sender, Source: TObject; Canvas: TCanvas); virtual; procedure EvBeforeDrawButton(Sender, Source: TObject; Canvas: TCanvas; var DefaultDraw: Boolean); virtual; procedure DoAfterDrawButtonWidget(btn: QPushButtonH; Canvas: TCanvas); function DoBeforeDrawButtonWidget(btn: QPushButtonH; Canvas: TCanvas): Boolean; procedure EvDrawTrackBar(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove, TickBelow: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawTrackBarMask(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove, TickBelow: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawTrackBarGroove(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawComboButton(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Sunken, ReadOnly, Enabled: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawCheck(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked, Grayed, Down, Enabled: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawRadio(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked, Down, Enabled: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawRadioMask(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked: Boolean); procedure EvDrawFrame(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Sunken: Boolean; LineWidth: Integer; var DefaultDraw: Boolean); virtual; procedure EvDrawScrollBar(Sender: TObject; ScrollBar: QScrollBarH; Canvas: TCanvas; const Rect: TRect; SliderStart, SliderLength, ButtonSize: Integer; Controls: TScrollBarControls; DownControl: TScrollBarControl; var DefaultDraw: Boolean); virtual; procedure EvDrawHeaderSection(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Down: Boolean; var DefaultDraw: Boolean); virtual; procedure EvDrawMenuFrame(Sender: TObject; Canvas: TCanvas; const R: TRect; LineWidth: Integer; var DefaultDraw: Boolean); procedure EvMenuItemHeight(Sender, Source: TObject; Checkable: Boolean; FontMetrics: QFontMetricsH; var Height: Integer); protected procedure HookedCustomTabControlPaint; virtual; procedure HookedDoHotTrack(Index: Integer); virtual; procedure HookedTabSheetPaint; virtual; procedure HookedProgressBarPaint; virtual; procedure HookedWidgetControlPainting(Sender: QObjectH; EventRegion: QRegionH); virtual; procedure HookedToolButtonPaint; virtual; // procedure HookedToolBarPaint; virtual; procedure HookedSpeedButtonPaint; virtual; procedure HookedControlMouseMove(Shift: TShiftState; X, Y: Integer); virtual; function HookedListViewHeaderEventFilter(Sender: QObjectH; Event: QEventH): Boolean; protected procedure AppIdle(Sender: TObject); virtual; procedure MouseEnter(Control: TControl); virtual; procedure MouseLeave(Control: TControl); virtual; procedure DrawGroupBox(Control: TCustomGroupBox; Canvas: TCanvas); virtual; procedure SetDefaultStyle(const Value: TDefaultStyle); override; procedure Initialize; virtual; procedure Finalize; virtual; public constructor Create; override; destructor Destroy; override; property MenusEnabled: Boolean read FMenusEnabled write FMenusEnabled; property Active: Boolean read GetActive write SetActive; end; function IsMouseOver(Control: TControl): Boolean; overload; function IsMouseOver(Widget: QWidgetH; ARect: PRect): Boolean; overload; procedure RepaintControl(Control: TControl); procedure PaintWidget(Widget: QWidgetH); procedure PaintControl(Control: TControl); procedure QExcludeClipRect(DC: QPainterH; x0, y0, x1, y1: Integer); function GetWindowFromPainter(Painter: QPainterH): Cardinal; // needs Canvas.Start/call/Stop function GetWidgetFromPainter(Painter: QPainterH): QWidgetH; // needs Canvas.Start/call/Stop var ThemedStyle: TThemedStyle; implementation uses uCommon; {$IFDEF MSWINDOWS} {$R winxp.res} {$ENDIF MSWINDOWS} type TOpenControl = class(TControl); TOpenWidgetControl = class(TWidgetControl); TOpenCustomTabControl = class(TCustomTabControl); TOpenTab = class(TTab); TOpenCustomControl = class(TCustomControl); TOpenGraphicControl = class(TGraphicControl); TOpenProgressBar = class(TProgressBar); TOpenCustomGroupBox = class(TCustomGroupBox); TOpenFrameControl = class(TFrameControl); TOpenApplication = class(TApplication); TOpenToolButton = class(TToolButton); TOpenToolBar = class(TToolBar); TOpenSpeedButton = class(TSpeedButton); TOpenCustomHeaderControl = class(TCustomHeaderControl); TOpenCustomViewControl = class(TCustomViewControl); TPrivateApplication = class(TComponent) // Delphi 6, Delphi 7, Kylix 3 protected FHelpSystem: {IHelpSystem}IInterface; FArgv: PPChar; FTerminated: Boolean; FActive: Boolean; FShowMainForm: Boolean; FQtAccels: Boolean; FHintShortCuts: Boolean; FEffects: TAppEffects; FTimerMode: TTimerMode; FHintActive: Boolean; FShowHint: Boolean; FMinimized: Boolean; FMainFormSet: Boolean; FKeyState: TShiftState; FHandle: QApplicationH; FHooks: QObject_hookH; FOnException: TExceptionEvent; FMainForm: TCustomForm; FAppWidget: QWidgetH; FTitle: WideString; FHint: WideString; FHintColor: TColor; FHintControl: TControl; FHintCursorRect: TRect; FHintHidePause: Integer; FHintPause: Integer; FHintShortPause: Integer; FHintTimer: TComponent; FHintWindow: THintWindow; FIdleTimer: TComponent; FMouseControl: TControl; // we need this end; TPrivateCustomTabControl = class(TCustomControl) // Delphi 6 (patched), Delphi 7, Kylix 3 protected FErase: Boolean; FHotTrack: Boolean; FMultiLine: Boolean; FMultiSelect: Boolean; FOwnerDraw: Boolean; FRaggedRight: Boolean; FShowFrame: Boolean; FUpdating: Boolean; FStyle: TTabStyle; FBitmap: TBitmap; FButtons: array [TTabButtons] of TSpeedButton; FDblBuffer: TBitmap; FFirstVisibleTab: Integer; FHotImages: TCustomImageList; FHotTrackColor: TColor; FImageBorder: Integer; FImageChangeLink: TChangeLink; FImages: TCustomImageList; FLastVisibleTab: Integer; FLayoutCount: Integer; FMouseOver: Integer; FRowCount: Integer; FTabIndex: Integer; FTabs: TTabs; FTabSize: TSmallPoint; FTracking: Integer; end; TPrivateCustomControl = class(TWidgetControl) protected FCanvas: TCanvas; end; TPrivateGraphicControl = class(TControl) protected FCanvas: TCanvas; end; TPrivateListViewHeader = class(TCustomHeaderControl) protected FHidden: Boolean; end; function IsMouseOver(Control: TControl): Boolean; var Pt: TPoint; begin if Control <> nil then begin Pt := Control.ScreenToClient(Mouse.CursorPos); Result := PtInRect(Control.ClientRect, Pt); if Result then begin if Control is TWidgetControl then Result := FindControl(Mouse.CursorPos) = Control else Result := FindControl(Mouse.CursorPos) = Control.Parent; end; end else Result := False; end; function IsMouseOver(Widget: QWidgetH; ARect: PRect): Boolean; var Pt: TPoint; R: TRect; begin if Widget <> nil then begin Pt := Mouse.CursorPos; QWidget_mapFromGlobal(Widget, @Pt, @Pt); if ARect = nil then begin QWidget_geometry(Widget, @R); OffsetRect(R, -R.Left, -R.Top); end else R := ARect^; Result := PtInRect(R, Pt); end else Result := False; end; procedure RepaintControl(Control: TControl); begin if Control is TWidgetControl then QWidget_repaint(TWidgetControl(Control).Handle) else Control.Repaint; end; procedure PaintWidget(Widget: QWidgetH); var R: TRect; EventRegion: QRegionH; ForcedPaintEvent: QPaintEventH; begin QWidget_geometry(Widget, @R); OffsetRect(R, -R.Left, -R.Top); EventRegion := QRegion_create(@R, QRegionRegionType_Rectangle); ForcedPaintEvent := QPaintEvent_create(EventRegion, False); try QObject_event(Widget, ForcedPaintEvent); finally QPaintEvent_destroy(ForcedPaintEvent); QRegion_destroy(EventRegion); end; end; procedure PaintControl(Control: TControl); var R: TRect; ControlRegion: QRegionH; WidgetControl: TWidgetControl; begin R := Control.BoundsRect; if Control is TWidgetControl then begin WidgetControl := TWidgetControl(Control); OffsetRect(R, -R.Left, -R.Top); end else WidgetControl := Control.Parent; ControlRegion := QRegion_create(@R, QRegionRegionType_Rectangle); try TOpenWidgetControl(WidgetControl).Painting(WidgetControl.Handle, ControlRegion); finally QRegion_destroy(ControlRegion); end; end; procedure QExcludeClipRect(DC: QPainterH; x0, y0, x1, y1: Integer); var ExcludeRgn, Rgn: QRegionH; Matrix: QWMatrixH; begin if QPainter_hasWorldXForm(DC) then begin Matrix := QPainter_worldMatrix(DC); QWMatrix_map(Matrix, x0, y0, @x0, @y0); QWMatrix_map(Matrix, x1, y1, @x1, @y1); end; ExcludeRgn := QRegion_create(x0, y0, x1 - x0, y1 - y0, QRegionRegionType_Rectangle); Rgn := QPainter_clipRegion(DC); QRegion_subtract(Rgn, Rgn, ExcludeRgn); QPainter_setClipRegion(DC, Rgn); QPainter_setClipping(DC, True); QRegion_destroy(ExcludeRgn); end; procedure QIntersectClipRect(DC: QPainterH; ClipRect: TRect); var IntersectRgn, Rgn: QRegionH; Matrix: QWMatrixH; begin if QPainter_hasWorldXForm(DC) then begin Matrix := QPainter_worldMatrix(DC); QWMatrix_map(Matrix, PRect(@ClipRect), PRect(@ClipRect)); end; IntersectRgn := QRegion_create(@ClipRect, QRegionRegionType_Rectangle); Rgn := QPainter_clipRegion(DC); if QRegion_isNull(Rgn) then Rgn := IntersectRgn else QRegion_intersect(Rgn, Rgn, IntersectRgn); QPainter_setClipRegion(DC, Rgn); QPainter_setClipping(DC, True); QRegion_destroy(IntersectRgn); end; {$IFDEF MSWINDOWS} function GetWindowFromPainter(Painter: QPainterH): Cardinal; var dc: HDC; begin Result := 0; dc := QPainter_handle(Painter); if dc <> 0 then Result := Cardinal(WindowFromDC(dc)); end; {$ELSE} function GetWindowFromPainter(Painter: QPainterH): Cardinal; var dev: QPaintDeviceH; begin dev := QPainter_device(Painter); if dev <> nil then Result := Cardinal(QPaintDevice_handle(dev)) else Result := 0; end; {$ENDIF MSWINDOWS} function GetWidgetFromPainter(Painter: QPainterH): QWidgetH; var wnd: Cardinal; begin Result := nil; wnd := GetWindowFromPainter(Painter); if wnd <> 0 then Result := QWidget_find(wnd); end; const // constants for Canvas.TextRect AlignLeft = 1 { $1 }; AlignRight = 2 { $2 }; AlignHCenter = 4 { $4 }; AlignTop = 8 { $8 }; AlignBottom = 16 { $10 }; AlignVCenter = 32 { $20 }; AlignCenter = 36 { $24 }; SingleLine = 64 { $40 }; DontClip = 128 { $80 }; ExpandTabs = 256 { $100 }; ShowPrefix = 512 { $200 }; WordBreak = 1024 { $400 }; ModifyString = 2048 { $800 }; DontPrint = 4096 { $1000 }; ClipPath = 8192 { $2000 }; ClipName = 16386 { $4000 }; CalcRect = 32768 { $8000 } ; {$IFDEF LINUX} const { ClxDrawText() Format Flags } DT_TOP = 0; // default DT_LEFT = 0; // default DT_CENTER = 1; DT_RIGHT = 2; DT_VCENTER = 4; DT_BOTTOM = 8; DT_WORDBREAK = $10; DT_SINGLELINE = $20; DT_EXPANDTABS = $40; //DT_TABSTOP = $80; DT_NOCLIP = $100; //DT_EXTERNALLEADING = $200; DT_CALCRECT = $400; DT_NOPREFIX = $800; //DT_INTERNAL = $1000; //DT_HIDEPREFIX = $00100000; //DT_PREFIXONLY = $00200000; //DT_EDITCONTROL = $2000; DT_PATH_ELLIPSIS = $4000; DT_END_ELLIPSIS = $8000; DT_ELLIPSIS = DT_END_ELLIPSIS; DT_MODIFYSTRING = $10000; // DT_RTLREADING = $20000; // DT_WORD_ELLIPSIS = $40000; { ClxExtTextOut() Format Flags } ETO_OPAQUE = 2; ETO_CLIPPED = 4; //ETO_GLYPH_INDEX = $10; ETO_RTLREADING = $80; // ignored //ETO_NUMERICSLOCAL = $400; //ETO_NUMERICSLATIN = $800; //ETO_IGNORELANGUAGE = $1000; //ETO_PDY = $2000; { ShowWindow() Commands } SW_HIDE = 0; SW_SHOWNORMAL = 1; SW_NORMAL = 1; SW_SHOWMINIMIZED = 2; SW_SHOWMAXIMIZED = 3; SW_MAXIMIZE = 3; SW_SHOWNOACTIVATE = 4; SW_SHOW = 5; SW_MINIMIZE = 6; SW_SHOWMINNOACTIVE = 7; SW_SHOWNA = 8; SW_RESTORE = 9; SW_SHOWDEFAULT = 10; SW_MAX = 10; {$ENDIF LINUX} function ClxDrawTextW(Canvas: TCanvas; var Caption: WideString; var R: TRect; Flags: Integer): Integer; var Flgs: Word; Text: string; begin Text := Caption; with Canvas do begin Flgs := 0; if Flags and DT_SINGLELINE <> 0 then Flgs := SingleLine; if Flags and DT_WORDBREAK <> 0 then Flgs := Flgs or WordBreak; if Flags and DT_EXPANDTABS <> 0 then Flgs := Flgs or ExpandTabs; if Flags and DT_NOPREFIX = 0 then Flgs := Flgs or ShowPrefix; if Flags and DT_RIGHT <> 0 then Flgs := Flgs or AlignRight else if Flags and DT_CENTER <> 0 then Flgs := Flgs or AlignHCenter else Flgs := Flgs or AlignLeft ; // default // vertical alignment if Flags and DT_BOTTOM <> 0 then Flgs := Flgs or AlignTop else if Flags and DT_VCENTER <> 0 then Flgs := Flgs or AlignVCenter else Flgs := Flgs or AlignTop; // default if Flags and DT_CALCRECT <> 0 then begin TextExtent(Caption, R, flgs); Result := R.Bottom - R.Top; Exit; end; Canvas.TextRect(R, R.Left, R.Top, Text, Flgs); if Flags and DT_MODIFYSTRING <> 0 then Caption := Text; end; Result := 1; end; function RGB(r, g, b: Integer): TColor; var C: QColorH; begin C := QColor_create(r, g, b); Result := QColorColor(C); QColor_destroy(C); end; procedure DimBitmap(ABitmap: TBitmap; Value: integer); function NewColor(ACanvas: TCanvas; clr: TColor; Value: integer): TColor; var r, g, b: integer; begin if Value > 100 then Value := 100; clr := ColorToRGB(clr); r := Clr and $000000FF; g := (Clr and $0000FF00) shr 8; b := (Clr and $00FF0000) shr 16; r := r + Round((255 - r) * (value / 100)); g := g + Round((255 - g) * (value / 100)); b := b + Round((255 - b) * (value / 100)); { ACanvas.Start; Result := Windows.GetNearestColor(HDC(QPainter_handle(ACanvas.Handle)), RGB(r, g, b)); ACanvas.Stop;} Result := RGB(r, g, b); end; var x, y: integer; LastColor1, LastColor2, Color: TColor; begin if Value > 100 then Value := 100; LastColor1 := -1; LastColor2 := -1; ABitmap.Canvas.Start; try for y := 0 to ABitmap.Height - 1 do for x := 0 to ABitmap.Width - 1 do begin Color := ABitmap.Canvas.Pixels[x, y]; if Color = LastColor1 then ABitmap.Canvas.Pixels[x, y] := LastColor2 else begin LastColor2 := NewColor(ABitmap.Canvas, Color, Value); ABitmap.Canvas.Pixels[x, y] := LastColor2; LastColor1 := Color; end; end; finally ABitmap.Canvas.Stop; end; end; procedure GrayBitmap(ABitmap: TBitmap; Value: integer); function GrayColor(Clr: TColor; Value: integer): TColor; var r, g, b, avg: integer; begin clr := ColorToRGB(clr); r := Clr and $000000FF; g := (Clr and $0000FF00) shr 8; b := (Clr and $00FF0000) shr 16; Avg := (r + g + b) div 3; Avg := Avg + Value; if Avg > 240 then Avg := 240; Result := RGB(Avg, Avg, Avg); end; var x, y: integer; LastColor1, LastColor2, Color: TColor; begin LastColor1 := 0; LastColor2 := 0; ABitmap.Canvas.Start; try for y := 0 to ABitmap.Height - 1 do for x := 0 to ABitmap.Width - 1 do begin Color := ABitmap.Canvas.Pixels[x, y]; if Color = LastColor1 then ABitmap.Canvas.Pixels[x, y] := LastColor2 else begin LastColor2 := GrayColor(Color, Value); ABitmap.Canvas.Pixels[x, y] := LastColor2; LastColor1 := Color; end; end; finally ABitmap.Canvas.Stop; end; end; procedure DrawBitmapShadow(Bmp: TBitmap; Canvas: TCanvas; X, Y: integer; ShadowColor: TColor); var BX, BY: integer; TransparentColor: TColor; begin Bmp.Canvas.Start; try TransparentColor := Bmp.Canvas.Pixels[0, Bmp.Height - 1]; for BY := 0 to Bmp.Height - 1 do for BX := 0 to Bmp.Width - 1 do if Bmp.Canvas.Pixels[BX, BY] <> TransparentColor then Canvas.Pixels[X + BX, Y + BY] := ShadowColor; finally Bmp.Canvas.Stop; end; end; function PrivateApp: TPrivateApplication; begin Result := TPrivateApplication(Application); end; // ------- BEGIN Memory manipulation functions ---------- function WriteProtectedMemory(BaseAddress, Buffer: Pointer; Size: Cardinal; out WrittenBytes: Cardinal): Boolean; {$IFDEF MSWINDOWS} begin Result := WriteProcessMemory(GetCurrentProcess, BaseAddress, Buffer, Size, WrittenBytes); end; {$ENDIF MSWINDOWS} {$IFDEF LINUX} var AlignedAddress: Cardinal; PageSize, ProtectSize: Cardinal; begin Result := False; WrittenBytes := 0; PageSize := Cardinal(getpagesize); AlignedAddress := Cardinal(BaseAddress) and not (PageSize - 1); // start memory page // get the number of needed memory pages ProtectSize := PageSize; while Cardinal(BaseAddress) + Size > AlignedAddress + ProtectSize do Inc(ProtectSize, PageSize); if mprotect(Pointer(AlignedAddress), ProtectSize, PROT_READ or PROT_WRITE or PROT_EXEC) = 0 then // obtain write access begin try Move(Buffer^, BaseAddress^, Size); // replace code Result := True; WrittenBytes := Size; finally // Is there any function that returns the current page protection? // mprotect(p, ProtectSize, PROT_READ or PROT_EXEC); // lock memory page end; end; end; {$ENDIF LINUX} function ReadProtectedMemory(BaseAddress, Buffer: Pointer; Size: Cardinal; out ReadBytes: Cardinal): Boolean; {$IFDEF MSWINDOWS} begin Result := ReadProcessMemory(GetCurrentProcess, BaseAddress, Buffer, Size, ReadBytes); end; {$ENDIF MSWINDOWS} {$IFDEF LINUX} begin Move(BaseAddress^, Buffer^, Size); // read data Result := True; ReadBytes := Size; end; {$ENDIF LINUX} procedure CodeRedirect(Proc: Pointer; NewProc: Pointer; out Data: TRedirectCode); type TRelocationRec = packed record Jump: Word; Address: PPointer; end; var Code: TRedirectCode; Relocation: TRelocationRec; n: Cardinal; begin ReadProtectedMemory(Proc, @Data, 5, n); if Data.Jump = $ff then // Proc is in an dll or package begin if not ReadProtectedMemory(Proc, @Relocation, SizeOf(TRelocationRec), n) then RaiseLastOSError; Data.RealProc := Relocation.Address^; Proc := Data.RealProc; if not ReadProtectedMemory(Proc, @Data, 5, n) then RaiseLastOSError; end else Data.RealProc := Proc; Code.Jump := $e9; Code.Offset := Integer(NewProc) - Integer(Proc) - 5; if not WriteProtectedMemory(Proc, @Code, 5, n) then RaiseLastOSError; end; procedure CodeRestore(Proc: Pointer; const Data: TRedirectCode); var n: Cardinal; begin if Data.RealProc = nil then Exit; WriteProtectedMemory(Data.RealProc, @Data, 5, n); end; procedure ReplaceVmtField(AClass: TClass; OldProc, NewProc: Pointer); type PVmt = ^TVmt; TVmt = array[0..MaxInt div SizeOf(Pointer) - 1] of Pointer; TRelocationRec = packed record Jump: Byte; Res: Byte; Address: PPointer; end; var I: Integer; Vmt: PVmt; Relocation: TRelocationRec; n: Cardinal; begin if not ReadProtectedMemory(OldProc, @Relocation, SizeOf(TRelocationRec), n) then RaiseLastOSError; if Relocation.Jump = $ff then // Proc is in an dll or package OldProc := Relocation.Address^; if not ReadProtectedMemory(NewProc, @Relocation, SizeOf(TRelocationRec), n) then RaiseLastOSError; if Relocation.Jump = $ff then // Proc is in an dll or package NewProc := Relocation.Address^; I := 0; Vmt := Pointer(AClass); while Vmt[I] <> nil do begin if Vmt[I] = OldProc then begin WriteProtectedMemory(@Vmt[I], @NewProc, SizeOf(NewProc), n); Break; end; Inc(I); end; end; function GetSubCallAddress(Proc: Pointer; CallNum: Integer): Pointer; type TRelocationRec = packed record Jump: Word; Address: PPointer; end; var Code: TRedirectCode; Relocation: TRelocationRec; n: Cardinal; P: PByte; begin ReadProtectedMemory(Proc, @Code, 5, n); if Code.Jump = $ff then // Proc is in an dll or package begin if not ReadProtectedMemory(Proc, @Relocation, SizeOf(TRelocationRec), n) then RaiseLastOSError; Proc := Relocation.Address^; end; P := Proc; // A very, very small disassembler that is not really correct but it does its // job. while P^ <> $C3 do // "ret" begin case P^ of $3B: Inc(P, 2); // CMP reg,reg $53: Inc(P); // PUSH EBX $55: Inc(P); // PUSH EBP $5B: Inc(P); // POP EBX $5D: Inc(P); // POP EBP $83: begin Inc(P); if P^ = $CA then Inc(P, 2); end; $8B: Inc(P, 2); // MOV reg,reg $E8: // CALL xxxx begin Dec(CallNum); Inc(P); if CallNum = 0 then begin Result := Pointer(Integer(P) - 1 + PInteger(P)^ + 5); Exit; end; Inc(P, 4); end; $E9: Inc(P, 4 + 1); // JMP xxxx else Inc(P); end; end; Result := nil; end; // ------- END Memory manipulation functions ---------- var OrgQFrame_drawFrame: procedure(Handle: QWidgetH; Painter: QPainterH); cdecl; procedure HookedQFrame_drawFrame(Handle: QWidgetH; Painter: QPainterH); cdecl; var Control: TWidgetControl; DrawRect: TRect; Details: TThemedElementDetails; MaskSingle, MaskSunken3D: Integer; begin Control := FindControl(Handle); if not (Control is TFrameControl) or not (TOpenFrameControl(Control).BorderStyle in [bsSingle, bsSunken3d]) then begin if QObject_inherits(QObjectH(Handle), 'QFrame') then begin MaskSingle := Integer(QFrameShape_Box) or Integer(QFrameShadow_Plain); MaskSunken3D := Integer(QFrameShape_WinPanel) or Integer(QFrameShadow_Sunken); if ((QFrame_frameStyle(QFrameH(Handle)) and MaskSunken3D = MaskSunken3D)) or ((QFrame_frameStyle(QFrameH(Handle)) and MaskSingle = MaskSingle)) then begin QWidget_geometry(Handle, @DrawRect); OffsetRect(DrawRect, -DrawRect.Left, -DrawRect.Top); QPainter_save(Painter); try with DrawRect do QExcludeClipRect(Painter, Left + 2, Top + 2, Right - 2, Bottom - 2); Details := ThemeServices.GetElementDetails(teEditTextNormal); ThemeServices.DrawElement(Painter, Details, DrawRect); finally QPainter_restore(Painter); end; Exit; end; end; CodeRestore(@OrgQFrame_drawFrame, ThemedStyle.FCodeQFrame_drawFrame); try OrgQFrame_drawFrame(Handle, Painter); finally CodeRedirect(@OrgQFrame_drawFrame, @HookedQFrame_drawFrame, ThemedStyle.FCodeQFrame_drawFrame); end; Exit; end; if Control is TFrameControl then ThemeServices.PaintBorder(Control, False, Painter) end; function GetAddress_QFrame_drawFrame(Handle: QWidgetH): Pointer; const {$MESSAGE WARN 'Qt 2.3 related code'} {$IFDEF MSWINDOWS} VMT_OFFSET = $08; VMT_OFFSET_QFrame_drawFrame = $67; {$ENDIF MSWINDOWS} {$IFDEF LINUX} VMT_OFFSET = $20; VMT_OFFSET_QFrame_drawFrame = $66; {$ENDIF LINUX} type QVmtExtraData = packed record {$IFDEF LINUX} {$MESSAGE WARN 'gcc 2.95 related code'} { gcc 2.95 VMT structure } Reserved: Pointer; RTTIFunc: Pointer; {$ENDIF LINUX} end; QVmtH = ^QVmt; QVmt = packed record ExtraData: QVmtExtraData; Entry: packed array[0..65535] of Pointer; end; function GetQVmt(Handle: QWidgetH): QVmtH; begin Result := QVmtH(PInteger(Cardinal(Handle) + VMT_OFFSET)^); end; begin Result := GetQVmt(Handle).Entry[VMT_OFFSET_QFrame_drawFrame]; end; procedure DrawThemedFlatButtonFace(Canvas: TCanvas; const Client: TRect; IsDown: Boolean; DrawContent: Boolean; IsMouseOverFlag: Integer = 0); var Details: TThemedElementDetails; ToolBtn: TThemedToolBar; PaintRect, ExcludeRect: TRect; begin ToolBtn := ttbButtonNormal; if (IsMouseOverFlag = 0) and (Canvas is TControlCanvas) then if IsMouseOver(TControlCanvas(Canvas).Control) then ToolBtn := ttbButtonHot; if IsMouseOverFlag = 1 then ToolBtn := ttbButtonHot; if IsDown then ToolBtn := ttbButtonPressed; if Canvas is TControlCanvas then if not TControlCanvas(Canvas).Control.Enabled then ToolBtn := ttbButtonDisabled; if ToolBtn = ttbButtonNormal then Exit; PaintRect := Client; Details := ThemeServices.GetElementDetails(ToolBtn); Canvas.Start; try QPainter_save(Canvas.Handle); try ExcludeRect := PaintRect; InflateRect(ExcludeRect, -2, -2); if not DrawContent then begin with ExcludeRect do QExcludeClipRect(Canvas.Handle, Left, Top, Right, Bottom); end; ThemeServices.DrawElement(Canvas, Details, PaintRect); finally QPainter_restore(Canvas.Handle); end; finally Canvas.Stop; end; Canvas.SetClipRect(ExcludeRect); end; function DrawButtonFaceEx(Canvas: TCanvas; const Client: TRect; BevelWidth: Integer; IsDown, IsFocused: Boolean; Flat: Boolean = False; IsMouseOverFlag: Integer = 0; FillColor: TColor = clButton; FillStyle: TBrushStyle = bsSolid): TRect; forward; function DrawThemedButtonFace(Canvas: TCanvas; const Client: TRect; BevelWidth: Integer; IsDown, IsFocused: Boolean; Flat: Boolean = False; FillColor: TColor = clButton; FillStyle: TBrushStyle = bsSolid): TRect; begin Result := DrawButtonFaceEx(Canvas, Client, BevelWidth, IsDown, IsFocused, Flat, 0, FillColor, FillStyle); end; function DrawButtonFaceEx(Canvas: TCanvas; const Client: TRect; BevelWidth: Integer; IsDown, IsFocused: Boolean; Flat: Boolean = False; IsMouseOverFlag: Integer = 0; FillColor: TColor = clButton; FillStyle: TBrushStyle = bsSolid): TRect; var Details: TThemedElementDetails; Button: TThemedButton; begin if FillColor <> clButton then begin CodeRestore(@DrawButtonFace, ThemedStyle.FCodeDrawButtonFace); try Result := DrawButtonFace(Canvas, Client, BevelWidth, IsDown, IsFocused, Flat, FillColor, FillStyle); finally CodeRedirect(@DrawButtonFace, @DrawThemedButtonFace, ThemedStyle.FCodeDrawButtonFace); end; Exit; end; Result := Client; if not Flat then begin Button := tbPushButtonNormal; if IsFocused then Button := tbPushButtonDefaulted; if (IsMouseOverFlag = 0) and (Canvas is TControlCanvas) then if IsMouseOver(TControlCanvas(Canvas).Control) then Button := tbPushButtonHot; if IsMouseOverFlag = 1 then Button := tbPushButtonHot; if IsDown then Button := tbPushButtonPressed; if Canvas is TControlCanvas then if not TControlCanvas(Canvas).Control.Enabled then Button := tbPushButtonDisabled; if Flat and (Button = tbPushButtonNormal) then Exit; Details := ThemeServices.GetElementDetails(Button); ThemeServices.DrawElement(Canvas, Details, Result); end else DrawThemedFlatButtonFace(Canvas, Client, IsDown, True); end; procedure DrawThemedEdge(Canvas: TCanvas; R: TRect; EdgeInner, EdgeOuter: TEdgeStyle; EdgeBorders: TEdgeBorders); begin if Canvas is TControlCanvas then begin if TControlCanvas(Canvas).Control is TSpeedButton then begin DrawThemedFlatButtonFace(Canvas, R, EdgeOuter = esLowered, True); Exit; end; end; CodeRestore(@DrawEdge, ThemedStyle.FCodeDrawEdge); try DrawEdge(Canvas, R, EdgeInner, EdgeOuter, EdgeBorders); finally CodeRedirect(@DrawEdge, @DrawThemedEdge, ThemedStyle.FCodeDrawEdge); end; end; var OrgqDrawShadePanel: procedure(p: QPainterH; r: PRect; g: QColorGroupH; sunken: Boolean; lineWidth: Integer; fill: QBrushH); cdecl; procedure DrawThemedShadePanel(p: QPainterH; r: PRect; g: QColorGroupH; sunken: Boolean; lineWidth: Integer; fill: QBrushH); cdecl; var Details: TThemedElementDetails; ClipRect: TRect; begin if sunken and (lineWidth = 1) and (r <> nil) then begin QPainter_save(p); try ClipRect := r^; with ClipRect do QExcludeClipRect(p, Left + 2, Top + 2, Right - 2, Bottom - 2); Details := ThemeServices.GetElementDetails(teEditTextNormal); ThemeServices.DrawElement(p, Details, r^); finally QPainter_restore(p); with ClipRect do begin // exclude 2 pixel from each side QExcludeClipRect(p, Left, Top, Left + 2, Bottom); QExcludeClipRect(p, Right, Top, Right - 2, Bottom); QExcludeClipRect(p, Left, Top, Right, Top + 2); QExcludeClipRect(p, Left, Bottom, Right, Bottom - 2); end; end; end else begin try CodeRestore(@OrgqDrawShadePanel, ThemedStyle.FCodeDrawShadePanel); OrgqDrawShadePanel(p, r, g, sunken, lineWidth, fill); finally CodeRedirect(@OrgqDrawShadePanel, @DrawThemedShadePanel, ThemedStyle.FCodeDrawShadePanel); end; end; end; { TThemedStyle } constructor TThemedStyle.Create; begin if ThemedStyle <> nil then begin Free; Exit; end; ThemedStyle := Self; inherited Create; FControlInfo := TStringList.Create; FNotifyObject := TThemedStyleNotify.Create(nil); Application.Style := Self; Initialize; FMenusEnabled := True; end; destructor TThemedStyle.Destroy; var I: Integer; begin try Finalize; finally ThemedStyle := nil; for I := 0 to FControlInfo.Count - 1 do TComponent(FControlInfo.Objects[I]).RemoveFreeNotification(FNotifyObject); FControlInfo.Free; FNotifyObject.Free; end; inherited Destroy; end; procedure TThemedStyle.DrawPushButtonHook(btn: QPushButtonH; p: QPainterH; var Stage: Integer); var Canvas: TCanvas; Source: TObject; begin if (btn = nil) or (p = nil) then Exit; try Source := FindControl(btn); Canvas := TCanvas.Create; try Canvas.Handle := p; Canvas.Start(False); if Source <> nil then begin case Stage of DrawStage_Pre: if DoBeforeDrawButton(Source, Canvas) then Stage := DrawStage_DefaultDraw; DrawStage_Post: DoAfterDrawButton(Source, Canvas); end; end else begin case Stage of DrawStage_Pre: if DoBeforeDrawButtonWidget(btn, Canvas) then Stage := DrawStage_DefaultDraw; DrawStage_Post: DoAfterDrawButtonWidget(btn, Canvas); end; end; Canvas.Stop; finally Canvas.Free; end; except Application.HandleException(Self); end; end; procedure TThemedStyle.DrawPopupMenuItemHook(p: QPainterH; checkable: Boolean; maxpmw, tab: Integer; mi: QMenuItemH; itemID: Integer; act, enabled: Boolean; x, y, w, h: Integer; var Stage: Integer); var // Source: TObject; Canvas: TCanvas; R: TRect; begin try Canvas := TCanvas.Create; try Canvas.Handle := p; R := Rect(x, y, x + w, y + h); Canvas.Start(False); { Source := FindObject(QObjectH(mi)); if Source <> nil then DoDrawMenuItem(Source, Canvas, act, enabled, R, checkable, maxpmw, tab, Stage) else} DoDrawMenuItemObject(mi, Canvas, act, enabled, R, checkable, maxpmw, tab, Stage); Canvas.Stop; finally Canvas.Free; end; except Application.HandleException(Self); end; end; {$IFDEF LINUX} // MDI Child title buttons under Linux. Under Windows this is done in EvDrawHeaderSection procedure TThemedStyle.DrawQToolButton(Canvas: TCanvas; R: TRect; Down, Focused: Boolean); begin InflateRect(R, 2, 2); DrawThemedButtonFace(Canvas, R, 2, False, Focused); // background InflateRect(R, -1, -1); DrawThemedButtonFace(Canvas, R, 2, Down, Focused); end; procedure TThemedStyle.DoDrawToolButtonHook(p: QPainterH; x, y, w, h: Integer; g: QColorGroupH; sunken: Boolean; fill: QBrushH); var Canvas: TCanvas; R: TRect; begin try Canvas := TCanvas.Create; try Canvas.Handle := p; R := Rect(x, y, x + w, y + h); Canvas.Start(False); DrawQToolButton(Canvas, R, sunken, False); Canvas.Stop; finally Canvas.Free; end; except Application.HandleException(Self); end; end; procedure TThemedStyle.DoDrawToolButton2Hook(btn: QToolButtonH; p: QPainterH); var Canvas: TCanvas; R: TRect; begin if btn = nil then Exit; Canvas := TCanvas.Create; try Canvas.Handle := p; QWidget_geometry(btn, @R); Canvas.Start(False); DrawQToolButton(Canvas, R, QButton_isDown(btn), QWidget_isActiveWindow(btn)); Canvas.Stop; finally Canvas.Free; end; end; {$ENDIF LINUX} procedure TThemedStyle.EvBeforeDrawButton(Sender, Source: TObject; Canvas: TCanvas; var DefaultDraw: Boolean); var R: TRect; begin R := TWidgetControl(Source).ClientRect; DefaultDraw := False; ThemeServices.DrawParentBackground(TWidgetControl(Source).Handle, Canvas, nil, False, @R); end; procedure TThemedStyle.EvAfterDrawButton(Sender, Source: TObject; Canvas: TCanvas); var Details: TThemedElementDetails; Button: TThemedButton; Down: Boolean; R: TRect; Control: TWidgetControl; begin if Source is TButton then Down := TButton(Source).Down else if Source is TSpinEdit then begin Details := ThemeServices.GetElementDetails(tsArrowBtnUpNormal); R := TControl(Source).ClientRect; R.Bottom := R.Top + (R.Bottom - R.Top) div 2; ThemeServices.DrawElement(Canvas, Details, R); Details := ThemeServices.GetElementDetails(tsArrowBtnDownNormal); R := TControl(Source).ClientRect; R.Top := R.Top + (R.Bottom - R.Top) div 2; ThemeServices.DrawElement(Canvas, Details, R); Exit; end else Down := False; Control := TWidgetControl(Source); Button := tbPushButtonNormal; if ((Source is TButton) and (TButton(Source).Default)) or (Control.Focused) then Button := tbPushButtonDefaulted; if IsMouseOver(Control) then Button := tbPushButtonHot; if Down then Button := tbPushButtonPressed; if not Control.Enabled then Button := tbPushButtonDisabled; Details := ThemeServices.GetElementDetails(Button); ThemeServices.DrawElement(Canvas, Details, Control.ClientRect); end; function TThemedStyle.DoBeforeDrawButtonWidget(btn: QPushButtonH; Canvas: TCanvas): Boolean; var R: TRect; begin Result := False; QWidget_geometry(btn, @R); OffsetRect(R, -R.Left, -R.Top); ThemeServices.DrawParentBackground(btn, Canvas, nil, False, @R); end; procedure TThemedStyle.DoAfterDrawButtonWidget(btn: QPushButtonH; Canvas: TCanvas); var Details: TThemedElementDetails; Button: TThemedButton; Down: Boolean; R: TRect; begin QWidget_geometry(btn, @R); OffsetRect(R, -R.Left, -R.Top); Down := QButton_isDown(btn); Button := tbPushButtonNormal; if QPushButton_isDefault(btn) then Button := tbPushButtonDefaulted; // if IsMouseOver(QWidgetH(btn), nil) then Button := tbPushButtonHot; if Down then Button := tbPushButtonPressed; if not QWidget_isEnabled(btn) then Button := tbPushButtonDisabled; Details := ThemeServices.GetElementDetails(Button); ThemeServices.DrawElement(Canvas, Details, R); end; procedure TThemedStyle.EvDrawComboButton(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Sunken, ReadOnly, Enabled: Boolean; var DefaultDraw: Boolean); var Details: TThemedElementDetails; ComboBox: TThemedComboBox; R: TRect; begin DefaultDraw := False; Details := ThemeServices.GetElementDetails(teEditTextNormal); ThemeServices.DrawElement(Canvas, Details, Rect); ComboBox := tcDropDownButtonNormal; if Sunken then ComboBox := tcDropDownButtonPressed; if (not Enabled) then ComboBox := tcDropDownButtonDisabled; Details := ThemeServices.GetElementDetails(ComboBox); R := Rect;R.Left := R.Right - 19; InflateRect(R, -1, -1); ThemeServices.DrawElement(Canvas, Details, R); end; procedure TThemedStyle.EvDrawCheck(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked, Grayed, Down, Enabled: Boolean; var DefaultDraw: Boolean); var Details: TThemedElementDetails; Button: TThemedButton; begin DefaultDraw := False; if Grayed then begin Button := tbCheckBoxMixedNormal; if Down then Button := tbCheckBoxMixedPressed; if not Enabled then Button := tbCheckBoxMixedDisabled; end else if Checked then begin Button := tbCheckBoxCheckedNormal; if Down then Button := tbCheckBoxCheckedPressed; if not Enabled then Button := tbCheckBoxCheckedDisabled; end else begin Button := tbCheckBoxUncheckedNormal; if Down then Button := tbCheckBoxUncheckedPressed; if not Enabled then Button := tbCheckBoxUncheckedDisabled; end; Details := ThemeServices.GetElementDetails(Button); ThemeServices.DrawElement(Canvas, Details, Rect); end; // TRadioButton procedure TThemedStyle.EvDrawRadio(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked, Down, Enabled: Boolean; var DefaultDraw: Boolean); var Details: TThemedElementDetails; Button: TThemedButton; begin DefaultDraw := False; Canvas.Brush.Color := clBackground; Canvas.FillRect(Rect); if Checked then begin Button := tbRadioButtonCheckedNormal; if Down then Button := tbRadioButtonCheckedPressed; if not Enabled then Button := tbRadioButtonCheckedDisabled; end else begin Button := tbRadioButtonUncheckedNormal; if Down then Button := tbRadioButtonUncheckedPressed; if not Enabled then Button := tbRadioButtonUncheckedDisabled; end; Details := ThemeServices.GetElementDetails(Button); ThemeServices.DrawElement(Canvas, Details, Rect); end; procedure TThemedStyle.EvDrawRadioMask(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Checked: Boolean); var R: TRect; begin R := Rect; Dec(R.Left); Dec(R.Top); {$IFDEF USE_WHITE_RADIOMASK} Canvas.Brush.Color := clWhite; // needed for TRadioGroup {$ELSE} Canvas.Brush.Color := clBlack; {$ENDIF USE_WHITE_RADIOMASK} Canvas.Ellipse(R); end; // ****** procedure TThemedStyle.EvDrawFrame(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Sunken: Boolean; LineWidth: Integer; var DefaultDraw: Boolean); var Details: TThemedElementDetails; begin DefaultDraw := False; Details := ThemeServices.GetElementDetails(teEditTextNormal); ThemeServices.DrawElement(Canvas, Details, Rect); end; procedure TThemedStyle.EvDrawScrollBar(Sender: TObject; ScrollBar: QScrollBarH; Canvas: TCanvas; const Rect: TRect; SliderStart, SliderLength, ButtonSize: Integer; Controls: TScrollBarControls; DownControl: TScrollBarControl; var DefaultDraw: Boolean); procedure DrawItem(const R: TRect; Scroll: TThemedScrollBar); var Details: TThemedElementDetails; begin if QScrollBar_orientation(ScrollBar) = Orientation_Horizontal then begin case Scroll of tsArrowBtnUpNormal: Scroll := tsArrowBtnLeftNormal; tsArrowBtnUpHot: Scroll := tsArrowBtnLeftHot; tsArrowBtnUpPressed: Scroll := tsArrowBtnLeftPressed; tsArrowBtnUpDisabled: Scroll := tsArrowBtnLeftDisabled; tsArrowBtnDownNormal: Scroll := tsArrowBtnRightNormal; tsArrowBtnDownHot: Scroll := tsArrowBtnRightHot; tsArrowBtnDownPressed: Scroll := tsArrowBtnRightPressed; tsArrowBtnDownDisabled: Scroll := tsArrowBtnRightDisabled; tsThumbBtnHorzNormal: Scroll := tsThumbBtnVertNormal; tsThumbBtnHorzHot: Scroll := tsThumbBtnVertHot; tsThumbBtnHorzPressed: Scroll := tsThumbBtnVertPressed; tsThumbBtnHorzDisabled: Scroll := tsThumbBtnVertDisabled; end; end; Details := ThemeServices.GetElementDetails(Scroll); ThemeServices.DrawElement(Canvas, Details, R); end; var Details: TThemedElementDetails; TopRect, BottomRect, ThumbRect, FillRect, FillRectTop, FillRectBottom: TRect; Scroll: TThemedScrollBar; WindowTop, WindowBottom: TThemedScrollBar; begin if ScrollBar = nil then Exit; DefaultDraw := False; if QScrollBar_orientation(ScrollBar) = Orientation_Horizontal then begin TopRect := Types.Rect(0, 0, QWidget_height(ScrollBar), ButtonSize); BottomRect := Types.Rect(QWidget_width(ScrollBar) - ButtonSize, 0, QWidget_width(ScrollBar), QWidget_height(ScrollBar)); ThumbRect := Types.Rect(SliderStart, 0, SliderStart + SliderLength, QWidget_height(ScrollBar)); FillRect := Types.Rect(ButtonSize - 1, 0, QWidget_width(ScrollBar) - ButtonSize, QWidget_height(ScrollBar)); FillRectTop := FillRect;FillRectTop.Right := ThumbRect.Left; FillRectBottom := FillRect;FillRectBottom.Left := ThumbRect.Right; if not QWidget_isEnabled(ScrollBar) then WindowTop := tsUpperTrackHorzDisabled else if DownControl = sbcAddPage then WindowTop := tsUpperTrackHorzPressed else if IsMouseOver(QWidgetH(ScrollBar), @BottomRect) then WindowTop := tsUpperTrackHorzHot else WindowTop := tsUpperTrackHorzNormal; if not QWidget_isEnabled(ScrollBar) then WindowBottom := tsLowerTrackHorzDisabled else if DownControl = sbcSubPage then WindowBottom := tsLowerTrackHorzPressed else if IsMouseOver(QWidgetH(ScrollBar), @BottomRect) then WindowBottom := tsLowerTrackHorzHot else WindowBottom := tsLowerTrackHorzNormal; end else begin TopRect := Types.Rect(0, 0, QWidget_width(ScrollBar), ButtonSize); BottomRect := Types.Rect(0, QWidget_height(ScrollBar) - ButtonSize, QWidget_width(ScrollBar), QWidget_height(ScrollBar)); ThumbRect := Types.Rect(0, SliderStart, QWidget_width(ScrollBar), SliderStart + SliderLength); FillRect := Types.Rect(0, ButtonSize - 1, QWidget_width(ScrollBar), QWidget_height(ScrollBar) - ButtonSize); FillRectTop := FillRect;FillRectTop.Bottom := ThumbRect.Top; FillRectBottom := FillRect;FillRectBottom.Top := ThumbRect.Bottom; if not QWidget_isEnabled(ScrollBar) then WindowTop := tsUpperTrackVertDisabled else if DownControl = sbcAddPage then WindowTop := tsUpperTrackVertPressed else if IsMouseOver(QWidgetH(ScrollBar), @BottomRect) then WindowTop := tsUpperTrackVertHot else WindowTop := tsUpperTrackVertNormal; if not QWidget_isEnabled(ScrollBar) then WindowBottom := tsLowerTrackVertDisabled else if DownControl = sbcSubPage then WindowBottom := tsLowerTrackVertPressed else if IsMouseOver(QWidgetH(ScrollBar), @BottomRect) then WindowBottom := tsLowerTrackVertHot else WindowBottom := tsLowerTrackVertNormal; end; { sbcAddPage, sbcSubPage } Details := ThemeServices.GetElementDetails(WindowBottom); ThemeServices.DrawElement(Canvas, Details, FillRectTop); Details := ThemeServices.GetElementDetails(WindowTop); ThemeServices.DrawElement(Canvas, Details, FillRectBottom); if not QWidget_isEnabled(ScrollBar) then Scroll := tsArrowBtnUpDisabled else if DownControl = sbcSubButton then Scroll := tsArrowBtnUpPressed else if IsMouseOver(QWidgetH(ScrollBar), @TopRect) then Scroll := tsArrowBtnUpHot else Scroll := tsArrowBtnUpNormal; DrawItem(TopRect, Scroll); if not QWidget_isEnabled(ScrollBar) then Scroll := tsArrowBtnDownDisabled else if DownControl = sbcAddButton then Scroll := tsArrowBtnDownPressed else if IsMouseOver(QWidgetH(ScrollBar), @BottomRect) then Scroll := tsArrowBtnDownHot else Scroll := tsArrowBtnDownNormal; DrawItem(BottomRect, Scroll); if not QWidget_isEnabled(ScrollBar) then Scroll := tsThumbBtnVertDisabled else if DownControl = sbcSlider then Scroll := tsThumbBtnVertPressed else if IsMouseOver(QWidgetH(ScrollBar), @ThumbRect) then Scroll := tsThumbBtnVertHot else Scroll := tsThumbBtnVertNormal; DrawItem(ThumbRect, Scroll); end; procedure TThemedStyle.EvDrawTrackBar(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove, TickBelow: Boolean; var DefaultDraw: Boolean); var Details: TThemedElementDetails; TrackBar: TThemedTrackBar; begin DefaultDraw := False; if Horizontal then begin if TickAbove and not TickBelow then TrackBar := ttbThumbTopNormal else if not TickAbove and TickBelow then TrackBar := ttbThumbBottomNormal else TrackBar := ttbThumbNormal end else begin if TickAbove and not TickBelow then TrackBar := ttbThumbLeftNormal else if not TickAbove and TickBelow then TrackBar := ttbThumbRightNormal else TrackBar := ttbThumbVertNormal; end; Details := ThemeServices.GetElementDetails(TrackBar); ThemeServices.DrawElement(Canvas, Details, Rect); end; procedure TThemedStyle.EvDrawTrackBarMask(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal, TickAbove, TickBelow: Boolean; var DefaultDraw: Boolean); var Bmp: TBitmap; X, Y: Integer; R: TRect; begin Bmp := TBitmap.Create; try Bmp.Canvas.Brush.Color := clBlack; Bmp.Width := Rect.Right - Rect.Left; Bmp.Height := Rect.Bottom - Rect.Top; Bmp.Canvas.Start; try Bmp.Canvas.FillRect(Types.Rect(0, 0, Bmp.Width, Bmp.Height)); R := Rect; OffsetRect(R, -R.Left, -R.Top); EvDrawTrackBar(Sender, Bmp.Canvas, R, Horizontal, TickAbove, TickBelow, DefaultDraw); for X := 0 to Bmp.Width - 1 do for Y := 0 to Bmp.Height - 1 do if Bmp.Canvas.Pixels[X, Y] <> 0 then Bmp.Canvas.Pixels[X, Y] := clBlack else Bmp.Canvas.Pixels[X, Y] := clWhite; finally Bmp.Canvas.Stop; end; Canvas.Draw(Rect.Left, Rect.Top, Bmp); finally Bmp.Free; end; end; procedure TThemedStyle.EvDrawTrackBarGroove(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Horizontal: Boolean; var DefaultDraw: Boolean); const h = 10; var Details: TThemedElementDetails; TrackBar: TThemedTrackBar; R: TRect; begin DefaultDraw := False; TrackBar := ttbTrack; R := Rect; R.Top := R.Top + ((R.Bottom - R.Top) - h) div 2; R.Bottom := R.Top + h; Details := ThemeServices.GetElementDetails(TrackBar); ThemeServices.DrawElement(Canvas, Details, R); end; procedure TThemedStyle.EvDrawHeaderSection(Sender: TObject; Canvas: TCanvas; const Rect: TRect; Down: Boolean; var DefaultDraw: Boolean); var Details: TThemedElementDetails; Header: TThemedHeader; wnd: Cardinal; PaintRect, R: TRect; Widget: QWidgetH; begin PaintRect := Rect; Widget := nil; Canvas.Start; try wnd := GetWindowFromPainter(Canvas.Handle); if wnd <> 0 then begin {$IFDEF MSWINDOWS} GetWindowRect(HWND(wnd), R); {$ENDIF MSWINDOWS} Widget := QWidget_find(Cardinal(wnd)); {$IFDEF LINUX} if Widget <> nil then begin QWidget_geometry(Widget, @R); QWidget_mapToGlobal(Widget, @R.TopLeft, @R.TopLeft); QWidget_mapToGlobal(Widget, @R.BottomRight, @R.BottomRight); end; {$ENDIF LINUX} end; // no default drawing from this point DefaultDraw := False; if Widget = nil then begin // MDI Childframe buttons Canvas.Brush.Color := clActiveHighlight; Canvas.FillRect(Rect); R := Rect; //InflateRect(R, 1, 1); DrawButtonFace(Canvas, R, 1, Down, False, False); Exit; end; if Down then Header := thHeaderItemPressed else if (wnd <> 0) and (PtInRect(R, Mouse.CursorPos)) and (PtInRect(Rect, Point(Mouse.CursorPos.X - R.Left, Mouse.CursorPos.Y - R.Top))) then Header := thHeaderItemHot else Header := thHeaderItemNormal; { // Windows XP does not draw the left and right orientated controls if QHeader_orientation(QHeaderH(Widget)) = Orientation_Vertical then begin Control := FindControl(Widget); if (Control <> nil) and (Control.Align = alLeft) then case Header of thHeaderItemNormal: Header := thHeaderItemLeftNormal; thHeaderItemPressed: Header := thHeaderItemLeftPressed; thHeaderItemHot: Header := thHeaderItemLeftHot; end else case Header of thHeaderItemNormal: Header := thHeaderItemRightNormal; thHeaderItemPressed: Header := thHeaderItemRightPressed; thHeaderItemHot: Header := thHeaderItemRightHot; end; end;} Details := ThemeServices.GetElementDetails(Header); ThemeServices.DrawElement(Canvas, Details, PaintRect); finally Canvas.Stop; end; end; procedure TThemedStyle.EvDrawMenuFrame(Sender: TObject; Canvas: TCanvas; const R: TRect; LineWidth: Integer; var DefaultDraw: Boolean); var Details: TThemedElementDetails; begin if not FMenusEnabled then Exit; DefaultDraw := False; Details := ThemeServices.GetElementDetails(ttPane); ThemeServices.DrawElement(Canvas, Details, R); end; procedure TThemedStyle.EvMenuItemHeight(Sender, Source: TObject; Checkable: Boolean; FontMetrics: QFontMetricsH; var Height: Integer); begin if not FMenusEnabled then Exit; if TMenuItem(Source).Parent <> nil then if TMenuItem(Source).Parent.IndexOf(TMenuItem(Source)) = TMenuItem(Source).Parent.Count - 1 then Inc(Height, 2); if TMenuItem(Source).Caption = '-' then Inc(Height); end; type TQMenuItem = class RadioItem: Boolean; Checked: Boolean; Enabled: Boolean; Count: Integer; Caption: WideString; ShortCut: WideString; end; procedure TThemedStyle.DoDrawMenuItemObject(Item: QMenuItemH; Canvas: TCanvas; Highlighted, Enabled: Boolean; const Rect: TRect; Checkable: Boolean; CheckMaxWidth, LabelWidth: Integer; var Stage: Integer); const DrawSelect = True; FlatMenu = True; const Color = $00FAFCFC {clWindow}; IconBackColor = $00DEEDEF; {clBtnFace} SelectColor = $00ECCFBD; {clHighlight} SelectBorderColor = clHighlight; MenuBarColor = clBtnFace; DisabledColor = $00A3B1B4;{clInactiveCaption} SeparatorColor = $00B3BEC1{clSilver}; CheckedColor = clHighlight; SelectFontColor = clWindowText;// FFont.Color; CheckedAreaColor = SelectColor; CheckedAreaSelectColor = SelectColor; GrayLevel = 10; DimLevel = 30; IconWidth = 24; function GetShadeColor(clr: TColor; Value: Integer): TColor; var r, g, b: integer; begin clr := ColorToRGB(clr); r := Clr and $000000FF; g := (Clr and $0000FF00) shr 8; b := (Clr and $00FF0000) shr 16; r := (r - value); if r < 0 then r := 0; if r > 255 then r := 255; g := (g - value) + 2; if g < 0 then g := 0; if g > 255 then g := 255; b := (b - value); if b < 0 then b := 0; if b > 255 then b := 255; Result := RGB(r, g, b); end; procedure DrawCheckedItem(MenuItem: TQMenuItem; Selected, Enabled, HasImgLstBitmap: Boolean; ACanvas: TCanvas; CheckedRect: TRect); var X1, X2: integer; begin if MenuItem.RadioItem then begin if MenuItem.Checked then begin if Enabled then begin Canvas.Pen.color := SelectBorderColor; if Selected then Canvas.Brush.Color := CheckedAreaSelectColor else Canvas.Brush.Color := CheckedAreaColor; end else Canvas.Pen.Color := DisabledColor; Canvas.Brush.Style := bsSolid; if HasImgLstBitmap then Canvas.RoundRect(CheckedRect.Left, CheckedRect.Top, CheckedRect.Right, CheckedRect.Bottom, 6, 6) else ACanvas.Ellipse(CheckedRect) end; end else begin if MenuItem.Checked then if not HasImgLstBitmap then begin if Enabled then begin Canvas.Pen.Color := CheckedColor; if Selected then Canvas.Brush.Color := CheckedAreaSelectColor else Canvas.Brush.Color := CheckedAreaColor; end else Canvas.Pen.Color := DisabledColor; Canvas.Brush.Style := bsSolid; Canvas.Rectangle(CheckedRect); if Enabled then Canvas.Pen.Color := clBlack else Canvas.Pen.Color := DisabledColor; x1 := CheckedRect.Left + 1; x2 := CheckedRect.Top + 5; Canvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 2; Canvas.LineTo(x1, x2); //-- x1 := CheckedRect.Left + 2; x2 := CheckedRect.Top + 5; Canvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 3; Canvas.LineTo(x1, x2); //-- x1 := CheckedRect.Left + 2; x2 := CheckedRect.Top + 4; Canvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 5; x2 := CheckedRect.Bottom - 3; Canvas.LineTo(x1, x2); //----------------- x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 3; Canvas.MoveTo(x1, x2); x1 := CheckedRect.Right + 2; x2 := CheckedRect.Top - 1; Canvas.LineTo(x1, x2); //-- x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 2; Canvas.MoveTo(x1, x2); x1 := CheckedRect.Right - 2; x2 := CheckedRect.Top + 3; Canvas.LineTo(x1, x2); end else begin if Enabled then begin Canvas.Pen.Color := SelectBorderColor; if Selected then Canvas.Brush.Color := CheckedAreaSelectColor else Canvas.Brush.Color := CheckedAreaColor; end else ACanvas.Pen.Color := DisabledColor; ACanvas.Brush.Style := bsSolid; ACanvas.Rectangle(CheckedRect); end; end; end; procedure DrawTheText(Sender: TObject; Text, ShortCutText: WideString; Canvas: TCanvas; TextRect: TRect; Selected, Enabled, Default: Boolean; var TextFont: TFont; TextFormat: Integer); var DefColor: TColor; R: TRect; begin R := TextRect; DefColor := TextFont.Color; Canvas.Font.Assign(TextFont); if Selected then DefColor := SelectFontColor; if not Enabled then DefColor := DisabledColor; Canvas.Font.Color := DefColor; // will not affect Buttons if Default and Enabled then begin Inc(TextRect.Left, 1); Canvas.Font.Color := GetShadeColor(Canvas.Pixels[TextRect.Left, TextRect.Top], 30); ClxDrawTextW(Canvas, Text, TextRect, TextFormat); Dec(TextRect.Left, 1); Inc(TextRect.Top, 2); Inc(TextRect.Left, 1); Inc(TextRect.Right, 1); Canvas.Font.Color := GetShadeColor(Canvas.Pixels[TextRect.Left, TextRect.Top], 30); ClxDrawTextW(Canvas, Text, TextRect, TextFormat); Dec(TextRect.Top, 1); Dec(TextRect.Left, 1); Dec(TextRect.Right, 1); Canvas.Font.Color := GetShadeColor(Canvas.Pixels[TextRect.Left, TextRect.Top], 40); ClxDrawTextW(Canvas, Text, TextRect, TextFormat); Inc(TextRect.Left, 1); Inc(TextRect.Right, 1); Canvas.Font.Color := GetShadeColor(Canvas.Pixels[TextRect.Left, TextRect.Top], 60); ClxDrawTextW(Canvas, Text, TextRect, TextFormat); Dec(TextRect.Left, 1); Dec(TextRect.Right, 1); Dec(TextRect.Top, 1); Canvas.Font.Color := DefColor; end; ClxDrawTextW(Canvas, Text, TextRect, TextFormat); Text := ShortCutText + ' '; Canvas.Font.Color := GetShadeColor(DefColor, -40); Dec(TextRect.Right, 10); TextFormat := DT_RIGHT; ClxDrawTextW(Canvas, Text, TextRect, TextFormat); if TQMenuItem(Sender).Count > 0 then begin Canvas.Font.Name := 'Webdings'; Text := '4'; Dec(TextRect.Top, 3); TextRect.Right := R.Right; ClxDrawTextW(Canvas, Text, TextRect, TextFormat); end; end; procedure DrawIcon(Sender: TObject; Canvas: TCanvas; Bmp: TBitmap; IconRect: TRect; Hot, Selected, Enabled, Checked: Boolean); var DefColor: TColor; X, Y: integer; begin if (Bmp <> nil) and (Bmp.Width > 0) then begin X := IconRect.Left; Y := IconRect.Top + 1; if Sender is TQMenuItem then begin Inc(Y, 2); if IconWidth > Bmp.Width then X := X + ((IconWidth - Bmp.Width) div 2) - 1 else X := IconRect.Left + 2; end; if Hot and (Enabled) and (not Checked) then if not Selected then begin Dec(X, 1); Dec(Y, 1); end; if (not Hot) and (Enabled) and (not Checked) then DimBitmap(Bmp, DimLevel{30}); if not Enabled then begin GrayBitmap(Bmp, GrayLevel); DimBitmap(Bmp, 40); end; if (Hot) and (Enabled) and (not Checked) then begin DefColor := GetShadeColor(SelectColor, 50); DrawBitmapShadow(Bmp, Canvas, X + 2, Y + 2, DefColor); end; Bmp.Transparent := True; Canvas.Draw(X, Y, Bmp); end; end; var Text: WideString; Bmp: TBitmap; IconRect, TextRect, CheckedRect: TRect; X1, X2: Integer; TextFormat: Integer; HasImgLstBitmap, HasBitmap: Boolean; IsLine: Boolean; Images: TCustomImageList; ImgIndex: Integer; ARect: TRect; Font: TFont; MenuItem: TQMenuItem; ClxMenuItem: TMenuItem; ps: Integer; begin if Stage <> DrawStage_Pre then begin Stage := DrawStage_DefaultDraw; Exit; end; if not FMenusEnabled then Exit; ARect := Rect; MenuItem := TQMenuItem.Create; try ClxMenuItem := TMenuItem(FindObject(QObjectH(Item))); if ClxMenuItem <> nil then begin MenuItem.Checked := ClxMenuItem.Checked; MenuItem.RadioItem := ClxMenuItem.RadioItem; MenuItem.Enabled := ClxMenuItem.Enabled; MenuItem.Count := ClxMenuItem.Count; MenuItem.Caption := ClxMenuItem.Caption; MenuItem.ShortCut := ShortCutToText(ClxMenuItem.ShortCut); end else if Item <> nil then begin MenuItem.Checked := QMenuItem_isChecked(Item); QMenuItem_text(Item, @MenuItem.Caption); MenuItem.Enabled := Enabled; if QMenuItem_popup(Item) <> nil then MenuItem.Count := 1; if QMenuItem_isSeparator(Item) then MenuItem.Caption := '-'; ps := Pos(#9, MenuItem.Caption); if ps > 0 then begin try MenuItem.ShortCut := Trim(Copy(MenuItem.Caption, ps + 1, MaxInt)); MenuItem.Caption := Copy(MenuItem.Caption, 1, ps - 1); except end; end; end; IsLine := MenuItem.Caption = '-'; if ClxMenuItem <> nil then // last menu item if ClxMenuItem.Parent.IndexOf(ClxMenuItem) = ClxMenuItem.Parent.Count - 1 then Dec(ARect.Bottom, 2); Inc(ARect.Bottom, 1); Dec(ARect.Right, 1); TextRect := ARect; Text := ' ' + MenuItem.Caption; Font := TFont.Create; Bmp := TBitmap.Create; try Canvas.Font.Assign(Font); HasBitmap := False; HasImgLstBitmap := False; if ClxMenuItem <> nil then begin if (ClxMenuItem.Parent.GetParentMenu.Images <> nil) then HasImgLstBitmap := ClxMenuItem.ImageIndex <> -1; if ClxMenuItem.Bitmap.Width > 0 then HasBitmap := True; if HasBitmap then begin Bmp.Width := ClxMenuItem.Bitmap.Width; Bmp.Height := ClxMenuItem.Bitmap.Height; Bmp.Canvas.CopyRect(Types.Rect(0, 0, Bmp.Width, Bmp.Height), ClxMenuItem.Bitmap.Canvas, Types.Rect(0, 0, Bmp.Width, Bmp.Height)); end; if HasImgLstBitmap then begin if ClxMenuItem.Parent.GetParentMenu.Images <> nil then begin Images := ClxMenuItem.Parent.GetParentMenu.Images; ImgIndex := ClxMenuItem.ImageIndex; Bmp.Width := ClxMenuItem.Parent.GetParentMenu.Images.Width; Bmp.Height := ClxMenuItem.Parent.GetParentMenu.Images.Height; Bmp.Canvas.Brush.Color := Canvas.Pixels[2,2]; Bmp.Canvas.FillRect(Types.Rect(0, 0, Bmp.Width, Bmp.Height)); Images.Draw(Bmp.Canvas, 0, 0, ImgIndex); end; end; end; X1 := ARect.Left; X2 := ARect.Left + IconWidth; IconRect := Types.Rect(X1, ARect.Top, X2, ARect.Bottom); if HasImgLstBitmap or HasBitmap then begin CheckedRect := IconRect; Inc(CheckedRect.Left, 1); Inc(CheckedRect.Top, 2); Dec(CheckedRect.Right, 3); Dec(CheckedRect.Bottom, 2); end else begin CheckedRect.Left := IconRect.Left + (IConRect.Right - IconRect.Left - 10) div 2; CheckedRect.Top := IconRect.Top + (IConRect.Bottom - IconRect.Top - 10) div 2; CheckedRect.Right := CheckedRect.Left + 10; CheckedRect.Bottom := CheckedRect.Top + 10; end; if Bmp.Width > IconWidth then CheckedRect.Right := CheckedRect.Left + Bmp.Width; X1 := ARect.Left; Inc(X1, IconWidth); if (ARect.Left + Bmp.Width) > X1 then X1 := ARect.Left + Bmp.Width + 4; X2 := ARect.Right; TextRect := Types.Rect(X1, ARect.Top, X2, ARect.Bottom); Canvas.Brush.Color := Color; Canvas.FillRect(ARect); Canvas.Brush.Color := IconBackColor; Canvas.FillRect(IconRect); if Item = nil then Exit; // empty menu item if MenuItem.Enabled then Canvas.Font.Color := Font.Color else Canvas.Font.Color := DisabledColor; if Highlighted and DrawSelect then begin Canvas.Brush.Style := bsSolid; if MenuItem.Enabled then begin Inc(ARect.Top, 1); Dec(ARect.Bottom, 1); if FlatMenu then Dec(ARect.Right, 1); Canvas.Brush.Color := SelectColor; Canvas.FillRect(ARect); Canvas.Pen.Color := SelectBorderColor; Canvas.Brush.Style := bsClear; Canvas.RoundRect(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom, 0, 0); Dec(ARect.Top, 1); Inc(ARect.Bottom, 1); if FlatMenu then Inc(ARect.Right, 1); end; end; DrawCheckedItem(MenuItem, Highlighted, MenuItem.Enabled, HasImgLstBitmap or HasBitmap, Canvas, CheckedRect); if not IsLine then begin TextFormat := 0; Inc(TextRect.Left, 3); TextRect.Top := TextRect.Top + ((TextRect.Bottom - TextRect.Top) - Canvas.TextHeight('W')) div 2; DrawTheText(MenuItem, Text, MenuItem.ShortCut, Canvas, TextRect, Highlighted, MenuItem.Enabled, False{MenuItem.Default}, Font, TextFormat); end else begin X1 := TextRect.Left + 7; X2 := TextRect.Right; Canvas.Pen.Color := SeparatorColor; Canvas.MoveTo(X1, TextRect.Top + Round((TextRect.Bottom - TextRect.Top) / 2)); Canvas.LineTo(X2, TextRect.Top + Round((TextRect.Bottom - TextRect.Top) / 2)); end; DrawIcon(MenuItem, Canvas, Bmp, IconRect, Highlighted, False, MenuItem.Enabled, MenuItem.Checked); finally Bmp.Free; Font.Free; end; finally MenuItem.Free; end; end; procedure TThemedStyle.InternalDrawTab(Index: Integer); const SELECTED_TAB_SIZE_DELTA = 2; var TabControl: TOpenCustomTabControl; Details: TThemedElementDetails; Tab: TThemedTab; R: TRect; X, Y: Integer; function GetMaxTabHeight: Integer; var I: Integer; begin with TabControl do begin Result := 0; for I := 0 to Tabs.Count - 1 do if Tabs[I].Visible then if Result < Tabs[I].TabRect.Bottom then Result := Tabs[I].TabRect.Bottom; end; end; function RightSide: Integer; begin with TPrivateCustomTabControl(Self) do begin if FButtons[tbLeft].Visible then Result := FButtons[tbLeft].Left - 1 else Result := Width - 2; end; end; var OwnClipRect: Boolean; bMouseOver: Integer; ButtonRect: TRect; begin TabControl := TOpenCustomTabControl(Self); with TabControl do begin if (Style = tsNoTabs) then Exit; Canvas.Start; OwnClipRect := False; if Canvas.ClipRect.Right <> RightSide then begin R := Rect(0, 0, RightSide, GetMaxTabHeight + 1); if not MultiLine then begin Canvas.SetClipRect(R); OwnClipRect := True; end; end; try R := Tabs[Index].TabRect; AdjustTabRect(R); ButtonRect := R; if Index = TabIndex then InflateRect(R, SELECTED_TAB_SIZE_DELTA, SELECTED_TAB_SIZE_DELTA); if R.Right > RightSide then R.Right := RightSide; if DrawTab(Index, R, Tabs[Index].Enabled) then begin case Style of tsTabs: begin Tab := ttTabItemNormal; if Index = TabIndex then Tab := ttTabItemSelected; if Tabs[Index].Highlighted then Tab := ttTabItemLeftEdgeFocused; if TPrivateCustomTabControl(TabControl).FMouseOver = Index then {if IsMouseOver(QWidgetH(TabControl.Handle), @R) then }Tab := ttTabItemHot; if not Tabs[Index].Enabled then Tab := ttTabItemDisabled; Details := ThemeServices.GetElementDetails(Tab); ThemeServices.DrawElement(Canvas, Details, R); R := Tabs[Index].TabRect; InflateRect(R, -3, -3); Inc(R.Bottom, 3); if Index <> TabIndex then Inc(R.Top); {$IFDEF LINUX} Dec(R.Top, 2); {$ENDIF LINUX} X := R.Left; Y := R.Top; end; tsButtons, tsFlatButtons: begin if Style = tsFlatButtons then begin if Index > TPrivateCustomTabControl(TabControl).FFirstVisibleTab then begin Canvas.Pen.Style := psSolid; Canvas.Pen.Color := clGray; Canvas.MoveTo(ButtonRect.Left - 4, ButtonRect.Top + 2); Canvas.LineTo(ButtonRect.Left - 4, ButtonRect.Bottom - 2); Canvas.Pen.Color := clWhite; Canvas.MoveTo(ButtonRect.Left - 3, ButtonRect.Top + 3); Canvas.LineTo(ButtonRect.Left - 3, ButtonRect.Bottom - 1); end; end; if HotTrack and (TPrivateCustomTabControl(TabControl).FMouseOver = Index) then bMouseOver := 1 else bMouseOver := 2; if (Style <> tsFlatButtons) or (Index = TabIndex) or (bMouseOver <> 2) then DrawButtonFaceEx(Canvas, ButtonRect, 1, Index = TabIndex, Index = TabIndex, Style = tsFlatButtons, bMouseOver); with Tabs[Index].TabRect do begin X := Left + ((Right - Left) - Canvas.TextWidth(Tabs[Index].Caption)) div 2; Y := Top + ((Bottom - Top) - Canvas.TextHeight(Tabs[Index].Caption)) div 2 + 1; end; end; else Exit; end; // case if (Tabs[Index].ImageIndex <> -1) and (Images <> nil) then begin if Style <> tsTabs then Dec(X, (Images.Width + 1) div 2); Images.Draw(Canvas, X, Y, Tabs[Index].ImageIndex, itImage, Tabs[Index].Enabled); Inc(X, Images.Width + 2); end; if (Style <> tsTabs) and (Index = TabIndex) then begin Inc(Y); Inc(X); end; Canvas.TextRect(R, X, Y, Tabs[Index].Caption, Integer(AlignmentFlags_SingleLine) or Integer(AlignmentFlags_ShowPrefix)); if (Index = TabIndex) and Focused and (Style = tsTabs) then begin R := Tabs[Index].TabRect; InflateRect(R, -1, -1); Inc(R.Top); Canvas.DrawFocusRect(R); end; end; finally if OwnClipRect then Canvas.ResetClipRegion; Canvas.Stop; end; end; end; procedure TThemedStyle.HookedCustomTabControlPaint; // Self = TCustomTabControl var Details: TThemedElementDetails; TabControl: TOpenCustomTabControl; R: TRect; I: Integer; function GetMaxTabHeight: Integer; var I: Integer; begin with TabControl do begin Result := 0; for I := 0 to Tabs.Count - 1 do if Tabs[I].Visible then if Result < Tabs[I].TabRect.Bottom then Result := Tabs[I].TabRect.Bottom; end; end; function RightSide: Integer; begin with TPrivateCustomTabControl(Self) do begin if FButtons[tbLeft].Visible then Result := FButtons[tbLeft].Left - 1 else Result := Width - 2; end; end; function InheritedCall: Boolean; var OldProc: procedure(Self: TObject); begin with TOpenCustomTabControl(Self) do begin Canvas.Start; QPainter_save(Canvas.Handle); try QIntersectClipRect(Canvas.Handle, Rect(-1, -1, -1, -1)); CodeRestore(@TOpenCustomTabControl.Paint, ThemedStyle.FCodeDrawTab); try OldProc := @TOpenCustomTabControl.Paint; OldProc(Self); // enable buttons, ... finally CodeRedirect(@TOpenCustomTabControl.Paint, @TThemedStyle.HookedCustomTabControlPaint, ThemedStyle.FCodeDrawTab); end; finally QPainter_restore(Canvas.Handle); Canvas.Stop; end; Result := Style = tsNoTabs; end; // with end; begin TabControl := TOpenCustomTabControl(Self); with TabControl do begin if (TPrivateCustomTabControl(TabControl).FLayoutCount > 0) then LayoutTabs; if (not MultiLine) or (Style = tsNoTabs) then if InheritedCall then Exit; Canvas.Start; try R := ClientRect; ThemeServices.DrawParentBackground(Handle, Canvas, nil, False); R.Top := GetMaxTabHeight; Details := ThemeServices.GetElementDetails(ttPane); ThemeServices.DrawElement(Canvas, Details, R); R := Rect(0, 0, RightSide, GetMaxTabHeight + 1); if not MultiLine then Canvas.SetClipRect(R); try with TPrivateCustomTabControl(TabControl) do begin if Tabs.Count > 0 then begin for I := FFirstVisibleTab to FLastVisibleTab do begin if (Tabs[I].Visible) and (I <> TabIndex) then InternalDrawTab(I); end; if (TabIndex <> -1) and (Tabs[TabIndex].Visible) then if (TabIndex >= FFirstVisibleTab) and (TabIndex <= FLastVisibleTab) then InternalDrawTab(TabIndex); end; end; finally if not MultiLine then Canvas.ResetClipRegion; end; finally Canvas.Stop; end; end; end; procedure TThemedStyle.HookedDoHotTrack(Index: Integer); procedure DrawHotTrack(Erase: Boolean); var idx: Integer; i: Integer; begin with TPrivateCustomTabControl(Self), TOpenCustomTabControl(Self) do if FMouseOver <> -1 then begin idx := FMouseOver; if Erase then FMouseOver := -1; InternalDrawTab(idx); if Erase and (Style = tsFlatButtons) then for i := FFirstVisibleTab to FLastVisibleTab do InvalidateRect(Tabs[i].TabRect, False); end; end; begin with TPrivateCustomTabControl(Self), TOpenCustomTabControl(Self) do begin if (FMouseOver <> Index) then begin if MultiLine or ((FMouseOver >= FFirstVisibleTab) and (FMouseOver <= FLastVisibleTab)) then DrawHotTrack(True); FMouseOver := Index; if HotTrack or (FTracking = Index) then DrawHotTrack(False); end; end; end; procedure TThemedStyle.HookedTabSheetPaint; // Self = TTabSheet var Details: TThemedElementDetails; TabSheet: TTabSheet; begin TabSheet := TTabSheet(Self); if TabSheet.PageControl.Style = tsTabs then begin Details := ThemeServices.GetElementDetails(ttBody); ThemeServices.DrawElement(TOpenCustomControl(TabSheet).Canvas, Details, TabSheet.ClientRect); end; end; procedure TThemedStyle.HookedProgressBarPaint; // Self = TProgressBar var Details: TThemedElementDetails; Progress: TThemedProgress; ProgressBar: TOpenProgressBar; R: TRect; begin ProgressBar := TOpenProgressBar(Self); with ProgressBar do begin Transparent := True; // prevent that SetPosition() calls InternalPaint if Orientation = pbHorizontal then Progress := tpBar else Progress := tpBarVert; R := ClientRect; // fix WindowsXP theming bug with Height < 10 if (Orientation = pbHorizontal) and (Height < 10) then Dec(R.Top, 10 - Height) else if (Orientation = pbVertical) and (Width < 10) then Dec(R.Left, 10 - Width); Details := ThemeServices.GetElementDetails(Progress); ThemeServices.DrawElement(Canvas, Details, R); R := ThemeServices.ContentRect(Canvas, Details, ClientRect); if Position > Min then begin if Orientation = pbHorizontal then begin Progress := tpChunk; R.Right := MulDiv(Abs(Position - Min), (R.Right - R.Left), (Max - Min)); end else begin Progress := tpChunkVert; R.Top := MulDiv(Abs(Position - Max), (R.Bottom - R.Top), (Max - Min)); end; Details := ThemeServices.GetElementDetails(Progress); ThemeServices.DrawElement(Canvas, Details, R, @R); end; end; end; procedure TThemedStyle.HookedWidgetControlPainting(Sender: QObjectH; EventRegion: QRegionH); var ForcedPaintEvent: QPaintEventH; Canvas: TControlCanvas; begin with TOpenWidgetControl(Self) do begin if TWidgetControl(Self) is TCustomGroupBox then begin Canvas := TControlCanvas.Create; try Canvas.Control := TWidgetControl(Self); Canvas.StartPaint; try QPainter_setClipRegion(Canvas.Handle, EventRegion); ThemedStyle.DrawGroupBox(TCustomGroupBox(Self), Canvas); finally Canvas.StopPaint; end; finally Canvas.Free; end; Exit; end; // original code ForcedPaintEvent := QPaintEvent_create(EventRegion, False); try ControlState := ControlState + [csWidgetPainting]; try QObject_event(Sender, ForcedPaintEvent); finally ControlState := ControlState - [csWidgetPainting]; end; finally QPaintEvent_destroy(ForcedPaintEvent); end; end; end; procedure TThemedStyle.DrawGroupBox(Control: TCustomGroupBox; Canvas: TCanvas); var Details: TThemedElementDetails; R, CaptionRect: TRect; begin with TOpenCustomGroupBox(Control) do begin R := BoundsRect; OffsetRect(R, -R.Left, -R.Top); ThemeServices.DrawParentBackground(Handle, Canvas, nil, False, @R); if Enabled then Details := ThemeServices.GetElementDetails(tbGroupBoxNormal) else Details := ThemeServices.GetElementDetails(tbGroupBoxDisabled); Inc(R.Top, Canvas.TextHeight('0') div 2); ThemeServices.DrawElement(Canvas.Handle, Details, R); CaptionRect := Rect(9, 0, Min(Canvas.TextWidth(Caption) + 9, ClientWidth - 8), Canvas.TextHeight(Caption)); ThemeServices.DrawParentBackground(Handle, Canvas, nil, False, @CaptionRect); ThemeServices.DrawText(Canvas, Details, Caption, CaptionRect, DT_LEFT, 0); end; end; procedure TThemedStyle.HookedToolButtonPaint; // Self = TToolButton const TBSpacing = 3; procedure DrawDropDown; var R: TRect; MidX, MidY: Integer; Pts: array of TPoint; begin with TOpenToolButton(Self) do begin R := Types.Rect(Width - DropDownWidth, 1, Width, Height - 1); if Down then OffsetRect(R, 1, 1); Canvas.Pen.Color := clButtonText; Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := clButtonText; MidX := R.Left + (R.Right - R.Left) div 2; MidY := R.Top + (R.Bottom - R.Top) div 2; SetLength(Pts, 4); Pts[0] := Types.Point(MidX - 2, MidY - 1); Pts[1] := Types.Point(MidX + 2, MidY - 1); Pts[2] := Types.Point(MidX, MidY + 1); Pts[3] := Pts[0]; Canvas.Polygon(Pts); if not FToolBar.Flat or (FToolBar.Flat and IsMouseOver(TControl(Self))) then DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]); end; end; function CaptionRect(var R: TRect): TRect; begin with TOpenToolButton(Self) do begin if Style = tbsDropDown then Dec(R.Right, 14); Result := R; if (ToolBar.Images <> nil) and (ToolBar.Images.Count > 0) then begin if ToolBar.List then begin R.Left := R.Left + TBSpacing; R.Right := R.Left + ToolBar.Images.Width; R.Top := ((R.Bottom - R.Top) div 2) - (ToolBar.Images.Height div 2); R.Bottom := R.Top + ToolBar.Images.Height; Result.Left := R.Right; end else begin R.Left := ((R.Right - R.Left) div 2) - (ToolBar.Images.Width div 2); R.Top := R.Top + TBSpacing; R.Right := R.Left + ToolBar.Images.Width; R.Bottom := R.Top + ToolBar.Images.Height; end; end; if ToolBar.List then Result.Top := Result.Top + TBSpacing else if (ToolBar.Images <> nil) and (ToolBar.Images.Count > 0) then Result.Top := R.Bottom + TBSpacing else Result.Top := R.Top + TBSpacing; Result.Left := Result.Left + TBSpacing; Result.Right := Result.Right - TBSpacing; Result.Bottom := Result.Bottom - TBSpacing; end; end; var Details: TThemedElementDetails; Bar: TThemedToolBar; R, CR: TRect; Ind: Boolean; DrawFlags: Integer; begin with TOpenToolButton(Self) do begin if FToolBar = nil then Exit; case Style of tbsButton, tbsCheck: begin if ToolBar.Flat then Bar := ttbButtonNormal else Bar := ttbButtonHot; if IsMouseOver(TControl(Self)) then if Marked then Bar := ttbButtonCheckedHot else Bar := ttbButtonHot; if Down then Bar := ttbButtonPressed; if Indeterminate or Marked then Bar := ttbButtonChecked; if not Enabled then Bar := ttbButtonDisabled; end; tbsDropDown: begin if ToolBar.Flat then Bar := ttbDropDownButtonNormal else Bar := ttbDropDownButtonHot; if IsMouseOver(TControl(Self)) then if Marked then Bar := ttbDropDownButtonCheckedHot else Bar := ttbDropDownButtonHot; if Down then Bar := ttbDropDownButtonPressed; if Indeterminate or Marked then Bar := ttbDropDownButtonChecked; if not Enabled then Bar := ttbDropDownButtonDisabled; end; tbsSeparator, tbsDivider: begin if Toolbar.Align in [alLeft, alRight] then begin Bar := ttbSeparatorVertNormal; if IsMouseOver(TControl(Self)) then if Marked then Bar := ttbSeparatorVertCheckedHot else Bar := ttbSeparatorVertHot; if Down then Bar := ttbSeparatorVertPressed; if Indeterminate or Marked then Bar := ttbSeparatorVertChecked; if not Enabled then Bar := ttbSeparatorVertDisabled; end else begin Bar := ttbSeparatorNormal; if IsMouseOver(TControl(Self)) then if Marked then Bar := ttbSeparatorCheckedHot else Bar := ttbSeparatorHot; if Down then Bar := ttbSeparatorPressed; if Indeterminate or Marked then Bar := ttbSeparatorChecked; if not Enabled then Bar := ttbSeparatorDisabled; end; end; else Exit; end; R := ClientRect; ThemeServices.DrawParentBackground(Handle, Canvas, nil, False, @R); Details := ThemeServices.GetElementDetails(Bar); ThemeServices.DrawElement(Canvas, Details, ClientRect, nil); // draw content if Style in [tbsDropDown, tbsButton, tbsCheck] then begin DrawFlags := Integer(AlignmentFlags_ShowPrefix) or Integer(AlignmentFlags_AlignVCenter); if FToolBar.List then DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignLeft) else DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignHCenter); if Style = tbsDropDown then DrawDropDown; Ind := Indeterminate and not Down; R := ClientRect; CR := CaptionRect(R); if Down then begin OffsetRect(R, 1, 1); OffsetRect(CR, 1, 1); end; //draw image Canvas.Brush.Style := bsSolid; if (ImageIndex > -1) and (ToolBar.Images <> nil) and (ToolBar.Images.Count > 0) then begin if Assigned(ToolBar.HotImages) and IsMouseOver(TControl(Self)) and IsEnabled and (ImageIndex < ToolBar.HotImages.Count) then Toolbar.HotImages.Draw(Canvas, R.Left, R.Top, ImageIndex, itImage, not Ind) else if Assigned(ToolBar.DisabledImages) and not IsEnabled and (ImageIndex < ToolBar.DisabledImages.Count) then Toolbar.DisabledImages.Draw(Canvas, R.Left, R.Top, ImageIndex, itImage, not Ind) else if Assigned(ToolBar.Images) and (ImageIndex < ToolBar.Images.Count) then ToolBar.Images.Draw(Canvas, R.Left, R.Top, ImageIndex, itImage, IsEnabled and not Ind); end; { draw caption } if (Caption <> '') and ToolBar.ShowCaptions then begin Canvas.Brush.Style := bsClear; Canvas.Font := ToolBar.Font; if not IsEnabled then Canvas.Font.Color := clDisabledText; Canvas.TextRect(CR, CR.Left, CR.Top, Caption, DrawFlags); end; end; end; end; { procedure TThemedStyle.HookedToolBarPaint; // Self = TToolBar var Details: TThemedElementDetails; begin with TOpenToolBar(Self) do begin Details := ThemeServices.GetElementDetails(trRebarRoot); ThemeServices.DrawElement(Canvas, Details, ClientRect); end; end; } procedure TThemedStyle.HookedSpeedButtonPaint; // Self = TSpeedButton var P: procedure(Self: TObject); begin with TOpenSpeedButton(Self) do begin // call original method P := @TOpenSpeedButton.Paint; CodeRestore(@TOpenSpeedButton.Paint, ThemedStyle.FCodeSpeedButtonPaint); try P(Self); finally CodeRedirect(@TOpenSpeedButton.Paint, @TThemedStyle.HookedSpeedButtonPaint, ThemedStyle.FCodeSpeedButtonPaint); end; if Flat then begin // redraw button border, no button content if Down or (FState = bsExclusive) then DrawThemedFlatButtonFace(Canvas, ClientRect, True, False); end; end; end; procedure TThemedStyle.HookedControlMouseMove(Shift: TShiftState; X, Y: Integer); // Self = TControl var Index: Integer; NewSection: Integer; P: PInteger; begin with TOpenControl(Self) do begin if TControl(Self) is TCustomHeaderControl then begin Index := ThemedStyle.FControlInfo.IndexOfObject(Self); if Index = -1 then begin Index := ThemedStyle.FControlInfo.AddObject('0', Self); TComponent(Self).FreeNotification(ThemedStyle.FNotifyObject); end; if TOpenCustomHeaderControl(Self).Orientation = hoHorizontal then P := @X else P := @Y; NewSection := QHeader_sectionAt(QHeaderH(THeaderControl(Self).Handle), P^); if NewSection + 1 <> StrToIntDef(ThemedStyle.FControlInfo[Index], 0) then begin ThemedStyle.FControlInfo[Index] := IntToStr(NewSection + 1); PaintControl(TControl(Self)); end; end; // original code Application.HintMouseMessage(TControl(Self), Shift, X, Y); if Assigned(OnMouseMove) then OnMouseMove(TControl(Self), Shift, X, Y); end; end; function TThemedStyle.HookedListViewHeaderEventFilter(Sender: QObjectH; Event: QEventH): Boolean; // Self = TListViewHeader var Method: TMethod; Index: Integer; begin with TPrivateListViewHeader(Self) do begin if FHidden then begin Method.Code := @TOpenCustomHeaderControl.EventFilter; Method.Data := Self; Result := TEventFilter(Method)(Sender, Event); end else begin case QEvent_type(Event) of QEventType_MouseMove: begin if QHeader_orientation(QHeaderH(Handle)) = Orientation_Vertical then Index := QHeader_sectionAt(QHeaderH(Handle), QMouseEvent_y(QMouseEventH(Event))) else Index := QHeader_sectionAt(QHeaderH(Handle), QMouseEvent_x(QMouseEventH(Event))); if Tag <> Index + 1 then begin Tag := Index + 1; PaintWidget(QWidgetH(Sender)); end; end; QEventType_Leave: begin PaintWidget(QWidgetH(Sender)); Tag := 0; end; end; Result := False; end; end; end; procedure TThemedStyle.Initialize; type QClxStyle_drawPushButton_Event = procedure (btn: QPushButtonH; p: QPainterH; var Stage: Integer) of object cdecl; QClxStyle_drawPopupMenuItem_Event = procedure (p: QPainterH; checkable: Boolean; maxpmw: Integer; tab: Integer; mi: QMenuItemH; itemID: Integer; act: Boolean; enabled: Boolean; x: Integer; y: Integer; w: Integer; h: Integer; var Stage: Integer) of object cdecl; var Method: TMethod; F: QFrameH; ViewControl: TOpenCustomViewControl; EventEvent: TEventFilter; begin with Application do begin // Button Style.BeforeDrawButton := EvBeforeDrawButton; Style.AfterDrawButton := EvAfterDrawButton; Style.DrawComboButton := EvDrawComboButton; Style.DrawCheck := EvDrawCheck; Style.DrawRadio := EvDrawRadio; Style.DrawRadioMask := EvDrawRadioMask; Style.DrawFrame := EvDrawFrame; Style.DrawScrollBar := EvDrawScrollBar; Style.DrawTrackBar := EvDrawTrackBar; Style.DrawTrackBarMask := EvDrawTrackBarMask; Style.DrawTrackBarGroove := EvDrawTrackBarGroove; Style.DrawHeaderSection := EvDrawHeaderSection; Style.DrawMenuFrame := EvDrawMenuFrame; Style.MenuItemHeight := EvMenuItemHeight; end; QClxStyle_drawPushButton_Event(Method) := DrawPushButtonHook; QClxStyleHooks_hook_drawPushButton(Hooks, Method); QClxStyle_drawPopupMenuItem_Event(Method) := DrawPopupMenuItemHook; QClxStyleHooks_hook_drawPopupMenuItem(Hooks, Method); {$IFDEF LINUX} QClxStyle_drawToolButton_Event(Method) := DoDrawToolButtonHook; QClxStyleHooks_hook_drawToolButton(Hooks, Method); QClxStyle_drawToolButton2_Event(Method) := DoDrawToolButton2Hook; QClxStyleHooks_hook_drawToolButton2(Hooks, Method); {$ENDIF LINUX} CodeRedirect(@TOpenCustomTabControl.Paint, @TThemedStyle.HookedCustomTabControlPaint, ThemedStyle.FCodeDrawTab); ReplaceVmtField(TTabSheet, @TOpenCustomControl.Paint, @TThemedStyle.HookedTabSheetPaint); CodeRedirect(@TOpenProgressBar.Paint, @TThemedStyle.HookedProgressBarPaint, ThemedStyle.FCodeProgressBarPaint); CodeRedirect(@TOpenWidgetControl.Painting, @TThemedStyle.HookedWidgetControlPainting, ThemedStyle.FCodeWidgetControlPainting); CodeRedirect(@TOpenToolButton.Paint, @TThemedStyle.HookedToolButtonPaint, ThemedStyle.FCodeToolButtonPaint); // CodeRedirect(@TOpenToolBar.Paint, @TThemedStyle.HookedToolBarPaint, ThemedStyle.FCodeToolBarPaint); CodeRedirect(@TOpenSpeedButton.Paint, @TThemedStyle.HookedSpeedButtonPaint, ThemedStyle.FCodeSpeedButtonPaint); CodeRedirect(@TOpenControl.MouseMove, @TThemedStyle.HookedControlMouseMove, ThemedStyle.FCodeControlMouseMove); FDoHotTrack := GetSubCallAddress(@TOpenCustomTabControl.MouseLeave, 2); if FDoHotTrack <> nil then CodeRedirect(FDoHotTrack, @TThemedStyle.HookedDoHotTrack, ThemedStyle.FCodeCustomTabControlDoHotTrack); F := QFrame_create(nil, nil, 0, False); try OrgQFrame_drawFrame := GetAddress_QFrame_drawFrame(F); finally QFrame_destroy(F); end; CodeRedirect(@OrgQFrame_drawFrame, @HookedQFrame_drawFrame, ThemedStyle.FCodeQFrame_drawFrame); ViewControl := TOpenCustomViewControl.Create(nil); try EventEvent := TOpenCustomHeaderControl(ViewControl.Columns.Owner).EventFilter; FOrgListViewHeaderEventFilter := TMethod(EventEvent).Code; finally ViewControl.Free; end; CodeRedirect(FOrgListViewHeaderEventFilter, @TThemedStyle.HookedListViewHeaderEventFilter, FCodeListViewHeaderEventFilters); CodeRedirect(@DrawButtonFace, @DrawThemedButtonFace, ThemedStyle.FCodeDrawButtonFace); CodeRedirect(@DrawEdge, @DrawThemedEdge, ThemedStyle.FCodeDrawEdge); OrgqDrawShadePanel := GetProcAddress(GetModuleHandle(PChar(QtIntf)), QtNamePrefix + 'QClxDrawUtil_DrawShadePanel2'); if Assigned(OrgqDrawShadePanel) then CodeRedirect(@OrgqDrawShadePanel, @DrawThemedShadePanel, ThemedStyle.FCodeDrawShadePanel); FOldAppIdle := TTimer(PrivateApp.FIdleTimer).OnTimer; TTimer(PrivateApp.FIdleTimer).OnTimer := AppIdle; end; procedure TThemedStyle.Finalize; begin if Assigned(PrivateApp.FIdleTimer) then TTimer(PrivateApp.FIdleTimer).OnTimer := FOldAppIdle; CodeRestore(@TOpenCustomTabControl.Paint, ThemedStyle.FCodeDrawTab); ReplaceVmtField(TTabSheet, @TThemedStyle.HookedTabSheetPaint, @TOpenCustomControl.Paint); CodeRestore(@TOpenProgressBar.Paint, ThemedStyle.FCodeProgressBarPaint); CodeRestore(@TOpenWidgetControl.Painting, ThemedStyle.FCodeWidgetControlPainting); CodeRestore(@TOpenToolButton.Paint, ThemedStyle.FCodeToolButtonPaint); // CodeRestore(@TOpenToolBar.Paint, ThemedStyle.FCodeToolBarPaint); CodeRestore(@TOpenSpeedButton.Paint, ThemedStyle.FCodeSpeedButtonPaint); CodeRestore(@TOpenControl.MouseMove, ThemedStyle.FCodeControlMouseMove); CodeRestore(FOrgListViewHeaderEventFilter, FCodeListViewHeaderEventFilters); if FDoHotTrack <> nil then CodeRestore(FDoHotTrack, ThemedStyle.FCodeCustomTabControlDoHotTrack); CodeRestore(@DrawButtonFace, ThemedStyle.FCodeDrawButtonFace); CodeRestore(@DrawEdge, ThemedStyle.FCodeDrawEdge); CodeRestore(@OrgQFrame_drawFrame, ThemedStyle.FCodeQFrame_drawFrame); if Assigned(OrgqDrawShadePanel) then CodeRestore(@OrgqDrawShadePanel, ThemedStyle.FCodeDrawShadePanel); end; procedure TThemedStyle.AppIdle(Sender: TObject); var Control: TControl; App: TPrivateApplication; begin App := TPrivateApplication(Application); Control := App.FMouseControl; FOldAppIdle(Sender); if Control <> App.FMouseControl then begin if Control <> nil then MouseLeave(Control); if App.FMouseControl <> nil then MouseEnter(App.FMouseControl); end; end; procedure TThemedStyle.MouseEnter(Control: TControl); begin if (Control is TButton) or (Control is TCustomHeaderControl) or (Control is TScrollBar) then RepaintControl(Control); if (Control is TSpeedButton) and not TSpeedButton(Control).Flat then TOpenSpeedButton(Control).Paint; end; procedure TThemedStyle.MouseLeave(Control: TControl); begin if (Control is TButton) or (Control is TCustomHeaderControl) or (Control is TScrollBar) then RepaintControl(Control); if (Control is TSpeedButton) then begin if TSpeedButton(Control).Flat then Control.Invalidate else TOpenSpeedButton(Control).Paint; end else if Control is TCustomHeaderControl then FNotifyObject.Notification(Control, opRemove); end; function TThemedStyle.GetActive: Boolean; begin Result := (Application.Style = Self) and (Application.Style.DefaultStyle = dsSystemDefault); end; procedure TThemedStyle.SetActive(const Value: Boolean); begin SetDefaultStyle(dsSystemDefault); end; procedure TThemedStyle.SetDefaultStyle(const Value: TDefaultStyle); begin if Value <> DefaultStyle then begin if Value = dsSystemDefault then begin Application.Style := nil; // destroys ThemedStyle TThemedStyle.Create; // assigns Application.Style to ThemedStyle Exit; end else if Active then Finalize; inherited SetDefaultStyle(Value); end; end; { TThemedStyleNotify } procedure TThemedStyleNotify.Notification(AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then begin Index := ThemedStyle.FControlInfo.IndexOfObject(AComponent); if Index >= 0 then ThemedStyle.FControlInfo.Delete(Index); end; end; initialization ThemedStyle := nil; ThemeServices.ThemesDir:=getSystemInfo(XP_BASE_DIR); if ThemeServices.ThemesEnabled then TThemedStyle.Create; // sets ThemedStyle application.font.name:='tahoma'; application.font.Size:=11; finalization if ThemedStyle <> nil then Application.Style := nil; // frees ThemedStyle end.
unit aeVectorBuffer; interface uses windows, classes, types, dglOpenGL, aeLoggingManager; type TaeVectorBuffer = class private // opengl buffer ID for this data _gpuBufferID: Cardinal; _data: Array of TVectorArray; _index: Cardinal; _critsect: TRTLCriticalSection; public constructor Create; destructor Destroy; override; /// <summary> /// Preallocate memory!. /// </summary> procedure PreallocateVectors(nVectors: Cardinal); /// <summary> /// Add a vector range to the array. vector_count is the number of vectors (12 byte chunks). /// </summary> procedure AddVectorRange(v0: PSingle; vector_count: integer); /// <summary> /// Add a single vertex to the array. /// </summary> procedure AddVector(v0: TVectorArray); /// <summary> /// Adds three vertices to the array. /// </summary> procedure Add3Vectors(v0, v1, v2: TVectorArray); /// <summary> /// Clear the vector array. /// </summary> procedure Clear; /// <summary> /// Returns true if buffer is empty. /// </summary> function Empty: boolean; /// <summary> /// Reduces the capacity to the actual length. Cuts of excess space that is not used. /// </summary> procedure Pack; /// <summary> /// Returns number of vectors in this buffer. /// </summary> function count: Cardinal; /// <summary> /// Gets the OpenGL Buffer ID. /// </summary> function GetOpenGLBufferID: Cardinal; /// <summary> /// Uploads data to GPU as vertex data. /// </summary> function UploadToGPU: boolean; /// <summary> /// Deletes data on GPU. /// </summary> function RemoveFromGPU: boolean; /// <summary> /// Returns pointer to start of vector array. /// </summary> function GetVectorData: Pointer; /// <summary> /// Returns certain vector of vector array. /// </summary> function GetVector(indx: Cardinal): TVectorArray; /// <summary> /// Locks this buffer for other threads. /// </summary> procedure Lock; /// <summary> /// Unlocks this buffer for other threads. /// </summary> procedure Unlock; end; implementation { TaeVectorBuffer } procedure TaeVectorBuffer.Add3Vectors(v0, v1, v2: TVectorArray); begin self.AddVector(v0); self.AddVector(v1); self.AddVector(v2); end; procedure TaeVectorBuffer.AddVector(v0: TVectorArray); begin self._data[_index] := v0; inc(_index); end; procedure TaeVectorBuffer.AddVectorRange(v0: PSingle; vector_count: integer); begin CopyMemory(@self._data[self._index], v0, vector_count * 12); inc(self._index, vector_count); end; procedure TaeVectorBuffer.Clear; begin self._index := 0; SetLength(self._data, 0); Finalize(self._data); self._data := nil; end; function TaeVectorBuffer.count: Cardinal; begin Result := self._index; end; constructor TaeVectorBuffer.Create; begin self.Clear; InitializeCriticalSection(self._critsect); self._gpuBufferID := 0; end; destructor TaeVectorBuffer.Destroy; begin self.Clear; self.RemoveFromGPU; DeleteCriticalSection(self._critsect); inherited; end; function TaeVectorBuffer.Empty: boolean; begin Result := self._index = 0; end; function TaeVectorBuffer.GetOpenGLBufferID: Cardinal; begin Result := self._gpuBufferID; end; function TaeVectorBuffer.GetVector(indx: Cardinal): TVectorArray; begin Result := self._data[indx]; end; function TaeVectorBuffer.GetVectorData: Pointer; begin Result := @self._data[0]; end; procedure TaeVectorBuffer.Lock; begin EnterCriticalSection(self._critsect); end; procedure TaeVectorBuffer.Pack; begin SetLength(self._data, self._index); end; procedure TaeVectorBuffer.PreallocateVectors(nVectors: Cardinal); begin SetLength(self._data, nVectors); end; function TaeVectorBuffer.RemoveFromGPU: boolean; begin if (self._gpuBufferID > 0) then begin glDeleteBuffers(1, @self._gpuBufferID); self._gpuBufferID := 0; Result := true; end; end; procedure TaeVectorBuffer.Unlock; begin LeaveCriticalSection(self._critsect); end; function TaeVectorBuffer.UploadToGPU: boolean; begin // if buffer object is still 0, we need to create one first! if (self._gpuBufferID = 0) then begin // create a buffer object glGenBuffers(1, @self._gpuBufferID); // mark buffer as active glBindBuffer(GL_ARRAY_BUFFER, self._gpuBufferID); // upload data glBufferData(GL_ARRAY_BUFFER, self._index * 3 * 4, @self._data[0], GL_STATIC_DRAW); Result := true; end else begin AE_LOGGING.AddEntry('TaeVectorBuffer.UploadToGPU() : Attempt to overwrite existing buffer with a new one!', AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); Result := false; end; end; end.
{ duallist unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit duallist; interface {$I rx.inc} uses Classes, Controls; type { TDualListDialog } TDualListDialog = class(TComponent) private FCtl3D: Boolean; FSorted: Boolean; FTitle:string; FLabel1Caption: TCaption; FLabel2Caption: TCaption; FOkBtnCaption: TCaption; FCancelBtnCaption: TCaption; FHelpBtnCaption: TCaption; FHelpContext: THelpContext; FList1: TStrings; FList2: TStrings; FShowHelp: Boolean; procedure SetList1(Value: TStrings); procedure SetList2(Value: TStrings); function IsLabel1Custom: Boolean; function IsLabel2Custom: Boolean; function IsOkBtnCustom: Boolean; function IsCancelBtnCustom: Boolean; function IsHelpBtnCustom: Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; published property Ctl3D: Boolean read FCtl3D write FCtl3D default True; property Sorted: Boolean read FSorted write FSorted; property Title: string read FTitle write FTitle; property Label1Caption: TCaption read FLabel1Caption write FLabel1Caption stored IsLabel1Custom; property Label2Caption: TCaption read FLabel2Caption write FLabel2Caption stored IsLabel2Custom; property OkBtnCaption: TCaption read FOkBtnCaption write FOkBtnCaption stored IsOkBtnCustom; property CancelBtnCaption: TCaption read FCancelBtnCaption write FCancelBtnCaption stored IsCancelBtnCustom; property HelpBtnCaption: TCaption read FHelpBtnCaption write FHelpBtnCaption stored IsHelpBtnCustom; property HelpContext: THelpContext read FHelpContext write FHelpContext; property List1: TStrings read FList1 write SetList1; property List2: TStrings read FList2 write SetList2; property ShowHelp: Boolean read FShowHelp write FShowHelp default True; end; implementation uses SysUtils, Forms, FDualLst, VCLUtils, LCLStrConsts, rxconst; { TDualListDialog } constructor TDualListDialog.Create(AOwner: TComponent); begin inherited Create(AOwner); FCtl3D := True; FShowHelp := True; FList1 := TStringList.Create; FList2 := TStringList.Create; FLabel1Caption := SDualListSrcCaption; FLabel2Caption := SDualListDestCaption; OkBtnCaption := rsmbOK; CancelBtnCaption := rsmbCancel; HelpBtnCaption := rsmbHelp; Title:=SDualListCaption; end; destructor TDualListDialog.Destroy; begin List1.Free; List2.Free; inherited Destroy; end; procedure TDualListDialog.SetList1(Value: TStrings); begin FList1.Assign(Value); end; procedure TDualListDialog.SetList2(Value: TStrings); begin FList2.Assign(Value); end; function TDualListDialog.IsLabel1Custom: Boolean; begin Result := CompareStr(Label1Caption, SDualListSrcCaption) <> 0; end; function TDualListDialog.IsLabel2Custom: Boolean; begin Result := CompareStr(Label2Caption, SDualListDestCaption) <> 0; end; function TDualListDialog.IsOkBtnCustom: Boolean; begin Result := CompareStr(OkBtnCaption, rsmbOK) <> 0; end; function TDualListDialog.IsCancelBtnCustom: Boolean; begin Result := CompareStr(CancelBtnCaption, rsmbCancel) <> 0; end; function TDualListDialog.IsHelpBtnCustom: Boolean; begin Result := CompareStr(HelpBtnCaption, rsmbHelp) <> 0; end; function TDualListDialog.Execute: Boolean; var Form: TDualListForm; begin Form := TDualListForm.Create(Application); try with Form do begin Ctl3D := Self.Ctl3D; if NewStyleControls then Font.Style := []; ShowHelp := Self.ShowHelp; SrcList.Sorted := Sorted; DstList.Sorted := Sorted; SrcList.Items := List1; DstList.Items := List2; if Self.Title <> '' then Form.Caption := Self.Title; if Label1Caption <> '' then SrcLabel.Caption := Label1Caption; if Label2Caption <> '' then DstLabel.Caption := Label2Caption; ButtonPanel1.OKButton.Caption := OkBtnCaption; ButtonPanel1.CancelButton.Caption := CancelBtnCaption; ButtonPanel1.HelpButton.Caption := HelpBtnCaption; HelpContext := Self.HelpContext; ButtonPanel1.HelpButton.HelpContext := HelpContext; end; Result := (Form.ShowModal = mrOk); if Result then begin List1 := Form.SrcList.Items; List2 := Form.DstList.Items; end; finally Form.Free; end; end; end.
unit atLogger; // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atLogger.pas" // Стереотип: "UtilityPack" // Элемент модели: "atLogger" MUID: (4808B6A20344) interface uses l3IntfUses , atInterfaces , Windows , SyncObjs , SysUtils ; type PFormatSettings = ^TFormatSettings; TatLogMessageType = ( lmtNone , lmtInfo , lmtWarning , lmtError , lmtException );//TatLogMessageType TatLogger = class(TInterfacedObject, IatLogger) private f_TlsIndex: DWORD; f_CS: TCriticalSection; private function GetFormatSettings: PFormatSettings; virtual; protected procedure WriteMessage(const formattedMsg: AnsiString); virtual; abstract; procedure AddMessage(msgType: TatLogMessageType; const msg: AnsiString); function Info(const msg: AnsiString): AnsiString; overload; function Warning(const msg: AnsiString): AnsiString; overload; function Error(const msg: AnsiString): AnsiString; overload; procedure Exception(ex: Exception; const prefix: AnsiString = ''); function Info(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; function Warning(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; function Error(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; public constructor Create; reintroduce; destructor Destroy; override; end;//TatLogger TatLoggerStub = class(TInterfacedObject, IatLogger) protected function Info(const msg: AnsiString): AnsiString; overload; function Warning(const msg: AnsiString): AnsiString; overload; function Error(const msg: AnsiString): AnsiString; overload; procedure Exception(ex: Exception; const prefix: AnsiString = ''); function Info(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; function Warning(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; function Error(const aFormat: AnsiString; const anArgs: array of const): AnsiString; overload; end;//TatLoggerStub TatConsoleLogger = class(TatLogger) protected procedure WriteMessage(const formattedMsg: AnsiString); override; end;//TatConsoleLogger TatFileLogger = class(TatLogger) private f_File: Text; protected procedure WriteMessage(const formattedMsg: AnsiString); override; public constructor Create(const fileName: AnsiString); reintroduce; destructor Destroy; override; end;//TatFileLogger var Logger: IatLogger; var DbgLogger: IatLogger; implementation uses l3ImplUses //#UC START# *4808B6A20344impl_uses* //#UC END# *4808B6A20344impl_uses* ; procedure TatLogger.AddMessage(msgType: TatLogMessageType; const msg: AnsiString); //#UC START# *4808B7CF01A2_4808A17901C6_var* type TatLogMessageHeaders = array[TatLogMessageType] of string; const LogMessageHeaders : TatLogMessageHeaders = ('', 'INFO', 'WARNING', 'ERROR', 'EXCEPTION'); var strToAdd : String; dateTime : String; //#UC END# *4808B7CF01A2_4808A17901C6_var* begin //#UC START# *4808B7CF01A2_4808A17901C6_impl* case msgType of lmtInfo, lmtWarning, lmtError, lmtException : begin // создаем строку для записи DateTimeToString(dateTime, 'dd-mm-yyyy hh:nn:ss.zzz', Now, GetFormatSettings^); strToAdd := dateTime + ' | ' + IntToStr(GetCurrentThreadId) + ' | ' + LogMessageHeaders[msgType] + ': ' + msg; end; lmtNone : Exit; // нет сообщения end; // пишем f_CS.Acquire; try WriteMessage(strToAdd); finally f_CS.Leave; end; //#UC END# *4808B7CF01A2_4808A17901C6_impl* end;//TatLogger.AddMessage constructor TatLogger.Create; //#UC START# *4808B8250055_4808A17901C6_var* //#UC END# *4808B8250055_4808A17901C6_var* begin //#UC START# *4808B8250055_4808A17901C6_impl* inherited; // f_TlsIndex := TlsAlloc; if f_TlsIndex = $FFFFFFFF then Raise SysUtils.Exception.Create('Can not allocate tls index!'); f_CS := TCriticalSection.Create; //#UC END# *4808B8250055_4808A17901C6_impl* end;//TatLogger.Create function TatLogger.GetFormatSettings: PFormatSettings; //#UC START# *5076D63901B2_4808A17901C6_var* //#UC END# *5076D63901B2_4808A17901C6_var* begin //#UC START# *5076D63901B2_4808A17901C6_impl* Result := TlsGetValue(f_TlsIndex); if Result = nil then if GetLastError = NO_ERROR then begin New(Result); // это вызовется для каждого вошедшего сюда потока, а освобождать негде, поэтому будет утечка GetLocaleFormatSettings(SysLocale.DefaultLCID, Result^); TlsSetValue(f_TlsIndex, Result); end else Raise SysUtils.Exception.Create('Can not get valid tls value!'); //#UC END# *5076D63901B2_4808A17901C6_impl* end;//TatLogger.GetFormatSettings function TatLogger.Info(const msg: AnsiString): AnsiString; //#UC START# *4808B42B0093_4808A17901C6_var* //#UC END# *4808B42B0093_4808A17901C6_var* begin //#UC START# *4808B42B0093_4808A17901C6_impl* AddMessage(lmtInfo, msg); Result := msg; //#UC END# *4808B42B0093_4808A17901C6_impl* end;//TatLogger.Info function TatLogger.Warning(const msg: AnsiString): AnsiString; //#UC START# *4808B44F022E_4808A17901C6_var* //#UC END# *4808B44F022E_4808A17901C6_var* begin //#UC START# *4808B44F022E_4808A17901C6_impl* AddMessage(lmtWarning, msg); Result := msg; //#UC END# *4808B44F022E_4808A17901C6_impl* end;//TatLogger.Warning function TatLogger.Error(const msg: AnsiString): AnsiString; //#UC START# *4808B45F00DA_4808A17901C6_var* //#UC END# *4808B45F00DA_4808A17901C6_var* begin //#UC START# *4808B45F00DA_4808A17901C6_impl* AddMessage(lmtError, msg); Result := msg; //#UC END# *4808B45F00DA_4808A17901C6_impl* end;//TatLogger.Error procedure TatLogger.Exception(ex: Exception; const prefix: AnsiString = ''); //#UC START# *4808B46D01DF_4808A17901C6_var* var l_P : String; //#UC END# *4808B46D01DF_4808A17901C6_var* begin //#UC START# *4808B46D01DF_4808A17901C6_impl* l_P := prefix; if Length(l_P) > 0 then l_P := l_P + ' '; AddMessage( lmtException, l_P + 'Class: "' + ex.ClassName + '"; Message: "' + ex.Message + '"' ); //#UC END# *4808B46D01DF_4808A17901C6_impl* end;//TatLogger.Exception function TatLogger.Info(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A74A700FD_4808A17901C6_var* //#UC END# *484A74A700FD_4808A17901C6_var* begin //#UC START# *484A74A700FD_4808A17901C6_impl* Result := Info( Format(aFormat, anArgs, GetFormatSettings^) ); //#UC END# *484A74A700FD_4808A17901C6_impl* end;//TatLogger.Info function TatLogger.Warning(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A76C6037D_4808A17901C6_var* //#UC END# *484A76C6037D_4808A17901C6_var* begin //#UC START# *484A76C6037D_4808A17901C6_impl* Result := Warning( Format(aFormat, anArgs, GetFormatSettings^) ); //#UC END# *484A76C6037D_4808A17901C6_impl* end;//TatLogger.Warning function TatLogger.Error(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A76ED00FD_4808A17901C6_var* //#UC END# *484A76ED00FD_4808A17901C6_var* begin //#UC START# *484A76ED00FD_4808A17901C6_impl* Result := Error( Format(aFormat, anArgs, GetFormatSettings^) ); //#UC END# *484A76ED00FD_4808A17901C6_impl* end;//TatLogger.Error destructor TatLogger.Destroy; //#UC START# *48077504027E_4808A17901C6_var* //#UC END# *48077504027E_4808A17901C6_var* begin //#UC START# *48077504027E_4808A17901C6_impl* TlsFree(f_TlsIndex); FreeAndNil(f_CS); // inherited; //#UC END# *48077504027E_4808A17901C6_impl* end;//TatLogger.Destroy function TatLoggerStub.Info(const msg: AnsiString): AnsiString; //#UC START# *4808B42B0093_4808BAD201EB_var* //#UC END# *4808B42B0093_4808BAD201EB_var* begin //#UC START# *4808B42B0093_4808BAD201EB_impl* // это заглушка //#UC END# *4808B42B0093_4808BAD201EB_impl* end;//TatLoggerStub.Info function TatLoggerStub.Warning(const msg: AnsiString): AnsiString; //#UC START# *4808B44F022E_4808BAD201EB_var* //#UC END# *4808B44F022E_4808BAD201EB_var* begin //#UC START# *4808B44F022E_4808BAD201EB_impl* // это заглушка //#UC END# *4808B44F022E_4808BAD201EB_impl* end;//TatLoggerStub.Warning function TatLoggerStub.Error(const msg: AnsiString): AnsiString; //#UC START# *4808B45F00DA_4808BAD201EB_var* //#UC END# *4808B45F00DA_4808BAD201EB_var* begin //#UC START# *4808B45F00DA_4808BAD201EB_impl* // это заглушка //#UC END# *4808B45F00DA_4808BAD201EB_impl* end;//TatLoggerStub.Error procedure TatLoggerStub.Exception(ex: Exception; const prefix: AnsiString = ''); //#UC START# *4808B46D01DF_4808BAD201EB_var* //#UC END# *4808B46D01DF_4808BAD201EB_var* begin //#UC START# *4808B46D01DF_4808BAD201EB_impl* // это заглушка //#UC END# *4808B46D01DF_4808BAD201EB_impl* end;//TatLoggerStub.Exception function TatLoggerStub.Info(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A74A700FD_4808BAD201EB_var* //#UC END# *484A74A700FD_4808BAD201EB_var* begin //#UC START# *484A74A700FD_4808BAD201EB_impl* // это заглушка //#UC END# *484A74A700FD_4808BAD201EB_impl* end;//TatLoggerStub.Info function TatLoggerStub.Warning(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A76C6037D_4808BAD201EB_var* //#UC END# *484A76C6037D_4808BAD201EB_var* begin //#UC START# *484A76C6037D_4808BAD201EB_impl* // это заглушка //#UC END# *484A76C6037D_4808BAD201EB_impl* end;//TatLoggerStub.Warning function TatLoggerStub.Error(const aFormat: AnsiString; const anArgs: array of const): AnsiString; //#UC START# *484A76ED00FD_4808BAD201EB_var* //#UC END# *484A76ED00FD_4808BAD201EB_var* begin //#UC START# *484A76ED00FD_4808BAD201EB_impl* // это заглушка //#UC END# *484A76ED00FD_4808BAD201EB_impl* end;//TatLoggerStub.Error procedure TatConsoleLogger.WriteMessage(const formattedMsg: AnsiString); //#UC START# *4808B7840086_4808BB4F028A_var* var tmpStr : String; //#UC END# *4808B7840086_4808BB4F028A_var* begin //#UC START# *4808B7840086_4808BB4F028A_impl* SetLength(tmpStr, Length(formattedMsg) + 1); UniqueString(tmpStr); CharToOem(PAnsiChar(formattedMsg), PAnsiChar(tmpStr)); WriteLn(tmpStr); //#UC END# *4808B7840086_4808BB4F028A_impl* end;//TatConsoleLogger.WriteMessage constructor TatFileLogger.Create(const fileName: AnsiString); //#UC START# *4808BC73011C_4808BC490355_var* //#UC END# *4808BC73011C_4808BC490355_var* begin //#UC START# *4808BC73011C_4808BC490355_impl* inherited Create; // AssignFile(f_File, fileName); if FileExists(fileName) then Append(f_File) else Rewrite(f_File); WriteLn(f_File, ''); //#UC END# *4808BC73011C_4808BC490355_impl* end;//TatFileLogger.Create procedure TatFileLogger.WriteMessage(const formattedMsg: AnsiString); //#UC START# *4808B7840086_4808BC490355_var* //#UC END# *4808B7840086_4808BC490355_var* begin //#UC START# *4808B7840086_4808BC490355_impl* WriteLn(f_File, formattedMsg); Flush(f_File); //#UC END# *4808B7840086_4808BC490355_impl* end;//TatFileLogger.WriteMessage destructor TatFileLogger.Destroy; //#UC START# *48077504027E_4808BC490355_var* //#UC END# *48077504027E_4808BC490355_var* begin //#UC START# *48077504027E_4808BC490355_impl* CloseFile(f_File); // inherited; //#UC END# *48077504027E_4808BC490355_impl* end;//TatFileLogger.Destroy initialization //#UC START# *4808BA9401C5* Logger := TatConsoleLogger.Create; DbgLogger := TatLoggerStub.Create; //#UC END# *4808BA9401C5* finalization //#UC START# *4808BAA1027F* Logger := nil; DbgLogger := nil; //#UC END# *4808BAA1027F* end.
unit uXMLHelpers; { Ollivier Civiol - 2019 ollivier@civiol.eu https://ollivierciviolsoftware.wordpress.com/ } {$mode objfpc}{$H+} interface uses SysUtils, Variants, Classes, ComCtrls, Controls, Grids, uxmldoc; //MSAccess, dxmdaset; const CS_DATASETS = 'DataSets'; CS_MAXLEN_TEXT = 30; type TXMLProgress = procedure(aMin, aMax, aPosition : Integer) of object; { TXMLQUery = CLass helper for TMSQuery public procedure SaveToXml(aXMLDoc : TXMLDoc; OnProgress : TXMLProgress = nil); End; TXMLDataSet = class helper for TdxMemData public procedure SaveToXml(aXMLDoc : TXMLDoc; OnProgress : TXMLProgress = nil); procedure LoadFromXml(aNode : TXmlElement; OnProgress : TXMLProgress = nil); end; } TTreeView = Class(ComCtrls.TTreeView) private function GetSelectedXML:TXMLElement; inline; protected public procedure Init(zNode : TXmlElement; OnProgress : TXMLProgress = nil); procedure AddTreeNodes(Elem: TXmlElement; ANode: TTreeNode; OnProgress : TXMLProgress = nil); property SelectedXML : TXMLElement read GetSelectedXML; End; TStringGrid = class(Grids.TStringGrid) private FNode : TXMLElement; protected procedure Resize; override; public procedure ClearGrid; procedure Init(aNode : TXmlElement; OnProgress : TXMLProgress = nil); property Node : TXMLElement read FNode; end; implementation uses Forms, Dialogs; { type DataTypeInfo = record Name : string; DataType : TFieldType; end; const DataTypes : array[0..49] of DataTypeInfo = ( (Name:'ftUnknown'; DAtaType:ftUnknown), (Name:'ftString'; DAtaType:ftString), (Name:'ftSmallint'; DAtaType:ftSmallint), (Name:'ftInteger'; DAtaType:ftInteger), (Name:'ftWord'; DAtaType:ftWord), (Name:'ftBoolean'; DAtaType:ftBoolean), (Name:'ftFloat'; DAtaType:ftFloat), (Name:'ftCurrency'; DAtaType:ftCurrency), (Name:'ftBCD'; DAtaType:ftBCD), (Name:'ftDate'; DAtaType:ftDate), (Name:'ftTime'; DAtaType:ftTime), (Name:'ftDateTime'; DAtaType:ftDateTime), (Name:'ftBytes'; DAtaType:ftBytes), (Name:'ftVarBytes'; DAtaType:ftVarBytes), (Name:'ftAutoInc'; DAtaType:ftAutoInc), (Name:'ftBlob'; DAtaType:ftBlob), (Name:'ftMemo'; DAtaType:ftMemo), (Name:'ftGraphic'; DAtaType:ftGraphic), (Name:'ftFmtMemo'; DAtaType:ftFmtMemo), (Name:'ftParadoxOle'; DAtaType:ftParadoxOle), (Name:'ftDBaseOle'; DAtaType:ftDBaseOle), (Name:'ftTypedBinary'; DAtaType:ftTypedBinary), (Name:'ftCursor'; DAtaType:ftCursor), (Name:'ftFixedChar'; DAtaType:ftFixedChar), (Name:'ftWideString'; DAtaType:ftWideString), (Name:'ftLargeint'; DAtaType:ftLargeint), (Name:'ftADT'; DAtaType:ftADT), (Name:'ftArray'; DAtaType:ftArray), (Name:'ftReference'; DAtaType:ftReference), (Name:'ftDataSet'; DAtaType:ftDataSet), (Name:'ftOraBlob'; DAtaType:ftOraBlob), (Name:'ftOraClob'; DAtaType:ftOraClob), (Name:'ftVariant'; DAtaType:ftVariant), (Name:'ftInterface'; DAtaType:ftInterface), (Name:'ftIDispatch'; DAtaType:ftIDispatch), (Name:'ftGuid'; DAtaType:ftGuid), (Name:'ftTimeStamp'; DAtaType:ftTimeStamp), (Name:'ftFMTBcd'; DAtaType:ftFMTBcd), (Name:'ftFixedWideChar'; DAtaType:ftFixedWideChar), (Name:'ftWideMemo'; DAtaType:ftWideMemo), (Name:'ftOraTimeStamp'; DAtaType:ftOraTimeStamp), (Name:'ftOraInterval'; DAtaType:ftOraInterval), (Name:'ftLongWord'; DAtaType:ftLongWord), (Name:'ftShortint'; DAtaType:ftShortint), (Name:'ftByte'; DAtaType:ftByte), (Name:'ftConnection'; DAtaType:ftConnection), (Name:'ftParams'; DAtaType:ftParams), (Name:'ftStream'; DAtaType:ftStream), (Name:'ftTimeStampOffset'; DAtaType:ftTimeStampOffset), (Name:'ftObject'; DAtaType:ftObject) ); function StringToType(aType : String):TFieldType; var z : integer; begin result := ftString; for z := Low(DataTypes) to High(DataTypes) do if DataTypes[z].Name = aType then begin result := DataTypes[z].DataType; exit; end; end; function TypeToString(aType : TFieldType):string; var z : integer; begin for z := Low(DataTypes) to High(DataTypes) do if DataTypes[z].DataType = aType then begin result := DataTypes[z].Name; exit; end; end; procedure DatasetToXml(aDataSet : TDataSet; aNode : TXMLElement; OnProgress : TXMLProgress = nil); var m, p, j : integer; bm : TArray<Byte>; begin // save field names with aDataSet do begin DisableControls; try bm := GetBookmark; Last; m := RecordCount; First; // save fields with aNode.AddChildNode('Fields') do for j := 0 to FieldCount - 1 do with AddChildNode('Field') do begin SetAttribute('name', Fields[j].FieldName); SetAttribute('type', TypeToString(Fields[j].DataType)); SetAttributeBool('isblob', Fields[j].IsBlob); SetAttribute('displayname', Fields[j].DisplayName); SetAttribute('editmask', Fields[j].EditMask); SetAttributeBool('isindexed', Fields[j].IsIndexField); SetAttribute('size', Fields[j].Size); SetAttribute('DisplayLabel', Fields[j].DisplayLabel); SetAttribute('DisplayWidth', Fields[j].DisplayWidth); end; // save data p := 0; with aNode.AddChildNode('Rows') do while not eof do begin with AddChildNode('Row') do for j := 0 to FieldCount - 1 do with Fields[j] do if (not IsNull) then if IsBlob then SetAttributeHex(FieldName, AsBytes) else SetAttribute(FieldName, AsVariant); Next; if Assigned(OnProgress) then OnProgress(0, m, p); Inc(p); end; finally if Assigned(OnProgress) then OnProgress(0, 0, 0); GotoBookmark(bm); EnableControls; end; end; end; procedure TXMLQUery.SaveToXml(aXMLDoc : TXMLDoc; OnProgress : TXMLProgress = nil); var aNode : TXMLElement; s : string; begin // save field names aNode := aXmlDoc.GetNodeFromPath('/'+CS_DATASETS); // get table name from select s := inputbox('Dataset Name', 'Choose a name the dataset', '_'+name); aNode := aNode.GetNode(s); DatasetToXml(self, aNode, OnProgress); end; procedure TXMLDataSet.SaveToXml(aXMLDoc : TXmlDoc; OnProgress : TXMLProgress = nil); var aNode : TXMLElement; begin aNode := aXmlDoc.GetNodeFromPath('/'+CS_DATASETS); aNode := aNode.GetNode(Name); DatasetToXml(self, aNode, OnProgress); end; procedure TXMLDataSet.LoadFromXml(aNode : TXmlElement; OnProgress : TXMLProgress = nil); var i, j, m, p : integer; AField: TField; aArr : TArray<Byte>; begin DisableControls; try Close; while Fields.Count > 0 do Fields[0].Free; name := aNode.TagName; FieldDefs.Clear; // create fields with aNode.GetNode('Fields') do for I := 0 to NbElements - 1 do with Elements[i] do with FieldDefs.AddFieldDef do begin Name := GetAttribute('name'); DataType := StringToType(GetAttribute('type')); DisplayName := GetAttribute('displayname'); Size := GetAttribute('size'); with CreateField(Self) do begin Tag := Integer(GetAttributeBool('isblob')); DisplayLabel := GetAttribute('DisplayLabel'); DisplayWidth := GetAttribute('DisplayWidth'); EditMask := GetAttribute('EditMask'); end; end; Open; // load data with aNode.GetNode('Rows') do begin p := 0; m := NbElements; for I := 0 to NbElements - 1 do with Elements[i] do begin Append; for J := 0 to Attributes.Count - 1 do begin AField := FieldByName(AttributeName[J]); // blobs if Boolean(AField.Tag) then begin GetattributeHex(AttributeName[J], aArr); AField.AsBytes := aArr; end else AField.AsVariant := GetAttribute(AttributeName[J]); end; Post; if Assigned(OnProgress) then OnProgress(0, m, p); inc(p); end; end; finally if Assigned(OnProgress) then OnProgress(0, 0, 0); First; EnableControls; end; end; } function MaxLengthText(const aText : string; MaxLen : integer):String; begin result := aText; if Length(Result) > MaxLen then result := Copy(Result, 1, MaxLen) + '...'; end; function MakeNodeText(aElement: TXmlElement): String; var theattribs: string; begin // create node name result := aElement.TagName; // append attributes to name theattribs := aElement.Attribs; if (theattribs <> '') or (aElement.Text <> '') then result := result + ' ('; if theattribs <> '' then result := result + theattribs + ' '; if aElement.Text <> '' then result := result + 'Text=' + MaxLengthText(aElement.Text, CS_MAXLEN_TEXT); if (theattribs <> '') or (aElement.Text <> '') then result := result + ')'; end; procedure TTreeView.AddTreeNodes(Elem: TXmlElement; ANode: TTreeNode; OnProgress : TXMLProgress = nil); var i: Integer; t: TTreeNode; s: String; begin with Elem do begin for i := 0 to NbElements - 1 do begin // create node name s := MakeNodeText(Elements[i]); // add node t := Items.AddChildObject(ANode, s, Elements[i]); // add text if any //if Elements[i].Text <> '' then // Items.AddChildObject(t, Elements[i].Text, Elements[i]); // if childnodes then add them if Elements[i].NbElements > 0 then AddTreeNodes(Elements[i], t); end; end; end; function TTreeView.GetSelectedXML:TXMLElement; begin result := TXMLElement(Selected.Data); end; procedure TTreeView.Init(zNode : TXmlElement; OnProgress : TXMLProgress = nil); var attrib, ss: string; procedure ExpandTree(ANode: TTreeNode; aMaxLvl: Integer); var tn: TTreeNode; begin if ANode.Level > aMaxLvl then Exit; ANode.Expand(False); tn := ANode.GetFirstChild; if Assigned(tn) then repeat tn.Expand(False); if tn.HasChildren then ExpandTree(tn, aMaxLvl); tn := tn.GetNextChild(tn); until tn = nil; end; begin if zNode.NbElements > 0 then With Items do try Screen.Cursor := crHourGlass; BeginUpdate; Clear; ss := zNode.TagName; attrib := zNode.Attribs; if (attrib <> '') or (zNode.Text <> '') then ss := ss + ' ('; if attrib <> '' then ss := ss + attrib + ' '; if zNode.Text <> '' then ss := ss + 'Text=' + MaxLengthText(zNode.Text, CS_MAXLEN_TEXT); if (attrib <> '') or (zNode.Text <> '') then ss :=ss + ')'; AddTreeNodes(zNode, AddChildObject(nil, ss, zNode), OnProgress); // expand ExpandTree(Items[0], 1); Selected := Items[0].GetFirstChild; Selected.MakeVisible; finally EndUpdate; Screen.Cursor := crDefault; end; end; procedure TStringGrid.Resize; var i, z : Integer; begin inherited; if Colcount < 2 then Exit; // first col = 1/3 ColWidths[0] := width div 3; // other cols z := ((Width - ColWidths[0]) - 20) div (ColCount - 1); for i := 1 to Colcount - 1 do begin ColWidths[i] := z; end; end; procedure TStringGrid.ClearGrid; begin RowCount := 1; RowCount := 2; ColCount := 2; FixedCols := 1; FixedRows := 1; Cells[0, 0] := 'Attribute'; Cells[1, 0] := 'Value'; end; procedure TStringGrid.Init(aNode : TXmlElement; OnProgress : TXMLProgress = nil); var i: Integer; begin FNode := aNode; ClearGrid; // RowCount := aNode.Attributes.Count+1; if Assigned(aNode) then begin Enabled := aNode.TagName <> 'xml'; // attribs if aNode.NbAttributes > 0 then begin RowCount := aNode.NbAttributes + 1; with aNode do for i := 0 to NbAttributes - 1 do begin Cells[0, i+1] := AttributeName[i]; if Length(AttributeValue[i]) > 255 then Cells[1, i+1] := ShortAttributeValue[i] else Cells[1, i+1] := AttributeValue[i]; end; end; end; end; end.
unit UnitDataModule; interface uses SysUtils, Classes, DB, ADODB, frxClass, frxDBSet, frxExportRTF, frxExportXLS, frxExportPDF, StrUtils; type TDataModuleAjendam = class(TDataModule) frxPDFExport1: TfrxPDFExport; frxXLSExport1: TfrxXLSExport; frxRTFExport1: TfrxRTFExport; frxDBDataset1: TfrxDBDataset; frxReport1: TfrxReport; dsHistory: TDataSource; tbHistory: TADOTable; dsBulan: TDataSource; tbBulan: TADOTable; dsVerifikasi: TDataSource; tbVerifikasi: TADOTable; tbVerifikasiCalcTanggalPensiun: TStringField; tbVerifikasiID: TAutoIncField; tbVerifikasiNRP: TWideStringField; tbVerifikasiNama: TWideStringField; tbVerifikasiKode_Pangkat: TSmallintField; tbVerifikasiPangkat: TWideStringField; tbVerifikasiKesatuan: TWideStringField; tbVerifikasiNo_SKEP: TWideStringField; tbVerifikasiTanggal_Pensiun: TDateTimeField; tbVerifikasiTanggal_Pensiun_Indonesia: TWideStringField; tbVerifikasiBulan_Pensiun: TWideStringField; tbVerifikasiBulan_Pensiun_Bulan: TIntegerField; tbVerifikasiBulan_Pensiun_Tahun: TIntegerField; tbVerifikasiCalcBulanPensiun: TStringField; tbVerifikasiCalcKodePangkat: TIntegerField; cnAjendam: TADOConnection; qrVerCount: TADOQuery; dsVerCount: TDataSource; qrVerInvalid: TADOQuery; dsVerInvalid: TDataSource; tbVerHis: TADOTable; dsVerHis: TDataSource; qrDML: TADOQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure tbVerifikasiCalcFields(DataSet: TDataSet); procedure dsVerifikasiDataChange(Sender: TObject; Field: TField); procedure dsVerifikasiUpdateData(Sender: TObject); procedure dsVerifikasiStateChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure RefreshQuery; function ChangeDatePensToString(): String; function ChangeMonthPensToString(): String; function ChangePangkatToInt(): Integer; end; var DataModuleAjendam: TDataModuleAjendam; implementation {$R *.dfm} procedure TDataModuleAjendam.DataModuleCreate(Sender: TObject); begin cnAjendam.Open('', ''); end; procedure TDataModuleAjendam.DataModuleDestroy(Sender: TObject); begin cnAjendam.Close; end; procedure TDataModuleAjendam.dsVerifikasiDataChange(Sender: TObject; Field: TField); begin RefreshQuery; end; procedure TDataModuleAjendam.dsVerifikasiStateChange(Sender: TObject); begin RefreshQuery; end; procedure TDataModuleAjendam.dsVerifikasiUpdateData(Sender: TObject); begin RefreshQuery; end; procedure TDataModuleAjendam.tbVerifikasiCalcFields(DataSet: TDataSet); begin tbVerifikasi.FieldValues['CalcTanggalPensiun'] := ChangeDatePensToString; tbVerifikasi.FieldValues['CalcBulanPensiun'] := ChangeMonthPensToString; tbVerifikasi.FieldValues['CalcKodePangkat'] := ChangePangkatToInt; end; function TDataModuleAjendam.ChangeDatePensToString : String; var myYear, myMonth, myDay: Word; tdt: TDateTime; idMonth: String; begin tdt := DataModuleAjendam.tbVerifikasi.FieldByName('Tanggal_Pensiun').AsDateTime; DecodeDate(tdt, myYear, myMonth, myDay); case myMonth of 1: idMonth := 'Januari'; 2: idMonth := 'Februari'; 3: idMonth := 'Maret'; 4: idMonth := 'April'; 5: idMonth := 'Mei'; 6: idMonth := 'Juni'; 7: idMonth := 'Juli'; 8: idMonth := 'Agustus'; 9: idMonth := 'September'; 10: idMonth := 'Oktober'; 11: idMonth := 'November'; 12: idMonth := 'Desember'; end; Result := IntToStr(myDay) + ' ' + idMonth + ' ' + IntToStr(myYear); end; function TDataModuleAjendam.ChangeMonthPensToString; var sBulan, sTahun: String; iBulan, iTahun: Integer; begin iBulan := DataModuleAjendam.tbVerifikasi.FieldByName('Bulan_Pensiun_Bulan').AsInteger; iTahun := DataModuleAjendam.tbVerifikasi.FieldByName('Bulan_Pensiun_Tahun').AsInteger; case iBulan of 1: sBulan := 'Januari'; 2: sBulan := 'Februari'; 3: sBulan := 'Maret'; 4: sBulan := 'April'; 5: sBulan := 'Mei'; 6: sBulan := 'Juni'; 7: sBulan := 'Juli'; 8: sBulan := 'Agustus'; 9: sBulan := 'September'; 10: sBulan := 'Oktober'; 11: sBulan := 'November'; 12: sBulan := 'Desember'; end; sTahun := IntToStr(iTahun); Result := sBulan + ' ' + sTahun; end; function TDataModuleAjendam.ChangePangkatToInt; var sPangkat: String; iPangkat: Integer; begin sPangkat := DataModuleAjendam.tbVerifikasi.FieldByName('Pangkat').AsString; if AnsiStartsStr('Kolonel', sPangkat) then iPangkat := 83 else if AnsiStartsStr('Letkol', sPangkat) then iPangkat := 82 else if AnsiStartsStr('Mayor', sPangkat) then iPangkat := 81 else if AnsiStartsStr('Kapten', sPangkat) then iPangkat := 73 else if AnsiStartsStr('Lettu', sPangkat) then iPangkat := 72 else if AnsiStartsStr('Letda', sPangkat) then iPangkat := 71 else if AnsiStartsStr('Peltu', sPangkat) then iPangkat := 66 else if AnsiStartsStr('Pelda', sPangkat) then iPangkat := 65 else if AnsiStartsStr('Serma', sPangkat) then iPangkat := 64 else if AnsiStartsStr('Serka', sPangkat) then iPangkat := 63 else if AnsiStartsStr('Sertu', sPangkat) then iPangkat := 62 else if AnsiStartsStr('Serda', sPangkat) then iPangkat := 61 else if AnsiStartsStr('Kopka', sPangkat) then iPangkat := 56 else if AnsiStartsStr('Koptu', sPangkat) then iPangkat := 55 else if AnsiStartsStr('Kopda', sPangkat) then iPangkat := 54 else if AnsiStartsStr('Praka', sPangkat) then iPangkat := 53 else if AnsiStartsStr('Pratu', sPangkat) then iPangkat := 52 else if AnsiStartsStr('Prada', sPangkat) then iPangkat := 51 else iPangkat := 0; Result := iPangkat; end; procedure TDataModuleAjendam.RefreshQuery; begin qrVerCount.Close; qrVerCount.Open; qrVerInvalid.Close; qrVerInvalid.Open; end; end.
unit Model.Devolucao; interface uses Common.ENum, FireDAC.Comp.Client; type TDevolucao = class private FObjeto: Integer; FContainer: Integer; FExpedicao: TDateTime; FLacre: String; FNossoNumero: String; FVolumes: Integer; FAgente: Integer; FMotorista: String; FRetirada: TDateTime; FRecebedor: String; FRecepcao: TDateTime; FConferente: String; FConferencia: TDateTime; FPesoContainer: Double; FStatusContainer: Integer; FDivergencia: String; FDescricao: String; FStatusobjeto: Integer; FProtocolo: String; FDescoberto: String; FOcorrencia: String; FUsuario: String; FManutencao: TDateTime; FAcao: TAcao; public property Objeto: Integer read FObjeto write FObjeto; property Container: Integer read FContainer write FContainer; property Expedicao: TDateTime read FExpedicao write FExpedicao; property Lacre: String read FLacre write FLacre; property NossoNumero: String read FNossoNumero write FNossoNumero; property Volumes: Integer read FVolumes write FVolumes; property Agente: Integer read FAgente write FAgente; property Motorista: String read FMotorista write FMotorista; property Retirada: TDateTime read FRetirada write FRetirada; property Recebedor: String read FRecebedor write FRecebedor; property Recepcao: TDateTime read FRecepcao write FRecepcao; property Conferente: String read FConferente write FConferente; property Conferencia: TDateTime read FConferencia write FConferencia; property PesoContainer: Double read FPesoContainer write FPesoContainer; property StatusContainer: Integer read FStatusContainer write FStatusContainer; property Divergencia: String read FDivergencia write FDivergencia; property Descricao: String read FDescricao write FDescricao; property Statusobjeto: Integer read FStatusobjeto write FStatusobjeto; property Protocolo: String read FProtocolo write FProtocolo; property Descoberto: String read FDescoberto write FDescoberto; property Ocorrencia: String read FOcorrencia write FOcorrencia; property Usuario: String read FUsuario write FUsuario; property Manutencao: TDateTime read FManutencao write FManutencao; property Acao: TAcao read FAcao write FAcao; function GetID(): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TDevolucao } uses DAO.Devolucao; function TDevolucao.GetID: Integer; var devolucaoDAO : TDevolucaoDAO; begin try devolucaoDAO := TDevolucaoDAO.Create; Result := devolucaoDAO.GetID; finally devolucaoDAO.Free; end; end; function TDevolucao.Gravar: Boolean; var devolucaoDAO: TDevolucaoDAO; begin try devolucaoDAO := TDevolucaoDAO.Create; case FAcao of Common.ENum.tacIncluir : Result := devolucaoDAO.Inserir(Self); Common.ENum.tacAlterar : Result := devolucaoDAO.Alterar(Self); Common.ENum.tacExcluir : Result := devolucaoDAO.Excluir(Self); end; finally devolucaoDAO.Free; end; end; function TDevolucao.Localizar(aParam: array of variant): TFDQuery; var devolucaoDAO: TDevolucaoDAO; begin try devolucaoDAO := TDevolucaoDAO.Create; Result := devolucaoDAO.Pesquisar(aParam); finally devolucaoDAO.Free; end; end; end.
unit DealTime; interface type TStockDealTimeType = ( dealNone, dealRestDay, // 休息日 dealDayBefore, // 1-- 8 前一天交易 dealPrepare, // 8 -- 9:15 dealRequestStart, // 9:15 -- 9:25 集合竞价 dealing1, // 交易中 上午 9:25 -- 11:30 dealNoontime, // 11:30 -- 1:00 dealing2, // 交易中 下午 1:00 -- 3:08 dealDayAfter, // 交易结算 下午 3:05 -- 3:30 dealDayEnd // 15:30-- 24:00 ); function stockDealTimeType(ADateTime: TDateTime): TStockDealTimeType; function IsValidStockDealTime(ADateTime: TDateTime = 0): Boolean; implementation uses Sysutils; function stockDealTimeType(ADateTime: TDateTime): TStockDealTimeType; var tmpHour, tmpMin, tmpSec: Word; tmpWord: Word; begin Result := dealRestDay; tmpWord := DayOfWeek(ADateTime); if (1 = tmpWord) or (7 = tmpWord) then exit; Result := dealDayBefore; // 1-- 8 前一天交易 DecodeTime(ADateTime, tmpHour, tmpMin, tmpSec, tmpWord); if (tmpHour < 8) then exit; Result := dealPrepare; // 1-- 8 前一天交易 if (tmpHour = 9) then begin if 15 > tmpMin then exit; Result := dealRequestStart; // 9:15 -- 9:25 集合竞价 if 25 > tmpMin then exit; Result := dealing1;// 交易中 上午 9:25 -- 11:30 exit; end; Result := dealing1; if (10 = tmpHour) then exit; if (11 = tmpHour) then begin if 32 > tmpMin then exit; end; Result := dealNoontime; // 11:30 -- 1:00 if (tmpHour < 13) then exit; Result := dealing2; if (tmpHour < 15) then exit; if (tmpHour = 15) then begin if tmpMin < 05 then exit; Result := dealDayAfter; // 15:08-- 24:00 if tmpMin < 30 then exit; end; Result := dealDayEnd; // 15:08-- 24:00 end; function IsValidStockDealTime(ADateTime: TDateTime = 0): Boolean; var tmpHour, tmpMin, tmpSec, tmpMSec: Word; begin Result := false; if 0 = ADateTime then begin DecodeTime(now, tmpHour, tmpMin, tmpSec, tmpMSec); end else begin DecodeTime(ADateTime, tmpHour, tmpMin, tmpSec, tmpMSec); end; if 9 > tmpHour then exit; if 15 < tmpHour then exit; if 9 = tmpHour then begin if 29 > tmpMin then exit; end; if 11 = tmpHour then begin if 30 < tmpMin then exit; end; if 12 = tmpHour then exit; if 15 = tmpHour then begin if 1 < tmpMin then exit; end; Result := true; end; end.
unit ErrorIntf; interface type IError = interface(IInterface) ['{AB77CB0C-C18F-4F30-AD02-4C9E07DDA708}'] function GetMessage: string; procedure SetMessage(const Value: string); property Message: string read GetMessage write SetMessage; end; implementation end.
unit UPRT; interface type TPRT_STATE = ( psInitial, psStarting, psClosed, psStopped, psClosing, pStopping, psReqSend, psAckRcvd, psAckSent, psOpened ); const IO_RX = $0001; IO_TX = $0002; IO_TXEMPTY = $0004; IO_UP = $0008; type TIME_STAMP = Int64; TPRT_ABSTRACT = class(TObject) // Packet Receiver-Transmitter (Abstract) public procedure TxStr(const S:AnsiString); public // interface function Open:HRESULT;virtual;abstract; procedure Close;virtual;abstract; function RxSize():Integer;virtual;abstract; function Rx(var Data; MaxSize:Integer):Integer;virtual;abstract; procedure Tx(const Data; DataSize:Integer);virtual;abstract; function ProcessIO:Integer;virtual;abstract; end; TPRT = TPRT_ABSTRACT; implementation uses Classes; procedure TPRT_ABSTRACT.TxStr(const S:AnsiString); var Data:Pointer; begin if Length(S)=0 then Data:=nil else Data:=@S[1]; Tx(Data,Length(S)); end; end.
unit nsNativePara; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "f1DocumentTagsImplementation" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/f1DocumentTagsImplementation/nsNativePara.pas" // Начат: 2005/12/02 12:37:25 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::f1DocumentTagsImplementation::DocumentTagNodes::TnsNativePara // // "Родной" параграф. Не представлен нодой из адаптерного дерева // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses nsBaseTagNode, k2Interfaces, Classes, nevBase, k2Prim, k2BaseTypes, l3Types, l3Interfaces ; type _k2ParentedTagObject_Parent_ = TnsBaseTagNode; {$Include w:\common\components\rtl\Garant\K2\k2ParentedTagObject.imp.pas} _nsNativePara_Parent_ = _k2ParentedTagObject_; {$Include ..\f1DocumentTagsImplementation\nsNativePara.imp.pas} TnsNativePara = class(_nsNativePara_) {* "Родной" параграф. Не представлен нодой из адаптерного дерева } end;//TnsNativePara implementation uses k2Base, k2Facade, l3Base ; type _Instance_R_ = TnsNativePara; {$Include w:\common\components\rtl\Garant\K2\k2ParentedTagObject.imp.pas} {$Include ..\f1DocumentTagsImplementation\nsNativePara.imp.pas} end.
unit MultipleDepotMultipleDriverTestDataProviderUnit; interface uses SysUtils, BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit, OptimizationParametersUnit; type TMultipleDepotMultipleDriverTestDataProvider = class(TBaseOptimizationParametersProvider) protected function MakeAddresses(): TAddressesArray; override; function MakeRouteParameters(): TRouteParameters; override; /// <summary> /// After response some fields are changed from request. /// </summary> procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override; public end; implementation { TMultipleDepotMultipleDriverTestDataProvider } uses DateUtils, EnumsUnit, UtilsUnit; procedure TMultipleDepotMultipleDriverTestDataProvider.CorrectForResponse( OptimizationParameters: TOptimizationParameters); begin inherited; end; function TMultipleDepotMultipleDriverTestDataProvider.MakeAddresses: TAddressesArray; var FirstAddress: TAddress; begin Result := TAddressesArray.Create(); FirstAddress := TAddress.Create( '3634 W Market St, Fairlawn, OH 44333', 41.135762259364, -81.629313826561, 300); //indicate that this is a departure stop // single depot routes can only have one departure depot FirstAddress.IsDepot := True; //together these two specify the time window of a destination //seconds offset relative to the route start time for the open availability of a destination FirstAddress.TimeWindowStart := 28800; //seconds offset relative to the route end time for the open availability of a destination FirstAddress.TimeWindowEnd := 29465; AddAddress(FirstAddress, Result); AddAddress(TAddress.Create( '1218 Ruth Ave, Cuyahoga Falls, OH 44221', 41.135762259364, -81.629313826561, 300, 29465, 30529), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 30529, 33779), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 100, 33779, 33944), Result); AddAddress(TAddress.Create( '3495 Purdue St, Cuyahoga Falls, OH 44221', 41.162971496582, -81.479049682617, 300, 33944, 34801), Result); AddAddress(TAddress.Create( '1659 Hibbard Dr, Stow, OH 44224', 41.194505989552, -81.443351581693, 300, 34801, 36366), Result); AddAddress(TAddress.Create( '2705 N River Rd, Stow, OH 44224', 41.145240783691, -81.410247802734, 300, 36366, 39173), Result); AddAddress(TAddress.Create( '10159 Bissell Dr, Twinsburg, OH 44087', 41.340042114258, -81.421226501465, 300, 39173, 41617), Result); AddAddress(TAddress.Create( '367 Cathy Dr, Munroe Falls, OH 44262', 41.148578643799, -81.429229736328, 300, 41617, 43660), Result); AddAddress(TAddress.Create( '367 Cathy Dr, Munroe Falls, OH 44262', 41.148578643799, -81.429229736328, 300, 43660, 46392), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 46392, 48389), Result); AddAddress(TAddress.Create( '559 W Aurora Rd, Northfield, OH 44067', 41.315116882324, -81.558746337891, 50, 48389, 48449), Result); AddAddress(TAddress.Create( '3933 Klein Ave, Stow, OH 44224', 41.169467926025, -81.429420471191, 300, 48449, 50152), Result); AddAddress(TAddress.Create( '2148 8th St, Cuyahoga Falls, OH 44221', 41.136692047119, -81.493492126465, 300, 50152, 51982), Result); AddAddress(TAddress.Create( '3731 Osage St, Stow, OH 44224', 41.161357879639, -81.42293548584, 100, 51982, 52180), Result); AddAddress(TAddress.Create( '3731 Osage St, Stow, OH 44224', 41.161357879639, -81.42293548584, 300, 52180, 54379), Result); end; function TMultipleDepotMultipleDriverTestDataProvider.MakeRouteParameters: TRouteParameters; begin Result := TRouteParameters.Create(); // specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers Result.AlgorithmType := TAlgorithmType.CVRP_TW_MD; // set an arbitrary route name // this value shows up in the website, and all the connected mobile device Result.RouteName := 'Multiple Depot, Multiple Driver'; // the route start date in UTC, unix timestamp seconds (Tomorrow) Result.RouteDate := 53583232; //TUtils.ConvertToUnixTimestamp(IncDay(Now, 1)); // the time in UTC when a route is starting (7AM) Result.RouteTime := 60 * 60 * 7; // the maximum duration of a route Result.RouteMaxDuration := 86400; Result.VehicleCapacity := '1'; Result.VehicleMaxDistanceMI := '10000'; Result.Optimize := TOptimize.Distance; Result.DistanceUnit := TDistanceUnit.MI; Result.DeviceType := TDeviceType.Web; Result.TravelMode := TTravelMode.Driving; Result.Metric := TMetric.Geodesic; end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCDBIDX.PAS 2.17 *} {* Copyright 1995-98 (c) TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcDbIdx; {-Data-aware index selection combobox component} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Controls, Db, DbTables, {DbiProcs,} Forms, Graphics, Menus, {!!.13} Messages, StdCtrls, SysUtils, OvcBase, OvcConst, OvcData, OvcExcpt, OvcVer; type {possible display modes for the items shown in the drop-down list} TDisplayMode = (dmFieldLabel, dmIndexName, dmFieldNames, dmFieldNumbers, dmUserDefined); { dmFieldLabel - Displays the DisplayLabel of the primary field in the index dmIndexName - Displays the actual index name ("Default" for Paradox's primary index) dmFieldNames - Displays the list of field names that make up the index dmFieldNumbers - Displays the list of field numbers that make of the index dmUserDefined - Displays a string returned from calls to the OnGetDisplayLabel event handler } const DefDisplayMode = dmFieldLabel; DefMonitorIdx = False; DefShowHidden = True; type TOvcDbIndexSelect = class; TGetDisplayLabelEvent = procedure(Sender : TOvcDbIndexSelect; const FieldNames, IndexName : string; IndexOptions : TIndexOptions; var DisplayName : string) of object; TOvcIndexInfo = class(TObject) {.Z+} protected {private } FDisplayName : string; {display name} FFields : TStringList; {list of field names for this index} FFieldNames : string; {names of index fields} FIndexName : string; {name of this index} FIndexOptions : TIndexOptions; {index options} FOwner : TOvcDbIndexSelect; FTable : TTable; {table that has this index} procedure SetDisplayName(const Value : string); protected public {.Z-} constructor Create(AOwner : TOvcDbIndexSelect; ATable : TTable; const AIndexName, AFieldNames : string); {!!.13} virtual; {.Z+} destructor Destroy; override; {.Z-} procedure RefreshIndexInfo; property DisplayName : string read FDisplayName write SetDisplayName; property Fields : TStringList read FFields; property FieldNames : string read FFieldNames; property IndexName : string read FIndexName; end; {.Z+} TOvcIndexSelectDataLink = class(TDataLink) protected {private } FIndexSelect : TOvcDbIndexSelect; protected procedure ActiveChanged; override; procedure DataSetChanged; override; procedure LayoutChanged; override; public constructor Create(AIndexSelect : TOvcDbIndexSelect); end; {.Z-} TOvcDbIndexSelect = class(TCustomComboBox) {.Z+} protected {private} {property variables} FDataLink : TOvcIndexSelectDataLink; FDisplayMode : TDisplayMode; {what to display as index name} FMonitorIdx : Boolean; {True, to monitor index changes} FShowHidden : Boolean; {True, to show index for hidden fields} {event variables} FOnGetDisplayLabel : TGetDisplayLabelEvent; {internal variables} isRefreshPending : Boolean; {property methods} function GetDataSource : TDataSource; function GetVersion : string; {!!.13} procedure SetDataSource(Value : TDataSource); procedure SetDisplayMode(Value : TDisplayMode); procedure SetMonitorIdx(Value : Boolean); procedure SetShowHidden(Value : Boolean); procedure SetVersion(Value : string); {!!.13} {windows message handling methods} procedure WMPaint(var Msg : TWMPaint); message WM_PAINT; {internal methods} procedure isFindIndex; protected procedure Change; override; procedure ClearObjects; virtual; procedure CreateWnd; override; procedure DestroyWnd; override; procedure DropDown; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {.Z-} procedure RefreshList; procedure RefreshNow; procedure SetRefreshPendingFlag; {public properties} property Canvas; property Items; property MaxLength; property Text; published {properties} property DataSource : TDataSource read GetDataSource write SetDataSource; property DisplayMode : TDisplayMode read FDisplayMode write SetDisplayMode default DefDisplayMode; property MonitorIndexChanges : Boolean read FMonitorIdx write SetMonitorIdx default DefMonitorIdx; property ShowHidden : Boolean read FShowHidden write SetShowHidden default DefShowHidden; property Version : string {!!.13} read GetVersion {!!.13} write SetVersion {!!.13} stored False; {!!.13} {inherited properties} property Color; property Ctl3D; property DragMode; property DragCursor; property DropDownCount; property Enabled; property Font; property ItemHeight; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property TabStop; property Visible; {events} property OnGetDisplayLabel : TGetDisplayLabelEvent read FOnGetDisplayLabel write FOnGetDisplayLabel; {inherited events} property OnChange; property OnClick; property OnDblClick; property OnDrawItem; property OnDropDown; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; end; implementation {$IFDEF TRIALRUN} uses OrTrial; {$I ORTRIALF.INC} {$ENDIF} {*** TOvcIndexInfo ***} constructor TOvcIndexInfo.Create(AOwner : TOvcDbIndexSelect; ATable : TTable; const AIndexName, AFieldNames : string); {!!.13} begin inherited Create; FOwner := AOwner; FTable := ATable; FIndexName := AIndexName; {!!.13} FFieldNames := AFieldNames; FFields := TStringList.Create; RefreshIndexInfo; end; destructor TOvcIndexInfo.Destroy; begin FFields.Free; FFields := nil; inherited Destroy; end; procedure TOvcIndexInfo.RefreshIndexInfo; var I : Integer; ID : TIndexDef; Fld : TField; begin if not FTable.Active then Exit; {!!.13} {begin revised block} if FFieldNames = '' then begin {use the previously saved index name} FDisplayName := FIndexName; {is this a FlashFiler default index} if AnsiCompareText(FIndexName, 'Seq. Access Index') = 0 then FDisplayName := GetOrphStr(SCDefaultIndex); if (FOwner.DisplayMode = dmUserDefined) and Assigned(FOwner.FOnGetDisplayLabel) then FOwner.FOnGetDisplayLabel(FOwner, FFieldNames, FIndexName, FIndexOptions, FDisplayName); Exit; end; ID := nil; I := FTable.IndexDefs.IndexOf(FIndexName); if I > -1 then ID := FTable.IndexDefs[I]; {!!.13} {end revised block} if Assigned(ID) then begin FIndexName := ID.Name; FIndexOptions := ID.Options; {fill list with field names} I := 1; FFields.Clear; while I < Length(FFieldNames) do FFields.Add(ExtractFieldName(FFieldNames, I)); {set the text to use as the display name} if (FFields.Count > 0) and ((ID.Name > '') or (FOwner.DisplayMode in [dmFieldNames, dmFieldNumbers, dmUserDefined])) then begin Fld := FTable.FieldByName(FFields[0]); if (FOwner.DisplayMode = dmFieldLabel) and Assigned(Fld) then FDisplayName := Fld.DisplayLabel else if (FOwner.DisplayMode = dmFieldNames) then FDisplayName := FFieldNames else if (FOwner.DisplayMode = dmIndexName) then FDisplayName := FIndexName else if (FOwner.DisplayMode = dmFieldNumbers) and Assigned(Fld) then begin FDisplayName := ''; for I := 0 to Pred(FFields.Count) do begin Fld := FTable.FieldByName(FFields[I]); if Assigned(Fld) then begin if FDisplayName > '' then FDisplayName := FDisplayName + ';'; FDisplayName := FDisplayName + IntToStr(Fld.FieldNo); end; end; end else if (FOwner.DisplayMode = dmUserDefined) and Assigned(FOwner.FOnGetDisplayLabel) then begin FDisplayName := FIndexName; {set up default display name} FOwner.FOnGetDisplayLabel(FOwner, FFieldNames, FIndexName, FIndexOptions, FDisplayName); {if nothing else is possible, try these} end else if Assigned(Fld) then FDisplayName := Fld.DisplayLabel else FDisplayName := FIndexName; if not (FOwner.DisplayMode = dmUserDefined) then if (ixDescending in ID.Options) then FDisplayName := FDisplayName + GetOrphStr(SCDescending); end else FDisplayName := GetOrphStr(SCDefaultIndex); end; end; procedure TOvcIndexInfo.SetDisplayName(const Value : string); begin if (Value <> FDisplayName) then begin FDisplayName := Value; FOwner.SetRefreshPendingFlag; FOwner.Invalidate; end; end; {*** TOvcIndexSelectDataLink ***} procedure TOvcIndexSelectDataLink.ActiveChanged; begin inherited ActiveChanged; if not (csLoading in FIndexSelect.ComponentState) then FIndexSelect.RefreshNow; end; constructor TOvcIndexSelectDataLink.Create(AIndexSelect : TOvcDbIndexSelect); begin inherited Create; FIndexSelect := AIndexSelect; end; procedure TOvcIndexSelectDataLink.DataSetChanged; begin inherited DataSetChanged; FIndexSelect.isFindIndex; end; procedure TOvcIndexSelectDataLink.LayoutChanged; begin inherited LayOutChanged; if Active then FIndexSelect.SetRefreshPendingFlag; end; {*** TOvcDbIndexSelect ***} procedure TOvcDbIndexSelect.Change; var Table : TTable; IndexInfo : TOvcIndexInfo; begin if (DataSource = nil) or (DataSource.DataSet = nil) or not (DataSource.DataSet.Active) then Exit; {we have already verified that DataSet is a TTable} Table := TTable(DataSource.DataSet); if ItemIndex > -1 then begin IndexInfo := TOvcIndexInfo(Items.Objects[ItemIndex]); if IndexInfo.Fields.Count > 1 then Table.IndexFieldNames := IndexInfo.FieldNames else Table.IndexName := IndexInfo.IndexName; end; inherited Change; end; procedure TOvcDbIndexSelect.ClearObjects; var I : Integer; begin if not HandleAllocated then Exit; {free all associated TOvcIndexInfo objects} for I := 0 to Pred(Items.Count) do if (Items.Objects[I] <> nil) then begin Items.Objects[I].Free; Items.Objects[I] := nil; end; end; constructor TOvcDbIndexSelect.Create(AOwner : TComponent); begin inherited Create(AOwner); Style := csDropDownList; FDataLink := TOvcIndexSelectDataLink.Create(Self); FDisplayMode := DefDisplayMode; FMonitorIdx := DefMonitorIdx; FShowHidden := DefShowHidden; end; procedure TOvcDbIndexSelect.CreateWnd; {$IFDEF TRIALRUN} var X : Integer; {$ENDIF} begin inherited CreateWnd; SetRefreshPendingFlag; {$IFDEF TRIALRUN} X := _CC_; if (X < ccRangeLow) or (X > ccRangeHigh) then Halt; X := _VC_; if (X < ccRangeLow) or (X > ccRangeHigh) then Halt; {$ENDIF} end; destructor TOvcDbIndexSelect.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; procedure TOvcDbIndexSelect.DestroyWnd; begin {free field info objects here instead of in an overriden Clear method, because ancestor's Clear method isn't virtual} ClearObjects; inherited DestroyWnd; end; procedure TOvcDbIndexSelect.DropDown; begin if isRefreshPending then RefreshList; inherited DropDown; end; function TOvcDbIndexSelect.GetDataSource : TDataSource; begin if Assigned(FDataLink) then Result := FDataLink.DataSource else Result := nil; end; {!!.13} function TOvcDbIndexSelect.GetVersion : string; begin Result := OvcVersionStr; end; procedure TOvcDbIndexSelect.isFindIndex; var I : Integer; Idx : Integer; Table : TTable; IndexInfo : TOvcIndexInfo; begin if not FMonitorIdx then Exit; {exit if a refresh operation is pending--it will update the display} if isRefreshPending then Exit; if (DataSource = nil) or (DataSource.DataSet = nil) then Exit; {we have already verified that DataSet is a TTable} Table := TTable(DataSource.DataSet); {find the current index} Idx := -1; for I := 0 to Pred(Items.Count) do begin IndexInfo := TOvcIndexInfo(Items.Objects[I]); if Assigned(IndexInfo) then begin if (Table.IndexFieldNames = '') then begin if AnsiCompareText(IndexInfo.IndexName, Table.IndexName) = 0 then Idx := I; end else begin if AnsiCompareText(IndexInfo.FieldNames, Table.IndexFieldNames) = 0 then Idx := I; end; end; end; ItemIndex := Idx; end; procedure TOvcDbIndexSelect.RefreshList; var I : Integer; Idx : Integer; Fld : TField; Table : TTable; IndexInfo : TOvcIndexInfo; ActiveIndex : string; begin if not isRefreshPending then Exit; if not HandleAllocated then Exit; {clear refresh flag} isRefreshPending := False; {free field info objects} ClearObjects; {remove items from list} Items.Clear; if (DataSource = nil) or (DataSource.DataSet = nil) or not (DataSource.DataSet.Active) then Exit; {we have already verified that DataSet is a TTable} Table := TTable(DataSource.DataSet); if Table.MasterSource <> nil then raise EOvcException.CreateFmt(GetOrphStr(SCChildTableError), [Self.Name]); {update the index information} Table.IndexDefs.Update; ActiveIndex := ''; for I := 0 to Pred(Table.IndexDefs.Count) do begin IndexInfo := TOvcIndexInfo.Create(Self, Table, {!!.13} Table.IndexDefs.Items[I].Name, {!!.13} Table.IndexDefs.Items[I].Fields); {!!.13} if (Items.IndexOf(IndexInfo.DisplayName) < 0) and {!!.13} (Length(IndexInfo.DisplayName) > 0) then begin {!!.13} Items.AddObject(IndexInfo.DisplayName, IndexInfo); if (Table.IndexFieldNames = '') then begin if AnsiCompareText(Table.IndexDefs.Items[I].Name, Table.IndexName) = 0 then ActiveIndex := IndexInfo.DisplayName; end else begin if AnsiCompareText(Table.IndexFieldNames, Table.IndexDefs.Items[I].Fields) = 0 then ActiveIndex := IndexInfo.DisplayName; end; end else IndexInfo.Free; end; {conditionally remove non-visible Fields} if not ShowHidden and not (DataSource.DataSet.DefaultFields) then begin for I := Pred(Items.Count) downto 0 do begin IndexInfo := TOvcIndexInfo(Items.Objects[I]); Fld := Table.FieldByName(IndexInfo.FFields[0]); if Assigned(Fld) then begin if not Fld.Visible then begin Items.Objects[I].Free; Items.Delete(I); end; end; end; end; Idx := -1; for I := 0 to Pred(Items.Count) do if AnsiCompareText(Items[I], ActiveIndex) = 0 then Idx := I; ItemIndex := Idx; end; procedure TOvcDbIndexSelect.RefreshNow; begin SetRefreshPendingFlag; RefreshList; end; procedure TOvcDbIndexSelect.SetDataSource(Value : TDataSource); begin if Assigned(Value) and (Value.DataSet <> nil) and not (Value.DataSet is TTable) then raise EOvcException.Create(GetOrphStr(SCNoTableAttached)); FDataLink.DataSource := Value; {$IFDEF Win32} if (Value <> nil) then Value.FreeNotification(Self); {$ENDIF} if not (csLoading in ComponentState) then RefreshNow; end; procedure TOvcDbIndexSelect.SetDisplayMode(Value : TDisplayMode); begin if (Value <> FDisplayMode) then begin FDisplayMode := Value; if not (csLoading in ComponentState) then RefreshNow; end; end; procedure TOvcDbIndexSelect.SetMonitorIdx(Value : Boolean); begin if (Value <> FMonitorIdx) then begin FMonitorIdx := Value; if not (csLoading in ComponentState) then if FMonitorIdx then isFindIndex; end; end; procedure TOvcDbIndexSelect.SetRefreshPendingFlag; begin isRefreshPending := True; end; procedure TOvcDbIndexSelect.SetShowHidden(Value : Boolean); begin if (Value <> FShowHidden) then begin FShowHidden := Value; if not (csLoading in ComponentState) then RefreshNow; end; end; {!!.13} procedure TOvcDbIndexSelect.SetVersion(Value : string); begin end; procedure TOvcDbIndexSelect.WMPaint(var Msg : TWMPaint); begin if isRefreshPending then RefreshList; inherited; end; end.
unit AttributesKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Attributes } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\AttributesKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "AttributesKeywordsPack" MUID: (312806286B17) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , nscTreeViewWithAdapterDragDrop ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , Attributes_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_Attributes = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Attributes ---- *Пример использования*: [code] 'aControl' форма::Attributes TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Attributes Tkw_Attributes_Control_tvAttributes = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола tvAttributes ---- *Пример использования*: [code] контрол::tvAttributes TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Attributes_Control_tvAttributes Tkw_Attributes_Control_tvAttributes_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола tvAttributes ---- *Пример использования*: [code] контрол::tvAttributes:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Attributes_Control_tvAttributes_Push TkwAttributesFormTvAttributes = {final} class(TtfwPropertyLike) {* Слово скрипта .TAttributesForm.tvAttributes } private function tvAttributes(const aCtx: TtfwContext; aAttributesForm: TAttributesForm): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TAttributesForm.tvAttributes } 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;//TkwAttributesFormTvAttributes function Tkw_Form_Attributes.GetString: AnsiString; begin Result := 'AttributesForm'; end;//Tkw_Form_Attributes.GetString class function Tkw_Form_Attributes.GetWordNameForRegister: AnsiString; begin Result := 'форма::Attributes'; end;//Tkw_Form_Attributes.GetWordNameForRegister function Tkw_Attributes_Control_tvAttributes.GetString: AnsiString; begin Result := 'tvAttributes'; end;//Tkw_Attributes_Control_tvAttributes.GetString class procedure Tkw_Attributes_Control_tvAttributes.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_Attributes_Control_tvAttributes.RegisterInEngine class function Tkw_Attributes_Control_tvAttributes.GetWordNameForRegister: AnsiString; begin Result := 'контрол::tvAttributes'; end;//Tkw_Attributes_Control_tvAttributes.GetWordNameForRegister procedure Tkw_Attributes_Control_tvAttributes_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('tvAttributes'); inherited; end;//Tkw_Attributes_Control_tvAttributes_Push.DoDoIt class function Tkw_Attributes_Control_tvAttributes_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::tvAttributes:push'; end;//Tkw_Attributes_Control_tvAttributes_Push.GetWordNameForRegister function TkwAttributesFormTvAttributes.tvAttributes(const aCtx: TtfwContext; aAttributesForm: TAttributesForm): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TAttributesForm.tvAttributes } begin Result := aAttributesForm.tvAttributes; end;//TkwAttributesFormTvAttributes.tvAttributes class function TkwAttributesFormTvAttributes.GetWordNameForRegister: AnsiString; begin Result := '.TAttributesForm.tvAttributes'; end;//TkwAttributesFormTvAttributes.GetWordNameForRegister function TkwAttributesFormTvAttributes.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewWithAdapterDragDrop); end;//TkwAttributesFormTvAttributes.GetResultTypeInfo function TkwAttributesFormTvAttributes.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwAttributesFormTvAttributes.GetAllParamsCount function TkwAttributesFormTvAttributes.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TAttributesForm)]); end;//TkwAttributesFormTvAttributes.ParamsTypes procedure TkwAttributesFormTvAttributes.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству tvAttributes', aCtx); end;//TkwAttributesFormTvAttributes.SetValuePrim procedure TkwAttributesFormTvAttributes.DoDoIt(const aCtx: TtfwContext); var l_aAttributesForm: TAttributesForm; begin try l_aAttributesForm := TAttributesForm(aCtx.rEngine.PopObjAs(TAttributesForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aAttributesForm: TAttributesForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(tvAttributes(aCtx, l_aAttributesForm)); end;//TkwAttributesFormTvAttributes.DoDoIt initialization Tkw_Form_Attributes.RegisterInEngine; {* Регистрация Tkw_Form_Attributes } Tkw_Attributes_Control_tvAttributes.RegisterInEngine; {* Регистрация Tkw_Attributes_Control_tvAttributes } Tkw_Attributes_Control_tvAttributes_Push.RegisterInEngine; {* Регистрация Tkw_Attributes_Control_tvAttributes_Push } TkwAttributesFormTvAttributes.RegisterInEngine; {* Регистрация AttributesForm_tvAttributes } TtfwTypeRegistrator.RegisterType(TypeInfo(TAttributesForm)); {* Регистрация типа TAttributesForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop)); {* Регистрация типа TnscTreeViewWithAdapterDragDrop } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
(************************************************************************) unit main2; {$O+,F+} (************************************************************************) interface (************************************************************************) uses crt, dos, pxengine, utils; (************************************************************************) const MAX_TABLES = 126; (* max number of tables *) DELAY_SEC = 60; (* delay time between executing program again *) DELAY_RECONFIG= 3600; (* sets time tags in ini files to zero *) TYPEOVER = FALSE; TYPEAFTER = TRUE; OneBlank=' '; COLCART = 1; SHRINK = 2; SHRINK1 = 3; PHYSTEST = 4; PHYSTEST1 = 5; FLAMCART = 6; FIBERID = 7; PRICELIST = 8; APPEAR = 9; (***************************************************************) IniFileArray: array[1..MAX_TABLES] of string[8]=( 'GRAYCR8', (* 1 GrayCr8.DB *) 'GRAYCR16', (* 2 GrayCr16.DB *) 'CHRMCR8', (* 3 ChrMcr8.DB *) 'CHRMCR16', (* 4 ChrMcr16.DB *) 'FABWGHT', (* 5 FabWght.DB *) 'KNTCNT', (* 6 KntCnt.DB *) 'WOVCNT', (* 7 WovCnt.DB *) 'YARNSZ', (* 8 YARNSZ.DB *) 'DC158', (* 9 DC158.DB *) 'MWWTDL', (* 10 mwwtdl.DB *) 'MWCTDL', (* 11 MWCTDL.DB *) 'MWCLFTD', (* 12 MWCLFTD.DB *) 'MWCHTD', (* 13 MWCHTD.DB *) 'HDH', (* 14 HDH.DB *) 'GMWCTDL', (* 15 MWCGCTDL.DB *) 'GMWCLD', (* 16 MWCGCLD.DB *) 'GMWWTDL', (* 17 MWWGCTDL.DB *) 'GMWWLD', (* 18 MWWGCLD.DB *) 'GMWWLFTD', (* 19 MWWGCLFD.DB *) 'HPRESS', (* 20 HPRESS.DB *) 'HWCLD', (* 21 HWCLD.DB *) 'MWHTDH', (* 22 MWHTDH.DB *) 'HWCLFTD', (* 23 HWCLFTD.DB *) 'MWWHTD', (* 24 MWWHTD.DB *) 'MWWLFTD', (* 25 MWWLFTD.DB *) 'DIMCHGDC', (* 26 DIMCHGDC.DB *) 'N45FLAM', (* 27 N45FLAM.DB *) 'CPSP', (* 28 CPSP.DB *) 'CWAT', (* 29 CWAT.DB *) 'CFSEAWT', (* 30 CFSEAWT.DB *) 'CLND1A', (* 31 CLND1A.DB *) 'CLND2A', (* 32 CLND2A.DB *) 'CLND3A', (* 33 CLND3A.DB *) 'CLND4A', (* 34 CLND4A.DB *) 'ELMENDOR', (* 35 ELMENDOR.DB *) 'MACYS', (* 36 MACYS.DB *) 'MULBRST', (* 37 MULBRST.DB *) 'BALLBRST', (* 38 BALLBRST.DB *) 'EXTRASM', (* 39 EXTRASM.DB *) 'OTHERS', (* 40 OTHERS.DB used to be napinc.db *) 'TONGTER', (* 41 TONGTER.DB *) 'FPLAIN45', (* 42 *) 'FRAISE45', (* 43 *) 'TENSILE', (* 44 *) 'WRINK', (* 45 *) 'NRAIN2', (* 46 *) 'M_fabric', (* 47 *) 'WRECOVRY', (* 48 WRECOVRY.DB *) 'CDC', (* 49 *) 'KNITCNT', (* 50 OLD KnittCnt.DB *) 'WOVENCNT', (* 51 Old WovCnt.DB *) 'CIXENON', (* 52 CIXENON.DB *) 'QUVLIGHT', (* 53 QUVLIGHT.DB *) 'SPRAY', (* 54 QUVLIGHT.DB *) 'CNONCHL', (* 55 CNONCHL.DB *) 'CFPOOL', (* 56 CFPOOL.DB *) 'FID', (* 57 FID.DB *) 'FRUG', (* 58 FRUG.DB *) 'AATCC133', (* 59 AATCC133.DB *) 'CCHLBL', (* 60 CChlBl.DB *) 'WETHER', (* 61 WETHER.DB *) 'GARMENT', (* 62 GARMENT.DB *) 'FMVSS302', (* 63 FMVSS3O2.DB *) 'RND30', (* 64 RND30.DB *) 'ELASTP', (* 65 ELASTP.DB *) 'RND60', (* 66 RND60.DB *) 'BRUSHP', (* 67 BRUSHP.DB *) 'SEAM_UP', (* 68 SEAM_UP.DB *) 'HWWLFTD', (* 69 HWWLFTD.DB *) 'PASNAG', (* 70 PASNAG.DB used to be JCPSNAG.DB *) 'FLCAL117', (* 71 FLCAL117.DB *) 'FCHL15', (* 72 FCHL15.DB *) 'GAUGE', (* 73 GAUGE.DB *) 'SKEWNESS', (* 74 SKEWNESS.DB *) 'FIDMELT', (* 75 FIDMELT.DB *) 'WVE96W', (* 76 WVE96W.DB *) 'MARPIL', (* 77 MARPIL.DB *) 'SWIPIL', (* 78 SWIPIL.DB *) 'TABERA', (* 79 TABERA.DB *) 'TABERB', (* 80 TABERB.DB *) 'CFOZONH', (* 81 CFOZONH.DB *) 'FYARNT', (* 82 FYARNT.DB *) 'SYARNT', (* 83 SYARNT.DB *) 'AIRPERM', (* 84 AIRPERM.DB *) 'WVYNCRMP', (* 85 WVYNCRMP.DB *) 'YARNTN5', (* 86 YARNTN5.DB *) 'BIMP67', (* 87 BIMP67.DB *) 'BIMP44', (* 88 BIMP44.DB *) 'FL701S', (* 89 FL701S.DB *) 'FRM1124', (* 90 FRM1124.DB *) 'BURNTGAS', (* 91 BURNTGAS.DB *) 'AB3885', (* 92 AB3885.DB *) 'PH81', (* 93 PH81.DB *) 'TDI3', (* 94 TDI3.DB *) '99RELAX', (* 95 99RELAX.DB *) 'ST3107', (* 96 ST3107.DB *) 'CFOZONLH', (* 97 CFOZONLH.DB *) 'GMWCDF', (* 98 GMWCDF.DB *) 'CHCARPC', (* 99 CHCARPC.DB *) 'GRCARPC', (* 100 GRCARPC.DB *) 'CBACKBRK', (* 101 GBACKBRK.DB *) 'OILEXT', (* 102 OILEXT.DB *) 'SKEWBOW', (* 103 SKEWBOW.DB *) 'FABTHICK', (* 104 FABTHICK.DB *) 'YARNTYPE', (* 105 YARNTYPE.DB *) 'APPAFT', (* 106 APPAFT.DB *) 'AFW1', (* 107 AFW1.DB *) 'AFD1', (* 108 AFD1.DB *) 'AGD1', (* 109 AGD1.DB *) 'AGW1', (* 110 AGW1.DB *) 'AFW3', (* 111 AFW3.DB *) 'AGW3', (* 112 AGW3.DB *) 'AFD3', (* 113 AFD3.DB *) 'AGD3', (* 114 AGD3.DB *) 'AFW5', (* 115 AFW5.DB *) 'AGW5', (* 116 AGW5.DB *) 'AFD5', (* 117 AFD5.DB *) 'AGD5', (* 118 AGD5.DB *) 'MACESNAG', (* 119 MACESNAG.DB *) 'HIRNG', (* 120 AFD5.DB *) 'LIRNG', (* 121 AGD5.DB *) 'SOIL130', (* 122 SOIL130.DB *) 'SPECTRO', (* 123 SPECTRO.DB *) 'YELLOW', (* 124 YELLOW.DB *) 'MVTRAN', (* 125 MVTRAN.DB *) 'FCHVGPU' (* 126 FCHVGPU.DB *) ); (*********** ASCII character set *******************************) BACKSPACE = #8; RETURN = #13; FUNCTIONKEY = #0; COL = 7; ESCAPE = #27; TAB = #9; BOLD = #64; block=177; (************************************************************************) type string1 = string[1]; string10= string[10]; string70= string[70]; string60= string[60]; strings= string[255]; s_array= array[1..255] of char; (* holds file names *) fileString= string[12]; FileOfChar= File of Char; anarray = packed array [1..60] Of char; TableArray= Array[1..MAX_TABLES] of boolean; var gstopProgram, gRunNextTable : boolean; gWpFileOpen : boolean; gTodayAls : string[6]; (* Today's ALS number *) sysErr : integer; (* Error returned by DOS *) boolTableArray : TableArray; (* boolean array of all tables *) (* paths to directories *) ClientsAtoLDir, ClientsMtoZDir, InvoiceDir, PdoxTblDir, PdoxNetDir, PriceListDir, NetDir: string[60]; gTurnOfTable, gTableNum: byte; (* current table working with *) old_hour, old_min, old_sec : byte; (* info of table worked with *) old_num_of_recs: word; gSearchString: string; (* global search string *) gWPSourceDoc, gCopiedFile:strings; (* wp files *) client, als, flag, comment : string; (* common fields to tables *) field1, field2, field3, field4, field5, (* fields of tables *) field6, field7, field8, field9, field10, App1, App2, App3, App4, PriceClient, PriceAls: string; TestMethod: string; (* Test Method abbreviation string *) mPtr : text; f, fout : text; wp1, wp2, wp3: FileOfChar; (* date and time stamps of file/table *) datentime:datetime; (* errors returned by system or engine *) pxErr: integer; price_table, tablename : string; (* paradox engine types *) tblhandle, pricehandle: tablehandle; fldhandle, pricefld : fieldhandle; rechandle, pricerec : recordhandle; TotalRecords, TotalPriceRecords, RecNumber, PriceNumber: recordnumber; gExitLoop, locks : boolean; transferredtoWP : boolean; savedExitProc : Pointer; gCurrent_w3_pos : LongInt; (************************************************************************) function RemovePointZero( astring: string): string; function confirmExit:boolean; function ParseFileName( var inString: string): string; function d2( n:word): word; function whatTimeIsIt:LongInt; function mpty( theString: string):boolean; function fopen(var fptr: FileOfChar; openfile:string; openMode: char ):boolean; function fReadWrite(var fptr: Text; openfile:string; openMode: char ):boolean; function AppendFile( var fileptr: TEXT; file2open:string):byte; function OpenThirdDoc( DocNum: byte; var OpenedFile: boolean):boolean; function IsFileOpen( theFile: String):boolean; function too_large( fname: strings ):boolean; function GetTimeStamps( thisfile: string):boolean; function SameOldTags:BOOLEAN; function CompareTimeTags( file1, file2: string):byte; function DOSCopy( sString, dString: strings):boolean; function compareString( a, b: strings; n:integer) : boolean; function IsItBlank( fhandle: fieldHandle):boolean; function GetMax( var1, var2 : byte): byte; function AveNDoubPlus( var fhandle: fieldhandle; n: byte; var dvar: double; Var AddTest:boolean):boolean; function MAX( var fhandle: fieldhandle; n: byte ):double; function ValueFound( var fhandle: fieldhandle; n: byte; in_eq: string; in_val: byte ):boolean; function AddFields( var fhandle: fieldhandle; n: byte ):double; function MaxRange( var fhandle: fieldhandle; n: byte ):double; function MaxCarpetRange( var fhandle: fieldhandle; n: byte ):double; function AveFlameDouble( var fhandle: fieldhandle; n: byte; var dvar: double; Var AddTest:boolean):boolean; function IncludeAvg(fldhandle: fieldhandle):boolean; function AveNDblFields( var fhandle: fieldhandle; n: byte; var dvar: double):boolean; function FldsGreaterThanOne( var fhandle: fieldhandle; n: byte; var dvar: double):boolean; function NegativeFields( var fhandle: fieldhandle; n: byte):boolean; function CheckFields( var fhandle: fieldhandle; n: byte ):boolean; (*************************************************************) procedure displayTime( countdown: byte); procedure waitDelaySecs; procedure sysError( nameOFile: string); procedure ReadIniFile( var TheFilename:string); procedure ResetTimeFlags( TableNumber: byte ); procedure padString( var theString: string; numofchars:byte); procedure debug( outstring: string; toSleep: byte); procedure EngError( pxErr:integer); procedure printf( outstring: string); procedure display_table( tname: string); procedure displaySucks( thechar: char); procedure dRecNum( rn: recordnumber; totRecs: recordnumber); procedure SaveNewTimeTags( var filename:string); procedure FormFileName( var exist:boolean); procedure lookup_file( var exist:boolean); procedure incorrectAls; procedure update_table( theChar: char); procedure clearGlobalFields; procedure dWhatHappened( var retChar: char); procedure PlaceString(source:string); procedure shiftLeftString( var a: s_array; n:integer; ch:char); procedure FindAndcopy( var ptr2file: FileOfChar; targetString, sourceString: string; inclusive: boolean; var same: boolean); procedure MemorizeWp1; procedure RepositionWp1; procedure ReplaceSource( var ptr2file: FileOfChar;targetString, sourceString: string; var same: boolean); procedure MoveTo( var ptr2file:FileOfChar; targetString: string; var same:boolean); procedure CopyDocument( var retChar: char); procedure Getalphafield( var fldhandle:fieldhandle; var avalue:string; echo : boolean ); procedure GetFloat( var fldhandle:fieldhandle; var fieldcontent: string; decimalPlaces: word ); procedure GetDoubleField( var fhandle:fieldHandle; var dvalue:double; var var_blank:boolean ); procedure GetDoubStringAndBlank( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); procedure GetInt( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); procedure GetShort( var TheFieldNumber: fieldHandle; var RetString: string; var IsItBlank: boolean); procedure TwoPlacesDouble( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); procedure CalcSkewField( var TheFieldNumber: fieldHandle; var DoubleVar: double; var FieldsFilled: boolean; n: byte); procedure AveStrFields( var fhandle: fieldhandle; n: byte; var avalue: string; var tvalue: string); procedure Find_Damaged( var fhandle: fieldhandle; n: byte; var avalue: byte; var tvalue: string); procedure dNotEmptyFlag( var pnum: byte); procedure dErrMsg( var p: boolean); Procedure ReBoot; procedure NewClient; Procedure ReadIniData; procedure GetWindowCoords( var px1, py1, px2, py2: byte); procedure closefiles( var xfered: boolean; placeFlagChar: char); procedure redirect_output( thefile: string); procedure w_date_time; procedure ProcTableHeader( var FlagChar: Char); procedure ConvertDoub2str( var dvar:double; var theString: string); procedure Double2Str( dvar: double; var astr: string; decplaces:byte); procedure ConvToPoint5( dvar: double; var TheString: string); Procedure TaberToPoint5( dvar: double; var TheString: string); Procedure RoundTo50( ivar: integer; var TheString: string); Procedure RoundToDec( ivar, dec: integer; var TheString: string); (************************************************************************) implementation (************************************************************************) (* returns time since midnight in secs *) function whatTimeIsIt:LongInt; var hour, min, sec, sec100: word; timeNow: LongInt; begin gettime( hour, min, sec, sec100); timeNow:= (hour*3600)+(min*60)+ sec; whatTimeIsIt:= timeNow; end; (**************************************************************************) function confirmExit:boolean; var x, y: byte; break: boolean; inchar: char; begin break:=false; DeskTop; gotoxy( 22, 12); write('Do you wish to exit program (Y/N)?'); x:=wherex; y:=wherey; RestoreCursor; repeat inchar:=upcase(readkey); write( inchar); gotoxy( x, y); if inchar=functionkey then inchar:=readkey else if inchar='Y' then begin break:=TRUE; confirmExit:=TRUE; end else if inchar='N' then begin break:=TRUE; confirmExit:=FALSE; end; until break; HideCursor; gotoxy( 1, wherey); end; (************************************************************************) function parseFileName( var inString: string): string; var len, i,j: byte; outString: string; inchar: char; continue:boolean; begin continue:=TRUE; len:=length(inString); i:=0; while (continue) do begin inchar:= inString[len-i]; if inchar='\' then continue:=FALSE else inc(i); end; for j:=1 to i do outString[j]:=inString[len-i+j]; outString[0]:= chr( i); parseFileName:=outString; end; (***************************************************************************) procedure SysError( nameOFile: string); begin (* is the file already open ie. Sharing Violation *) if (sysErr=163) then begin writeln('Sharing Violation: ERROR_NUM_163'); if (boolTableArray[ gTurnOfTable ]=TRUE) then begin ResetTimeFlags( gTurnOfTable ); end; BoolTableArray[ gTurnOfTable ]:= FALSE; end else begin writeln; writeln( 'Can not open file ', nameOFile, '.'); writeln( 'Run-Time Error Number: ', sysErr ); clreol; end; end; (***************************************************************************) function RemovePointZero( astring: string): string; var i: byte; begin i:=pos( '.0', astring ); if (i>0) then delete( astring, i, 2 ); RemovePointZero:= astring; end; (***********************************************************************) procedure ResetTimeFlags( TableNumber: byte ); var fptr : text; filename: string; begin filename:=''; filename := iniFileArray[ TableNumber ] + '.INI'; if ( NOT DosFile( filename, 0)) then begin writeln( 'Could Not find file ', filename, '.'); writeln( 'Therefore can not reset time stamps of the file.'); sleep( 5000); Exit; end; ReadIniFile( filename ); {$i-} assign( fptr, filename); rewrite( fptr); {$i+} sysErr:=ioresult; if (sysErr<>0) then sysError( filename ) else begin writeln(fptr, PdoxTblDir); writeln(fptr, '0'); writeln(fptr, '0'); writeln(fptr, '0'); writeln(fptr, '0'); close( fptr); writeln('Reset Time Tags on ', filename); end; end; (***************************************************************************) procedure ReadIniFile( var TheFilename:string); var fhandle : text; begin if ( DosFile( TheFilename, 0) ) then begin assign( fhandle, TheFilename); {$i-} reset ( fhandle); sysErr:=ioresult; {$i+} if (sysErr<>0) then sysError( TheFilename ); (* global strings are assigned their corresponding paths *) readln( fhandle, PdoxTblDir); (* gets time stamp of old table last worked on *) readln( fhandle, old_hour); readln( fhandle, old_min); readln( fhandle, old_sec); (* gets the number of records stored in the old table *) readln( fhandle, old_num_of_recs); close ( fhandle); (* remove Any blank spaces *) PdoxTblDir := removeBlanks( PdoxTblDir ); end; end; (**************************************************************************) (* display integer in 2 spaces/digits *) function d2( n:word): word; begin if (n<10) then write('0'); d2:=n; end; (**************************************************************************) (* display table name on border *) procedure displayTime( countdown:byte); var x, y: byte; hh, mm, ss, sec100: word; begin gettime( hh, mm, ss, sec100); x:=wherex; y:=wherey; window( 1, 1, 80, 25); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( 5,23); write('COUNT DOWN: ', countdown:2); gotoxy( 70, y2); write( d2(hh), ':', d2(mm), ':', d2(ss) ); window( x1+1, y1+1, x2-1, y2-1); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( x, y); end; (**************************************************************************) (* display table name on border *) procedure displayDate; var x, y: byte; yy, mm, dd, dofw: word; today: string[12]; ystr, mstr, dstr: string[3]; begin x:=wherex; y:=wherey; window( 1, 1, 80, 25); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy(5,25); TextColor(LightRed); write( ' TAPICS - Contact ADAM R. VARLEY for support (c) Vartest 1990-2001 '); GetDate( yy, mm, dd, dofw); yy:= yy MOD 100; gotoxy( 5, y1); textcolor(14); writeln( ' Date: ', d2(mm), '/', d2(dd), '/', d2(yy), ' ' ); str( yy:2, yStr); str( mm:2, mStr); str( dd:2, dStr); if ( pos(' ', mStr) > 0 ) then mStr[Pos(' ', mStr)] := '0'; if ( pos(' ', dStr) > 0 ) then dStr[Pos(' ', dStr)] := '0'; if ( pos(' ', yStr) > 0 ) then yStr[Pos(' ', yStr)] := '0'; gTodayAls:= mStr + dStr + yStr ; window( x1+1, y1+1, x2-1, y2-1); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( x, y); end; (*************************************************************************) procedure DisplaySharingViolations; var i: byte; ncount: byte; begin ncount:=0; gotoxy( 3, 12); TextColor(White); TextBackground(Cyan); write( 'Sharing Violations on the following tables:'); TextColor(14); TextBackground(Blue); gotoxy( 5, 13); for i:= 1 to MAX_TABLES do begin if (boolTableArray[i]=FALSE) then begin if ( ( ncount MOD 6)=5 ) then begin gotoxy( 5, wherey + 1 ); end; inc( ncount); write( iniFileArray[i], oneBlank:12-length( iniFileArray[i]) ); end; end; (* if no sharing violations then clear it line *) if ( ncount=0) then begin gotoxy( 1, 12); clreol; end; end; (**************************************************************************) procedure RunOtherTable( var IsNext: byte); var NextTable: string; i, AnswerIs: byte; begin gotoxy( 5, 17); clreol; RestoreCursor; write('Enter the name of the table to run next: '); Readln( NextTable); HideCursor; capitalize( NextTable); i:= pos('.', NextTable); if ((i>0) and (i<9)) then begin NextTable[0]:= chr(i-1); end; while ( NextTable[1]=' ') do delete( NextTable, 1, 1); AnswerIs:=99; for i:= 1 to MAX_TABLES do begin if ( iniFileArray[ i ] = NextTable ) then begin AnswerIs:= i; resetTimeFlags( i); end; end; if (AnswerIs<>99) then begin writeln('The Answer is ', AnswerIs); writeln('Table=', iniFileArray[ AnswerIs ], '; Looking for ', NextTable,';'); IsNext:= AnswerIs; gRunNextTable:=TRUE; end else if ( length(NextTable)=0 ) then begin end else begin writeln( NextTable,'?'); writeln( 'Sorry, I Don''t recognize ', NextTable); sleep( 5000); writeln; writeln; end; end; (***************************************************************************) (* resets time stamps on all ini files every hour *) procedure testReconfig; var hour, min, sec, sec100: word; NumOfSecs: word; i : byte; begin gettime( hour, min, sec, sec100); NumOfSecs:= (min*60)+ sec; if ( (NumOfSecs<=59) AND (NumOfSecs>=0) ) then begin clrscr; gotoxy( 1, 1); writeln('Please Wait....'); writeln('Trying to reset time tags on all INI Files'); for i:=1 to MAX_TABLES do begin resetTimeFlags( i); delay( 1000); end; clrscr; end; end; (**************************************************************************) procedure WaitDelaySecs; var continue: boolean; ch: char; dummyStr: string; lastDelay, TimeNow : LongInt; CountDown: byte; begin deskTop; (* New deskTop *) if ( DosFile( 'MESSAGES.TXT', 0) ) then begin gotoxy(5, 2); TextColor(white); TextBackground(Cyan); writeln('There are messages in the Message Queue'); TextColor(14); TextBackground(Blue); end; if ( DosFile( 'NONEXIST.TXT', 0) ) then begin gotoxy(5, 4); TextColor(white); TextBackground(Cyan); writeln('Encountered incorrect ALSes'); TextColor(14); TextBackground(Blue); end; displayDate; gotoxy( 5, 7); write( 'ALS: ', gTodayAls, ';' ); DisplaySharingViolations; (* testReConfig; *) LastDelay:= WhatTimeIsIt; continue:=TRUE; while (continue) do begin TimeNow:= WhatTimeIsIt; CountDown:= DELAY_SEC-(TimeNow-lastDelay); if ( (CountDown > 60) OR (CountDown<0) ) then begin continue:=FALSE; end else begin displayTime( CountDown ); ch:=process0; if (ch=ESCAPE) then begin if (confirmExit) then gstopProgram:=TRUE; Exit; end else if ch in ['b', 'B'] then begin ReBoot; end else if ch in ['M', 'm'] then begin NewClient; end else if ch in ['R', 'r'] then begin RunOtherTable( gTableNum); Exit; end else if ch in ['S', 's'] then Exit; end; end; end; (************************************************************************) procedure PadString( var theString: string; numofchars:byte); var StringSize, i: byte; begin StringSize:=length( theString); for i:= (StringSize+1) to numOfChars do TheString:= ' ' + TheString; TheString[0]:= Chr( NumOfChars); end; (************************************************************************) function mpty( theString: string):boolean; begin if (length( theString)=0) then mpty:=TRUE else mpty:=FALSE; end; (*************************************************************************) procedure debug( outstring: string; toSleep: byte); begin writeln( 'debug: ', outstring); if (toSleep>0) then Sleep(toSleep*1000); end; (*************************************************************************) procedure EngError( pxErr:integer); begin writeln( PxErrMsg( pxErr)); end; (***************************************************************************) procedure printf( outstring: string); begin writeln( f, outstring); writeln( fout, outstring); flush( fout ); end; (***************************************************************************) function fopen( var fptr: FileOfChar; openfile:string; openMode: char ):boolean; var RetVal: boolean; begin RetVal:=FALSE; assign( fptr, openFile ); {$i-} if openMode in ['r','R'] then reset( fptr) else if openMode in ['w','W'] then rewrite( fptr); {$i+} sysErr:=ioresult; if (sysErr<>0) then begin sysError( openFile ); RetVal:=FALSE; end else begin writeln( f, 'Opened file ', OpenFile:12,' in "',openMode,'" mode.'); RetVal:=TRUE; end; fopen:= RetVal; end; (***************************************************************************) function fReadWrite( var fptr: Text; openfile:string; openMode: char ):boolean; var outcome: boolean; begin assign( fptr, openFile ); {$i-} if openMode in ['r','R'] then reset( fptr) else if openMode in ['w','W'] then rewrite( fptr); {$i+} sysErr:=ioresult; if (sysErr<>0) then begin sysError( openFile ); outcome:=FALSE; end else begin writeln( f, 'Opened file ', OpenFile:12,' in "',openMode,'" mode.'); outcome:=TRUE; end; fReadWrite:= outcome; end; (***************************************************************************) (* display table name on border *) procedure display_table( tname: string); var x, y: integer; begin x:=wherex; y:=wherey; window( 1, 1, 80, 25); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( 5, 1); write( f, ' '); gotoxy( 5, 1); write( f, ' ', tname, ' ', '(TableNum= ', gTurnOfTable, ') '); window( x1+1, y1+1, x2-1, y2-1); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( x, y); end; (*************************************************************************) (* display table name on border *) procedure displaySucks( thechar: char); var x, y: integer; theString: string[ 21]; begin theString:= 'RESULT='; thestring[8]:= thechar; thestring[0]:= chr( 8 ); x:=wherex; y:=wherey; window( 1, 1, 80, 25); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( 5, y2); write( f, ' '); gotoxy( 5, y2); write( f, ' ', theString, ' ' ); window( x1+1, y1+1, x2-1, y2-1); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( x, y); end; (*************************************************************************) procedure dRecNum( rn: recordnumber; totRecs: recordnumber ); var x, y: integer; begin x:=wherex; y:=wherey; window( 1, 1, 80, 25); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( 45, 1); write ( f, ' '); gotoxy(45, 1); write( f, ' processing: ', rn ,' of ', totRecs, ' ' ); window( x1+1, y1+1, x2-1, y2-1); TextColor(14); { Yellow = 14 } TextBackground(Blue); gotoxy( x, y); end; (*************************************************************************) (* * returns 0 : file could not be opened * returns 1 : file opened and will append to it i.e. is not empty * returns 2 : file opened and is empty NOTE: user must close file after it's done with. ************************************************************************) function AppendFile( var fileptr: TEXT; file2open:string):byte; var retByte: byte; begin retbyte:=0; {$i-} if ( DosFile( file2open, 0) ) then begin (* file exists therefore add to the end of it *) assign( filePtr, file2open); append( filePtr); retByte:=1; end else begin (* file does not exist therefore opened file is empty *) assign( filePtr, file2open); rewrite( filePtr); retByte:= 2; end; {$i+} sysErr:= ioresult; if (sysErr<>0) then begin sysError( file2open ); retByte:= 0; end; appendFile:=retByte; end; (***************************************************************************) function OpenThirdDoc( DocNum: byte; var OpenedFile: boolean):boolean; const FirstDoc = 'DOC_1.WP'; SecondDoc= 'DOC_2.WP'; ThirdDoc = 'DOC_3.WP'; FourthDoc= 'DOC_4.WP'; FifthDoc = 'DOC_5.WP'; SixthDoc = 'DOC_6.WP'; SevenDoc = 'DOC_7.WP'; PriceDoc = 'DOC_8.WP'; AppearDoc= 'DOC_9.WP'; var tfname: string; RetVal: boolean; begin RetVal:=FALSE; if (DocNum=1) then tfname:= FirstDoc else if (DocNum=2) then tfname:= SecondDoc else if (DocNum=3) then tfname:= ThirdDoc else if (DocNum=4) then tfname:= FourthDoc else if (DocNum=5) then tfname:= FifthDoc else if (DocNum=6) then tfname:= SixthDoc else if (DocNum=7) then tfname:= SevenDoc else if (DocNum=8) then tfname:= PriceDoc else if (DocNum=9) then tfname:= AppearDoc; if ( DosFile( tfname, 0) ) then begin RetVal:= fopen( wp3, tfname, 'r'); end else begin field10:= 'File ' +tfname+ ' does not exist. Exiting out...'; printf( field10 ); RestoreCursor; Halt; end; writeln('Open Third Document RetVal= ', RetVal); OpenedFile := RetVal; openThirdDoc:= RetVal; end; (***************************************************************************) (* returns TRUE if dos file is opened by another user *) function IsFileOpen( theFile: String):boolean; var fp:TEXT; retval: boolean; begin retval:=FALSE; assign( fp, theFile ); {$i-} reset( fp); {$i+} sysErr:= ioresult; if (sysErr<>0) then begin sysError( theFile ); retval:=TRUE; end else close( fp); IsFileOpen:= retval; end; (*************************************************************************) (* returns TRUE if file is 10k bytes or more *) function too_large( fname: strings ):boolean; var sr:searchrec; begin findfirst( fname, 0, sr); if doserror=0 then begin with sr do begin if (size > (5*1024)) then too_large:=TRUE else too_large:=FALSE; end end end; (**************************************************************************) function GetTimeStamps( thisfile: string):boolean; var fp: file; s: string; time: longint; retval: boolean; begin retval:=FALSE; if (DosFile( thisfile, 0)) then begin assign( fp, thisfile ); {$i-} reset( fp); {$i+} sysErr:= ioresult; if (sysErr<>0) then begin sysError( thisFile ); end else begin getftime( fp, time); (* get time stamp of file *) if (doserror<>0) then writeln(f, 'Could NOT get time stamp of file : ', thisFile) else begin unpacktime( time, datentime); retval:= TRUE; end; close( fp); end end; GetTimeStamps:= retval; end; (****************************************************************************) (* returns TRUE if time stamps are same *) function SameOldTags:BOOLEAN; var retval : boolean; begin retval:=TRUE; if (GetTimeStamps(PdoxTblDir)) then begin (* mark table as closed/unlocked *) boolTableArray[ gTurnOfTable ]:= TRUE; with datentime do begin (* compare current attributes of table with older ones *) if ( (hour<>old_hour) OR (min<>old_min) OR (sec<>old_sec)) then begin retval:=FALSE; if ((old_hour=0) AND (old_min=0) AND (old_sec=0)) then writeln(f, 'Time Stamps have been reset already.') else ResetTimeFlags( gTurnOfTable); end end; end else boolTableArray[ gTurnOfTable ]:= FALSE; SameOldTags:= retval; end; (****************************************************************************) (* compares time stamps of two separate files *) (* returns one if time stamps are the same *) function CompareTimeTags( file1, file2: string):byte; var hour1, hour2, min1, min2, sec1, sec2: byte; retval: byte; begin retval:=3; (* could not get time stamps *) if (getTimeStamps(file1)) then begin min1:=datentime.min; hour1:=datentime.hour; sec1:=datentime.sec; if ( getTimeStamps(file2)) then begin min2:=datentime.min; hour2:=datentime.hour; sec2:=datentime.sec; if ((hour1=hour2) AND (min1=min2) AND (sec1=sec2)) then retval:=1 else retval:=0; end; end; CompareTimeTags:= retval; end; function IncludeAvg(fldhandle: fieldhandle):boolean; var Fchar: char; begin getalphafield ( fldhandle, flag, TRUE ); if (length( flag)=0) then Fchar:= ' ' else Fchar:= flag[1]; Fchar:= Upcase( Fchar); If Fchar in ['y', 'Y'] then IncludeAvg := True else IncludeAvg := False; end; { function InvludeAvg } (****************************************************************************) procedure SaveNewTimeTags( var filename:string); var fptr : text; gotTime : boolean; begin if (recNumber<totalRecords) then begin printf(' RecNumber < TotalRecords. Time stamps not reset! '); Exit; end; if (gWpFileOpen=TRUE) then begin printf('gWpFile Open is TRUE. Time stamps not reset!'); Exit; end; {$i-} assign( fptr, filename); rewrite( fptr); {$i+} sysErr:=ioresult; if (sysErr<>0) then sysError( filename ) else begin (* write paths to file *) writeln(fptr, PdoxTblDir); gotTime:= getTimeStamps( PdoxTblDir); (* write time stamps to ini file *) if (gotTime) then begin writeln(fptr, datentime.hour); writeln(fptr, datentime.min); writeln(fptr, datentime.sec); end else begin writeln(fptr, '0'); writeln(fptr, '0'); writeln(fptr, '0'); end; (* write total Number of records in table *) writeln(fptr, totalRecords); close( fptr); end; end; (***********************************************************************) (* forms a complete name for WP DOC to work with *) procedure FormFileName( var exist:boolean); var i:integer; achar:char; cmdline:string; begin exist:=FALSE; (* add extesion .wp *) gWPSourceDoc := als + '.WP'; achar := client[1]; if achar in ['A'..'L'] then gWPSourceDoc:= ClientsAtoLDir + '\' + client + '\' + gWPSourceDoc else gWPSourceDoc:= ClientsMtoZDir + '\' + client + '\' + gWPSourceDoc; i:= pos( '\\', gWPSourceDoc); if (i>0) then begin delete( gWpSourceDoc, i, 1 ); end; for i:=1 to length( gWPSourceDoc) do gWPSourceDoc[i]:=upcase( gWPSourceDoc[i]); if (DosFile( gWPSourceDoc, 0)) then begin writeln(f, 'File ' , gWPSourceDoc , ' exists.'); (* place source string in cmdline string *) for i:=1 to length( gWPSourceDoc) do cmdline[i]:=gWPSourceDoc[i]; cmdline[0]:= chr( i); (* return the name of the file only in destination string *) gCopiedFile:= parseFileName( cmdline); exist := DOSCopy( gWPSourceDoc, gCopiedFile); if (exist=FALSE) then gWpFileOpen:= TRUE; end else begin incorrectAls; exist:=FALSE; printf(' File ' + gWPSourceDoc + ' does NOT exist.'); end; end; (**************************************************************************) (* forms wp filename to store data in *) (* file formed should already exist under the proper directory *) procedure lookup_file( var exist:boolean); var inchar : char; i: integer; cread, cwrite: boolean; begin exist:=FALSE; (* returns true if file exists. *) FormFileName(exist); (* if file exists then go on with program *) if (exist) then begin (* writeln(f,'gCopiedFile: ', gCopiedFile); *) cread:= fopen( wp1, gCopiedFile, 'r'); if (exist) then cwrite:= fopen( wp2, 'DUMMY.WP', 'w'); if (cread) then writeln(f, ' WP source document: ', gCopiedFile:14) else if (cwrite) then begin close( wp2); writeln(f, 'Could not open WP1. Closing WP2'); end; if (cwrite) then writeln(f, ' WP dest document: ', 'DUMMY.WP':14) else if (cread) then begin close( wp1); writeln(f, 'Could not open WP2. Closing WP1'); end; if ( cwrite and cread) then exist:=TRUE else begin exist:=FALSE; writeln('fopen not successfull!'); end; end else begin printf('Aborting! WP source document not found.'); end; end; (**************************************************************************) function DOSCopy( sString, dString: strings):boolean; var cmdline : string; i : integer; retval : boolean; begin retval:=FALSE; i:=1; WHILE ( i>0 ) DO BEGIN i:=pos(' ', sString); if (i>0) then delete( sString, i, 1 ); END; i:=1; WHILE ( i>0 ) DO BEGIN i:=pos(' ', dString); if (i>0) then delete( dString, i, 1 ); END; if (NOT IsFileOpen( sString)) then begin (* Exec command messes up border rectangle *) (* therefore redirect its output to file junk.dat *) cmdline:='/C copy ' + sString + ' ' + dString + ' > NUL'; writeln( cmdline); SwapVectors; Exec( getEnv('COMSPEC'), cmdline ); SwapVectors; if (DosError<>0) then begin printf( cmdline); str( dosError, cmdline); printf('DOS copy returned run-time error #: ' + cmdline); sleep(5000); end else begin retval:=TRUE; end; end else printf('One copy of the file is opened already (SHARING_VIOLATION)'); DOSCopy:=retval; end; (**************************************************************************) procedure incorrectAls; const file2open='NONEXIST.TXT'; var filePtr: Text; ncount: byte; begin ncount:= AppendFile( filePtr, file2open); if (ncount>0) then begin if (ncount=2) then begin writeln( filePtr, 'TABLES', OneBlank:34-length('tables'), 'RECORD NUM', OneBlank: 10-length('client'), 'CLIENT', OneBlank: 10-length('als'), 'ALS'); end; (* if not today's ALS *) if (pos( gTodayAls, als)=0) then begin update_table('P'); writeln( filePtr, PdoxTblDir, OneBlank:35-length(PdoxTblDir), recNumber:9, OneBlank: 10-length(client), client, OneBlank: 10-length(als), als); end; close( filePtr); end; end; (**************************************************************************) (* places '1' or '0' in FLAG field of table *) procedure update_table( theChar: char); var search_for:strings; rec_num:recordnumber; begin (* empty the xfer rec buf *) pxErr:=Pxrecbufempty( rechandle); if (pxErr<>PXSUCCESS) then engError( pxErr); (* xfer contents of current record to the xfer rec buffer *) pxErr:=Pxrecget( tblhandle, rechandle); (* get field handle to FLAG field *) Px( Pxfldhandle( tblhandle, 'FLAG', fldhandle)); Px( Pxputalpha( rechandle, fldhandle, theChar)); (* update current record *) pxErr:= Pxrecupdate( tblhandle, rechandle); if pxErr <> PXSUCCESS then engError( pxErr); end; (***************************************************************************) procedure clearGlobalFields; begin field1:=''; field2:=''; field3:=''; field4:=''; field5:=''; field6:=''; field7:=''; field8:=''; field9:=''; field10:=''; client:=''; als:=''; flag:=''; comment:=''; App1:=''; App2:=''; App3:=''; App4:=''; end; (***************************************************************************) procedure dWhatHappened( var retChar: char); var astr: string[81]; begin retChar:='S'; astr:= ' Could not find string: ' + gSearchString + ' (STRINGS_NOT_FOUND)'; printf( astr); end; (*************************************************************************) (* returns true if the strings a and b are the same in n places *) function CompareString( a, b: strings; n:integer) : boolean; var i: integer; begin i:=0; (* compare until different chars or last char is reched *) repeat i:= i + 1 ; until (a[i] <> b[i]) or (i=n); (* an unequal pair is found or strings are identical *) compareString:= a[i] = b[i]; end; (**************************************************************************) function GetMax( var1, var2 : byte): byte; begin if (var1>var2) then GetMax:=var1 else GetMax:=var2; end; (**************************************************************************) procedure PlaceString(source:string); var i, len:integer; begin (* gotoxy( wherex, wherey-1 ); *) len:=length( source); if (len>0) then begin for i:=1 to len do write( wp2, source[i] ); writeln(f, ' Placed SourceString: ', source); end end; (**************************************************************************) (* shifts string of n chars left once; adds char in the nth position *) procedure ShiftLeftString( var a: s_array; n:integer; ch:char); var i :integer; b: strings; begin for i:=2 to n do b[i-1]:=a[i]; b[n]:=ch; for i:=1 to n do a[i]:=b[i]; end; (***************************************************************************) (*** places sourceString in WP2 ; * replaces 'targetString' with 'sourceString' * returns TRUE if replace is successfull * if unsuccessfull, places file pointers back to what they were initially ************************************************************************) procedure FindAndcopy( var ptr2file: FileOfChar; targetString, sourceString: string; inclusive: boolean; var same: boolean); var ch : char; cur_in_pos, cur_out_pos : longint; astring : s_array; (* for comparison *) i, n: byte; begin same:=FALSE; (* search string not found yet *) for i:=1 to length( astring) do astring[i]:= ' '; n:=length( targetString); gSearchString := ''; gSearchString := targetString; writeln( f, 'F&C Searching for: ', gSearchString); cur_in_pos:=filepos( ptr2file); cur_out_pos:=filepos( wp2); while ( (NOT eof(ptr2file)) AND (NOT same) ) do begin read( ptr2file, ch); write( wp2, ch); shiftLeftString( astring, n, ch); same:= CompareString( targetString, astring, n); if (same) then begin (* if inclusive then copy string-looking-for as well *) if (NOT inclusive) then seek(wp2, filepos(wp2)- n ); PlaceString(sourceString); end; end; if (NOT same) then begin (* place file ptr back to what it was originally *) seek( ptr2file, cur_in_pos); seek( wp2, cur_out_pos); end; end; (**************************************************************************) procedure MemorizeWp1; var same: boolean; begin gCurrent_w3_pos:=filepos( wp1) end; (**************************************************************************) procedure RepositionWp1; begin seek( wp1, gCurrent_w3_pos); end; (**************************************************************************) (*** replaces 'targetString' with 'sourceString' * replaces same number of chars as it removes * returns TRUE if replace is successfull * if unsuccessfull, places file pointers back to what they were initially ************************************************************************) procedure ReplaceSource( var ptr2file: FileOfChar; targetString, sourceString: string; var same: boolean); var ch : char; cur_in_pos, cur_out_pos : longint; astring : s_array; (* for comparison *) i, TargetSize, SourceSize, delta: byte; begin delta:=0; same:=FALSE; (* search string not found yet *) for i:=1 to length( astring) do astring[i]:= ' '; TargetSize:=length( targetString); SourceSize:=length( SourceString); gSearchString:=''; gSearchString := targetString; cur_in_pos:=filepos( ptr2file); cur_out_pos:=filepos( wp2); writeln( f, 'R_S Searching for: ', gSearchString); while ( (NOT eof(ptr2file)) AND (NOT same) ) do begin read( ptr2file, ch); write( wp2, ch); shiftLeftString( astring, TargetSize, ch); same:=compareString( targetString, astring, TargetSize); if (same) then begin seek(wp2, filepos(wp2)- TargetSize ); placeString(sourceString); if ( SourceSize > TargetSize) then begin (* written more chars than read *) delta:= SourceSize - TargetSize; for i:= 1 to delta do read( ptr2file, ch); end else if ( TargetSize > SourceSize) then begin (* read more chars than written *) delta:= TargetSize - SourceSize; ch:=' '; for i:= 1 to delta do write( wp2, ch); end; end; end; if (NOT same) then begin SourceString:= 'Can Not find field '+ TargetString; printf( SourceString); (* place file ptr back to what it was originally *) seek( ptr2file, cur_in_pos); seek( wp2, cur_out_pos); end; end; (**************************************************************************) (*** Moves to targetString in WP1 * Does not copy chars from WP1 to WP2 while searching for targetString ************************************************************************) procedure MoveTo( var ptr2file:FileOfChar; targetString: string; var same:boolean); var ch : char; cur_in_pos : longint; astring : s_array; (* for comparison *) i, n : byte; begin same:= FALSE; for i:=1 to length( astring) do astring[i]:= ' '; n:= length( targetString); gSearchString:=''; gSearchString:= targetString; writeln(f, 'M_2 Searching for: ', gSearchString); cur_in_pos:=filepos( ptr2file ); while ( (NOT eof(ptr2file)) AND (NOT same) ) do begin read( ptr2file, ch); shiftLeftString( astring, n, ch); same:= compareString( targetstring, astring, n); end; if (NOT same) then seek( ptr2file, cur_in_pos); end; (**************************************************************************) (* copies document WP1 to WP2 from WP1's current file pointer's position *) procedure CopyDocument( var retChar: char); var ch:char; begin writeln(f, 'Transferring the rest of the document...'); while (NOT EOF(wp1)) do begin read( wp1, ch); write( wp2, ch); end; printf( 'Finished with document.'); retChar:='1'; end; (**************************************************************************) (* * returns contents of field in string, avalue * echo parameter displays contents of field *) procedure getalphafield( var fldhandle:fieldhandle; var avalue:string; echo : boolean ); begin (* returns string from an alphanumeric field *) pxErr:=pxgetalpha(rechandle, fldhandle, avalue); if (pxErr <> pxsuccess) then writeln(f, 'Did NOT transfer an alpha field... ', pxerrmsg(pxerr)); if echo then writeln(f, 'Field number ', fldhandle:2,' has contents: ', avalue ); end; (**************************************************************************) (* * returns contents of field in string, fieldcontent * displays contents of field ***************************************************************************) procedure GetFloat( var fldhandle:fieldhandle; var fieldcontent: string; decimalPlaces: word ); var rvalue: double; blankField: boolean; begin pxErr:= PxFldBlank( recHandle, fldHandle, blankField ); if (pxErr <> pxsuccess) then writeln(f, 'Error in statement PxFldBlank :: ', pxerrmsg(pxerr)); if (blankField) then begin fieldcontent:=''; end else begin (* returns string from an alphanumeric field *) pxErr:=pxGetDoub( rechandle, fldhandle, rvalue); if (pxErr <> pxsuccess) then writeln( f, 'Did NOT transfer an alpha field... ', pxerrmsg(pxerr)); (* convert float1 to ascii string (max size 12 chars) *) str( rvalue:10:decimalPlaces, fieldcontent); (* remove any blanks from ascii string *) fieldcontent:= removeBlanks( fieldcontent); end; writeln(f, 'Field number ', fldhandle:2, ' has contents: ', fieldcontent); end; (**************************************************************************) (* * returns contents of field in double variable, dvalue * displays contents of field * returns true if field was empty ***********************************************************************) procedure GetDoubleField( var fhandle: fieldHandle; var dvalue: double; var var_blank: boolean ); var TempString: string[20]; icode: integer; begin dvalue:=0; var_blank:=FALSE; pxErr:=PXGetDoub( RecHandle, FHandle, dvalue); if (pxErr <> PXsuccess) then writeln( 'Did not transfer a double field...',PXErrMsg(Pxerr)) else writeln('Field number ', fhandle:2,' has contents: ', dvalue:10:2); if IsBlankDouble(dvalue) then var_blank:=TRUE else begin str( dvalue:10:2, TempString); TempString:= RemoveBlanks( TempString); val( TempString, dvalue, icode); end; end; (**************************************************************************) function IsItBlank( fhandle: fieldHandle):boolean; var VarBlank : boolean; begin pxErr:=PXFldBlank( RecHandle, FHandle, VarBlank); if (pxErr <> PXsuccess) then writeln( 'Could not test for blank condition. ', PXErrMsg(Pxerr)) else begin if (VarBlank) then writeln('The Field is Blank.') else writeln('The Field is NOT blank.'); end; IsItBlank:= VarBlank; end; (**************************************************************************) (**** * given fieldhandle returns the following for a Numeric field: * Double Var representation ( rounds off to tenth position only ) * String representation * whether the field is blank *********************************************************************) (****** changed 3-16-94 *********) procedure GetDoubStringAndBlank( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); var icode: integer; begin GetDoubleField( TheFieldNumber, DoubleVar, IsItBlank ); if (NOT IsItBlank) then begin str( DoubleVar:10:1, RetString); RetString:= removeBlanks( RetString); val( RetString, DoubleVar, icode); end else begin DoubleVar:=0.0; RetString:=''; end; end; procedure GetInt( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); var icode: integer; begin GetDoubleField( TheFieldNumber, DoubleVar, IsItBlank ); if (NOT IsItBlank) then begin str( DoubleVar:10:2, RetString); RetString:= removeBlanks( RetString); end else begin DoubleVar:=0; RetString:=''; end; end; procedure GetShort( var TheFieldNumber: fieldHandle; var RetString: string; var IsItBlank: boolean); var dvalue, icode: integer; begin dvalue:=0; IsItBlank:=FALSE; pxErr:=PXGetShort( RecHandle, TheFieldNumber, dvalue); if (pxErr <> PXsuccess) then writeln( 'Did not transfer an integer field...',PXErrMsg(Pxerr)) else writeln('Field number ', TheFieldNumber:2,' has contents: ', dvalue:10); if IsBlankDouble(dvalue) then IsItBlank:=TRUE else begin str( dvalue:10, RetString); RetString:= RemoveBlanks( RetString); val( RetString, dvalue, icode); end; end; (**************************************************************************) procedure TwoPlacesDouble( var TheFieldNumber: fieldHandle; var DoubleVar: double; var RetString: string; var IsItBlank: boolean); var icode: integer; begin GetDoubleField( TheFieldNumber, DoubleVar, IsItBlank ); if (NOT IsItBlank) then begin str( DoubleVar:10:2, RetString); RetString:= removeBlanks( RetString); val( RetString, DoubleVar, icode); end else begin DoubleVar:=0.0; RetString:=''; end; end; (**************************************************************************) procedure CalcSkewField( var TheFieldNumber: fieldHandle; var DoubleVar: double; var FieldsFilled: boolean; n: byte); const max = 2; var IsItBlank : boolean; icode, i: integer; AC, BD: double; dsum : array[1..max] of double; begin FieldsFilled := TRUE; for i:=1 to n do begin GetDoubleField( TheFieldNumber, DoubleVar, IsItBlank ); if (NOT IsItBlank) then begin dsum[i] := DoubleVar; end else FieldsFilled:=FALSE; TheFieldNumber:= TheFieldNumber+1; end; {for ..} If (FieldsFilled) then begin AC := dsum[1]; BD := dsum[max]; DoubleVar := ((2*(AC - BD))/(AC + BD))*100; end; end; (**************************************************************************) function AveNDblFields( var fhandle: fieldhandle; n: byte; var dvar: double):boolean; var blanko,fieldsFilled: boolean; doublevar, dsum : double; i,count : byte; begin dsum:=0; dvar:=0; count:=0; fieldsFilled:=TRUE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin dsum:=dsum+doublevar; count:=count+1; end else fieldsFilled:=FALSE; fhandle:=fhandle+1; end; if (fieldsFilled) then dvar:= dsum/count; AveNDblFields:= fieldsFilled; end; function FldsGreaterThanOne( var fhandle: fieldhandle; n: byte; var dvar: double ):boolean; var blanko, FieldsFilled: boolean; doublevar : double; i : byte; begin fieldsFilled:=TRUE; (* assume: all fields are filled *) dvar:=0; for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin if (doublevar > 1) then dvar:= 2; end else fieldsFilled:=FALSE; fhandle:=fhandle+1; end; FldsGreaterThanOne:=FieldsFilled; end; function NegativeFields( var fhandle: fieldhandle; n: byte):boolean; var blanko, FieldIsNegative: boolean; doublevar : double; i : byte; begin fieldIsNegative:=FALSE; (* assume: all fields are positive *) for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin if (doublevar < 0) then fieldIsNegative:=TRUE; end; fhandle:=fhandle+1; end; NegativeFields:=FieldIsNegative; end; procedure AveStrFields( var fhandle: fieldhandle; n: byte; var avalue: string; var tvalue: string); (**********************************************************************) (** Averages a string and returns 3 different posibilities **********) (** Updated 1/26/95 *******) (**********************************************************************) const max = 3; var blanko,fieldsFilled: boolean; TempString : string; svalue, acc, unacc, mar : string; dsum : array [1..max] of string; i,count : byte; begin dsum[1] := ''; dsum[2] := ''; dsum[3]:= ''; tvalue := ''; acc:= ''; unacc:= ''; mar:= ''; count:=0; fieldsFilled:=TRUE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetAlphaField( fhandle, avalue, blanko ); svalue := RemoveBlanks(avalue); if (blanko) then begin count:=count+1; UpperCase(svalue); dsum[count] := svalue; end else fieldsFilled:=FALSE; fhandle:=fhandle+1; end; acc:=dsum[1]; unacc:=dsum[2]; mar:=dsum[3]; acc := RemoveBlanks(acc); unacc := RemoveBlanks(unacc); mar := RemoveBlanks(mar); If ((acc[1] = unacc[1]) and (unacc[1] = mar[1])) then tvalue := acc Else if (acc[1] = unacc[1]) and not ((acc[1] in ['A','U']) and (unacc[1] in ['A','U']) and (mar[1] in ['A','U'])) then tvalue := acc Else If (acc[1] = mar[1]) and not ((acc[1] in ['A','U']) and (unacc[1] in ['A','U']) and (mar[1] in ['A','U'])) then tvalue := mar Else If (unacc[1] = mar[1]) and not ((acc[1] in ['A','U']) and (unacc[1] in ['A','U']) and (mar[1] in ['A','U'])) then tvalue := unacc else tvalue := '0'; If (tvalue[1] = 'A') then TempString := 'Acceptable' else if (tvalue[1] = 'M') then TempString := 'Marginal' else if (tvalue[1] = 'U') then TempString := 'Unacceptable' else TempString := tvalue + ' is NOT a valid rating!!! Please retest!'; avalue:= TempString; end; procedure Find_Damaged( var fhandle: fieldhandle; n: byte; var avalue: byte; var tvalue: string); (**********************************************************************) (** Finds % of buttons cracked, chipped or broke **********) (** Updated 6/26/95 *******) (**********************************************************************) const max = 3; var blanko,fieldsFilled: boolean; charvalue : char; svalue : string; i : byte; begin tvalue := ''; avalue:=0; fieldsFilled:=TRUE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetAlphaField( fhandle, svalue, blanko ); charvalue := svalue[1]; if (blanko) then begin UpperCase(svalue); if (charvalue in ['C', 'H', 'B']) then avalue:=avalue+10 else tvalue:='Class A1'; end else fieldsFilled:=FALSE; fhandle:=fhandle+1; end; end; (**************************************************************************) procedure dNotEmptyFlag( var pnum: byte); var i : integer; begin writeln( f, ' Flag field is NOT empty.'); val( flag, pnum, i); end; (****************************************************************************) procedure dErrMsg( var p: boolean); begin writeln(f, 'All fields are not filled'); p:=FALSE; end; (***************************************************************************) Procedure ReBoot; const reboot= 'BE REBOOT'; var i: byte; begin if ( NOT DosFile( 'BE.EXE', 0)) then Exit; window( 1, 1, 80, 25); clrscr; TextColor(14); { Yellow = 14 } TextBackground(Blue); for i:= 1 to 255 do begin write(' Reboot'); end; sleep( 5000); clrscr; SwapVectors; Exec( getEnv('COMSPEC'), reboot ); SwapVectors; end; (***************************************************************************) procedure GetWindowCoords( var px1, py1, px2, py2: byte); begin px1:=lo( windMin) + 1; (* store current window coordinates *) py1:=hi( WindMin) + 1; px2:=lo( WindMax) + 1; py2:=hi( WindMax) + 1; end; (***************************************************************************) procedure NewClient; const MkDirFile='MKDIR.DAT'; var NewClientName : string[6]; CompleteDir : string; achar : char; TheError : word; mdfilePtr : TEXT; lx, ly, rx, ry, retbyte, i : byte; begin GetWindowCoords( lx, ly, rx, ry); window( 5, 16, 75, 22); clrscr; TextColor(14); { Yellow = 14 } TextBackground(Blue); NewClientName:=''; CompleteDir:=''; RestoreCursor; write('Enter Name of New Client (6 Characters): '); Readln( NewClientName); HideCursor; NewClientName:= removeBlanks( NewClientName ); if ( Length( NewClientName) > 0 ) then begin gotoxy( 1, 1); clreol; RestoreCursor; write('Make directory for ', NewClientName, '? (Yes/No) '); achar := readkey; HideCursor; if achar in ['Y', 'y'] then begin achar := upcase( NewClientName[1]); if achar in ['A'..'L'] then CompleteDir:= ClientsAtoLDir + '\' + NewClientName else CompleteDir:= ClientsMtoZDir + '\' + NewClientName; i:= pos( '\\', CompleteDir); if (i>0) then begin delete( CompleteDir, i, 1 ); end; gotoxy( 1, wherey); clreol; writeln( 'Created Directory ', CompleteDir); {$i-} mkdir( CompleteDir); {$i+} TheError:= IoResult; if ( TheError<>0 ) then begin if (TheError=5) then begin clrscr; writeln('Directory already exists!'); end else begin writeln(' Error creating directory ', CompleteDir); writeln(' Error Number Returned: ', TheError); end; writeln('Press any key to continue...'); achar:=readkey; clrscr; end else begin retbyte:= AppendFile( mdFilePtr, MkDirFile); if (retbyte in [ 1, 2]) then begin writeln( mdFilePtr, 'Created directory ', CompleteDir); close( mdFilePtr); end; clrscr; end; end; end; window( lx, ly, rx, ry); TextColor(14); { Yellow = 14 } TextBackground(Blue); end; (***************************************************************************) Procedure ReadIniData; var i: byte; ProgName: string; fptr : text; errcode: integer; begin Window( 1, 1, 80, 25); clrscr; TextColor(14); { Yellow = 14 } TextBackground(Blue); If (Lo( DosVersion ) < 3) Then ProgName:='CONFIGUR' else begin ProgName:= ParamStr(0); i:= pos( '.', ProgName); if (i>0) then ProgName[0]:= chr(i-1); end; writeln( 'Program Name: ', ProgName); ProgName:= ProgName + '.INI'; writeln( 'Looking for : ', ProgName,'.'); writeln; if ( DosFile( ProgName, 0) ) then begin assign( fptr, ProgName); {$i-} reset( fptr ); sysErr:=ioresult; {$i+} if (sysErr<>0) then sysError( ProgName ); (* global strings are assigned the corresponding paths *) Readln( fptr, PdoxNetDir ); (* read network path *) Readln( fptr, ClientsAtoLDir); (* read path for clients a to l *) readln( fptr, ClientsMtoZDir); (* read path for clients m to z *) readln( fptr, InvoiceDir); (* read path for client invoice directory *) readln( fptr, PriceListDir); (* read path for Price List *) PdoxNetDir := removeBlanks( PdoxNetDir); ClientsAtoLDir := removeBlanks( ClientsAToLDir ); ClientsMtoZDir := removeBlanks( ClientsMToZDir ); InvoiceDir := removeBlanks( InvoiceDir ); PriceListDir := removeBlanks( PriceListDir ); close(fptr); end else begin writeln; writeln(' Could NOT find ', ProgName,'.'); Writeln(' Need ', ProgName,' to start program.'); writeln; writeln(' You need to run the configuration program OR '); writeln(' create a new ', ProgName,' file with any text editor.'); writeln; writeln(' To create a new ', ProgName ,' file do the following:'); writeln(' 1) On the first line type the path to PARADOX.NET'); writeln(' 2) On the second line type the path to clients A to L'); writeln(' 3) On the third line type the path to clients M to Z'); writeln(' 4) On the fourth line type the path to Invoice for clients'); writeln(' 5) On the fifth line type the path to PRICELST table'); writeln; halt; end; end; (***************************************************************************) procedure closefiles( var xfered: boolean; placeFlagChar: char); var copied: boolean; rk: char; begin copied:=FALSE; if (xfered) then begin close(wp1); (* copiedFile *) close(wp2); (* dummy.wp *) if ( CompareTimeTags( gWPSourceDoc, gCopiedFile)=1 ) then copied:= DosCopy( 'DUMMY.WP', gWPSourceDoc ) else gWpFileOpen:=TRUE; if (copied) then begin update_table( placeFlagChar); printf( 'WP document updated successfully!'); displaySucks( placeFlagChar); end else begin update_table('0'); printf('WP client letter was NOT copied back to source drive!'); displaySucks( placeFlagChar ); end; erase( wp1); (* delete copiedFile *) erase( wp2); (* dummy.wp *) end else begin update_table( placeFlagChar); close( wp1); close( wp2); erase( wp1); (* delete copiedFile *) erase( wp2); (* dummy.wp *) displaySucks( placeFlagChar); end; end; (**************************************************************************) procedure redirect_output( thefile: string); var outputf: string; i: integer; begin outputf:=thefile; i:=pos( '.', outputf); (* creates output file with the same name but different ext *) outputf[i+1]:='O'; outputf[i+2]:='U'; outputf[i+3]:='T'; if (DosFile( outputf, 0) ) then begin if ( too_large( outputf) ) then begin (* create file *) assign( fout, outputf); rewrite( fout); end else begin (* append to existing file *) assign( fout, outputf); append( fout); end; end else begin (* create file *) assign( fout, outputf); rewrite( fout); end; w_date_time; end; (***********************************************************************) (* write date and time to file pointed to by var fout *) procedure w_date_time; var year, month, day, dayofweek: word; hour, minute, sec, sec100 : word; begin getdate( year, month, day, dayofweek); gettime( hour, minute, sec, sec100); write( fout,'********************* ', day, '/', month, '/', year,' **** '); writeln( fout, d2( hour), ':', d2(minute), ':', d2(sec), '*********************************'); end; (**************************************************************************) procedure ProcTableHeader( var FlagChar: Char); begin ClearGlobalFields; fldhandle:=1; getalphafield ( fldhandle, client, TRUE ); fldhandle:=2; getalphafield ( fldhandle, als , TRUE ); fldhandle:=3; getalphafield ( fldhandle, flag, TRUE ); if (length( flag)=0) then FlagChar:= ' ' else FlagChar:= flag[1]; FlagChar:= Upcase( FlagChar); writeln( 'Flag Field Char=', FlagChar, chr(BLOCK) ); end; (***************************************************************************) procedure convertDoub2str( var dvar:double; var theString: string); var i,j:byte; inchar: char; v,f,c: integer; begin str( dvar:5:1, theString); j:= pos( '.', theString); val(theString[j+1],v,c); val(theString[j-1],f,c); if (dvar > 0.00) and (dvar < 1) then begin if (v = 0) and (f=0) then theString[j-2]:=' '; end; if (dvar>0.00) then begin i:=0; repeat inc(i); until (theString[i]<>' '); if (i>1) then theString[i-1]:='+'; end; end; (***************************************************************************) procedure Double2Str( dvar: double; var astr: string; decplaces: byte); begin (* convert float1 to ascii string (max size 12 chars) *) str( dvar:10:decPlaces, astr); (* remove any blanks from ascii string *) astr:= removeBlanks( astr); end; (***************************************************************************) (* averages n double fields/variables; * returns True if all fields/variables have data in them * returns True value for AddTest if range values are dispersed ************) function AveNDoubPlus( var fhandle: fieldhandle; n: byte; var dvar: double; Var AddTest:boolean):boolean; var blanko,fieldsFilled: boolean; doublevar, dsum : double; minval, maxval : double; i,count : byte; begin AddTest:=FALSE; dsum:=0; dvar:=0; count:=0; fieldsFilled:=TRUE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin dsum:=dsum+doublevar; count:=count+1; (* keep track of min and max values *) if (i=1) then begin minval:= doublevar; maxval:= doublevar; end else begin minval:= MinDouble( minval, doublevar); maxval:= MaxDouble( maxval, doublevar); end; end else fieldsFilled:=FALSE; fhandle:=fhandle+1; end; if (fieldsFilled) then begin if (i=5) then AddTest := TRUE else AddTest := FALSE; dvar:= dsum/count; { if (i=3) then begin if (dvar<=20.0) then begin if ((MaxVal-MinVal) > 5.00) then AddTest:=TRUE; end else if (dvar<=120.0) then begin if ((MaxVal-MinVal) > 10.00) then AddTest:=TRUE; end; end; } end; AveNDoubPlus:= fieldsFilled; end; (***************************************************************************) (* returns MAX value from input fields, n = number of fields ************) (***************************************************************************) function MAX( var fhandle: fieldhandle; n: byte ):double; var doublevar : double; minval, maxval : double; blanko : boolean; i,count : byte; begin for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin (* keep track of min and max values *) if (i=1) then begin minval:= doublevar; maxval:= doublevar; end else begin minval:= MinDouble( minval, doublevar); maxval:= MaxDouble( maxval, doublevar); end; end; fhandle:=fhandle+1; end; MAX:= maxval; end; function ValueFound( var fhandle: fieldhandle; n: byte; in_eq: string; in_val: byte ):boolean; var doublevar : double; blanko : boolean; valExists : boolean; i,count : byte; decPart : string; decPartChar : char; TEMP : string; begin valExists := FALSE; for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin (* keep track of > and < values *) if in_eq = '<' then begin if doublevar < in_val then begin ValExists := TRUE; end; end; if in_eq = '>' then begin if doublevar > in_val then begin ValExists := TRUE; end; end; if in_eq = '.' then begin Double2str( doublevar, decPart,1); while Pos('.', decPart) > 0 do decPart := decPart[Pos('.', decPart)+1]; decPart := removeBlanks(decPart); decPartChar := decPart[1]; if NOT (decPartChar in ['0', '5']) then begin ValExists := TRUE; end; end; end; fhandle:=fhandle+1; end; ValueFound := valExists; end; (***************************************************************************) (* returns SUM of input fields, n = number of fields ************) (***************************************************************************) function AddFields( var fhandle: fieldhandle; n: byte ):double; var doublevar : double; val : double; blanko : boolean; i,count : byte; begin doublevar:=0.0; val :=0.0; for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin val:= val+doublevar; end; fhandle:=fhandle+1; end; AddFields:= val; end; (***************************************************************************) (***************************************************************************) (* returns maximum range from input fields, n = number of fields ********) (* Range = MAX-MIN value/MAX value ************) (***************************************************************************) function MaxRange( var fhandle: fieldhandle; n: byte ):double; var doublevar : double; minval, maxval : double; blanko : boolean; i,count : byte; begin for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin (* keep track of min and max values *) if (i=1) then begin minval:= doublevar; maxval:= doublevar; end else begin minval:= MinDouble( minval, doublevar); maxval:= MaxDouble( maxval, doublevar); end; end; fhandle:=fhandle+1; end; MaxRange:= (maxval-minval)/maxval; end; function MaxCarpetRange( var fhandle: fieldhandle; n: byte ):double; var doublevar : double; minval, maxval : double; blanko : boolean; i,count : byte; begin for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin (* keep track of min and max values *) if (i=1) then begin minval:= doublevar; maxval:= doublevar; end else begin minval:= MinDouble( minval, doublevar); maxval:= MaxDouble( maxval, doublevar); end; end; fhandle:=fhandle+1; end; MaxCarpetRange:= (maxval-minval); end; (***************************************************************************) function AveFlameDouble( var fhandle: fieldhandle; n: byte; var dvar: double; Var AddTest:boolean):boolean; var blanko,fieldsFilled: boolean; doublevar, dsum : double; minval, maxval : double; i,count : byte; begin AddTest:=FALSE; dsum:=0; dvar:=0; count:=0; fieldsFilled:=TRUE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin dsum:=dsum+doublevar; count:=count+1; (* keep track of min and max values *) if (i=1) then begin minval:= doublevar; maxval:= doublevar; end else begin minval:= MinDouble( minval, doublevar); maxval:= MaxDouble( maxval, doublevar); end; end else fieldsFilled:=FALSE; if (fhandle <= 7) then begin if (fhandle = 7) then fhandle:=15 else fhandle:=fhandle+1; end else if ((fhandle > 7) and (fhandle <=9)) then begin if (fhandle = 9) then fhandle:=17 else fhandle:=fhandle+1; end else if (fhandle > 15) and (fhandle <=16) then fhandle:=fhandle+1 else if (fhandle > 16) and (fhandle <=19) then fhandle:=fhandle+1; end; if (fieldsFilled) then begin { if (i=5) then AddTest := TRUE else AddTest := FALSE; } dvar:= dsum/count; if (i=5) then begin { if (dvar<=20.0) then begin if ((MaxVal-MinVal) > 5.00) then AddTest:=TRUE; end } if (dvar<=120.0) then begin if ((MaxVal-MinVal) > 10.00) then AddTest:=TRUE; end; end; end; dvar:=MaxVal; AveFlameDouble:= fieldsFilled; end; Procedure ConvToPoint5( dvar: double; var TheString: string); var TempString: String; fraction : String[5]; i, int, code : integer; begin Double2str( dvar, TempString, 2); i:= pos( '.', TempString); if (i>0) then begin fraction:= copy( TempString, i+1, 2); val( fraction, int, code); writeln; writeln( 'Double = ', dvar); writeln( 'Fraction= ', fraction); writeln( 'Integer = ', int ); if (int< 25) then fraction:='0' else if (int>=25) and (int<74) then fraction:='5' else begin dvar:= dvar+1.0; Double2str( dvar, TempString, 2); i:= pos( '.', TempString); fraction:= '0'; end; TempString[ i+1 ]:= fraction[1]; TempString[ 0 ] := chr( i+1); writeln( 'TheString= ', TempString); end; if (TempString='1.0') then TempString:= '1.0 Very severe pilling' else if (TempString='1.5') then TempString:= '1.5 Very severe to severe pilling' else if (TempString='2.0') then TempString:= '2.0 Severe pilling' else if (TempString='2.5') then TempString:= '2.5 Severe to moderate pilling' else if (TempString='3.0') then TempString:= '3.0 Moderate pilling' else if (TempString='3.5') then TempString:= '3.5 Moderate to slight pilling' else if (TempString='4.0') then TempString:= '4.0 Slight pilling' else if (TempString='4.5') then TempString:= '4.5 Slight to no pilling' else if (TempString='5.0') then TempString:= '5.0 No noticeable pilling' else TempString:= 'Ave ' + TempString + ' is NOT a valid rating!'; TheString:= TempString; end; Procedure RoundTo50( ivar: integer; var TheString: string); var TempString: String; digits : String[3]; ThirdDigit, ThirdVal, Third, ForthDigit: String[2]; i, int, dig, dig4, code : integer; begin Str( ivar, TempString); TempString:=RemoveBlanks(TempString); i:=Length(TempString); digits:=copy(TempString, i-1, 2); val(digits, int, code); if (int < 25) then begin TempString[i-1]:='0'; TempString[i]:='0'; end else if ((int > 25) and (int < 50)) then begin TempString[i-1]:='5'; TempString[i]:='0'; end else if ((int > 50) and (int < 75)) then begin TempString[i-1]:='5'; TempString[i]:='0'; end else if (int > 75) then begin ThirdDigit:=copy(TempString,i-2,1); val(ThirdDigit, dig, code); If (dig < 9) then begin dig:=dig+1; Str(dig,Third); delete(TempString,i-2,1); insert(Third,TempString,i-2); TempString[i-1]:='0'; TempString[i]:='0'; end else begin ForthDigit:=copy(TempString,i-3,1); val(ForthDigit, dig4, code); dig4:=dig4+1; Str(dig4,ForthDigit); delete(TempString,i-3,1); insert(ForthDigit,TempString,i-3); TempString[i-2]:='0'; TempString[i-1]:='0'; TempString[i]:='0'; end end; TheString:= TempString; end; Procedure RoundToDec( ivar, dec: integer; var TheString: string); var TempString: String; digits : String[3]; Value_Range : double; i, int, lastdigit, Rounded_value, code : integer; begin Case dec of 10 : Value_Range:=5; 25 : Value_Range:=12.5; 50 : Value_Range:=25; 100 : Value_Range:=50; end; Str( ivar, TempString); TempString:=RemoveBlanks(TempString); i:=Length(TempString); digits:=copy(TempString, i, 1); val(digits, int, code); lastdigit:=dec-(dec-int); if (int < Value_Range) then begin Rounded_value:= ivar-lastdigit; Str(Rounded_value,TempString) end else if (int >= Value_Range) then begin lastdigit:=dec-int; Rounded_value:= ivar+lastdigit; Str(Rounded_value,TempString) end; TheString:= TempString; end; (**************************************************************************) Procedure TaberToPoint5( dvar: double; var TheString: string); var TempString: String; fraction : String[5]; i, int, code : integer; begin Double2str( dvar, TempString, 2); i:= pos( '.', TempString); if (i>0) then begin fraction:= copy( TempString, i+1, 2); val( fraction, int, code); writeln; writeln( 'Double = ', dvar); writeln( 'Fraction= ', fraction); writeln( 'Integer = ', int ); if (int< 25) then fraction:='0' else if (int>=25) and (int<74) then fraction:='5' else begin dvar:= dvar+1.0; Double2str( dvar, TempString, 2); i:= pos( '.', TempString); fraction:= '0'; end; TempString[ i+1 ]:= fraction[1]; TempString[ 0 ] := chr( i+1); writeln( 'TheString= ', TempString); end; if (TempString='1.0') then TempString:= '1.0' else if (TempString='1.5') then TempString:= '1.5' else if (TempString='2.0') then TempString:= '2.0' else if (TempString='2.5') then TempString:= '2.5' else if (TempString='3.0') then TempString:= '3.0' else if (TempString='3.5') then TempString:= '3.5' else if (TempString='4.0') then TempString:= '4.0' else if (TempString='4.5') then TempString:= '4.5' else if (TempString='5.0') then TempString:= '5.0' else TempString:= 'Ave ' + TempString + ' is NOT a valid rating!'; TheString:= TempString; end; function CheckFields( var fhandle: fieldhandle; n: byte ):boolean; var blanko, fieldsChecked: boolean; doublevar, dsum : double; i,count : byte; begin dsum:=0; count:=0; fieldsChecked:=FALSE; (* assume: all fields of table are filled *) for i:=1 to n do begin GetDoubleField( fhandle, doublevar, blanko ); if (not blanko) then begin if (doublevar > 0.2) or (doublevar < 0.001) then fieldsChecked:=TRUE else fieldsChecked:=FALSE; end; fhandle:=fhandle+1; end; CheckFields:= fieldsChecked; end; end. (* Unit *) (************************************************************************)
unit uiform; interface uses ui, uimpl, uihandle; type TWinForm=class(TWinHandle) private protected public constructor Create(Owner:TWinHandle);override; procedure CreatePerform;override; procedure CustomPaint;override; end; TWinModal=class(TWinHandle) private protected wOnKillFocus:TWinHandleEvent; public constructor Create(Owner:TWinHandle);override; function ShowModal:integer;override; procedure Close; procedure CreatePerform;override; procedure ClosePerform;override; procedure KillFocusPerform(handle:HWND);override; property ModalResult:integer read wModalResult write wModalResult; property OnKillFocus:TWinHandleEvent read wOnKillFocus write wOnKillFocus; end; implementation constructor TWinForm.Create(Owner:TWinHandle); begin inherited Create(Owner); CreateFormStyle; hLeft:=50; hTop:=50; hWidth:=800; hHeight:=640; end; procedure TWinForm.CreatePerform; begin inherited; CreateFormWindow; end; procedure TWinForm.CustomPaint; //var r:trect; begin (* inherited; r:=GetClientRect; BeginPaint; Polygon(color, 0, r.Left, r.Top, r.Right-1, r.Bottom-1); DrawText(r, 'form', font, 0, 0, TRANSPARENT, DT_SINGLELINE or DT_CENTER or DT_VCENTER); EndPaint;*) end; constructor TWinModal.Create(Owner:TWinHandle); begin inherited Create(Owner); CreateModalStyle; end; procedure TWinModal.CreatePerform; begin inherited; CreateModalWindow; end; function TWinModal.ShowModal:integer; begin result:=ShowModalWindow; end; procedure TWinModal.Close; begin CloseModalWindow; end; procedure TWinModal.ClosePerform; begin inherited; CloseModalPerform; end; procedure TWinModal.KillFocusPerform; begin inherited; if Assigned(wOnKillFocus) then wOnKillFocus(self) end; end.
unit ARelatoriosServico; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, UCrpe32, StdCtrls, Buttons, Componentes1, ComCtrls, ExtCtrls, PainelGradiente, Localizacao, Mask, DBCtrls, Tabela, DBTables, Db, Grids, DBGrids, numericos; type TFRelatoriosServico = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor2: TPanelColor; Rel: TCrpe; BBotao: TBitBtn; Localiza: TConsultaPadrao; BFechar: TBitBtn; ScrollBox1: TScrollBox; Fundo: TPanelColor; PFilial: TPanelColor; Label24: TLabel; SpeedButton1: TSpeedButton; LFilial: TLabel; EFIlial: TEditLocaliza; PPeriodo: TPanelColor; Label4: TLabel; Data1: TCalendario; Data2: TCalendario; PCodVendedor: TPanelColor; LbVendedores: TLabel; SpeedButton4: TSpeedButton; LVendedor: TLabel; EVendedor: TEditLocaliza; PCodClientes: TPanelColor; Label18: TLabel; SpeedButton2: TSpeedButton; LCliente: TLabel; Eclientes: TEditLocaliza; PForcenecedor: TPanelColor; Label1: TLabel; SpeedButton3: TSpeedButton; Lfornecedor: TLabel; EFornecedor: TEditLocaliza; PLocal: TPanelColor; PFormaPagto: TPanelColor; Label20: TLabel; EFormaPgto: TEditLocaliza; SpeedButton5: TSpeedButton; LFormaPagto: TLabel; Label3: TLabel; Local: TComboBoxColor; PSituacao: TPanelColor; PTipoOS: TPanelColor; Label5: TLabel; TipoOs: TComboBoxColor; Label2: TLabel; ESituacao: TEditLocaliza; SpeedButton7: TSpeedButton; LSituacao: TLabel; PTecnico: TPanelColor; Label6: TLabel; SpeedButton6: TSpeedButton; LTecnico: TLabel; Etecnico: TEditLocaliza; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BBotaoClick(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure RelExecuteBegin(Sender: TObject; var Cancel: Boolean); procedure RelExecuteEnd(Sender: TObject); procedure EFIlialSelect(Sender: TObject); private Identificador : string; VetorMascara : array [1..6] of byte; function DesmontaMascara(var Vetor : array of byte; mascara:string):byte; function SomaPainel : integer; procedure ConfiguraPainels( NomeParametro : string); function RetornaParametro( NomeParametro : string) : string; function TextoDosFiltros : string; public function CarregaConfig(NomeRel, TituloForm : string) : Boolean; end; var FRelatoriosServico: TFRelatoriosServico; implementation uses funstring, fundata, constantes, funObjeto, APrincipal, constmsg, AInicio; {$R *.DFM} {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Formulario ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} { ****************** Na criação do Formulário ******************************** } procedure TFRelatoriosServico.FormCreate(Sender: TObject); begin EFIlial.APermitirVazio := Varia.FilialUsuario = ''; data1.DateTime := PrimeiroDiaMes(date); data2.DateTime := UltimoDiaMes(date); DesmontaMascara(vetormascara, varia.MascaraPlanoConta); end; { ******************* Quando o formulario e fechado ************************** } procedure TFRelatoriosServico.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := CaFree; end; {****************** no show do formulario *********************************** } procedure TFRelatoriosServico.FormShow(Sender: TObject); begin EFIlial.Text := IntToStr(varia.CodigoEmpFil); EFIlial.Atualiza; LOcal.ItemIndex := 0; TipoOS.ItemIndex := 0; end; {****************** fecha o formulario ************************************** } procedure TFRelatoriosServico.BFecharClick(Sender: TObject); begin self.close; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( funcoes de configuracao do relatorio ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******Desmonata a mascara pardão para a configuração das classificações*******} function TFRelatoriosServico.DesmontaMascara(var Vetor : array of byte; mascara:string):byte; var x:byte; 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; {************************** Soma altura dos paineis ***************************} function TFRelatoriosServico.SomaPainel : integer; var laco : Integer; begin result := 0; for laco := 0 to (Fundo.ControlCount -1) do if (Fundo.Controls[laco] is TPanelColor) then if (Fundo.Controls[laco] as TPanelColor).Visible then result := result + (Fundo.Controls[laco] as TPanelColor).Height; end; {*********************** Configura os paineis visiveis ***********************} procedure TFRelatoriosServico.ConfiguraPainels( NomeParametro : string); begin if UpperCase(NomeParametro) = 'FILIAL' then PFilial.Visible := true else if UpperCase(NomeParametro) = 'DIAINICIO' then begin PPeriodo.Visible := true; Data1.Visible := true; end else if UpperCase(NomeParametro) = 'DIAFIM' then begin PPeriodo.Visible := true; Data2.Visible := true; end else if UpperCase(NomeParametro) = 'CODVENDEDOR' then PCodVendedor.Visible := true; if UpperCase(NomeParametro) = 'CODCLIENTE' then PCodClientes.Visible := true; if UpperCase(NomeParametro) = 'CODFORNECEDOR' then PForcenecedor.Visible := true; if UpperCase(NomeParametro) = 'CODFORMAPAGTO' then PFormaPagto.Visible := true; if UpperCase(NomeParametro) = 'LOCALOS' then PLocal.Visible := true; if UpperCase(NomeParametro) = 'TIPOOS' then PTipoOS.Visible := true; if UpperCase(NomeParametro) = 'CODSITUACAO' then PSituacao.Visible := true; if UpperCase(NomeParametro) = 'CODTECNICO' then PTecnico.Visible := true; end; {******************** retorna o valor do parametro ***************************} function TFRelatoriosServico.RetornaParametro( NomeParametro : string) : string; begin result := '@ERRO@'; if UpperCase(NomeParametro) = 'TITULO' then result := 'Relatório de ' + trim(PainelGradiente1.Caption) else if UpperCase(NomeParametro) = 'NOMEEMPRESA' then result := Varia.NomeEmpresa + ' ' + CT_NomeEmpresa else if UpperCase(NomeParametro) = 'EMPRESA' then result := inttostr(varia.CodigoEmpresa) else if UpperCase(NomeParametro) = 'FILIAL' then result := EFilial.text else if UpperCase(NomeParametro) = 'DIAINICIO' then result := inttostr(dia(Data1.DateTime)) else if UpperCase(NomeParametro) = 'MESINICIO' then result := inttostr(mes(Data1.DateTime)) else if UpperCase(NomeParametro) = 'ANOINICIO' then result := inttostr(ano(Data1.DateTime)) else if UpperCase(NomeParametro) = 'DIAFIM' then result := inttostr(dia(Data2.DateTime)) else if UpperCase(NomeParametro) = 'MESFIM' then result := inttostr(mes(Data2.DateTime)) else if UpperCase(NomeParametro) = 'ANOFIM' then result := inttostr(ano(Data2.DateTime)) else if UpperCase(NomeParametro) = 'CODVENDEDOR' then result := EVendedor.Text else if UpperCase(NomeParametro) = 'CODCLIENTE' then result := EClientes.Text else if UpperCase(NomeParametro) = 'CODFORNECEDOR' then result := EFornecedor.Text else if UpperCase(NomeParametro) = 'CODFORMAPAGTO' then result := EFormaPgto.Text else if UpperCase(NomeParametro) = 'LOCALOS' then result := inttostr(Local.ItemIndex) else if UpperCase(NomeParametro) = 'TIPOOS' then result := inttostr(TipoOS.ItemIndex) else if UpperCase(NomeParametro) = 'CODTECNICO' then result := Etecnico.Text else if UpperCase(NomeParametro) = 'CODSITUACAO' then result := ESituacao.Text else aviso('Parametro não configurado ' + NomeParametro); end; function TFRelatoriosServico.TextoDosFiltros : string; begin result := Identificador; if PPeriodo.Visible then begin result := result + '-Período de '; if (Data1.Enabled) then result := result + datetostr(data1.date) else result := 'Todo'; if (Data2.visible) then result := result + ' à ' + datetostr(data2.date); end; if PFilial.Visible then begin result := result + '-Filial: '; if EFIlial.Text <> '' then result := result + LFilial.caption else result := result + 'Todas'; end; if PCodVendedor.Visible then begin result := result + '-Vendedor: '; if EVendedor.Text <> '' then result := result + LVendedor.caption else result := result + 'Todos'; end; if PForcenecedor.Visible then begin result := result + '-Fornecedor: '; if EFornecedor.Text <> '' then result := result + Lfornecedor.caption else result := result + 'Todos'; end; if PFormaPagto.Visible then begin result := result + '-Forma Pagto: '; if EFormaPgto.Text <> '' then result := result + LFormaPagto.caption else result := result + 'Todos'; end; if PSituacao.Visible then begin result := result + '-Situação: '; if ESituacao.Text <> '' then result := result + LSituacao.Caption else result := result + 'Todos'; end; if PCodVendedor.Visible then begin result := result + '-Técnico: '; if Etecnico.Text <> '' then result := result + LTecnico.caption else result := result + 'Todos'; end; end; {******************** Carrega Configuracoes da tela **************************} function TFRelatoriosServico.CarregaConfig(NomeRel, TituloForm : string) : Boolean; var laco : integer; begin result := false; PainelGradiente1.Caption := ' ' + copy(TituloForm,6,length(tituloForm)) + ' '; Identificador := DeletaChars(copy(TituloForm,1,5),'&'); if FileExists(varia.PathRel + NomeRel) then begin rel.ReportName := varia.PathRel + NomeRel; rel.Connect.Retrieve; rel.Connect.DatabaseName := varia.AliasBAseDados; rel.Connect.ServerName := varia.AliasRelatorio; rel.ParamFields.Retrieve; for laco := 0 to rel.ParamFields.Count -1 do ConfiguraPainels(Rel.ParamFields[laco].Name); self.ClientHeight := SomaPainel + 95; result := true; fundo.Align := alClient; end else Aviso('Relatório não encontrado "' + varia.PathRel + NomeRel + '"'); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Gera relatorio ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {*************** Gera o relatorio ****************************************** } procedure TFRelatoriosServico.BBotaoClick(Sender: TObject); var laco : integer; Parametro : string; begin for laco := 0 to rel.ParamFields.Count -1 do begin Parametro := RetornaParametro(Rel.ParamFields[laco].Name); if Parametro = '@ERRO@' then abort; if Parametro <> '' then rel.ParamFields[laco].value := Parametro else rel.ParamFields[laco].value := '0'; end; rel.ReportTitle := TextoDosFiltros; rel.Execute; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Filtros ))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} procedure TFRelatoriosServico.EFIlialSelect(Sender: TObject); begin EFIlial.ASelectLocaliza.Text := ' Select * from CadFiliais as fil ' + ' where c_nom_fan like ''@%'' ' + ' and i_cod_emp = ' + IntTostr(varia.CodigoEmpresa); EFIlial.ASelectValida.Text := ' Select * from CadFiliais where I_EMP_FIL = @% ' + ' and i_cod_emp = ' + IntTostr(varia.CodigoEmpresa); if Varia.FilialUsuario <> '' then begin EFIlial.ASelectValida.add(' and i_emp_fil not in ( ' + Varia.FilialUsuario + ')'); EFIlial.ASelectLocaliza.add(' and i_emp_fil not in ( ' + Varia.FilialUsuario + ')'); end; end; procedure TFRelatoriosServico.RelExecuteBegin(Sender: TObject; var Cancel: Boolean); begin FInicio := TFInicio.Create(SELF); finicio.MudaTexto('Gerando Relatório...'); FInicio.show; FInicio.Refresh; end; procedure TFRelatoriosServico.RelExecuteEnd(Sender: TObject); begin Finicio.close; end; Initialization RegisterClasses([TFRelatoriosServico]); end.
unit VehicleActionsUnit; interface uses SysUtils, BaseActionUnit, System.Generics.Collections, VehicleUnit; type TVehicleActions = class(TBaseAction) public function Get(VehicleId: String; out ErrorString: String): TVehicle; function GetList(out ErrorString: String): TVehicleList; end; implementation uses GenericParametersUnit, SettingsUnit; { TVehicleActions } function TVehicleActions.Get(VehicleId: String; out ErrorString: String): TVehicle; var Parameters: TGenericParameters; begin // todo 5: возвращает список всех автомобилей, а не только VehicleId. Спросил у Олега. Parameters := TGenericParameters.Create; try Parameters.AddParameter('vehicle_id', VehicleId); Result := FConnection.Get(TSettings.EndPoints.Vehicles, Parameters, TVehicle, ErrorString) as TVehicle; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'Vehicle not got'; finally FreeAndNil(Parameters); end; end; function TVehicleActions.GetList(out ErrorString: String): TVehicleList; var Parameters: TGenericParameters; Vehicles: TVehicleList; begin Result := TVehicleList.Create(); Parameters := TGenericParameters.Create; try Vehicles := FConnection.Get(TSettings.EndPoints.Vehicles, Parameters, TVehicleList, ErrorString) as TVehicleList; try if (Vehicles = nil) and (ErrorString = EmptyStr) then ErrorString := 'Vehicles not got'; if (Vehicles <> nil) then begin Result.AddRange(Vehicles); Vehicles.OwnsObjects := False; end; finally FreeAndNil(Vehicles); end; finally FreeAndNil(Parameters); end; end; end.
{ *************************************************************************** Copyright (c) 2015-2021 Kike Pérez Unit : Quick.JSON.Utils Description : Json utils Author : Kike Pérez Version : 1.4 Created : 21/09/2018 Modified : 09/03/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.JSON.Utils; {$i QuickLib.inc} interface uses SysUtils; type TJsonUtils = class public class function IncludeJsonBraces(const json : string) : string; class function RemoveJsonBraces(const json : string) : string; class function JsonFormat(const json : string): string; end; implementation class function TJsonUtils.IncludeJsonBraces(const json : string) : string; begin if (not json.StartsWith('{')) and (not json.EndsWith('}')) then Result := '{' + json + '}' else Result := json; end; class function TJsonUtils.RemoveJsonBraces(const json : string) : string; begin if (json.StartsWith('{')) and (json.EndsWith('}')) then Result := Copy(json,2,Json.Length - 2) else Result := json; end; class function TJsonUtils.JsonFormat(const json : string) : string; const {$IFNDEF DELPHIRX10_UP} sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF}; {$ENDIF} INDENT = ' '; SPACE = ' '; var c : char; LIndent : string; isEOL : Boolean; isIntoString : Boolean; isEscape : Boolean; i : Integer; begin Result := ''; isEOL := True; isIntoString := False; isEscape := False; {$IFNDEF NEXTGEN} for i := 1 to json.Length do {$ELSE} for i := 0 to json.Length - 1 do {$ENDIF} begin c := json[i]; if isIntoString then begin isEOL := False; Result := Result + c; end else begin case c of ':' : Result := Result + c + SPACE; '{','[' : begin LIndent := LIndent + INDENT; if (json[i+1] = '}') or (json[i+1] = ']') then Result := Result + c else Result := Result + c + sLineBreak + LIndent; isEOL := True; end; ',' : begin isEOL := False; Result := Result + c + sLineBreak + LIndent; end; '}',']' : begin Delete(LIndent, 1, Length(INDENT)); if not isEOL then Result := Result + sLineBreak ; if (i<json.Length) and (json[i+1] = ',') then Result := Result + LIndent + c else if (json[i-1] = '}') or (json[i-1] = ']') then Result := Result + c + sLineBreak else Result := Result + LIndent + c + sLineBreak ; isEOL := True; end; else begin isEOL := False; Result := Result + c; end; end; end; if not isEscape and (c = '"') then isIntoString := not isIntoString; isEscape := (c = '\') and not isEscape; end; end; end.
unit uRamalVO; interface uses System.SysUtils, uTableName, uKeyField, uRamalItensVO, System.Generics.Collections; type [TableName('Ramal')] TRamalVO = class private FId: Integer; FDepartamento: string; FItens: TObjectList<TRamalItensVO>; procedure SetDepartamento(const Value: string); procedure SetId(const Value: Integer); procedure SetItens(const Value: TObjectList<TRamalItensVO>); public [KeyField('Ram_Id')] property Id: Integer read FId write SetId; [FieldName('Ram_Departamento')] property Departamento: string read FDepartamento write SetDepartamento; property Itens: TObjectList<TRamalItensVO> read FItens write SetItens; constructor create; destructor destroy; override; end; TListaRamal = TObjectList<TRamalVO>; implementation { TRamalVO } constructor TRamalVO.create; begin inherited create; FItens := TObjectList<TRamalItensVO>.Create(); end; destructor TRamalVO.destroy; begin FreeAndNil(FItens); inherited; end; procedure TRamalVO.SetDepartamento(const Value: string); begin FDepartamento := Value; end; procedure TRamalVO.SetId(const Value: Integer); begin FId := Value; end; procedure TRamalVO.SetItens(const Value: TObjectList<TRamalItensVO>); begin FItens := Value; end; end.
unit kwPopComboBoxGetItemIndex; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopComboBoxGetItemIndex.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ControlsProcessing::pop_ComboBox_GetItemIndex // // *Формат:* // {code} // aControlObj pop:ComboBox:GetItemIdex // {code} // *Описание:* Возвращает текущее значение свойства ItemIndex у контрола TComboBox // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$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} TkwPopComboBoxGetItemIndex = {final} class(_kwComboBoxFromStack_) {* *Формат:* [code] aControlObj pop:ComboBox:GetItemIdex [code] *Описание:* Возвращает текущее значение свойства ItemIndex у контрола TComboBox } protected // realized methods procedure DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopComboBoxGetItemIndex {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopComboBoxGetItemIndex; {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} // start class TkwPopComboBoxGetItemIndex procedure TkwPopComboBoxGetItemIndex.DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); //#UC START# *5049C8740203_5049C6F80317_var* //#UC END# *5049C8740203_5049C6F80317_var* begin //#UC START# *5049C8740203_5049C6F80317_impl* aCtx.rEngine.PushInt(aCombobox.ItemIndex); //#UC END# *5049C8740203_5049C6F80317_impl* end;//TkwPopComboBoxGetItemIndex.DoWithComboBox class function TkwPopComboBoxGetItemIndex.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:ComboBox:GetItemIndex'; end;//TkwPopComboBoxGetItemIndex.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} {$IfEnd} //not NoScripts end.
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // Yawara static site generator // Static Site Generator unit // create CMS functionalities // @author : Zendrael <zendrael@gmail.com> // @date : 2013/10/20 //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ unit untSSG; {$mode objfpc}{$H+} interface uses Classes, SysUtils, math, //lets setup it first untSettings, untPost; type { TSSG } TSSG = class private //catalogs strMenus: TStringList; CatalogIndexes: array of TPost; CatalogTags: TStringList; intNumPosts : Integer; protected // Config: TSettings; Template : TStringList; public // constructor Create; destructor Destroy; override; // procedure Draft; procedure Update( strFileName: string ); procedure Publish; // procedure ProcessTemplate; //function ProcessPage( strDetail: string; strPost: TPost; createLink: boolean): WideString; //function ProcessPost( strDetail: string; strPost: TPost; createLink: boolean): WideString; procedure ProcessFile( strFileName: string; strPath: string; strLocation: String; strFileType:String; bolFinal: Boolean ); procedure CreateIndexes; function CreatePagination(intPage, intNumPages: Integer): String; procedure CreateTagPages; { procedure setCatalog( strTipo: string ); //tags ou posts procedure getCatalog( strTipo: string ); //tags ou posts } end; implementation { TSSG } constructor TSSG.Create; begin inherited Create; end; destructor TSSG.Destroy; begin inherited Destroy; end; procedure TSSG.Draft; var SR: TSearchRec; begin //prepare settings Config := TSettings.Create; Config.getConfig; //get files if FindFirst( Config.getPosts() +'*.txt', faAnyFile, SR) = 0 then begin WriteLn('Criando rascunho de:'); repeat WriteLn( ' ' + SR.Name ); ProcessFile( SR.Name, Config.getPreview(), Config.getPosts(), 'page', False ); until FindNext(SR) <> 0; end; FindClose(SR); Config.Destroy; end; procedure TSSG.Update(strFileName: string); begin if strFileName = EmptyStr then begin // end; end; procedure TSSG.Publish; var SR: TSearchRec; begin //prepare settings Config := TSettings.Create; Config.getConfig; Template := TStringList.Create; ProcessTemplate; //just ONE time intNumPosts:= 0; //only on first time, else get from catalog??? SetLength( CatalogIndexes, 1); //get posts if FindFirst( Config.getPosts() +'*.txt', faAnyFile, SR) = 0 then begin WriteLn('Publicando posts:'); repeat WriteLn( ' ' + SR.Name ); ProcessFile( SR.Name, Config.getFinal(), Config.getPosts(), 'post', True ); inc( intNumPosts ); SetLength( CatalogIndexes, intNumPosts+1); until FindNext(SR) <> 0; end; FindClose(SR); WriteLn(' '); //get pages if FindFirst( Config.getPages() +'*.txt', faAnyFile, SR) = 0 then begin WriteLn('Publicando páginas:'); repeat WriteLn( ' ' + SR.Name ); ProcessFile( SR.Name, Config.getFinal(), Config.getPages(), 'page', True ); until FindNext(SR) <> 0; end; FindClose(SR); //generate indexes CreateIndexes; //generate tags //CreateTagPages; //free memory FreeAndNil( Config ); end; procedure TSSG.ProcessTemplate; var strTheme, strHeader, strBody, strFooter, strMenu: TStringList; begin try //get all HTML of the main template strTheme := TStringList.Create; strTheme.LoadFromFile( Config.getThemes + Config.getThemeName + '/' + 'main.html' ); //replace all main blocks strHeader := TStringList.Create; strBody := TStringList.Create; strFooter := TStringList.Create; strMenu := TStringList.Create; strHeader.LoadFromFile( Config.getThemes + Config.getThemeName + '/' + 'header.html' ); strBody.LoadFromFile( Config.getThemes + Config.getThemeName + '/' + 'body.html' ); strFooter.LoadFromFile( Config.getThemes + Config.getThemeName + '/' + 'footer.html' ); strMenu.LoadFromFile( Config.getThemes + Config.getThemeName + '/' + 'menu.html' ); //build full page strTheme.Text := StringReplace(strTheme.Text, '%%HEADER%%', strHeader.Text, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%BODY%%', strBody.Text, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%FOOTER%%', strFooter.Text, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%MENUS%%', strMenu.Text, [rfreplaceAll]); //replace page info strTheme.Text := StringReplace(strTheme.Text, '%%TITLE%%', Config.getSiteName, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%DESCRIPTION%%', Config.getSiteDescription, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%KEYWORDS%%', Config.getSiteKeywords, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%AUTHOR%%', Config.getSiteAuthor, [rfreplaceAll]); strTheme.Text := StringReplace(strTheme.Text, '%%THEME%%', '../' + Config.getThemes + Config.getThemeName + '/', [rfreplaceAll]); //if is created Template.Text := strTheme.Text; finally FreeAndNil( strTheme ); FreeAndNil( strHeader ); FreeAndNil( strBody ); FreeAndNil( strFooter ); FreeAndNil( strMenu ); end; end; {function TSSG.ProcessPage(strDetail: string; strPost: TPost; createLink: boolean ): WideString; begin end; function TSSG.ProcessPost(strDetail: string; strPost: TPost; createLink: boolean ): WideString; begin end;} procedure TSSG.ProcessFile(strFileName: string; strPath: string; strLocation: String; strFileType:String; bolFinal: Boolean); var strPost: TPost; begin try //get full post strPost := TPost.Create; strPost.setTemplate( Config.getThemes + Config.getThemeName ); strPost.LoadFile( strLocation, strFileName ); strPost.applyTemplate( Template.Text ); strPost.save( strPath + strPost.getFileName ); //remove old extension and add .html //Delete( strFileName, Pos('.', strFileName), Length( strFileName ) ); CatalogIndexes[intNumPosts] := strPost; finally //free up memory //FreeAndNil( strPost ); end; end; procedure TSSG.CreateIndexes; var page, count, limit, startpost, endpost : Integer; index, postlist : TStringList; begin //prepare index := TStringList.Create; postlist := TStringList.Create; limit := StrToInt(Config.getPostsPerPage); startpost := 1; endpost := limit; for page := 1 to ceil( intNumPosts / limit ) do begin //build base file index.Text := Template.Text; postlist.Text := EmptyStr; //run thru posts for count := startpost to endpost do begin postlist.Add( CatalogIndexes[count-1].getSimplePost ); end; startpost := count+1; if page+1 < ceil( intNumPosts / limit ) then endpost := endpost + limit else endpost:= endpost + (intNumPosts mod limit); //replace content index.Text := StringReplace(index.Text, '%%POSTS%%', postlist.Text, [rfreplaceAll]); //replace PREVIOUS and NEXT page links index.Text := StringReplace(index.Text, '%%PAGINATION%%', CreatePagination( page, ceil( intNumPosts / limit ) ), [rfreplaceAll]); //save index if page = 1 then index.SaveToFile( Config.getFinal() + Config.getBlogPage + '.html' ) //'index.html' ) else index.SaveToFile( Config.getFinal() + Config.getBlogPage + '-'+ IntToStr(page) +'.html' );//'index-'+ IntToStr(page) +'.html' ); end; //free up memory FreeAndNil( index ); FreeAndNil( postlist ); end; function TSSG.CreatePagination(intPage, intNumPages: Integer): String; var strLinks : String; begin strLinks := '<ul>'; if intPage = 1 then strLinks := strLinks+'<li><a href="'+ Config.getBlogPage +'-2.html">'+ Config.getPageNext +'</a></li>' else if (intPage > 1) and (intPage < intNumPages) then if (intPage-1) = 1 then strLinks := strLinks+'<li><a href="'+ Config.getBlogPage +'.html">'+ Config.getPagePrev +'</a></li><li><a href="'+ Config.getBlogPage +'-'+IntToStr(intPage+1)+'.html">'+ Config.getPageNext +'</a></li>' else strLinks := strLinks+'<li><a href="'+ Config.getBlogPage +'-'+IntToStr(intPage-1)+'.html">'+ Config.getPagePrev +'</a></li><li><a href="'+ Config.getBlogPage +'-'+IntToStr(intPage+1)+'.html">'+ Config.getPageNext +'</a></li>' else if (intPage-1) = 1 then strLinks := strLinks+'<li><a href="'+ Config.getBlogPage +'.html">'+ Config.getPagePrev +'</a></li>' else strLinks := strLinks+'<li><a href="'+ Config.getBlogPage +'-'+IntToStr(intPage-1)+'.html">'+ Config.getPagePrev +'</a></li>'; strLinks := strLinks+'</ul>'; Result := strLinks; end; procedure TSSG.CreateTagPages; begin end; end.
unit uROHTTPWebsocketServer; interface uses Classes, IdServerIOHandlerWebsocket, IdIOHandlerWebsocket, uROIndyHTTPServer, uROClientIntf, uROServer, uROHTTPDispatch, IdContext, IdCustomHTTPServer, IdCustomTCPServer, uROHash, uROServerIntf; type TROIndyHTTPWebsocketServer = class(TROIndyHTTPServer) protected FHash: TROHash; procedure InternalServerCommandGet(AThread: TIdThreadClass; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override; function GetDispatchersClass: TROMessageDispatchersClass; override; procedure DoWSExecute(AThread: TIdThreadClass); public procedure AfterConstruction; override; destructor Destroy; override; procedure Loaded; override; end; TIdServerWSContext = class(TIdServerContext) private FWebSocketKey: string; FWebSocketVersion: Integer; FPath: string; FWebSocketProtocol: string; FResourceName: string; FOrigin: string; FQuery: string; FHost: string; FWebSocketExtensions: string; FCookie: string; public function IOHandler: TIdIOHandlerWebsocket; public property Path : string read FPath write FPath; property Query : string read FQuery write FQuery; property ResourceName: string read FResourceName write FResourceName; property Host : string read FHost write FHost; property Origin : string read FOrigin write FOrigin; property Cookie : string read FCookie write FCookie; property WebSocketKey : string read FWebSocketKey write FWebSocketKey; property WebSocketProtocol : string read FWebSocketProtocol write FWebSocketProtocol; property WebSocketVersion : Integer read FWebSocketVersion write FWebSocketVersion; property WebSocketExtensions: string read FWebSocketExtensions write FWebSocketExtensions; end; TROHTTPDispatcher_Websocket = class(TROHTTPDispatcher) public function CanHandleMessage(const aTransport: IROTransport; aRequeststream : TStream): boolean; override; end; TROHTTPMessageDispatchers_WebSocket = class(TROHTTPMessageDispatchers) protected function GetDispatcherClass : TROMessageDispatcherClass; override; end; TROTransportContext = class(TInterfacedObject, IROTransport, IROTCPTransport, IROActiveEventServer) private FROServer: TROIndyHTTPServer; FIdContext: TIdServerWSContext; FEventCount: Integer; FClientId: TGUID; private class var FGlobalEventCount: Integer; protected {IROTransport} function GetTransportObject: TObject; {IROTCPTransport} function GetClientAddress : string; {IROActiveEventServer} procedure EventsRegistered(aSender : TObject; aClient: TGUID); procedure DispatchEvent(anEventDataItem : TROEventData; aSessionReference : TGUID; aSender: TObject); // asender is TROEventRepository public //constructor Create(aROServer: TROIndyHTTPServer; aIOHandler: TIdIOHandlerWebsocket); constructor Create(aROServer: TROIndyHTTPServer; aIdContext: TIdServerWSContext); property ClientId: TGUID read FClientId write FClientId; end; implementation uses SysUtils, IdCoderMIME, Windows, uROEventRepository, uROSessions, uROClient; procedure TROIndyHTTPWebsocketServer.AfterConstruction; begin inherited; FHash := TROHash_SHA1.Create(nil); IndyServer.ContextClass := TIdServerWSContext; end; destructor TROIndyHTTPWebsocketServer.Destroy; begin FHash.Free; inherited; end; procedure TROIndyHTTPWebsocketServer.DoWSExecute(AThread: TIdThreadClass); var transport : TROTransportContext; strmRequest, strmResponse: TMemoryStream; wscode: TWSDataCode; wsIO: TIdIOHandlerWebsocket; cWSNR: array[0..3] of AnsiChar; iMsgNr: Integer; msg: TROMessageDispatcher; imsg: IROMessage; begin transport := nil; try while AThread.Connection.Connected do begin if (AThread.Connection.IOHandler.InputBuffer.Size > 0) or AThread.Connection.IOHandler.Readable(5 * 1000) then begin strmResponse := TMemoryStream.Create; strmRequest := TMemoryStream.Create; try wsIO := AThread.Connection.IOHandler as TIdIOHandlerWebsocket; strmRequest.Position := 0; //first is the type: text or bin wscode := TWSDataCode(wsIO.ReadLongWord); //then the length + data = stream wsIO.ReadStream(strmRequest); //ignore ping/pong messages if wscode in [wdcPing, wdcPong] then Continue; if strmRequest.Size < Length('WSNR') + SizeOf(iMsgNr) then Continue; //read messagenr from the end strmRequest.Position := strmRequest.Size - Length('WSNR') - SizeOf(iMsgNr); strmRequest.Read(cWSNR[0], Length(cWSNR)); if (cWSNR <> 'WSNR') then Continue; strmRequest.Read(iMsgNr, SizeOf(iMsgNr)); strmRequest.Position := 0; //trunc extra data strmRequest.Size := strmRequest.Size - Length('WSNR') - SizeOf(iMsgNr); transport := AThread.Data as TROTransportContext; //no RO transport object already made? if transport = nil then begin //create IROTransport object transport := TROTransportContext.Create(Self, AThread as TIdServerWSContext); (transport as IROTransport)._AddRef; //attach RO transport to indy context AThread.Data := transport; //read client GUID the first time (needed to be able to send RO events) msg := Self.Dispatchers.FindDispatcher(transport, strmRequest); imsg := (msg.MessageIntf as IROMessageCloneable).Clone(); imsg.InitializeRead(transport); imsg.ReadFromStream(strmRequest); transport.ClientId := imsg.ClientID; imsg := nil; Assert(not IsEqualGUID(transport.ClientID, EmptyGUID)); end; //EXECUTE FUNCTION Self.DispatchMessage(transport, strmRequest, strmResponse); //write number at end strmResponse.Position := strmResponse.Size; strmResponse.Write(AnsiString('WSNR'), Length('WSNR')); strmResponse.Write(iMsgNr, SizeOf(iMsgNr)); strmResponse.Position := 0; //write result back (of the same type: text or bin) if wscode = wdcText then wsIO.Write(strmResponse, wdtText) else wsIO.Write(strmResponse, wdtBinary) finally strmRequest.Free; strmResponse.Free; end; end else begin wsIO := AThread.Connection.IOHandler as TIdIOHandlerWebsocket; //ping wsIO.WriteData(nil, wdcPing); end; end; finally //detach RO transport if transport <> nil then (transport as IROTransport)._Release; AThread.Data := nil; end; end; function TROIndyHTTPWebsocketServer.GetDispatchersClass: TROMessageDispatchersClass; begin Result := TROHTTPMessageDispatchers_Websocket; end; procedure TROIndyHTTPWebsocketServer.InternalServerCommandGet(AThread: TIdThreadClass; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var sValue: string; context: TIdServerWSContext; begin (* GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 *) (* GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Origin: http://websocket.org Cookie: __utma=99as Connection: Upgrade Host: echo.websocket.org Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw== Upgrade: websocket Sec-WebSocket-Version: 13 *) //Connection: Upgrade if not SameText('Upgrade', ARequestInfo.Connection) then inherited InternalServerCommandGet(AThread, ARequestInfo, AResponseInfo) else begin context := AThread as TIdServerWSContext; //Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== sValue := ARequestInfo.RawHeaders.Values['sec-websocket-key']; //"The value of this header field MUST be a nonce consisting of a randomly // selected 16-byte value that has been base64-encoded" if (sValue <> '') then begin if (Length(TIdDecoderMIME.DecodeString(sValue)) = 16) then context.WebSocketKey := sValue else Abort; //invalid length end else //important: key must exists, otherwise stop! Abort; (* ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ] wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ] 2. The method of the request MUST be GET, and the HTTP version MUST be at least 1.1. For example, if the WebSocket URI is "ws://example.com/chat", the first line sent should be "GET /chat HTTP/1.1". 3. The "Request-URI" part of the request MUST match the /resource name/ defined in Section 3 (a relative URI) or be an absolute http/https URI that, when parsed, has a /resource name/, /host/, and /port/ that match the corresponding ws/wss URI. *) context.ResourceName := ARequestInfo.Document; if ARequestInfo.UnparsedParams <> '' then context.ResourceName := context.ResourceName + '?' + ARequestInfo.UnparsedParams; //seperate parts context.Path := ARequestInfo.Document; context.Query := ARequestInfo.UnparsedParams; //Host: server.example.com context.Host := ARequestInfo.RawHeaders.Values['host']; //Origin: http://example.com context.Origin := ARequestInfo.RawHeaders.Values['origin']; //Cookie: __utma=99as context.Cookie := ARequestInfo.RawHeaders.Values['cookie']; //Sec-WebSocket-Version: 13 //"The value of this header field MUST be 13" sValue := ARequestInfo.RawHeaders.Values['sec-websocket-version']; if (sValue <> '') then begin context.WebSocketVersion := StrToIntDef(sValue, 0); if context.WebSocketVersion < 13 then Abort; //must be at least 13 end else Abort; //must exist context.WebSocketProtocol := ARequestInfo.RawHeaders.Values['sec-websocket-protocol']; context.WebSocketExtensions := ARequestInfo.RawHeaders.Values['sec-websocket-extensions']; //Response (* HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= *) AResponseInfo.ResponseNo := 101; AResponseInfo.ResponseText := 'Switching Protocols'; AResponseInfo.CloseConnection := False; //Connection: Upgrade AResponseInfo.Connection := 'Upgrade'; //Upgrade: websocket AResponseInfo.CustomHeaders.Values['Upgrade'] := 'websocket'; //Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= sValue := Trim(context.WebSocketKey) + //... "minus any leading and trailing whitespace" '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; //special GUID sValue := string(FHash.CalcString(AnsiString(sValue))); //SHA1 + Base64 AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Accept'] := sValue; //send same protocol back? AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Protocol'] := context.WebSocketProtocol; //we do not support extensions yet (gzip deflate compression etc) //AResponseInfo.CustomHeaders.Values['Sec-WebSocket-Extensions'] := context.WebSocketExtensions; //http://www.lenholgate.com/blog/2011/07/websockets---the-deflate-stream-extension-is-broken-and-badly-designed.html //but is could be done using idZlib.pas and DecompressGZipStream etc //send response back AThread.Connection.IOHandler.InputBuffer.Clear; (AThread.Connection.IOHandler as TIdIOHandlerWebsocket).BusyUpgrading := True; AResponseInfo.WriteHeader; //handle all WS communication in seperate loop DoWSExecute(AThread); end; end; procedure TROIndyHTTPWebsocketServer.Loaded; begin inherited; if Self.IndyServer.IOHandler = nil then IndyServer.IOHandler := TIdServerIOHandlerWebsocket.Create(Self); end; { TROTransport } constructor TROTransportContext.Create(aROServer: TROIndyHTTPServer; aIdContext: TIdServerWSContext); begin FROServer := aROServer; FIdContext := aIdContext; end; procedure TROTransportContext.EventsRegistered(aSender: TObject; aClient: TGUID); begin // end; procedure TROTransportContext.DispatchEvent(anEventDataItem: TROEventData; aSessionReference: TGUID; aSender: TObject); var i: Integer; LContext: TIdContext; transport: TROTransportContext; l: TList; ws: TIdIOHandlerWebsocket; cWSNR: array[0..3] of AnsiChar; begin l := FROServer.IndyServer.Contexts.LockList; try if l.Count <= 0 then Exit; anEventDataItem.Data.Position := anEventDataItem.Data.Size - Length('WSNR') - SizeOf(FEventCount); anEventDataItem.Data.Read(cWSNR[0], Length(cWSNR)); //event number not written already? if cWSNR <> 'WSNR' then begin //new event nr FEventCount := -1 * InterlockedIncrement(FGlobalEventCount); //negative = event, positive is normal RO message //overflow? then start again from 0 if FEventCount > 0 then begin InterlockedExchange(FGlobalEventCount, 0); FEventCount := -1 * InterlockedIncrement(FGlobalEventCount); //negative = event, positive is normal RO message end; Assert(FEventCount < 0); //write nr at end of message anEventDataItem.Data.Position := anEventDataItem.Data.Size; anEventDataItem.Data.Write(AnsiString('WSNR'), Length('WSNR')); anEventDataItem.Data.Write(FEventCount, SizeOf(FEventCount)); anEventDataItem.Data.Position := 0; end; //search specific client for i := 0 to l.Count - 1 do begin LContext := TIdContext(l.Items[i]); transport := LContext.Data as TROTransportContext; if transport = nil then Continue; if not IsEqualGUID(transport.ClientId, aSessionReference) then Continue; //direct write event data ws := (LContext.Connection.IOHandler as TIdIOHandlerWebsocket); if not ws.IsWebsocket then Exit; ws.Lock; try ws.Write(anEventDataItem.Data, wdtBinary); finally ws.Unlock; end; end; finally FROServer.IndyServer.Contexts.UnlockList; end; end; function TROTransportContext.GetClientAddress: string; begin Result := FIdContext.Binding.PeerIP; end; function TROTransportContext.GetTransportObject: TObject; begin Result := FROServer; end; { TROHTTPMessageDispatchers_WebSocket } function TROHTTPMessageDispatchers_WebSocket.GetDispatcherClass: TROMessageDispatcherClass; begin result := TROHTTPDispatcher_Websocket; end; { TROHTTPDispatcher_Websocket } function TROHTTPDispatcher_Websocket.CanHandleMessage( const aTransport: IROTransport; aRequeststream: TStream): boolean; var tcp: IROTCPTransport; begin if aRequeststream = nil then result := FALSE else // for preventing warning in FPC result := FALSE; if not Enabled or not Supports(aTransport, IROTCPTransport, tcp) then Exit; if (tcp as TROTransportContext).FIdContext.IOHandler.IsWebsocket then begin //we can handle all kind of messages, independent on the path, so check which kind of message we have Result := Self.Message.IsValidMessage((aRequeststream as TMemoryStream).Memory, aRequeststream.Size); end else Result := inherited CanHandleMessage(aTransport, aRequeststream); end; { TIdServerWSContext } function TIdServerWSContext.IOHandler: TIdIOHandlerWebsocket; begin Result := Self.Connection.IOHandler as TIdIOHandlerWebsocket; end; end.
unit uLogin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFrmLogin = class(TFrame) Label1: TLabel; EdtAgencia: TEdit; Label2: TLabel; EdtContaCorrente: TEdit; BtnConfirmar: TButton; BtnCancelar: TButton; Label3: TLabel; EdtSenha: TEdit; LblAgencia: TLabel; LblConta: TLabel; procedure BtnConfirmarClick(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); procedure EdtAgenciaExit(Sender: TObject); procedure EdtContaCorrenteExit(Sender: TObject); private FConfirmou: boolean; { Identifica se o usuário confirmou ou cancelou o login } FTentativas: integer; { Número de tentativas } FAgenciaOk: boolean; { Confirma se agencia esta ok } FContaOk: boolean; { Confirma se a conta existe } FConta, FAgencia, FSenha: string; { Conta, Agencia e Senha para retornar } public procedure Inicializar; { Inicializa o frame } function Resultado(var Ag: string; var CC: string; var Senha: string): boolean; { Retorna o resultado do formulário } end; implementation uses uFormPrincipal; {$R *.dfm} procedure TFrmLogin.Inicializar; begin { Inicializa variáveis } FConfirmou := False; FTentativas := 0; EdtAgencia.Text := ''; EdtContaCorrente.Text := ''; EdtSenha.Text := ''; LblAgencia.Caption := ''; LblConta.Caption := ''; end; function TFrmLogin.Resultado(var Ag, CC, Senha: string): boolean; begin { Repassa os dados para o formulário que chamou a tela de login } Ag := EdtAgencia.Text; CC := EdtContaCorrente.Text; Senha := EdtSenha.Text; Result := FConfirmou; end; procedure TFrmLogin.BtnConfirmarClick(Sender: TObject); begin { Verifica se os campos estão preenchidos } if Trim(EdtAgencia.Text) = '' then begin ShowMessage('Preencha a agência!'); EdtAgencia.SetFocus; exit; end; if Trim(EdtContaCorrente.Text) = '' then begin ShowMessage('Preencha a conta corrente!'); EdtContaCorrente.SetFocus; exit; end; if Trim(EdtSenha.Text) = '' then begin ShowMessage('Preencha a senha!'); EdtSenha.SetFocus; exit; end; { Verifica se a agência está ok } if not FAgenciaOk then begin EdtAgencia.SetFocus; { incrementa em um o numero de tentativas } //inc(FTentativas); end else begin { Verifica se a conta está ok } if not FContaOk then begin EdtContaCorrente.SetFocus; { incrementa em um o numero de tentativas } inc(FTentativas); end else begin { Verifica se a senha está certa } if FrmPrincipal.CdsContas.FieldByName('SENHA').AsString <> EdtSenha.Text then begin ShowMessage('Senha não confere!'); EdtSenha.SetFocus; { incrementa em um o numero de tentativas } inc(FTentativas); end else begin if FAgenciaOk and FContaOK then FrmPrincipal.AlterarTela(4); end; end; end; { Verifica o total de tentativas } if FTentativas > 3 then begin { Nro nao permitido de tentativas } ShowMessage('Você esgotou as tentatívas possíveis!'); BtnCancelar.Click; exit; end; FConfirmou := True; FConta := EdtContaCorrente.Text; FAgencia := EdtAgencia.Text; FSenha := EdtSenha.Text; end; procedure TFrmLogin.BtnCancelarClick(Sender: TObject); begin { Ocorreu cancelamento } FConfirmou := False; FrmPrincipal.TelaAnterior; end; procedure TFrmLogin.EdtAgenciaExit(Sender: TObject); begin if Trim(EdtAgencia.Text) = '' then exit; { Verifica a existencia da agencia } if FrmPrincipal.CdsAgencias.Locate('CODIGO', EdtAgencia.Text, []) then begin LblAgencia.Caption := FrmPrincipal.CdsAgencias.FieldByName('NOME').AsString; FAgenciaOk := True; end else begin LblAgencia.Caption := 'Agencia inexistente!'; FAgenciaOk := False; end; end; procedure TFrmLogin.EdtContaCorrenteExit(Sender: TObject); begin if Trim(EdtContaCorrente.Text) = '' then exit; { Verifica a existencia da conta } if FrmPrincipal.CdsContas.Locate('AGENCIA;CONTACORRENTE', VarArrayOf([EdtAgencia.Text, EdtContaCorrente.Text]), []) then begin LblConta.Caption := ''; FContaOK := True; end else begin LblConta.Caption := 'Conta não existente!'; FContaOk := False; end; end; end.
unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types, FMX.Menus, System.Actions, FMX.ActnList, FMX.StdActns, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Objects, FMX.TabControl; type TForm1 = class(TForm) ActionList1: TActionList; ToolBar1: TToolBar; FileExit1: TFileExit; MainMenu1: TMainMenu; mnuFichier: TMenuItem; mnuFichierQuitter: TMenuItem; mnuMac: TMenuItem; mnuFichierOuvrir: TMenuItem; mnuFichierEnregistrer: TMenuItem; mnuFichierSeparateur: TMenuItem; btnNouveau: TButton; btnOuvrir: TButton; btnEnregistrer: TButton; btnFermer: TButton; svgOuvrir: TPath; svgEnregistrer: TPath; svgFermer: TPath; svgNew: TPath; mnuFichierFermer: TMenuItem; mnuFichierNouveau: TMenuItem; actNouveauFichier: TAction; actChargerFichier: TAction; actEnregistrerFichier: TAction; actFermerFichier: TAction; StyleBook1: TStyleBook; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; TabControl1: TTabControl; procedure FormCreate(Sender: TObject); procedure actNouveauFichierExecute(Sender: TObject); procedure actFermerFichierExecute(Sender: TObject); procedure actChargerFichierExecute(Sender: TObject); procedure actEnregistrerFichierExecute(Sender: TObject); procedure mmoChangeTracking(Sender: TObject); private procedure CreerUnOngletVide; procedure MetAJourTitreOnglet; procedure PositionneSurMemoDeLOngletActif; { Déclarations privées } protected public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.fmx} uses System.IOUtils; procedure TForm1.actChargerFichierExecute(Sender: TObject); begin if OpenDialog1.Execute and (OpenDialog1.FileName <> '') and tfile.Exists(OpenDialog1.FileName) then begin CreerUnOngletVide; TabControl1.ActiveTab.tagstring := OpenDialog1.FileName; (TabControl1.ActiveTab.TagObject as tmemo).Lines.LoadFromFile (TabControl1.ActiveTab.tagstring); TabControl1.ActiveTab.tag := 0; MetAJourTitreOnglet; end; PositionneSurMemoDeLOngletActif; end; procedure TForm1.actEnregistrerFichierExecute(Sender: TObject); var mmo: tmemo; NomDuFichierOuvert: string; begin if assigned(TabControl1.ActiveTab) and assigned(TabControl1.ActiveTab.TagObject) and (TabControl1.ActiveTab.TagObject is tmemo) and (TabControl1.ActiveTab.tag = 1) then mmo := TabControl1.ActiveTab.TagObject as tmemo else exit; if (mmo.Lines.Count < 1) or ((mmo.Lines.Count = 1) and (mmo.Lines[0].isempty)) then begin mmo.setfocus; TabControl1.ActiveTab.tag := 0; exit; end; NomDuFichierOuvert := TabControl1.ActiveTab.tagstring; if NomDuFichierOuvert.isempty and SaveDialog1.Execute and (SaveDialog1.FileName <> '') then NomDuFichierOuvert := SaveDialog1.FileName; if not NomDuFichierOuvert.isempty then begin mmo.Lines.SaveToFile(NomDuFichierOuvert, tencoding.UTF8); TabControl1.ActiveTab.tagstring := NomDuFichierOuvert; TabControl1.ActiveTab.tag := 0; MetAJourTitreOnglet; end; mmo.setfocus; end; procedure TForm1.actFermerFichierExecute(Sender: TObject); begin if assigned(TabControl1.ActiveTab) then begin if TabControl1.ActiveTab.tag = 1 then actEnregistrerFichierExecute(Sender); TabControl1.delete(TabControl1.ActiveTab.Index); end; PositionneSurMemoDeLOngletActif; end; procedure TForm1.actNouveauFichierExecute(Sender: TObject); begin CreerUnOngletVide; MetAJourTitreOnglet; PositionneSurMemoDeLOngletActif; end; procedure TForm1.CreerUnOngletVide; var ti: ttabitem; mmo: tmemo; begin ti := TabControl1.Add; ti.Text := ''; ti.tagstring := ''; ti.tag := 0; mmo := tmemo.Create(ti); mmo.Parent := ti; ti.TagObject := mmo; mmo.Align := talignlayout.Client; mmo.Lines.Clear; mmo.OnChangeTracking := mmoChangeTracking; TabControl1.ActiveTab := ti; mmo.setfocus; end; procedure TForm1.FormCreate(Sender: TObject); begin {$IF not Defined(MACOS)} // tout sauf macOS mnuMac.Visible := false; {$ELSE} // sur macOS mnuFichierSeparateur.Visible := false; mnuFichierQuitter.Visible := false; {$ENDIF} OpenDialog1.InitialDir := TPath.GetDocumentsPath; SaveDialog1.InitialDir := TPath.GetDocumentsPath; end; procedure TForm1.MetAJourTitreOnglet; begin TabControl1.ActiveTab.Text := TPath.GetFileNameWithoutExtension (TabControl1.ActiveTab.tagstring); if TabControl1.ActiveTab.tag = 1 then TabControl1.ActiveTab.Text := TabControl1.ActiveTab.Text + '(*)'; end; procedure TForm1.PositionneSurMemoDeLOngletActif; begin if assigned(TabControl1.ActiveTab) and assigned(TabControl1.ActiveTab.TagObject) and (TabControl1.ActiveTab.TagObject is tmemo) then (TabControl1.ActiveTab.TagObject as tmemo).setfocus; end; procedure TForm1.mmoChangeTracking(Sender: TObject); begin if TabControl1.ActiveTab.tag = 0 then begin TabControl1.ActiveTab.tag := 1; MetAJourTitreOnglet; end; end; end.
unit CviceniSNakresem; (* Trida TCviceniSNakresem *) interface uses Windows, SysUtils, Classes, Graphics, Controls, ComCtrls, Messages, Variants, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, jpeg, Cviceni,VzorGUI, MyUtils; type TCviceniSNakresem = class (TCviceni) private FPopis:TStringList; FVzor,FSmaz:TSpeedButton; FNakres,PrvniJmeno:String; procedure VzorClick(Sender: TObject); procedure SmazClick(Sender: TObject); public procedure setNazev(Value:String); override; procedure VykresliNakres(Cvs:TCanvas; sirka_nakresu,vyska_nakresu,x,y:integer); procedure VykresliPopis(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer); override; constructor Create(AOwner: TComponent); override; property Vzor:TSpeedButton read FVzor write FVzor; property Smaz:TSpeedButton read FSmaz write FSmaz; property Nakres:String read FNakres write FNakres; property Popis:TStringList read FPopis write FPopis; end; implementation (* procedure TCviceniSNakresem.VykresliNakres FUNKCE: Do zadaneho Canvasu vykresli nakres cviceni... ARGUMENTY: Cvs - Canvas do ktereho se ma kreslit sirka_nakresu - sirka jakou ma nakres mit vyska_nakresu - vyska jakou ma nakres mit x,y - souradnice 'x' a 'y' v plose kam se ma nakres vykreslit *) procedure TCviceniSNakresem.VykresliNakres(Cvs:TCanvas; sirka_nakresu,vyska_nakresu,x,y:integer); var copy,paste:TRect; copyjpg:TJpegImage; copybmp:TBitMap; begin with Cvs do begin //prevede nakres z JPG do bitmapy a tu pak nakopiruje na Canvas copyjpg:=TJpegImage.Create; copyjpg.LoadFromFile(Nakres); copybmp:=TBitMap.Create; copybmp.Assign(copyjpg); copy:=Rect(0,0,240,450); paste:=Rect(x,y, x+sirka_nakresu, y+vyska_nakresu); CopyRect(paste,copybmp.Canvas,copy); end; end; (* procedure TCviceniSNakresem.VykresliPopis FUNKCE: Do zadaneho Canvasu vypise udaje o cviceni... ARGUMENTY: Cvs - Canvas do ktereho se ma kreslit sirka - sirka plochy do ktere se kresli vyska - vyska plochy do ktere se kresli now_y - souradnice 'y' v plose kam se kresli (na jaky radek) *) procedure TCviceniSNakresem.VykresliPopis(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer); var dilek_x,dilek_y,now_x,i:integer; begin if (Delka>0) or (Popis.Count>0) then with Cvs do begin dilek_x:=round(Sirka/190); dilek_y:=round(Vyska/265); now_x:=dilek_x*5; Font.Height:=dilek_y*(-3); //vypise pocet minut a nazev cviceni Font.Style:=[fsBold]; TextOut(now_x,now_y,DelkaStr+' min'); now_x:=now_x+TextWidth('000 min')+dilek_x*5; TextOut(now_x,now_y,Nazev); //vypise komentar/popis cviceni Font.Style:=[]; now_y:=now_y+TextHeight('M')+dilek_y; for i:=0 to Popis.Count-1 do VypisTextDoObrazku(Cvs,now_x,sirka-(dilek_x*5),now_y,Popis.Strings[i]); now_y:=now_y+TextHeight('M')+dilek_y; end; end; procedure TCviceniSNakresem.setNazev(Value:String); begin inherited setNazev(Value); if PrvniJmeno='' then PrvniJmeno:=Value; end; procedure TCviceniSNakresem.VzorClick(Sender: TObject); begin if Vzor.Caption='Vybrat/Vytvořit' then begin Aktual:=0; Form2.Popis.WordWrap:=true; Form2.VypisCviceni(Aktual); end else begin Form2.Name.Text:=Nazev; Form2.Minut.Text:=DelkaStr; Form2.Image1.Picture.LoadFromFile(Nakres); Form2.Popis.Clear; Form2.Popis.Lines.AddStrings(Popis); Form2.Popis.WordWrap:=true; end; if Form2.ShowModal = mrOK then begin Vzor.Caption:='Editovat'; Smaz.Enabled:=true; Nazev:=Form2.Name.Text; if Form2.Minut.Text='' then Form2.Minut.Text:='0'; DelkaStr:=Form2.Minut.Text; Nakres:='cviceni\'+ExtractFileName(SeznamSouboru.Strings[Aktual]); Popis.Clear; Form2.Popis.WordWrap:=false; Popis.AddStrings(Form2.Popis.Lines); end; end; procedure TCviceniSNakresem.SmazClick(Sender: TObject); begin Vzor.Caption:='Vybrat/Vytvořit'; Smaz.Enabled:=false; Nazev:=PrvniJmeno; Nakres:='cviceni\empty.jpg'; Popis.Clear; Delka:=0; end; constructor TCviceniSNakresem.Create(AOwner: TComponent); begin inherited Create(AOwner); Komentar.Visible:=False; Label2.Caption:='Volby:'; //vytvoreni dalsich polozek Vzor:=TSpeedButton.Create(nil); Smaz:=TSpeedButton.Create(nil); //zobrazeni polozek Vzor.Parent:=self; Smaz.Parent:=self; //velikosti polozek Vzor.Height:=21; Smaz.Height:=21; Vzor.Width:=94; Smaz.Width:=94; //umisteni polozek svisle Vzor.Top:=1; Smaz.Top:=1; //umisteni polozek vodorovne Vzor.Left:=320; Smaz.Left:=424; //napisy na polozky Vzor.Caption:='Vybrat/Vytvořit'; Smaz.Caption:='Odstranit'; //font napisu Vzor.Font.Style:=[fsBold]; Smaz.Font.Style:=[fsBold]; //nastaveni funkci Vzor.OnClick:=VzorClick; Smaz.OnClick:=SmazClick; //disabling Smaz.Enabled:=False; //inicializace novych polozek PrvniJmeno:=''; Nakres:='cviceni\empty.jpg'; Popis:=TStringList.Create; end; end.
unit NtUtils.Lsa; interface uses Winapi.WinNt, Winapi.ntlsa, NtUtils.Exceptions, NtUtils.Security.Sid; type TNtxStatus = NtUtils.Exceptions.TNtxStatus; TTranslatedName = NtUtils.Security.Sid.TTranslatedName; TLsaHandle = Winapi.ntlsa.TLsaHandle; TPrivilegeDefinition = record Name: String; LocalValue: TLuid; end; TLogonRightRec = record Value: Cardinal; IsAllowedType: Boolean; Name, Description: String; end; { --------------------------------- Policy ---------------------------------- } // Open LSA for desired access function LsaxOpenPolicy(out PolicyHandle: TLsaHandle; DesiredAccess: TAccessMask; SystemName: String = ''): TNtxStatus; // Close LSA handle procedure LsaxClose(var LsaHandle: TLsaHandle); // Query policy information; free memory with LsaFreeMemory function LsaxQueryPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass; out Status: TNtxStatus): Pointer; // Set policy information function LsaxSetPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass; Data: Pointer): TNtxStatus; { --------------------------------- Accounts -------------------------------- } // Open an account from LSA database function LsaxOpenAccount(out hAccount: TLsaHandle; hPolicy: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; function LsaxOpenAccountEx(out hAccount: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; // Add an account to LSA database function LsaxCreateAccount(out hAccount: TLsaHandle; hPolicy: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; function LsaxCreateAccountEx(out hAccount: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; // Delete account from LSA database function LsaxDeleteAccount(hAccount: TLsaHandle): TNtxStatus; // Enumerate account in the LSA database function LsaxEnumerateAccounts(hPolicy: TLsaHandle; out Accounts: TArray<ISid>): TNtxStatus; // Enumerate privileges assigned to an account function LsaxEnumeratePrivilegesAccount(hAccount: TLsaHandle; out Privileges: TArray<TPrivilege>): TNtxStatus; function LsaxEnumeratePrivilegesAccountBySid(AccountSid: PSid; out Privileges: TArray<TPrivilege>): TNtxStatus; // Assign privileges to an account function LsaxAddPrivilegesAccount(hAccount: TLsaHandle; Privileges: TArray<TPrivilege>): TNtxStatus; // Revoke privileges to an account function LsaxRemovePrivilegesAccount(hAccount: TLsaHandle; RemoveAll: Boolean; Privileges: TArray<TPrivilege>): TNtxStatus; // Assign & revoke privileges to account in one operation function LsaxManagePrivilegesAccount(AccountSid: PSid; RemoveAll: Boolean; Add, Remove: TArray<TPrivilege>): TNtxStatus; // Query logon rights of an account function LsaxQueryRightsAccount(hAccount: TLsaHandle; out SystemAccess: Cardinal): TNtxStatus; function LsaxQueryRightsAccountBySid(AccountSid: PSid; out SystemAccess: Cardinal): TNtxStatus; // Set logon rights of an account function LsaxSetRightsAccount(hAccount: TLsaHandle; SystemAccess: Cardinal): TNtxStatus; function LsaxSetRightsAccountBySid(AccountSid: PSid; SystemAccess: Cardinal): TNtxStatus; { -------------------------------- Privileges ------------------------------- } // Enumerate all privileges on the system function LsaxEnumeratePrivileges(hPolicy: TLsaHandle; out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus; function LsaxEnumeratePrivilegesLocal( out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus; // Convert a numerical privilege value to internal name function LsaxQueryNamePrivilege(hPolicy: TLsaHandle; Luid: TLuid; out Name: String): TNtxStatus; // Convert an privilege's internal name to a description function LsaxQueryDescriptionPrivilege(hPolicy: TLsaHandle; const Name: String; out DisplayName: String): TNtxStatus; // Lookup multiple privilege names and descriptions at once function LsaxLookupMultiplePrivileges(Luids: TArray<TLuid>; out Names, Descriptions: TArray<String>): TNtxStatus; // Get the minimal integrity level required to use a specific privilege function LsaxQueryIntegrityPrivilege(Luid: TLuid): Cardinal; { ------------------------------- Logon Rights ------------------------------ } // Enumerate known logon rights function LsaxEnumerateLogonRights: TArray<TLogonRightRec>; { ----------------------------- SID translation ----------------------------- } // Convert SIDs to account names or at least to SDDL; always succeeds function LsaxLookupSid(Sid: PSid; var Name: TTranslatedName): TNtxStatus; function LsaxLookupSids(Sids: TArray<PSid>; out Names: TArray<TTranslatedName>): TNtxStatus; // Lookup an account on the machine function LsaxLookupUserName(UserName: String; out Sid: ISid): TNtxStatus; // Get current user name and domain function LsaxGetUserName(out Domain, UserName: String): TNtxStatus; overload; function LsaxGetUserName(out FullName: String): TNtxStatus; overload; implementation uses Ntapi.ntdef, Ntapi.ntstatus, Winapi.NtSecApi, Ntapi.ntseapi, System.SysUtils, NtUtils.Tokens.Misc, NtUtils.Access.Expected; { Basic operation } function LsaxOpenPolicy(out PolicyHandle: TLsaHandle; DesiredAccess: TAccessMask; SystemName: String): TNtxStatus; var ObjAttr: TObjectAttributes; SystemNameStr: TLsaUnicodeString; pSystemNameStr: PLsaUnicodeString; begin InitializeObjectAttributes(ObjAttr); if SystemName <> '' then begin SystemNameStr.FromString(SystemName); pSystemNameStr := @SystemNameStr; end else pSystemNameStr := nil; Result.Location := 'LsaOpenPolicy'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @PolicyAccessType; Result.Status := LsaOpenPolicy(pSystemNameStr, ObjAttr, DesiredAccess, PolicyHandle); end; procedure LsaxClose(var LsaHandle: TLsaHandle); begin LsaClose(LsaHandle); LsaHandle := 0; end; function LsaxQueryPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass; out Status: TNtxStatus): Pointer; begin Status.Location := 'LsaQueryInformationPolicy'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TPolicyInformationClass); RtlxComputePolicyQueryAccess(Status.LastCall, InfoClass); Status.Status := LsaQueryInformationPolicy(hPolicy, InfoClass, Result); end; function LsaxSetPolicy(hPolicy: TLsaHandle; InfoClass: TPolicyInformationClass; Data: Pointer): TNtxStatus; begin Result.Location := 'LsaSetInformationPolicy'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TPolicyInformationClass); RtlxComputePolicySetAccess(Result.LastCall, InfoClass); Result.Status := LsaSetInformationPolicy(hPolicy, InfoClass, Data); end; { Accounts } function LsaxOpenAccount(out hAccount: TLsaHandle; hPolicy: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'LsaOpenAccount'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @AccountAccessType; Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType); Result.Status := LsaOpenAccount(hPolicy, AccountSid, DesiredAccess, hAccount); end; function LsaxOpenAccountEx(out hAccount: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; var hPolicy: TLsaHandle; begin Result := LsaxOpenPolicy(hPolicy, POLICY_VIEW_LOCAL_INFORMATION); if Result.IsSuccess then begin Result := LsaxOpenAccount(hAccount, hPolicy, AccountSid, DesiredAccess); LsaxClose(hPolicy); end; end; function LsaxCreateAccount(out hAccount: TLsaHandle; hPolicy: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'LsaCreateAccount'; Result.LastCall.Expects(POLICY_CREATE_ACCOUNT, @PolicyAccessType); Result.Status := LsaCreateAccount(hPolicy, AccountSid, DesiredAccess, hAccount); end; function LsaxCreateAccountEx(out hAccount: TLsaHandle; AccountSid: PSid; DesiredAccess: TAccessMask): TNtxStatus; var hPolicy: TLsaHandle; begin // Try to open account if it already exists Result := LsaxOpenAccountEx(hAccount, AccountSid, DesiredAccess); if Result.Matches(STATUS_OBJECT_NAME_NOT_FOUND, 'LsaOpenAccount') then begin // Create it (requires different access to the policy object) Result := LsaxOpenPolicy(hPolicy, POLICY_CREATE_ACCOUNT); if Result.IsSuccess then begin Result := LsaxCreateAccount(hAccount, hPolicy, AccountSid, DesiredAccess); LsaxClose(hPolicy); end; end; end; function LsaxDeleteAccount(hAccount: TLsaHandle): TNtxStatus; begin Result.Location := 'LsaDelete'; Result.LastCall.Expects(_DELETE, @AccountAccessType); Result.Status := LsaDelete(hAccount); end; function LsaxEnumerateAccounts(hPolicy: TLsaHandle; out Accounts: TArray<ISid>): TNtxStatus; var EnumContext: TLsaEnumerationHandle; Buffer: PSidArray; Count, i: Integer; begin EnumContext := 0; Result.Location := 'LsaEnumerateAccounts'; Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType); Result.Status := LsaEnumerateAccounts(hPolicy, EnumContext, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Accounts, Count); for i := 0 to High(Accounts) do Accounts[i] := TSid.CreateCopy(Buffer{$R-}[i]{$R+}); LsaFreeMemory(Buffer); end; function LsaxEnumeratePrivilegesAccount(hAccount: TLsaHandle; out Privileges: TArray<TPrivilege>): TNtxStatus; var PrivilegeSet: PPrivilegeSet; i: Integer; begin Result.Location := 'LsaEnumeratePrivilegesOfAccount'; Result.LastCall.Expects(ACCOUNT_VIEW, @AccountAccessType); Result.Status := LsaEnumeratePrivilegesOfAccount(hAccount, PrivilegeSet); if not Result.IsSuccess then Exit; SetLength(Privileges, PrivilegeSet.PrivilegeCount); for i := 0 to High(Privileges) do Privileges[i] := PrivilegeSet.Privilege{$R-}[i]{$R+}; LsaFreeMemory(PrivilegeSet); end; function LsaxEnumeratePrivilegesAccountBySid(AccountSid: PSid; out Privileges: TArray<TPrivilege>): TNtxStatus; var hAccount: TLsaHandle; begin Result := LsaxOpenAccountEx(hAccount, AccountSid, ACCOUNT_VIEW); if Result.IsSuccess then begin Result := LsaxEnumeratePrivilegesAccount(hAccount, Privileges); LsaxClose(hAccount); end; end; function LsaxAddPrivilegesAccount(hAccount: TLsaHandle; Privileges: TArray<TPrivilege>): TNtxStatus; var PrivSet: PPrivilegeSet; begin PrivSet := NtxpAllocPrivilegeSet(Privileges); Result.Location := 'LsaAddPrivilegesToAccount'; Result.LastCall.Expects(ACCOUNT_ADJUST_PRIVILEGES, @AccountAccessType); Result.Status := LsaAddPrivilegesToAccount(hAccount, PrivSet); FreeMem(PrivSet); end; function LsaxRemovePrivilegesAccount(hAccount: TLsaHandle; RemoveAll: Boolean; Privileges: TArray<TPrivilege>): TNtxStatus; var PrivSet: PPrivilegeSet; begin PrivSet := NtxpAllocPrivilegeSet(Privileges); Result.Location := 'LsaRemovePrivilegesFromAccount'; Result.LastCall.Expects(ACCOUNT_ADJUST_PRIVILEGES, @AccountAccessType); Result.Status := LsaRemovePrivilegesFromAccount(hAccount, RemoveAll, PrivSet); FreeMem(PrivSet); end; function LsaxManagePrivilegesAccount(AccountSid: PSid; RemoveAll: Boolean; Add, Remove: TArray<TPrivilege>): TNtxStatus; var hAccount: TLsaHandle; begin if (Length(Add) = 0) and (Length(Remove) = 0) and not RemoveAll then begin Result.Status := STATUS_SUCCESS; Exit; end; // Open account when only removing, create account when adding if Length(Add) = 0 then Result := LsaxOpenAccountEx(hAccount, AccountSid, ACCOUNT_ADJUST_PRIVILEGES) else Result := LsaxCreateAccountEx(hAccount, AccountSid, ACCOUNT_ADJUST_PRIVILEGES); if not Result.IsSuccess then Exit; // Add privileges if Length(Add) > 0 then Result := LsaxAddPrivilegesAccount(hAccount, Add); // Remove privileges if Result.IsSuccess and (RemoveAll or (Length(Remove) > 0)) then Result := LsaxRemovePrivilegesAccount(hAccount, RemoveAll, Remove); LsaxClose(hAccount); end; function LsaxQueryRightsAccount(hAccount: TLsaHandle; out SystemAccess: Cardinal): TNtxStatus; begin Result.Location := 'LsaGetSystemAccessAccount'; Result.LastCall.Expects(ACCOUNT_VIEW, @AccountAccessType); Result.Status := LsaGetSystemAccessAccount(hAccount, SystemAccess); end; function LsaxQueryRightsAccountBySid(AccountSid: PSid; out SystemAccess: Cardinal): TNtxStatus; var hAccount: TLsaHandle; begin Result := LsaxOpenAccountEx(hAccount, AccountSid, ACCOUNT_VIEW); if Result.IsSuccess then begin Result := LsaxQueryRightsAccount(hAccount, SystemAccess); LsaxClose(hAccount); end; end; function LsaxSetRightsAccount(hAccount: TLsaHandle; SystemAccess: Cardinal) : TNtxStatus; begin Result.Location := 'LsaSetSystemAccessAccount'; Result.LastCall.Expects(ACCOUNT_ADJUST_SYSTEM_ACCESS, @AccountAccessType); Result.Status := LsaSetSystemAccessAccount(hAccount, SystemAccess); end; function LsaxSetRightsAccountBySid(AccountSid: PSid; SystemAccess: Cardinal): TNtxStatus; var hAccount: TLsaHandle; begin Result := LsaxCreateAccountEx(hAccount, AccountSid, ACCOUNT_ADJUST_SYSTEM_ACCESS); if Result.IsSuccess then begin Result := LsaxSetRightsAccount(hAccount, SystemAccess); LsaxClose(hAccount); end; end; { Privileges } function LsaxEnumeratePrivileges(hPolicy: TLsaHandle; out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus; var EnumContext: TLsaEnumerationHandle; Count, i: Integer; Buffer: PPolicyPrivilegeDefinitionArray; begin EnumContext := 0; Result.Location := 'LsaEnumeratePrivileges'; Result.LastCall.Expects(POLICY_VIEW_LOCAL_INFORMATION, @PolicyAccessType); Result.Status := LsaEnumeratePrivileges(hPolicy, EnumContext, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Privileges, Count); for i := 0 to High(Privileges) do begin Privileges[i].Name := Buffer{$R-}[i]{$R+}.Name.ToString; Privileges[i].LocalValue := Buffer{$R-}[i]{$R+}.LocalValue; end; LsaFreeMemory(Buffer); end; function LsaxEnumeratePrivilegesLocal( out Privileges: TArray<TPrivilegeDefinition>): TNtxStatus; var hPolicy: TLsaHandle; begin Result := LsaxOpenPolicy(hPolicy, POLICY_VIEW_LOCAL_INFORMATION); if Result.IsSuccess then begin Result := LsaxEnumeratePrivileges(hPolicy, Privileges); LsaxClose(hPolicy); end; end; function LsaxQueryNamePrivilege(hPolicy: TLsaHandle; Luid: TLuid; out Name: String): TNtxStatus; var Buffer: PLsaUnicodeString; begin Result.Location := 'LsaLookupPrivilegeName'; Result.LastCall.Expects(POLICY_LOOKUP_NAMES, @PolicyAccessType); Result.Status := LsaLookupPrivilegeName(hPolicy, Luid, Buffer); if Result.IsSuccess then begin Name := Buffer.ToString; LsaFreeMemory(Buffer); end; end; function LsaxQueryDescriptionPrivilege(hPolicy: TLsaHandle; const Name: String; out DisplayName: String): TNtxStatus; var NameStr: TLsaUnicodeString; BufferDisplayName: PLsaUnicodeString; LangId: SmallInt; begin NameStr.FromString(Name); Result.Location := 'LsaLookupPrivilegeDisplayName'; Result.LastCall.Expects(POLICY_LOOKUP_NAMES, @PolicyAccessType); Result.Status := LsaLookupPrivilegeDisplayName(hPolicy, NameStr, BufferDisplayName, LangId); if Result.IsSuccess then begin DisplayName := BufferDisplayName.ToString; LsaFreeMemory(BufferDisplayName); end; end; function LsaxLookupMultiplePrivileges(Luids: TArray<TLuid>; out Names, Descriptions: TArray<String>): TNtxStatus; var hPolicy: TLsaHandle; i: Integer; begin Result := LsaxOpenPolicy(hPolicy, POLICY_LOOKUP_NAMES); if not Result.IsSuccess then Exit; SetLength(Names, Length(Luids)); SetLength(Descriptions, Length(Luids)); for i := 0 to High(Luids) do if not LsaxQueryNamePrivilege(hPolicy, Luids[i], Names[i]).IsSuccess or not LsaxQueryDescriptionPrivilege(hPolicy, Names[i], Descriptions[i]).IsSuccess then begin Result.Location := 'LsaxQueryNamesPrivileges'; Result.Status := STATUS_SOME_NOT_MAPPED; end; end; function LsaxQueryIntegrityPrivilege(Luid: TLuid): Cardinal; begin // Some privileges require a specific integrity level to be enabled. // The ones that require more than Medium also trigger UAC to split logon // sessions. The following data is gathered by experimenting and should be // maintained in sync with Windows behavior when new privileges are // introduced. case TSeWellKnownPrivilege(Luid) of // Ten of them require High SE_CREATE_TOKEN_PRIVILEGE, SE_TCB_PRIVILEGE, SE_TAKE_OWNERSHIP_PRIVILEGE, SE_LOAD_DRIVER_PRIVILEGE, SE_BACKUP_PRIVILEGE, SE_RESTORE_PRIVILEGE, SE_DEBUG_PRIVILEGE, SE_IMPERSONATE_PRIVILEGE, SE_RELABEL_PRIVILEGE, SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE: Result := SECURITY_MANDATORY_HIGH_RID; // Three of them does not require anything SE_CHANGE_NOTIFY_PRIVILEGE, SE_UNDOCK_PRIVILEGE, SE_INCREASE_WORKING_SET_PRIVILEGE: Result := SECURITY_MANDATORY_UNTRUSTED_RID; else // All other require Medium Result := SECURITY_MANDATORY_MEDIUM_RID; end; end; { Logon rights } function LsaxEnumerateLogonRights: TArray<TLogonRightRec>; begin // If someone knows a system function to enumerate logon rights on the system // you are welcome to use it here. SetLength(Result, 10); Result[0].Value := SECURITY_ACCESS_INTERACTIVE_LOGON; Result[0].IsAllowedType := True; Result[0].Name := SE_INTERACTIVE_LOGON_NAME; Result[0].Description := 'Allow interactive logon'; Result[1].Value := SECURITY_ACCESS_NETWORK_LOGON; Result[1].IsAllowedType := True; Result[1].Name := SE_NETWORK_LOGON_NAME; Result[1].Description := 'Allow network logon'; Result[2].Value := SECURITY_ACCESS_BATCH_LOGON; Result[2].IsAllowedType := True; Result[2].Name := SE_BATCH_LOGON_NAME; Result[2].Description := 'Allow batch job logon'; Result[3].Value := SECURITY_ACCESS_SERVICE_LOGON; Result[3].IsAllowedType := True; Result[3].Name := SE_SERVICE_LOGON_NAME; Result[3].Description := 'Allow service logon'; Result[4].Value := SECURITY_ACCESS_REMOTE_INTERACTIVE_LOGON; Result[4].IsAllowedType := True; Result[4].Name := SE_REMOTE_INTERACTIVE_LOGON_NAME; Result[4].Description := 'Allow Remote Desktop Services logon'; Result[5].Value := SECURITY_ACCESS_DENY_INTERACTIVE_LOGON; Result[5].IsAllowedType := False; Result[5].Name := SE_DENY_INTERACTIVE_LOGON_NAME; Result[5].Description := 'Deny interactive logon'; Result[6].Value := SECURITY_ACCESS_DENY_NETWORK_LOGON; Result[6].IsAllowedType := False; Result[6].Name := SE_DENY_NETWORK_LOGON_NAME; Result[6].Description := 'Deny network logon'; Result[7].Value := SECURITY_ACCESS_DENY_BATCH_LOGON; Result[7].IsAllowedType := False; Result[7].Name := SE_DENY_BATCH_LOGON_NAME; Result[7].Description := 'Deny batch job logon'; Result[8].Value := SECURITY_ACCESS_DENY_SERVICE_LOGON; Result[8].IsAllowedType := False; Result[8].Name := SE_DENY_SERVICE_LOGON_NAME; Result[8].Description := 'Deny service logon'; Result[9].Value := SECURITY_ACCESS_DENY_REMOTE_INTERACTIVE_LOGON; Result[9].IsAllowedType := False; Result[9].Name := SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME; Result[9].Description := 'Deny Remote Desktop Services logon'; end; { SID translation} function LsaxLookupSid(Sid: PSid; var Name: TTranslatedName): TNtxStatus; var Sids: TArray<PSid>; Names: TArray<TTranslatedName>; begin SetLength(Sids, 1); Sids[0] := Sid; Result := LsaxLookupSids(Sids, Names); if Result.IsSuccess then Name := Names[0]; end; function LsaxLookupSids(Sids: TArray<PSid>; out Names: TArray<TTranslatedName>): TNtxStatus; var hPolicy: TLsaHandle; BufferDomains: PLsaReferencedDomainList; BufferNames: PLsaTranslatedNameArray; i: Integer; begin Result := LsaxOpenPolicy(hPolicy, POLICY_LOOKUP_NAMES); if not Result.IsSuccess then Exit; // Request translation for all SIDs at once Result.Location := 'LsaLookupSids'; Result.Status := LsaLookupSids(hPolicy, Length(Sids), Sids, BufferDomains, BufferNames); LsaxClose(hPolicy); // Even without mapping we get to know SID types if Result.Status = STATUS_NONE_MAPPED then Result.Status := STATUS_SOME_NOT_MAPPED; if not Result.IsSuccess then Exit; SetLength(Names, Length(SIDs)); for i := 0 to High(Sids) do begin Names[i].SidType := BufferNames{$R-}[i]{$R+}.Use; // Note: for some SID types LsaLookupSids might return SID's SDDL // representation in the Name field. In rare cases it might be empty. Names[i].UserName := BufferNames{$R-}[i]{$R+}.Name.ToString; if Names[i].SidType in [SidTypeInvalid, SidTypeUnknown] then RtlxpApplySddlOverrides(Sids[i], Names[i].UserName); // Negative DomainIndex means the SID does not reference a domain if (BufferNames{$R-}[i]{$R+}.DomainIndex >= 0) and (BufferNames{$R-}[i]{$R+}.DomainIndex < BufferDomains.Entries) then Names[i].DomainName := BufferDomains.Domains[ BufferNames{$R-}[i]{$R+}.DomainIndex].Name.ToString else Names[i].DomainName := ''; end; LsaFreeMemory(BufferDomains); LsaFreeMemory(BufferNames); end; function LsaxLookupUserName(UserName: String; out Sid: ISid): TNtxStatus; var hPolicy: TLsaHandle; Name: TLsaUnicodeString; BufferDomain: PLsaReferencedDomainList; BufferTranslatedSid: PLsaTranslatedSid2; begin Result := LsaxOpenPolicy(hPolicy, POLICY_LOOKUP_NAMES); if not Result.IsSuccess then Exit; Name.FromString(UserName); // Request translation of one name Result.Location := 'LsaLookupNames2'; Result.Status := LsaLookupNames2(hPolicy, 0, 1, Name, BufferDomain, BufferTranslatedSid); if Result.IsSuccess then Sid := TSid.CreateCopy(BufferTranslatedSid.Sid); // LsaLookupNames2 allocates memory even on some errors if Result.IsSuccess or (Result.Status = STATUS_NONE_MAPPED) then begin LsaFreeMemory(BufferDomain); LsaFreeMemory(BufferTranslatedSid); end; end; function LsaxGetUserName(out Domain, UserName: String): TNtxStatus; var BufferUser, BufferDomain: PLsaUnicodeString; begin Result.Location := 'LsaGetUserName'; Result.Status := LsaGetUserName(BufferUser, BufferDomain); if not Result.IsSuccess then Exit; Domain := BufferDomain.ToString; UserName := BufferUser.ToString; LsaFreeMemory(BufferUser); LsaFreeMemory(BufferDomain); end; function LsaxGetUserName(out FullName: String): TNtxStatus; var Domain, UserName: String; begin Result := LsaxGetUserName(Domain, UserName); if not Result.IsSuccess then Exit; if (Domain <> '') and (UserName <> '') then FullName := Domain + '\' + UserName else if Domain <> '' then FullName := Domain else if UserName <> '' then FullName := UserName else begin Result.Location := 'LsaxGetUserName'; Result.Status := STATUS_UNSUCCESSFUL; end; end; end.
// Original Author: Piotr Likus // Replace Components form that lists mapping groups unit GX_ReplaceCompMapGrpList; interface uses Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, GX_ReplaceCompData, GX_BaseForm; type TfmReplaceCompMapGrpList = class(TfmBaseForm) pnlButtons: TPanel; btnAdd: TButton; btnEdit: TButton; btnDelete: TButton; btnExport: TButton; btnImport: TButton; btnClear: TButton; pnlList: TPanel; lbxGroups: TListBox; pnlMain: TPanel; pnlFooter: TPanel; pnlFooterButtons: TPanel; btnOk: TButton; btnCancel: TButton; dlgGetImportFile: TOpenDialog; dlgGetExportFile: TSaveDialog; procedure FormShow(Sender: TObject); procedure lbxGroupsClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnImportClick(Sender: TObject); procedure btnExportClick(Sender: TObject); procedure lbxGroupsDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FConfigData: TReplaceCompData; procedure LoadGroupList; procedure UpdateBtns; procedure ClearAllGroups; function SelectedGroupName: string; procedure DeleteGroup(const GroupName: string; RefreshEnabled: Boolean = True); procedure RefreshList; procedure DeleteGroups(GroupList: TStringList); procedure DeleteSelectedGroups; procedure GetSelectedGroups(GroupList: TStringList); procedure ExecEditGroup(const GroupName: string); procedure ShowError(const Msg: string); procedure ValidateNewName(const OldName, NewName: string); function LocateGroup(const GroupName: string): Boolean; procedure ExecExportTo(const FileName: string); function ConfigurationKey: string; procedure LoadSettings; procedure SaveSettings; public constructor Create(Owner: TComponent; ConfigData: TReplaceCompData); reintroduce; end; implementation {$R *.dfm} uses SysUtils, GX_GenericUtils, GX_ConfigurationInfo; resourcestring SEnterNewName = 'Enter New Group Name'; SName = 'Name'; { TfmReplaceCompMapGrpList } constructor TfmReplaceCompMapGrpList.Create(Owner: TComponent; ConfigData: TReplaceCompData); begin inherited Create(Owner); FConfigData := ConfigData; LoadSettings; end; procedure TfmReplaceCompMapGrpList.FormShow(Sender: TObject); begin LoadGroupList; UpdateBtns; end; procedure TfmReplaceCompMapGrpList.UpdateBtns; var ItemSelectedFlag: Boolean; ItemSelectedCount: Integer; begin ItemSelectedCount := lbxGroups.SelCount; ItemSelectedFlag := (ItemSelectedCount > 0); btnEdit.Enabled := (ItemSelectedCount = 1); btnDelete.Enabled := ItemSelectedFlag; btnExport.Enabled := ItemSelectedFlag; btnClear.Enabled := (lbxGroups.Items.Count > 0); end; procedure TfmReplaceCompMapGrpList.RefreshList; begin LoadGroupList; UpdateBtns; end; procedure TfmReplaceCompMapGrpList.LoadGroupList; var i: Integer; begin lbxGroups.Clear; lbxGroups.Items.BeginUpdate; try for i := 0 to FConfigData.MapGroupList.Count-1 do lbxGroups.Items.Add(FConfigData.MapGroupList[i].Name); finally lbxGroups.Items.EndUpdate; end; end; procedure TfmReplaceCompMapGrpList.lbxGroupsClick(Sender: TObject); begin UpdateBtns; end; procedure TfmReplaceCompMapGrpList.ClearAllGroups; begin FConfigData.MapGroupList.Clear; end; procedure TfmReplaceCompMapGrpList.btnClearClick(Sender: TObject); resourcestring SConfirmClear = 'Are you sure you want to delete all groups?'; begin if MessageDlg(SConfirmClear, mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin ClearAllGroups; RefreshList; end; end; procedure TfmReplaceCompMapGrpList.GetSelectedGroups(GroupList: TStringList); var i: Integer; begin GroupList.Clear; for i := 0 to lbxGroups.Items.Count-1 do if lbxGroups.Selected[i] then GroupList.Add(lbxGroups.Items[i]); end; function TfmReplaceCompMapGrpList.SelectedGroupName: string; var i: Integer; begin Result := ''; i := 0; while i < lbxGroups.Items.Count do begin if lbxGroups.Selected[i] then begin Result := lbxGroups.Items[i]; Break; end else Inc(i); end; end; procedure TfmReplaceCompMapGrpList.DeleteGroup(const GroupName: string; RefreshEnabled: Boolean); var Idx: Integer; begin Idx := FConfigData.MapGroupList.IndexOf(GroupName); if Idx > -1 then begin FConfigData.MapGroupList.Delete(Idx); if RefreshEnabled then RefreshList; end; end; procedure TfmReplaceCompMapGrpList.DeleteGroups(GroupList: TStringList); var i: Integer; begin if GroupList.Count > 0 then begin for i := 0 to GroupList.Count-1 do DeleteGroup(GroupList[i], False); RefreshList; end; end; procedure TfmReplaceCompMapGrpList.DeleteSelectedGroups; var SelectedItems: TStringList; begin SelectedItems := TStringList.Create; try GetSelectedGroups(SelectedItems); DeleteGroups(SelectedItems); finally FreeAndNil(SelectedItems); end; end; procedure TfmReplaceCompMapGrpList.ShowError(const Msg: string); begin MessageDlg(Msg, mtError, [mbOK], 0); end; procedure TfmReplaceCompMapGrpList.btnDeleteClick(Sender: TObject); resourcestring SConfirmDelete = 'Are you sure you want to delete selected group(s)?'; begin if MessageDlg(SConfirmDelete, mtConfirmation, [mbYes, mbNo], 0) = mrYes then DeleteSelectedGroups; end; procedure TfmReplaceCompMapGrpList.ExecEditGroup(const GroupName: string); var GroupObject: TCompRepMapGroupItem; OldName, NewName: string; begin OldName := GroupName; GroupObject := FConfigData.MapGroupList.FindObject(OldName) as TCompRepMapGroupItem; if Assigned(GroupObject) then begin NewName := OldName; if InputQuery(SEnterNewName, SName, NewName) then begin NewName := Trim(NewName); ValidateNewName(OldName, NewName); GroupObject.Name := NewName; RefreshList; LocateGroup(NewName); end; end; end; function TfmReplaceCompMapGrpList.LocateGroup(const GroupName: string): Boolean; var Idx: Integer; begin Idx := lbxGroups.Items.IndexOf(GroupName); Result := (Idx >= 0); if Result then lbxGroups.ItemIndex := Idx; end; procedure TfmReplaceCompMapGrpList.btnEditClick(Sender: TObject); begin ExecEditGroup(SelectedGroupName); end; procedure TfmReplaceCompMapGrpList.ValidateNewName(const OldName, NewName: string); resourcestring SNameNonUnique = 'Name "%s" is not unique!'; SNameRequired = 'Name of group can not be empty!'; var NewIdx, OldIdx: Integer; begin if NewName = '' then begin ShowError(SNameRequired); Abort; end; if OldName = NewName then Exit; NewIdx := FConfigData.MapGroupList.IndexOf(NewName); OldIdx := FConfigData.MapGroupList.IndexOf(OldName); if (NewIdx >= 0) and (NewIdx <> OldIdx) then begin ShowError(Format(SNameNonUnique, [NewName])); Abort; end; end; procedure TfmReplaceCompMapGrpList.btnAddClick(Sender: TObject); var NewName: string; begin NewName := ''; if InputQuery(SEnterNewName, SName, NewName) then begin NewName := Trim(NewName); ValidateNewName('', NewName); FConfigData.MapGroupList.Add(NewName); RefreshList; LocateGroup(NewName); end; end; function TfmReplaceCompMapGrpList.ConfigurationKey: string; begin Result := FConfigData.RootConfigurationKey + PathDelim + Self.ClassName + '\Window'; end; procedure TfmReplaceCompMapGrpList.LoadSettings; var Settings: TGExpertsSettings; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.LoadForm(Self, ConfigurationKey); finally FreeAndNil(Settings); end; EnsureFormVisible(Self); end; procedure TfmReplaceCompMapGrpList.SaveSettings; var Settings: TGExpertsSettings; begin // Do not localize. Settings := TGExpertsSettings.Create; try if not (WindowState in [wsMinimized, wsMaximized]) then begin Settings.SaveForm(Self, ConfigurationKey); end; finally FreeAndNil(Settings); end; end; procedure TfmReplaceCompMapGrpList.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; procedure TfmReplaceCompMapGrpList.btnImportClick(Sender: TObject); begin if dlgGetImportFile.Execute then begin FConfigData.AppendFrom(dlgGetImportFile.FileName); RefreshList; end; end; procedure TfmReplaceCompMapGrpList.btnExportClick(Sender: TObject); begin if dlgGetExportFile.Execute then ExecExportTo(dlgGetExportFile.FileName); end; procedure TfmReplaceCompMapGrpList.ExecExportTo(const FileName: string); var GroupNames: TStringList; begin GroupNames := TStringList.Create; try GetSelectedGroups(GroupNames); FConfigData.SaveTo(FileName, GroupNames); finally FreeAndNil(GroupNames); end; end; procedure TfmReplaceCompMapGrpList.lbxGroupsDblClick(Sender: TObject); begin if btnEdit.Enabled then btnEdit.Click; end; procedure TfmReplaceCompMapGrpList.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i: Integer; begin if (Key = Ord('A')) and (Shift = [ssCtrl]) then begin for i := 0 to lbxGroups.Items.Count - 1 do lbxGroups.Selected[i] := True; Key := 0; end; end; end.
unit ddRTFState; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "dd" // Модуль: "w:/common/components/rtl/Garant/dd/ddRTFState.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::dd::RTFSupport::ddRTFState // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses l3ProtoPersistent, l3ProtoPersistentRefList, ddBase, ddRowProperty, RTFtypes, ddCharacterProperty, ddParagraphProperty, Classes ; type TddRTFState = class(Tl3ProtoPersistent) private // private fields f_BOP : TddBorder; {* Поле для свойства BOP} f_CEP : TddCellProperty; {* Поле для свойства CEP} f_CHP : TddCharacterProperty; {* Поле для свойства CHP} f_PAP : TddParagraphProperty; {* Поле для свойства PAP} f_RDS : TRDS; {* Поле для свойства RDS} f_SEP : TddSectionProperty; {* Поле для свойства SEP} f_TAP : TddRowProperty; {* Поле для свойства TAP} f_SkipGroup : Boolean; {* Поле для свойства SkipGroup} protected // property methods procedure pm_SetBOP(aValue: TddBorder); procedure pm_SetCHP(aValue: TddCharacterProperty); procedure pm_SetPAP(aValue: TddParagraphProperty); procedure pm_SetSEP(aValue: TddSectionProperty); procedure pm_SetTAP(aValue: TddRowProperty); protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // overridden public methods procedure Assign(Source: TPersistent); override; public // public methods function Clone: TddRTFState; constructor Create; reintroduce; public // public properties property BOP: TddBorder read f_BOP write pm_SetBOP; property CEP: TddCellProperty read f_CEP write f_CEP; property CHP: TddCharacterProperty read f_CHP write pm_SetCHP; property PAP: TddParagraphProperty read f_PAP write pm_SetPAP; property RDS: TRDS read f_RDS write f_RDS; property SEP: TddSectionProperty read f_SEP write pm_SetSEP; property TAP: TddRowProperty read f_TAP write pm_SetTAP; property SkipGroup: Boolean read f_SkipGroup write f_SkipGroup; end;//TddRTFState TrtfStateStack = class(Tl3ProtoPersistentRefList) public // public methods function Peek: TddRTFState; function Pop: TddRTFState; procedure Push; function PeekPrev: TddRTFState; end;//TrtfStateStack implementation uses SysUtils ; // start class TddRTFState function TddRTFState.Clone: TddRTFState; //#UC START# *51DBBF76006A_51D287250128_var* //#UC END# *51DBBF76006A_51D287250128_var* begin //#UC START# *51DBBF76006A_51D287250128_impl* Result := TddRTFState.Create; Result.Assign(Self); Result.PAP.anInherited := True; //#UC END# *51DBBF76006A_51D287250128_impl* end;//TddRTFState.Clone constructor TddRTFState.Create; //#UC START# *51DBBF960279_51D287250128_var* //#UC END# *51DBBF960279_51D287250128_var* begin //#UC START# *51DBBF960279_51D287250128_impl* inherited; f_CHP := TddCharacterProperty.Create(nil); f_CHP.Reset; f_PAP := TddParagraphProperty.Create(nil); f_BOP := TddBorder.Create(nil); f_BOP.IsFramed := False; f_TAP := TddRowProperty.Create(nil); f_TAP.Border.isFramed := False; f_CEP := TddCellProperty.Create(nil); f_CEP.Border.isFramed := False; f_SEP := TddSectionProperty.Create(nil); f_SkipGroup := False; f_RDS := rdsNone; //#UC END# *51DBBF960279_51D287250128_impl* end;//TddRTFState.Create procedure TddRTFState.pm_SetBOP(aValue: TddBorder); //#UC START# *51DBBCC90082_51D287250128set_var* //#UC END# *51DBBCC90082_51D287250128set_var* begin //#UC START# *51DBBCC90082_51D287250128set_impl* f_BOP.Assign(aValue); //#UC END# *51DBBCC90082_51D287250128set_impl* end;//TddRTFState.pm_SetBOP procedure TddRTFState.pm_SetCHP(aValue: TddCharacterProperty); //#UC START# *51DBBDAB0317_51D287250128set_var* //#UC END# *51DBBDAB0317_51D287250128set_var* begin //#UC START# *51DBBDAB0317_51D287250128set_impl* f_CHP.Assign(aValue); //#UC END# *51DBBDAB0317_51D287250128set_impl* end;//TddRTFState.pm_SetCHP procedure TddRTFState.pm_SetPAP(aValue: TddParagraphProperty); //#UC START# *51DBBDEB02B1_51D287250128set_var* //#UC END# *51DBBDEB02B1_51D287250128set_var* begin //#UC START# *51DBBDEB02B1_51D287250128set_impl* f_PAP.Assign(aValue); //#UC END# *51DBBDEB02B1_51D287250128set_impl* end;//TddRTFState.pm_SetPAP procedure TddRTFState.pm_SetSEP(aValue: TddSectionProperty); //#UC START# *51DBBEBC0085_51D287250128set_var* //#UC END# *51DBBEBC0085_51D287250128set_var* begin //#UC START# *51DBBEBC0085_51D287250128set_impl* f_SEP.Assign(aValue); //#UC END# *51DBBEBC0085_51D287250128set_impl* end;//TddRTFState.pm_SetSEP procedure TddRTFState.pm_SetTAP(aValue: TddRowProperty); //#UC START# *51DBBF08003A_51D287250128set_var* //#UC END# *51DBBF08003A_51D287250128set_var* begin //#UC START# *51DBBF08003A_51D287250128set_impl* f_TAP.Assign(aValue); //#UC END# *51DBBF08003A_51D287250128set_impl* end;//TddRTFState.pm_SetTAP procedure TddRTFState.Assign(Source: TPersistent); //#UC START# *478CF34E02CE_51D287250128_var* var aState: TddRTFState absolute Source; //#UC END# *478CF34E02CE_51D287250128_var* begin //#UC START# *478CF34E02CE_51D287250128_impl* if (Source Is TddRTFState) then begin f_PAP.Assign(aState.PAP); f_CHP.Assign(aState.CHP); f_BOP.Assign(aState.BOP); f_TAP.Assign(aState.TAP); f_Cep.Assign(aState.CEP); f_SkipGroup:= aState.SkipGroup; f_RDS:= aState.RDS; f_SEP.Assign(aState.SEP); end else inherited Assign(Source); //#UC END# *478CF34E02CE_51D287250128_impl* end;//TddRTFState.Assign procedure TddRTFState.Cleanup; //#UC START# *479731C50290_51D287250128_var* //#UC END# *479731C50290_51D287250128_var* begin //#UC START# *479731C50290_51D287250128_impl* FreeAndNil(f_CHP); FreeAndNil(f_PAP); FreeAndNil(f_BOP); FreeAndNil(f_TAP); FreeAndNil(f_CEP); FreeAndNil(f_SEP); inherited ; //#UC END# *479731C50290_51D287250128_impl* end;//TddRTFState.Cleanup // start class TrtfStateStack function TrtfStateStack.Peek: TddRTFState; //#UC START# *51DBC0660357_51DBBFFD0351_var* //#UC END# *51DBC0660357_51DBBFFD0351_var* begin //#UC START# *51DBC0660357_51DBBFFD0351_impl* if Count = 0 then Result := nil else Result := TddRTFState(Last); //#UC END# *51DBC0660357_51DBBFFD0351_impl* end;//TrtfStateStack.Peek function TrtfStateStack.Pop: TddRTFState; //#UC START# *51DBC08B031C_51DBBFFD0351_var* //#UC END# *51DBC08B031C_51DBBFFD0351_var* begin //#UC START# *51DBC08B031C_51DBBFFD0351_impl* Result := Peek; DeleteLast; //#UC END# *51DBC08B031C_51DBBFFD0351_impl* end;//TrtfStateStack.Pop procedure TrtfStateStack.Push; //#UC START# *51DBC0AA0101_51DBBFFD0351_var* var l_State: TddRTFState; //#UC END# *51DBC0AA0101_51DBBFFD0351_var* begin //#UC START# *51DBC0AA0101_51DBBFFD0351_impl* if Count = 0 then l_State := TddRTFState.Create else l_State := Peek.Clone; try Add(l_State); finally FreeAndNil(l_State); end; //#UC END# *51DBC0AA0101_51DBBFFD0351_impl* end;//TrtfStateStack.Push function TrtfStateStack.PeekPrev: TddRTFState; //#UC START# *51DD394E0093_51DBBFFD0351_var* var l_Count: Integer; //#UC END# *51DD394E0093_51DBBFFD0351_var* begin //#UC START# *51DD394E0093_51DBBFFD0351_impl* l_Count := Count; Dec(l_Count, 2); if l_Count < 0 then Result := nil else Result := TddRTFState(Items[l_Count]); //#UC END# *51DD394E0093_51DBBFFD0351_impl* end;//TrtfStateStack.PeekPrev end.
unit AceDS; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses {$ifdef AceBDE} db, {$ifndef VCL130PLUS} dbtables, {$endif} {$endif} classes; type TAceDataSource = class(TObject) private protected public DataSource: TDataSource; CloseDataSource: Boolean; UnableToActivate: Boolean; constructor Create(DS: TDataSource); virtual; destructor Destroy; override; procedure CloseSource; function OpenSource: Boolean; end; TAceDataSourceManager = class(TObject) private protected public DSList: TList; constructor Create; virtual; destructor Destroy; override; procedure CloseDataSources; function ActivateDataSource(DS: TDataSource): Boolean; end; implementation constructor TAceDataSource.Create(DS: TDataSource); begin DataSource := DS; CloseDataSource := False; UnableToActivate := False; end; destructor TAceDataSource.Destroy; begin CloseSource; inherited Destroy; end; function TAceDataSource.OpenSource: Boolean; begin Result := False; if DataSource <> nil then begin if DataSource.DataSet <> nil then begin if Not DataSource.DataSet.Active then begin try DataSource.DataSet.Active := True; CloseDataSource := DataSource.DataSet.Active; UnableToActivate := Not CloseDataSource; Result := CloseDataSource; except UnableToActivate := True; end; end else Result := True; end; end; end; procedure TAceDataSource.CloseSource; begin if CloseDataSource then begin if DataSource <> nil then begin if DataSource.DataSet <> nil then begin if DataSource.DataSet.Active then begin DataSource.DataSet.Active := False; CloseDataSource := False; end; end; end; end; UnableToActivate := False; end; constructor TAceDataSourceManager.Create; begin DSList := TList.Create; end; destructor TAceDataSourceManager.Destroy; begin CloseDataSources; if DSList <> nil then DSList.Free; inherited Destroy; end; function TAceDataSourceManager.ActivateDataSource(DS: TDataSource): Boolean; var ADS: TAceDataSource; Duplicate: Boolean; Spot: Integer; begin Result := False; if DS <> nil then begin Spot := 0; Duplicate := False; While Not Duplicate And ( Spot < DSList.Count) do begin ADS := DSList.Items[Spot]; if ADS.DataSource = DS then Duplicate := True; Inc(Spot); end; if Not Duplicate then begin ADS := TAceDataSource.Create(DS); DSList.Add(ADS); Result := ADS.OpenSource; end else begin if DS.DataSet <> nil then Result := DS.DataSet.Active; end; end; end; procedure TAceDataSourceManager.CloseDataSources; var ADS: TAceDataSource; Spot: Integer; begin for Spot := 0 to DSList.Count - 1 do begin ADS := DSList.Items[Spot]; ADS.CloseSource; ADS.Free; end; DSList.Clear; end; end.
/// <summary> /// From Microsoft Docs: Azure Data Lake Store is an enterprise-wide /// hyper-scale repository for big data analytic workloads. Azure Data Lake /// enables you to capture data of any size, type, and ingestion speed in one /// single place for operational and exploratory analytics /// </summary> /// <remarks> /// Some useful links: /// <list type="bullet"> /// <item> /// <see href="https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-overview"> /// Overview of Azure Data Lake Store</see> /// </item> /// </list> /// </remarks> unit ADLSMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ADLSConnector.Interfaces, ADLSConnector.Presenter, ADLSFileManager.Interfaces, ADLSFileManager.Presenter, IPPeerClient, REST.Response.Adapter, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, Vcl.ComCtrls, Vcl.Imaging.pngimage, System.Generics.Collections; type TfrmADLSMain= class(TForm, IADLSConnectorView, IADLSFileManagerView) pnlHeader: TPanel; pgcMain: TPageControl; tsConnector: TTabSheet; tsFileManager: TTabSheet; sbConnector: TScrollBox; edt_Connector_AccessTokenEndpoint: TLabeledEdit; edt_Connector_ClientID: TLabeledEdit; edt_Connector_ClientSecret: TLabeledEdit; edt_Connector_AccessToken: TLabeledEdit; edt_Connector_AuthCode: TLabeledEdit; edt_Connector_BaseURL: TLabeledEdit; edt_Connector_AuthorizationEndpoint: TLabeledEdit; edt_FilePath: TLabeledEdit; edt_FileManager_BaseURL: TLabeledEdit; btnGetToken: TButton; btnOpenFile: TButton; btnUpload: TButton; odSelectFile: TOpenDialog; imgAzureDataLake: TImage; sbResponse: TScrollBox; memoResponseData: TMemo; cbxADLSFolder: TComboBox; lblFolder: TLabel; btnFillCbxDirectory: TButton; pnlFooter: TPanel; procedure FormCreate(Sender: TObject); procedure btnGetTokenClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnOpenFileClick(Sender: TObject); procedure btnUploadClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnFillCbxDirectoryClick(Sender: TObject); private const APP_TITLE = 'Azure Data Lake Store Library for Delphi'; private FADLSConnectorPresenter: TADLSConnectorPresenter; FADLSFileManagerPresenter: TADLSFileManagerPresenter; public // Input connector function GetBaseURL: string; function GetClientID: string; function GetClientSecret: string; function GetAccessTokenEndpoint: string; function GetAuthorizationEndpoint: string; // Input file manager function GetFMBaseURL: string; function GetFMDirectory: string; function GetFMFilePath: string; // Output connector procedure SetAccessToken(const AValue: string); procedure SetResponseData(const AValue: string); procedure AddResponseData(const AValue: string); // Output file manager procedure DisplayFMMessage(AValue: string); procedure SetFMDirectory(AValue: TList<string>); procedure SetFMResponseData(const AValue: string); procedure AddFMResponseData(const AValue: string); end; var frmADLSMain: TfrmADLSMain; implementation {$R *.dfm} { TfrmADLSConnector } procedure TfrmADLSMain.AddFMResponseData(const AValue: string); begin memoResponseData.Lines.Add(AValue); end; procedure TfrmADLSMain.AddResponseData(const AValue: string); begin memoResponseData.Lines.Add(AValue); end; procedure TfrmADLSMain.btnFillCbxDirectoryClick(Sender: TObject); begin FADLSFileManagerPresenter.ListFolders; end; procedure TfrmADLSMain.btnGetTokenClick(Sender: TObject); begin FADLSConnectorPresenter.GetAccessToken; end; procedure TfrmADLSMain.btnOpenFileClick(Sender: TObject); begin odSelectFile.Filter := 'JSON and TXT files (*.json; *.txt)|*.json; *.txt'; odSelectFile.FilterIndex := 2; if odSelectFile.Execute then edt_FilePath.Text := odSelectFile.FileName; end; procedure TfrmADLSMain.btnUploadClick(Sender: TObject); begin FADLSFileManagerPresenter.UploadFile; end; procedure TfrmADLSMain.Button1Click(Sender: TObject); begin FADLSFileManagerPresenter.GetListFolders; end; procedure TfrmADLSMain.DisplayFMMessage(AValue: string); begin Application.MessageBox(PChar(AValue), PChar(APP_TITLE), MB_OK); end; procedure TfrmADLSMain.FormClose(Sender: TObject; var Action: TCloseAction); begin FADLSFileManagerPresenter.Free; FADLSConnectorPresenter.Free; end; procedure TfrmADLSMain.FormCreate(Sender: TObject); begin FADLSConnectorPresenter := TADLSConnectorPresenter.Create(Self); FADLSFileManagerPresenter := TADLSFileManagerPresenter.Create(FADLSConnectorPresenter, Self); SetResponseData(''); end; function TfrmADLSMain.GetAccessTokenEndpoint: string; begin Result := edt_Connector_AccessTokenEndpoint.Text; end; function TfrmADLSMain.GetAuthorizationEndpoint: string; begin Result := edt_Connector_AuthorizationEndpoint.Text end; function TfrmADLSMain.GetBaseURL: string; begin Result := edt_Connector_BaseURL.Text; end; function TfrmADLSMain.GetClientID: string; begin Result := edt_Connector_ClientID.Text; end; function TfrmADLSMain.GetClientSecret: string; begin Result := edt_Connector_ClientSecret.Text; end; function TfrmADLSMain.GetFMDirectory: string; begin Result := cbxADLSFolder.Text; end; function TfrmADLSMain.GetFMBaseURL: string; begin Result := edt_FileManager_BaseURL.Text; end; function TfrmADLSMain.GetFMFilePath: string; begin Result := edt_FilePath.Text end; procedure TfrmADLSMain.SetAccessToken(const AValue: string); begin edt_Connector_AccessToken.Text := AValue; end; procedure TfrmADLSMain.SetFMDirectory(AValue: TList<string>); var i: Integer; begin cbxADLSFolder.Clear; cbxADLSFolder.Sorted := True; for i := 0 to AValue.Count - 1 do cbxADLSFolder.Items.Add(AValue.Items[i]); end; procedure TfrmADLSMain.SetFMResponseData(const AValue: string); begin memoResponseData.Lines.Text := AValue; end; procedure TfrmADLSMain.SetResponseData(const AValue: string); begin memoResponseData.Lines.Text := AValue; end; end.
unit untPages; interface Uses // VCL Windows, Classes, SysUtils, Forms, Grids, Controls, ComObj, StdCtrls, // This SizeableForm; type TPage = class; TPageClass = class of TPage; TChangeType = (ctStart, ctStop); { TPages } TPages = class private FList: TList; function GetCount: Integer; function GetItem(Index: Integer): TPage; function GetItemIndex(AItem: TPage): Integer; procedure InsertItem(AItem: TPage); procedure RemoveItem(AItem: TPage); public Password: Integer; destructor Destroy; override; function ValidIndex(Value: Integer): Boolean; property Count: Integer read GetCount; property Items[Index: Integer]: TPage read GetItem; default; end; { TPage } TPage = class(TSizeableForm) private FOwner: TPages; FButton: TButton; function GetIndex: Integer; public destructor Destroy; override; procedure Initialize; virtual; procedure UpdatePage; virtual; procedure UpdateObject; virtual; procedure SetOwner(AOwner: TPages); procedure Check(ResultCode: Integer); function LoadDefaults: Integer; virtual; procedure EnableButtons(Value: Boolean); override; property Index: Integer read GetIndex; end; TPageNotifyEvent = procedure(Sender: TObject; ChangeType: TChangeType) of object; { TPageNotifier } TPageNotifier = class private FOnChange: TPageNotifyEvent; procedure DoChange(ChangeType: TChangeType); public property OnChange: TPageNotifyEvent read FOnChange write FOnChange; end; function PageNotifier: TPageNotifier; implementation var FPageNotifier: TPageNotifier; function PageNotifier: TPageNotifier; begin if FPageNotifier = nil then FPageNotifier := TPageNotifier.Create; Result := FPageNotifier; end; procedure EnableControlButtons(WinControl: TWinControl; Value: Boolean; var AButton: TButton); var i: Integer; Button: TButton; Control: TControl; begin for i := 0 to WinControl.ControlCount-1 do begin Control := WinControl.Controls[i]; if Control is TWinControl then EnableControlButtons(Control as TWinControl, Value, AButton); end; if (WinControl is TButton) then begin Button := WinControl as TButton; if Value then begin Button.Enabled := True; if Button = AButton then Button.SetFocus; end else begin if Button.Focused then AButton := Button; Button.Enabled := False; end; end; end; { TPages } destructor TPages.Destroy; begin while Count > 0 do Items[0].Free; inherited Destroy; end; function TPages.GetCount: Integer; begin if FList = nil then Result := 0 else Result := FList.Count; end; function TPages.GetItem(Index: Integer): TPage; begin Result := FList[Index]; end; function TPages.GetItemIndex(AItem: TPage): Integer; begin Result := FList.IndexOf(AItem); end; procedure TPages.InsertItem(AItem: TPage); begin if FList = nil then FList := TList.Create; FList.Add(AItem); AItem.FOwner := Self; end; procedure TPages.RemoveItem(AItem: TPage); begin AItem.FOwner := nil; FList.Remove(AItem); if FList.Count = 0 then begin FList.Free; FList := nil; end; end; function TPages.ValidIndex(Value: Integer): Boolean; begin Result := (Value >= 0)and(Value < Count); end; { TPage } destructor TPage.Destroy; begin SetOwner(nil); inherited Destroy; end; procedure TPage.SetOwner(AOwner: TPages); begin if FOwner <> nil then FOwner.RemoveItem(Self); if AOwner <> nil then AOwner.InsertItem(Self); end; function TPage.GetIndex: Integer; begin Result := FOwner.GetItemIndex(Self); end; procedure TPage.Initialize; begin end; procedure TPage.UpdatePage; begin end; procedure TPage.UpdateObject; begin end; function TPage.LoadDefaults: Integer; begin Result := 0; end; procedure TPage.EnableButtons(Value: Boolean); begin if Value then begin PageNotifier.DoChange(ctStop); end else begin PageNotifier.DoChange(ctStart); end; EnableControlButtons(Self, Value, FButton); end; procedure TPage.Check(ResultCode: Integer); begin if ResultCode <> 0 then Abort; end; { TPageNotifier } procedure TPageNotifier.DoChange(ChangeType: TChangeType); begin if Assigned(FOnChange) then FOnChange(Self, ChangeType); end; initialization finalization FPageNotifier.Free; FPageNotifier := nil; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSocks; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, WinSock, {$ELSE} System.Classes, System.SysUtils, Winapi.WinSock, {$ENDIF} clSocket, clSocketUtils, clUtils, clIpAddress; type TclSocksConnectionState = (csHello, csAuthenticate, csCommand, csOpenSession, csData); EclSocksFirewallError = class(EclSocketError); TclSocksNetworkStream = class(TclNetworkStream) private FTargetPort: Integer; FTargetServer: string; FReadBuffer: TStream; FUserName: string; FPassword: string; FState: TclSocksConnectionState; FBaseStream: TclNetworkStream; protected procedure ByteArrayWriteIP(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); procedure ByteArrayWriteString(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); procedure ByteArrayWriteStringVar(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); procedure BuildCommand(var ACommand: TclByteArray); virtual; abstract; function ParseResponse(const ACommand: TclByteArray): Boolean; virtual; abstract; function GetBytesToRead: Integer; virtual; abstract; property State: TclSocksConnectionState read FState write FState; public constructor Create(ABaseStream: TclNetworkStream); destructor Destroy; override; procedure SetConnection(AConnection: TclConnection); override; procedure Assign(ASource: TclNetworkStream); override; function Connect(Addr_: TclIPAddress; APort: Integer): Boolean; override; procedure ConnectEnd; override; procedure Close(ANotifyPeer: Boolean); override; procedure StreamReady; override; function Read(AData: TStream): Boolean; override; function Write(AData: TStream): Boolean; override; function GetReadBatchSize: Integer; override; function GetWriteBatchSize: Integer; override; procedure UpdateProgress(ABytesProceed: Int64); override; procedure InitClientSession; override; procedure Broadcast; override; procedure Listen; override; procedure Accept; override; procedure InitServerSession; override; function ReadFrom(AData: TStream; Addr: TclIPAddress; var APort: Integer): Boolean; override; function WriteTo(AData: TStream; Addr: TclIPAddress; APort: Integer): Boolean; override; property BaseStream: TclNetworkStream read FBaseStream; property TargetServer: string read FTargetServer write FTargetServer; property TargetPort: Integer read FTargetPort write FTargetPort; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; end; TclSocks4NetworkStream = class(TclSocksNetworkStream) private function GetSocksErrorMessage(AErrorCode: Integer): string; protected procedure BuildCommand(var ACommand: TclByteArray); override; function ParseResponse(const ACommand: TclByteArray): Boolean; override; function GetBytesToRead: Integer; override; end; TclSocks5NetworkStream = class(TclSocksNetworkStream) private FBytesToRead: Integer; procedure BuildAuthenticate(var ACommand: TclByteArray); procedure BuildConnect(var ACommand: TclByteArray); procedure BuildHello(var ACommand: TclByteArray); function ParseAuthenticate(const ACommand: TclByteArray): Boolean; function ParseCommand(const ACommand: TclByteArray): Boolean; function ParseHello(const ACommand: TclByteArray): Boolean; function GetSocksErrorMessage(AErrorCode: Integer): string; protected procedure BuildCommand(var ACommand: TclByteArray); override; function ParseResponse(const ACommand: TclByteArray): Boolean; override; function GetBytesToRead: Integer; override; public function Connect(Addr_: TclIPAddress; APort: Integer): Boolean; override; end; resourcestring cSocksUnknown = 'Unknown SOCKS error occured'; cSocks4RequestOk = 'Request granted'; cSocks4RequestFail = 'SOCKS error: request rejected or failed'; cSocks4IdentdConnectFail = 'SOCKS error: request rejected becasue SOCKS server cannot connect to identd on the client'; cSocks4IdentdDiffer = 'SOCKS error: request rejected because the client program and identd report different user-ids'; cSocks5AuthError = 'SOCKS error: authentication failed'; cSocks5AuthMethodError = 'SOCKS error: No acceptable authentication methods'; cSocks5Succeeded = 'Succeeded'; cSocks5Failure = 'General SOCKS server failure'; cSocks5Denied = 'SOCKS error: connection not allowed by ruleset'; cSocks5NetworkError = 'SOCKS error: Network unreachable'; cSocks5HostError = 'SOCKS error: Host unreachable'; cSocks5ConnectionError = 'SOCKS error: Connection refused'; cSocks5Timeout = 'SOCKS error: TTL expired'; cSocks5CommandError = 'SOCKS error: Command not supported'; cSocks5AddressError = 'SOCKS error: Address type not supported'; implementation { TclSocksNetworkStream } procedure TclSocksNetworkStream.Accept; begin Assert(False, 'Not implemented'); end; procedure TclSocksNetworkStream.Assign(ASource: TclNetworkStream); var src: TclSocksNetworkStream; begin inherited Assign(ASource); if (ASource is TclSocksNetworkStream) then begin src := ASource as TclSocksNetworkStream; FTargetServer := src.TargetServer; FTargetPort := src.TargetPort; FUserName := src.UserName; FPassword := src.Password; end; end; procedure TclSocksNetworkStream.SetConnection(AConnection: TclConnection); begin inherited SetConnection(AConnection); BaseStream.SetConnection(AConnection); end; procedure TclSocksNetworkStream.StreamReady; begin if (State = csOpenSession) then begin State := csData; InitClientSession(); end else if (State = csData) then begin BaseStream.StreamReady(); end; end; procedure TclSocksNetworkStream.UpdateProgress(ABytesProceed: Int64); begin if (State = csData) then begin BaseStream.UpdateProgress(ABytesProceed); end; end; procedure TclSocksNetworkStream.Broadcast; begin Assert(False, 'Not implemented'); end; procedure TclSocksNetworkStream.ByteArrayWriteIP(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); var i: Integer; begin for i := 1 to WordCount(AValue, ['.']) do begin ADestination[AIndex] := Byte(StrToIntDef(ExtractWord(i, AValue, ['.']), 0)); Inc(AIndex); end; end; procedure TclSocksNetworkStream.ByteArrayWriteString(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); var i: Integer; begin for i := 1 to Length(AValue) do begin ADestination[AIndex] := Ord(AValue[i]); Inc(AIndex); end; ADestination[AIndex] := 0; Inc(AIndex); end; procedure TclSocksNetworkStream.ByteArrayWriteStringVar(const AValue: string; var ADestination: TclByteArray; var AIndex: Integer); var i: Integer; begin ADestination[AIndex] := Length(AValue); Inc(AIndex); for i := 1 to Length(AValue) do begin ADestination[AIndex] := Ord(AValue[i]); Inc(AIndex); end; end; procedure TclSocksNetworkStream.Close(ANotifyPeer: Boolean); begin inherited Close(ANotifyPeer); BaseStream.Close(ANotifyPeer); end; function TclSocksNetworkStream.Connect(Addr_: TclIPAddress; APort: Integer): Boolean; begin FState := csHello; Result := inherited Connect(Addr_, APort); end; procedure TclSocksNetworkStream.ConnectEnd; begin inherited ConnectEnd(); BaseStream.ConnectEnd(); end; constructor TclSocksNetworkStream.Create(ABaseStream: TclNetworkStream); begin inherited Create(); FReadBuffer := TMemoryStream.Create(); FBaseStream := ABaseStream; FState := csHello; FReadBuffer.Size := 0; SetNextAction(saWrite); end; destructor TclSocksNetworkStream.Destroy; begin FBaseStream.Free(); FReadBuffer.Free(); inherited Destroy(); end; function TclSocksNetworkStream.GetReadBatchSize: Integer; begin if (State = csData) then begin Result := BaseStream.GetReadBatchSize(); end else begin Result := inherited GetReadBatchSize(); end; end; function TclSocksNetworkStream.GetWriteBatchSize: Integer; begin if (State = csData) then begin Result := BaseStream.GetWriteBatchSize(); end else begin Result := inherited GetWriteBatchSize(); end; end; procedure TclSocksNetworkStream.Listen; begin Assert(False, 'Not implemented'); end; procedure TclSocksNetworkStream.InitClientSession; begin if (State = csData) then begin ClearNextAction(); BaseStream.InitClientSession(); SetNextAction(BaseStream.NextAction); end else begin FState := csHello; FReadBuffer.Size := 0; SetNextAction(saWrite); end; end; procedure TclSocksNetworkStream.InitServerSession; begin Assert(False, 'Not implemented'); end; function TclSocksNetworkStream.Read(AData: TStream): Boolean; var len: Integer; cmd: TclByteArray; begin {$IFNDEF DELPHI2005}cmd := nil;{$ENDIF} if (State = csData) then begin ClearNextAction(); Result := BaseStream.Read(AData); SetNextAction(BaseStream.NextAction); end else begin len := GetBytesToRead() - FReadBuffer.Size; InitProgress(); Connection.BytesToProceed := len; FReadBuffer.Seek(0, soEnd); try Result := inherited Read(FReadBuffer); HasReadData := Result; finally Connection.BytesToProceed := -1; end; SetLength(cmd, len); FReadBuffer.Position := 0; if (len > 0) then begin len := FReadBuffer.Read(cmd[0], len); SetLength(cmd, len); end; if ParseResponse(cmd) then begin FReadBuffer.Size := 0; end; end; end; function TclSocksNetworkStream.ReadFrom(AData: TStream; Addr: TclIPAddress; var APort: Integer): Boolean; begin Assert(False, 'Not implemented'); Result := False; end; function TclSocksNetworkStream.Write(AData: TStream): Boolean; var cmdStream: TStream; cmd: TclByteArray; begin {$IFNDEF DELPHI2005}cmd := nil;{$ENDIF} if (State = csData) then begin ClearNextAction(); Result := BaseStream.Write(AData); SetNextAction(BaseStream.NextAction); end else begin cmdStream := TMemoryStream.Create(); try BuildCommand(cmd); Assert(Length(cmd) > 0); cmdStream.Write(cmd[0], Length(cmd)); cmdStream.Position := 0; InitProgress(); Result := inherited Write(cmdStream); finally cmdStream.Free(); end; SetNextAction(saRead); end; end; function TclSocksNetworkStream.WriteTo(AData: TStream; Addr: TclIPAddress; APort: Integer): Boolean; begin Assert(False, 'Not implemented'); Result := False; end; { TclSocks4NetworkStream } procedure TclSocks4NetworkStream.BuildCommand(var ACommand: TclByteArray); var ind: Integer; begin SetLength(ACommand, 1024); ind := 0; ACommand[ind] := 4; //VER Inc(ind); ACommand[ind] := 1; //CONNECT Inc(ind); ByteArrayWriteWord(TargetPort, ACommand, ind); if not TclIPAddress4.IsHostIP(TargetServer) then begin ByteArrayWriteIP('0.0.0.1', ACommand, ind); end else begin ByteArrayWriteIP(TargetServer, ACommand, ind); end; ByteArrayWriteString(UserName, ACommand, ind); if not TclIPAddress4.IsHostIP(TargetServer) then begin ByteArrayWriteString(TargetServer, ACommand, ind); end; SetLength(ACommand, ind); end; function TclSocks4NetworkStream.GetBytesToRead: Integer; begin Result := 8; end; function TclSocks4NetworkStream.GetSocksErrorMessage(AErrorCode: Integer): string; begin case AErrorCode of 90: Result := cSocks4RequestOk; 91: Result := cSocks4RequestFail; 92: Result := cSocks4IdentdConnectFail; 93: Result := cSocks4IdentdDiffer else Result := cSocksUnknown; end; end; function TclSocks4NetworkStream.ParseResponse(const ACommand: TclByteArray): Boolean; var len: Integer; begin Result := True; len := Length(ACommand); if(len < 8) then begin Result := False; SetNextAction(saRead); end else if ((ACommand[0] <> 0) or (ACommand[1] <> 90)) then begin raise EclSocksFirewallError.Create(GetSocksErrorMessage(ACommand[1]), ACommand[1]); end else begin State := csOpenSession; StreamReady(); end; end; { TclSocks5NetworkStream } procedure TclSocks5NetworkStream.BuildHello(var ACommand: TclByteArray); var ind: Integer; begin SetLength(ACommand, 1024); ind := 0; ACommand[ind] := 5; //VER Inc(ind); ACommand[ind] := 1; //NMETHODS Inc(ind); if (UserName <> '') then begin ACommand[ind] := 2; //USERNAME/PASSWORD Inc(ind); end else begin ACommand[ind] := 0; //NO AUTH Inc(ind); end; SetLength(ACommand, ind); FBytesToRead := 2; end; function TclSocks5NetworkStream.Connect(Addr_: TclIPAddress; APort: Integer): Boolean; begin FBytesToRead := 0; Result := inherited Connect(Addr_, APort); end; procedure TclSocks5NetworkStream.BuildAuthenticate(var ACommand: TclByteArray); var ind: Integer; begin SetLength(ACommand, 1024); ind := 0; ACommand[ind] := 1; //VER Inc(ind); ByteArrayWriteStringVar(UserName, ACommand, ind); ByteArrayWriteStringVar(Password, ACommand, ind); SetLength(ACommand, ind); FBytesToRead := 2; end; procedure TclSocks5NetworkStream.BuildConnect(var ACommand: TclByteArray); var ind: Integer; begin SetLength(ACommand, 1024); ind := 0; ACommand[ind] := 5; //VER Inc(ind); ACommand[ind] := 1; //CONNECT Inc(ind); ACommand[ind] := 0; //RSV Inc(ind); if not TclIPAddress4.IsHostIP(TargetServer) then//TODO ipv6 support begin ACommand[ind] := 3; //DOMAIN Inc(ind); ByteArrayWriteStringVar(TargetServer, ACommand, ind); end else begin ACommand[ind] := 1; //IP Inc(ind); ByteArrayWriteIP(TargetServer, ACommand, ind); end; ByteArrayWriteWord(TargetPort, ACommand, ind); SetLength(ACommand, ind); FBytesToRead := 10; end; procedure TclSocks5NetworkStream.BuildCommand(var ACommand: TclByteArray); begin case FState of csHello: BuildHello(ACommand); csAuthenticate: BuildAuthenticate(ACommand); csCommand: BuildConnect(ACommand) else Assert(False); end; end; function TclSocks5NetworkStream.GetBytesToRead: Integer; begin Result := FBytesToRead; end; function TclSocks5NetworkStream.GetSocksErrorMessage(AErrorCode: Integer): string; begin case AErrorCode of 0: Result := cSocks5Succeeded; 1: Result := cSocks5Failure; 2: Result := cSocks5Denied; 3: Result := cSocks5NetworkError; 4: Result := cSocks5HostError; 5: Result := cSocks5ConnectionError; 6: Result := cSocks5Timeout; 7: Result := cSocks5CommandError; 8: Result := cSocks5AddressError else Result := cSocksUnknown; end; end; function TclSocks5NetworkStream.ParseHello(const ACommand: TclByteArray): Boolean; var len: Integer; begin Result := True; len := Length(ACommand); if(len < GetBytesToRead()) then begin Result := False; SetNextAction(saRead); end else if ((ACommand[0] = 5) and (ACommand[1] = 0)) then begin State := csCommand; SetNextAction(saWrite); end else if ((ACommand[0] = 5) and (ACommand[1] = 2)) then begin State := csAuthenticate; SetNextAction(saWrite); end else begin raise EclSocksFirewallError.Create(cSocks5AuthMethodError, ACommand[1]); end; end; function TclSocks5NetworkStream.ParseAuthenticate(const ACommand: TclByteArray): Boolean; var len: Integer; begin Result := True; len := Length(ACommand); if(len < GetBytesToRead()) then begin Result := False; SetNextAction(saRead); end else if ((ACommand[0] = 1) and (ACommand[1] = 0)) then begin State := csCommand; SetNextAction(saWrite); end else begin raise EclSocksFirewallError.Create(cSocks5AuthError, ACommand[1]); end; end; function TclSocks5NetworkStream.ParseCommand(const ACommand: TclByteArray): Boolean; var len: Integer; begin Result := True; len := Length(ACommand); if(len < GetBytesToRead()) then begin Result := False; SetNextAction(saRead); end else if ((ACommand[0] <> 5) or (ACommand[1] <> 0)) then begin raise EclSocksFirewallError.Create(GetSocksErrorMessage(ACommand[1]), ACommand[1]); end else begin Assert(ACommand[3] = 1); State := csOpenSession; StreamReady(); end; end; function TclSocks5NetworkStream.ParseResponse(const ACommand: TclByteArray): Boolean; begin Result := True; case FState of csHello: Result := ParseHello(ACommand); csAuthenticate: Result := ParseAuthenticate(ACommand); csCommand: Result := ParseCommand(ACommand) else Assert(False); end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clNntpUtils; interface {$I clVer.inc} const DefaultNntpPort = 119; type TclNntpModeType = (mtDefault, mtReader, mtStream); function GetNormMessageID(const AMessageID: string): string; function BuildNntpQuery(ADate: TDateTime; AGMT: Boolean; const ADistributions: string): string; procedure ParseNntpQuery(const AQuery: string; var ADate: TDateTime; var AGMT: Boolean; var ADistributions: string); implementation uses {$IFNDEF DELPHIXE2} SysUtils, {$ELSE} System.SysUtils, {$ENDIF} clUtils; function GetNormMessageID(const AMessageID: string): string; begin Result := AMessageID; if (Result <> '') then begin Result := GetQuotedString(Result, '<', '>'); end; end; function BuildNntpQuery(ADate: TDateTime; AGMT: Boolean; const ADistributions: string): string; begin Result := FormatDateTime('yymmdd hhnnss', ADate); if AGMT then begin Result:= Result + ' GMT'; end; if Length(ADistributions) > 0 then begin Result := Result + ' <' + ADistributions + '>'; end; end; procedure ParseNntpQuery(const AQuery: string; var ADate: TDateTime; var AGMT: Boolean; var ADistributions: string); var ind, y, m, d, h, n, s: Integer; begin ADate := Now(); AGMT := False; ADistributions := ''; try if Length(AQuery) >= Length('yymmdd hhnnss') then begin y := StrToInt(system.Copy(AQuery, 1, 2)); m := StrToInt(system.Copy(AQuery, 3, 2)); d := StrToInt(system.Copy(AQuery, 5, 2)); h := StrToInt(system.Copy(AQuery, 8, 2)); n := StrToInt(system.Copy(AQuery, 10, 2)); s := StrToInt(system.Copy(AQuery, 12, 2)); y := GetCorrectY2k(y); ADate := EncodeDate(y, m, d) + EncodeTime(h, n, s, 0); end; AGMT := (system.Pos('GMT', UpperCase(AQuery)) > 0); ind := system.Pos('<', AQuery); if (ind > 0) then begin ADistributions := system.Copy(AQuery, ind + 1, Length(AQuery)); ind := system.Pos('>', ADistributions); if (ind > 0) then begin SetLength(ADistributions, ind - 1); end; end; except on EConvertError do ; end; end; end.
// Last edited: 18.11.2020 // Version: 1.1.1 uses SysUtils, Classes; const // Начало периода рестарта сервера RestartTime: TDateTime = StrToDateTime('18:58:00'); // Продолжительность рестарта сервера "ЧЧ:ММ:СС" RestartDelay: TDateTime = StrToDateTime('00:05:00'); // Путь к файлу запуска L2 клиента gamePath = 'C:\Games\L2_Interlude_L2KOT.RU\system\l2.exe'; // Файл с описанием персонажей трейна trainMembersFile = 'D:\Adrenalin-Data\Rori_Train.txt'; // Задержка после закрытия окна L2 afterCloseGameDelay: cardinal = 3000; // Задержка перед повторной проверкой окончания периода рестарта сервера serverRestartingCheckDelay: cardinal = 10000; // Задержка перед повторной проверкой на дисконект disconnectCheckPeriod: cardinal = 3000; // Время ожидания прогрузки окна клиента сразу после его старта loadingAuthScreenDelay: cardinal = 20000; // Задержка после нажатия на "Принять" лицензионное соглашение, "Выбор сервера", "Выбор персонажа" ingameScreensDelay: cardinal = 5000; // Задержка после входа игру персонажем charLoggingInDelay: cardinal = 20000; // Периодичность очистки списка неопознанных ботов unknownBotsClearDelay: cardinal = 600000; var RestartByTime: boolean; log: String; // Id=Ticks unknownBotsIds: TStringList; // Char localTrainCharNames: TStringList; function ShellExecuteW(hwnd: integer; lpOperation, lpFile, lpParameters, lpDirectory: PChar; nShowCmd: integer): integer; stdcall; external 'Shell32.dll'; function keybd_event(bVk, bScan: byte; dwFlags, dwExtraInfo: integer): integer; stdcall; external 'user32.dll'; function ShowWindow(hwnd: cardinal; action: integer): boolean; stdcall; external 'user32.dll'; // Чтение названия чаров и их логопасов из файла, запись их в обще-аккаунтовое хранилище ShMem procedure initTrain; begin unknownBotsIds := TStringList.Create; parseTrainFile(trainMembersFile); // Если на момент запуска скрипта в боте уже кто-то залогинен, обновляем память initBotNumShMem(localTrainCharNames); // Залогиниваем всех персонажей трейна по очереди if (checkTrainMembersOnline(localTrainCharNames)) then print('------- ИНИЦИАЛИЗАЦИЯ ТРЕЙНА ЗАВЕРШЕНА -------'); end; // Парсим файл со списком персонажей бот-трейна и заполняем память, возвращаем список персонажей трейна procedure parseTrainFile(trainMembersFile: string); var trainList: TStringList; account: String; i: integer; begin trainList := TStringList.Create; localTrainCharNames := TStringList.Create; trainList.LoadFromFile(trainMembersFile); for i := 0 to trainList.Count - 1 do begin writeAccountToShMem(getDelimitedItems(trainList[i], ';')); localTrainCharNames.Add(getDelimitedItems(trainList[i], ';')[0]); end; trainList.Free; end; // Функция проверки что все персонажи трейна онлайн function checkTrainMembersOnline(trainChars: TStringList): boolean; var charName: String; i: integer; begin for i := 0 to trainChars.Count - 1 do begin if (not(isTrainMemberOnline(trainChars[i]))) then begin log := '==== ' + trainChars[i] + ' !!! OFFLINE !!! ===='; print(log); log := 'Начинаем загрузку персонажа ' + trainChars[i]; print(log); bootTrainMember(trainChars[i]); end else begin log := '==== ' + trainChars[i] + ' Online ===='; print(log); end; end; Result := true; end; // Функция проверки что персонаж трейна в онлайне function isTrainMemberOnline(charName: string): boolean; var botNum: integer; begin // Если это первый запуск скрипта и персонаж еще не логинился if (getBotNumFromShMem(charName) = -1) then begin Result := logInToGame(charName); exit; end; if (TBot(BotList[getBotNumFromShMem(charName)]).UserName = charName) then Result := (TBot(BotList[getBotNumFromShMem(charName)]) .Control.Status = lsOnline); end; // Функция загрузки персонажа трейна в игру procedure bootTrainMember(charName: string); begin // Пытаемся залогиниться до победного while not(logInToGame(charName)) do closeGame(TBot(BotList[getBotNumFromShMem(charName)])); end; function logInToGame(charName: string): boolean; var currentBot: TBot; logPrefix: string; begin logPrefix := '[' + charName + '] '; // Запускаем L2 клиент log := logPrefix + 'Попытка запустить L2-клиент...'; print(log); ShellExecuteW(0, 'open', PChar(gamePath), nil, nil, 0); Delay(loadingAuthScreenDelay); // Вводим логопас currentBot := checkBotNumber(charName); if (currentBot.Control.LoginStatus = 0) then // if (currentBot.Control.GameWindow <> 0) then begin log := logPrefix + 'Попытка залогиниться...'; print(log); currentBot.Control.AuthLogin(getAccountFromShMem(charName)[1], getAccountFromShMem(charName)[2]); Delay(ingameScreensDelay); end else begin log := logPrefix + 'Ошибка обнаружения окна L2 на этапе ввода логопаса.'; print(log); Result := false; exit; end; // Принимаем лицензионное соглашение if (currentBot.Control.LoginStatus = 1) then begin log := logPrefix + 'Попытка принять лицензионное соглашение...'; print(log); currentBot.Control.UseKey('Enter'); Delay(ingameScreensDelay); end else begin log := logPrefix + 'Ошибка обнаружения экрана принятия лицензионного соглашения.'; print(log); Result := false; exit; end; // Выбираем сервер if (currentBot.Control.LoginStatus = 1) then begin log := logPrefix + 'Попытка выбора сервера...'; print(log); currentBot.Control.UseKey('Enter'); Delay(ingameScreensDelay); end else begin log := logPrefix + 'Ошибка обнаружения экрана выбора сервера.'; print(log); Result := false; exit; end; // Заходим в игру персонажем if (currentBot.Control.LoginStatus = 2) then begin log := logPrefix + 'Попытка входа персонажа в игру...'; print(log); currentBot.Control.GameStart; Delay(charLoggingInDelay); end else begin log := logPrefix + 'Ошибка обнаружения экрана выбора персонажа.'; print(log); Result := false; exit; end; // Проверяем что успешно зашли if (currentBot.Control.Status = lsOnline) then begin log := logPrefix + 'Активация бота...'; print(log); // Включаем интерфейс currentBot.Control.FaceControl(0, true); Result := true; end else begin log := logPrefix + 'Ошибка проверки статуса персонажа.'; print(log); Result := false; exit; end; log := logPrefix + 'Бот активирован!'; print(log); end; function checkBotNumber(charName: string): TBot; var botNum: integer; begin botNum := getBotNumFromShMem(charName); if (botNum = -1) then Result := mapBotNumber(charName) else begin log := '[' + charName + '] ' + ' Использует бота №' + IntToStr(botNum); print(log); Result := TBot(BotList[botNum]); end; end; // Функция создания привязки Char -> TBot function mapBotNumber(charName: string): TBot; var botNum: integer; begin botNum := getFirstUnknownBotNum(); if (botNum = -1) then botNum := BotList.Count - 1; writeBotNumToShMem(charName, botNum); Result := TBot(BotList[botNum]); end; // Возвращаем номер первого попавшегося безымянного бота. Возвращаем -1 если не найдены function getFirstUnknownBotNum(): integer; var i: integer; begin for i := 0 to BotList.Count - 1 do begin if (TBot(BotList[i]).UserName = '') then begin Result := i; exit; end; end; Result := -1; end; // ###################################### // ########### Работа с ShMem ########### procedure initBotNumShMem(trainCharNames: TStringList); var i, k: integer; begin for i := 0 to trainCharNames.Count - 1 do begin for k := 0 to BotList.Count - 1 do begin if (TBot(BotList[k]).UserName = trainCharNames[i]) then begin writeBotNumToShMem(trainCharNames[i], k); break; end; end; end; end; // Получаем номер бота персонажа из памяти. При ошибке возвращает -1 function getBotNumFromShMem(charName: String): integer; var charIdx: integer; begin if (ShMem[1] = 0) then begin // ShMem[1] is not initialized Result := -1; exit; end; charIdx := TStringList(ShMem[1]).IndexOfName(charName); if (charIdx = -1) then begin // Character not found in ShMem[1] Result := -1; exit; end; Result := StrToInt(TStringList(ShMem[1]).Values[charName]); end; // Записываем в память привязку Char=BotNum в память procedure writeBotNumToShMem(charName: String; botNum: integer); var charIdx: integer; begin if (ShMem[1] = 0) then begin ShMem[1] := integer(TStringList.Create); end; charIdx := TStringList(ShMem[1]).IndexOfName(charName); if (charIdx = -1) then begin TStringList(ShMem[1]).Add(charName + '=' + IntToStr(botNum)); log := 'Сохранена привязка персонажа ' + charName + ' к боту №' + IntToStr(botNum) + ' [Память ботов: ' + IntToStr(TStringList(ShMem[1]).Count) + ']'; end else begin TStringList(ShMem[1])[charIdx] := charName + '=' + IntToStr(botNum); log := 'Обновлена привязка персонажа ' + charName + ' к боту №' + IntToStr(botNum) + ' [Память ботов: ' + IntToStr(TStringList(ShMem[1]).Count) + ']'; end; print(log); end; // Получаем список Char,Login,Password из памяти function getAccountFromShMem(charName: string): TStringList; var charIdx: integer; results: TStringList; begin results := TStringList.Create; if (ShMem[0] = 0) then begin Result := results; log := 'ERROR: ShMem[0] is not initialized.'; print(log); exit; end; charIdx := TStringList(ShMem[0]).IndexOfName(charName); if (charIdx = -1) then begin Result := results; log := 'ERROR: Account not found in ShMem[0].'; print(log); exit; end; results.Add(charName); results.AddStrings(getDelimitedItems(TStringList(ShMem[0]) .Values[charName], ';')); Result := results; end; // Записываем в память Char=Login;Password procedure writeAccountToShMem(accountEntry: TStringList); var charIdx: integer; begin if (ShMem[0] = 0) then begin ShMem[0] := integer(TStringList.Create); end; charIdx := TStringList(ShMem[0]).IndexOfName(accountEntry[0]); if (charIdx = -1) then begin TStringList(ShMem[0]).Add(accountEntry[0] + '=' + accountEntry[1] + ';' + accountEntry[2]); log := 'Сохранён аккаунт персонажа ' + accountEntry [0] + ' [Память аккаунтов: ' + IntToStr(TStringList(ShMem[0]).Count) + ']'; end else begin TStringList(ShMem[0])[charIdx] := accountEntry[0] + '=' + accountEntry[1] + ';' + accountEntry[2]; log := 'Обновлен аккаунт персонажа ' + accountEntry [0] + ' [Память аккаунтов: ' + IntToStr(TStringList(ShMem[0]).Count) + ']'; end; print(log); end; // Пример с delim = ';'. На входе 'abc;abc;abc', на выходе список из трёх 'abc'. function getDelimitedItems(rawString: string; delim: Char): TStringList; var results: TStringList; begin results := TStringList.Create; results.Delimiter := delim; results.DelimitedText := rawString; Result := results; end; // ###################################### procedure disconnectMonitor; var i, k, botNum: integer; begin initTrain(); while Delay(disconnectCheckPeriod) do begin // Если начал действовать период рестарта сервера if (Time > RestartTime) and (Time < RestartTime + RestartDelay) then RestartByTime := true else RestartByTime := false; // Проверяем для каждого персонажа трейна for i := 0 to localTrainCharNames.Count - 1 do begin botNum := getBotNumFromShMem(localTrainCharNames[i]); // Если имя бота не пустое if (TBot(BotList[botNum]).UserName <> '') then handleDisconnect(localTrainCharNames[i]) else // Обновляем список игнорируемых безымянных ботов refreshUnknownBots(botNum); end; end; end; procedure handleDisconnect(charName: String); var currentBot: TBot; begin currentBot := TBot(BotList[getBotNumFromShMem(charName)]); // Ожидаем окончания периода рестарта if (RestartByTime) then begin closeTrainGameWindows(); if (Time < RestartTime + RestartDelay) then begin log := '[' + charName + '] ' + 'Сервер в процессе рестарта...'; print(log); Delay(serverRestartingCheckDelay); exit; end else RestartByTime := false; end else begin // Если персонаж не в игре, закрываем L2 клиент и пытаемся зайти обратно if (currentBot.Control.Status <> lsOnline) and (Not(RestartByTime)) then begin log := charName + ' ### DISCONNECTED ###'; print(log); // Закрываем L2 клиент, если открыт closeGame(currentBot); // Пытаемся зайти в игру до победного while not(logInToGame(charName)) do closeGame(currentBot); end; end; end; procedure closeTrainGameWindows; var i: integer; begin for i := 0 to localTrainCharNames.Count - 1 do begin closeGame(TBot(BotList[getBotNumFromShMem(localTrainCharNames[i])])); end; end; procedure closeGame(bot: TBot); begin if (bot.Control.GameWindow <> 0) then begin bot.Control.FaceControl(0, false); bot.Control.GameClose; Delay(afterCloseGameDelay); end; end; procedure refreshUnknownBots(botNum: integer); var i: integer; key: String; begin if (unknownBotsIds.Count = 0) or (unknownBotsIds.IndexOfName(IntToStr(botNum)) = -1) then begin markUnknownBotIgnored(botNum); exit; end; for i := 0 to unknownBotsIds.Count - 1 do begin key := unknownBotsIds.Names[i]; if (StrToInt(unknownBotsIds.Values[key]) + unknownBotsClearDelay < GetTickCount()) then begin unknownBotsIds.Delete(StrToInt(unknownBotsIds[i])); log := 'Перестаём игнорировать неопознанного бота №' + unknownBotsIds.Values[key]; print(log); exit; end; end; end; procedure markUnknownBotIgnored(botNum: integer); begin unknownBotsIds.Add(IntToStr(botNum) + '=' + IntToStr(GetTickCount())); log := 'Неопознанный бот №' + IntToStr(botNum) + ' добавлен в список игнорируемых на ' + FloatToStr(unknownBotsClearDelay / 1000) + ' секунд.'; print(log); end; begin Script.NewThread(@disconnectMonitor); end.
unit lazeyes2form; {$mode objfpc}{$H+} interface uses Classes, Math, SysUtils, Graphics, Forms, LResources, StdCtrls, ExtCtrls, Controls, LCLType, LCLIntf, lazeyes2painter; type { TMainForm } TMainForm = class(TForm) public MyTimer: TTimer; FirstOnTimer: Boolean; WindowDragMousePos, WindowDragTopLeft: TPoint; WindowDragStarted: Boolean; Painter: TLazEye2Painter; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CalculateEyePosition( EyeXc, EyeYc: Integer): TPoint; procedure HandleOnTimer(ASender: TObject); procedure HandleOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HandleOnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure HandleOnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetWindowRegion(); end; var MainForm: TMainForm; implementation { TMainForm } constructor TMainForm.Create(AOwner: TComponent); begin inherited Create(AOwner); // basic initial data MousePos := Mouse.CursorPos; // create child objects MyTimer := TTimer.Create(Self); MyTimer.Interval := 1000 div 60; MyTimer.OnTimer := @HandleOnTimer; MyTimer.Enabled := True; FirstOnTimer := True; Painter := TLazEye2Painter.Create(Self); Painter.Parent := Self; Painter.Align := alClient; Painter.DoubleBuffered := True; // set events OnMouseMove := @HandleOnMouseMove; OnMouseDown := @HandleOnMouseDown; OnMouseUp := @HandleOnMouseUp; Painter.OnMouseMove := @HandleOnMouseMove; Painter.OnMouseDown := @HandleOnMouseDown; Painter.OnMouseUp := @HandleOnMouseUp; // set window properties BorderStyle := bsNone; Position := poScreenCenter; // set window transparency SetWindowRegion(); end; destructor TMainForm.Destroy; begin // free child object MyTimer.Free; inherited Destroy; end; { Calculates where the eye should be painted EyeXc, EyeYc is the center of the eye ellipse The size of the ellipse is given by the constants INT_EYE_WIDTH and INT_EYE_HEIGHT } function TMainForm.CalculateEyePosition( EyeXc, EyeYc: Integer): TPoint; var RelMousePos: TPoint; MousePosAngle: Double; DeltaX, DeltaY: Double; AbsEyeXc, AbsEyeYc: Integer; begin // Get the mouse position relative to the window RelMousePos.X := MousePos.X - Left; RelMousePos.Y := MousePos.Y - Top; // Get the eye center absolute position in the screen AbsEyeXc := EyeXc + Left; AbsEyeYc := EyeYc + Top; // First check if the cursor is inside the eye, in a // position that it will fall right over the eye pupil // eye pupil elipse area equation: // (X - Xc)^2 / A^2 + (Y - Yc)^2 / B^2 <= 1 // (Xc, Yc) is the center of the elipse // A and B are the half axis of the elipse if (Sqr(RelMousePos.X - EyeXc) / INT_EYE_HALFWIDTH_SQR) + (Sqr(RelMousePos.Y - EyeYc) / INT_EYE_HALFHEIGHT_SQR) <= 1 then begin Result.X := RelMousePos.X; Result.Y := RelMousePos.Y; Exit; end; // Calculate the position of the eye, by calculating how // many grads the cursor is forming with the center of // the eye. The polar equation of the elipse is: // X = Xc + A * cos(t) // Y = Yc + B * sen(t) if MousePos.X - AbsEyeXc = 0 then MousePosAngle := Pi / 2 else MousePosAngle := arctan(Abs(MousePos.Y - AbsEyeYc) / Abs(MousePos.X - AbsEyeXc)); DeltaX := INT_EYE_HALFWIDTH * Cos(MousePosAngle); DeltaY := INT_EYE_HALFHEIGHT * Sin(MousePosAngle); // 1st quadrant if (MousePos.X >= AbsEyeXc) and (MousePos.Y <= AbsEyeYc) then begin Result.X := Round(EyeXc + DeltaX); Result.Y := Round(EyeYc - DeltaY); end // 2nd quadrant else if (MousePos.X >= AbsEyeXc) and (MousePos.Y >= AbsEyeYc) then begin Result.X := Round(EyeXc + DeltaX); Result.Y := Round(EyeYc + DeltaY); end // 3rd quadrant else if (MousePos.X <= AbsEyeXc) and (MousePos.Y >= AbsEyeYc) then begin Result.X := Round(EyeXc - DeltaX); Result.Y := Round(EyeYc + DeltaY); end // 4th quadrant else begin Result.X := Round(EyeXc - DeltaX); Result.Y := Round(EyeYc - DeltaY); end; end; { Timer event - Updates the eyes if the mouse moved } procedure TMainForm.HandleOnTimer(ASender: TObject); begin {$ifdef LCLGtk2} if FirstOnTimer then SetWindowRegion(); FirstOnTimer := False; {$endif} // Check if mouse position changed if (MousePos.X = Mouse.CursorPos.X) and (MousePos.Y = Mouse.CursorPos.Y) then Exit; MousePos := Mouse.CursorPos; // Calculate the position of the eyes LeftEyePos := CalculateEyePosition( INT_EYE_HALFWIDTH + INT_BORDER_WIDTH, INT_EYE_HALFHEIGHT + INT_BORDER_WIDTH); RightEyePos := CalculateEyePosition( INT_OUTER_EYE_WIDTH + INT_INTEREYE_SPACE + INT_EYE_HALFWIDTH + INT_BORDER_WIDTH, INT_EYE_HALFHEIGHT + INT_BORDER_WIDTH); // Redraw the eye Invalidate; end; { MouseDown - Code to drag the main window using the mouse} procedure TMainForm.HandleOnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin WindowDragStarted := True; WindowDragMousePos := Mouse.CursorPos; WindowDragTopLeft.X := Left; WindowDragTopLeft.Y := Top; end; { MouseMove - Code to drag the main window using the mouse} procedure TMainForm.HandleOnMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if WindowDragStarted then begin Left := WindowDragTopLeft.X + (Mouse.CursorPos.X - WindowDragMousePos.X); Top := WindowDragTopLeft.Y + (Mouse.CursorPos.Y - WindowDragMousePos.Y); end; end; { MouseUp - Code to drag the main window using the mouse } procedure TMainForm.HandleOnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin WindowDragStarted := False; end; procedure TMainForm.SetWindowRegion(); var Rgn1, Rgn2, TotalRgn: HRGN; begin Rgn1 := CreateEllipticRgn( 0, 0, INT_OUTER_EYE_WIDTH, INT_OUTER_EYE_HEIGHT); Rgn2 := CreateEllipticRgn( INT_OUTER_EYE_WIDTH + INT_INTEREYE_SPACE, 0, 2*INT_OUTER_EYE_WIDTH + INT_INTEREYE_SPACE, INT_OUTER_EYE_HEIGHT); // The dest region needs to exist before calling // CombineRgn, so we create it with dummy values TotalRgn := CreateEllipticRgn(0, 0, 10, 10); LCLIntf.CombineRgn(TotalRgn, Rgn1, Rgn2, RGN_OR); LCLIntf.SetWindowRgn(Handle, TotalRgn, True); end; end.
Unit TERRA_TestXML; {$I terra.inc} Interface Uses TERRA_TestSuite; Type TERRAXML_TestSimple = class(TestCase) Procedure Run; Override; End; TERRAXML_TestShortcuts = class(TestCase) Procedure Run; Override; End; Implementation Uses TERRA_String, TERRA_Utils, TERRA_XML; Procedure TERRAXML_TestSimple.Run; Var S:TERRAString; Doc:XMLDocument; Node:XMLNode; Function Expect(Root:XMLNode; Const Name, Value:TERRAString):XMLNode; Begin If Assigned(Root) Then Result := Root.GetNodeByName(Name) Else Result := Nil; Check(Assigned(Result), 'Could not find node "'+Name+'"'); If Assigned(Result) Then Check(Value = Result.Value, 'Expected value "'+Value+'" in node "'+Name+'" but got "'+Result.Value+'"'); End; Begin S := '<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Dont forget me this weekend!</body></note>'; Doc := XMLDocument.Create(); Doc.LoadFromString(S, encodingUTF8); Node := Expect(Doc.Root, 'to', 'Tove'); Node := Expect(Doc.Root, 'from', 'Jani'); Node := Expect(Doc.Root, 'heading', 'Reminder'); Node := Expect(Doc.Root, 'body', 'Dont forget me this weekend!'); Doc.Release(); End; Procedure TERRAXML_TestShortcuts.Run; Var S:TERRAString; Doc:XMLDocument; Node:XMLNode; Function Expect(Root:XMLNode; Const Name, Value:TERRAString):XMLNode; Begin If Assigned(Root) Then Result := Root.GetNodeByName(Name) Else Result := Nil; Check(Assigned(Result), 'Could not find node "'+Name+'"'); If Assigned(Result) Then Check(Value = Result.Value, 'Expected value "'+Value+'" in node "'+Name+'" but got "'+Result.Value+'"'); End; Begin S := '<test x="100" y="200" />'; Doc := XMLDocument.Create(); Doc.LoadFromString(S, encodingUTF8); Node := Expect(Doc.Root, 'x', '100'); Node := Expect(Doc.Root, 'y', '200'); Doc.Release(); End; End.
unit MultEdit.Helpers; interface uses System.SysUtils, System.Classes; const REGEX_MAIL = '([a-z][a-z0-9\-\_]+\.?[a-z0-9\-\_]+)@((?![0-9]+\.)([a-z][a-z0-9\-]{0,24}[a-z0-9])\.)[a-z]{3}(\.[a-z]{2,3})?'; REGEX_URL = '(https?:\/\/)?((www|w3)\.)?([-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/=]*))'; REGEX_PHONE = '^[1-9]{2}(?:[6-9]|9[1-9])[0-9]{3}[0-9]{4}$'; MASK_Phone = '!\(99\)99999-9999;0;_'; MASK_CPF = '999.999.999-99;0'; MASK_CNPJ = '99.999.999/9999-99;0'; MASK_CEP = '99.999-999;0'; MASK_KEY_NUMBERS = '9'; MSG_VALID = 'Valid'; MSG_INVALID = 'Invalid'; COLOR_VALID = $00D9FFD9; COLOR_INVALID = $00C4C4FF; VALIDATION_SIZE_EMAIL = 5; VALIDATION_SIZE_URL = 8; NUMBERS = ['0'..'9']; VERSION_NUMBER = '1.0.3'; function CPFValid(AValue: string): Boolean; function CNPJValid(AValue: string): Boolean; function CEPValid(AValue: string): Boolean; implementation function CPFValid(AValue: string): Boolean; var FPos1, FPos2, FPos3, FPos4, FPos5, FPos6, FPos7, FPos8, FPos9 : integer; FDig1, FDig2 : integer; FValue, FCalculated : string; FEqual : Boolean; begin try if Trim(AValue) = EmptyStr then Exit(False); FPos1 := StrToInt(AValue[1]); FPos2 := StrToInt(AValue[2]); FPos3 := StrToInt(AValue[3]); FPos4 := StrToInt(AValue[4]); FPos5 := StrToInt(AValue[5]); FPos6 := StrToInt(AValue[6]); FPos7 := StrToInt(AValue[7]); FPos8 := StrToInt(AValue[8]); FPos9 := StrToInt(AValue[9]); FDig1 := FPos9*2 + FPos8*3 + FPos7*4 + FPos6*5 + FPos5*6 + FPos4*7 + FPos3*8 + FPos2*9 + FPos1*10; FDig1 := 11-(FDig1 mod 11); if FDig1 >= 10 then FDig1 := 0; FDig2 := FDig1*2 + FPos9*3 + FPos8*4 + FPos7*5 + FPos6*6 + FPos5*7 + FPos4*8 + FPos3*9 + FPos2*10 + FPos1*11; FDig2 := 11-(FDig2 mod 11); if FDig2 >= 10 then FDig2 := 0; FCalculated := IntToStr(FDig1) + IntToStr(FDig2); FValue := AValue[10] + AValue[11]; FEqual := (FPos1 = FPos2) and (FPos2 = FPos3) and (FPos3 = FPos4) and (FPos4 = FPos5) and (FPos5 = FPos6) and (FPos6 = FPos7) and (FPos7 = FPos8) and (FPos8 = FPos9); Result := (FCalculated = FValue) and (not FEqual); except Result := False; end; end; function CNPJValid(AValue: string): Boolean; var FPos1, FPos2, FPos3, FPos4, FPos5, FPos6, FPos7, FPos8, FPos9, FPos10,FPos11,FPos12 : Integer; FDig, FDig2 : Integer; FValue, FCalculated : string; FEqual : Boolean; begin try if Trim(AValue) = EmptyStr then Exit(False); FPos1 := StrToInt(AValue[1]); FPos2 := StrToInt(AValue[2]); FPos3 := StrToInt(AValue[3]); FPos4 := StrToInt(AValue[4]); FPos5 := StrToInt(AValue[5]); FPos6 := StrToInt(AValue[6]); FPos7 := StrToInt(AValue[7]); FPos8 := StrToInt(AValue[8]); FPos9 := StrToInt(AValue[9]); FPos10 := StrToInt(AValue[10]); FPos11 := StrToInt(AValue[11]); FPos12 := StrToInt(AValue[12]); FDig := FPos12*2 + FPos11*3 + FPos10*4 + FPos9*5 + FPos8*6 + FPos7*7 + FPos6*8 + FPos5*9 + FPos4*2 + FPos3*3 + FPos2*4 + FPos1*5; FDig := 11 - (FDig mod 11); if FDig >= 10 then FDig := 0; FDig2 := FDig*2 + FPos12*3 + FPos11*4 + FPos10*5 + FPos9*6 + FPos8*7 + FPos7*8 + FPos6*9 + FPos5*2 + FPos4*3 + FPos3*4 + FPos2*5 + FPos1*6; FDig2 := 11-(FDig2 mod 11); if FDig2 >= 10 then FDig2 := 0; FCalculated := IntToStr(FDig) + IntToStr(FDig2); FValue := AValue[13] + AValue[14]; FEqual := (FPos1 = FPos2) and (FPos2 = FPos3) and (FPos3 = FPos4) and (FPos4 = FPos5) and (FPos5 = FPos6) and (FPos6 = FPos7) and (FPos7 = FPos8) and (FPos8 = FPos9) and (FPos9 = FPos10) and (FPos10 = FPos11) and (FPos11 = FPos12); Result := (FCalculated = FValue) and (not FEqual); except Result := false; end; end; function CEPValid(AValue: string): Boolean; begin if AValue = EmptyStr then Exit(False); Result := (StrToInt(AValue) >= 1001000) and (StrToInt(AValue) <= 99999999); end; end.
unit cyhtAnalysisForm; interface uses Forms, BaseForm, Classes, Controls, SysUtils, StdCtrls, QuickSortList, QuickList_double, StockDayDataAccess, define_price, define_dealitem, define_datasrc, Rule_CYHT, Rule_BDZX; type TfrmCyhtAnalysisData = record StockDayDataAccess: TStockDayDataAccess; end; TfrmCyhtAnalysis = class(TfrmBase) btncomputecyht: TButton; edtstock: TEdit; edtdatasrc: TComboBox; lbl1: TLabel; lbl2: TLabel; btncomputebdzx: TButton; procedure btncomputecyhtClick(Sender: TObject); procedure btncomputebdzxClick(Sender: TObject); protected fCyhtAnalysisData: TfrmCyhtAnalysisData; function getDataSrc: TDealDataSource; function getDataSrcWeightMode: TRT_WeightMode; function getStockCode: integer; procedure ComputeCYHT(ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode; AStockPackCode: integer); overload; procedure ComputeCYHT(ADataSrc: TDealDataSource; ADealItem: PRT_DealItem; AWeightMode: TRT_WeightMode; AOutput: TALDoubleList); overload; procedure ComputeBDZX(ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode; AStockPackCode: integer); overload; procedure ComputeBDZX(ADataSrc: TDealDataSource; ADealItem: PRT_DealItem; AWeightMode: TRT_WeightMode; AOutput: TALDoubleList); overload; public constructor Create(AOwner: TComponent); override; end; implementation {$R *.dfm} uses BaseRuleData, define_dealstore_file, define_stock_quotes, StockDayData_Load, BaseStockFormApp; constructor TfrmCyhtAnalysis.Create(AOwner: TComponent); begin inherited; FillChar(fCyhtAnalysisData, SizeOf(fCyhtAnalysisData), 0); end; function TfrmCyhtAnalysis.getDataSrc: TDealDataSource; begin Result := Src_163; end; function TfrmCyhtAnalysis.getDataSrcWeightMode: TRT_WeightMode; begin Result := weightNone; end; function TfrmCyhtAnalysis.getStockCode: integer; begin Result := getStockCodePack(edtstock.Text); end; procedure TfrmCyhtAnalysis.btncomputebdzxClick(Sender: TObject); begin ComputeBDZX(getDataSrc, getDataSrcWeightMode, getStockCode); end; procedure TfrmCyhtAnalysis.btncomputecyhtClick(Sender: TObject); begin ComputeCYHT(getDataSrc, getDataSrcWeightMode, getStockCode); end; procedure TfrmCyhtAnalysis.ComputeCYHT(ADataSrc: TDealDataSource; ADealItem: PRT_DealItem; AWeightMode: TRT_WeightMode; AOutput: TALDoubleList); var tmpSK: double; tmpOutput: TStringList; i: Integer; tmpStr: string; tmpDayData: PRT_Quote_Day; tmpRule_Cyht_Price: TRule_Cyht_Price; begin if nil = ADealItem then exit; if 0 = ADealItem.EndDealDate then begin if nil <> fCyhtAnalysisData.StockDayDataAccess then begin fCyhtAnalysisData.StockDayDataAccess.Free; end; fCyhtAnalysisData.StockDayDataAccess := TStockDayDataAccess.Create(ADealItem, ADataSrc, AWeightMode); try StockDayData_Load.LoadStockDayData(App, fCyhtAnalysisData.StockDayDataAccess); if (0 < fCyhtAnalysisData.StockDayDataAccess.RecordCount) then begin tmpRule_Cyht_Price := TRule_Cyht_Price.Create(); try tmpRule_Cyht_Price.OnGetDataLength := fCyhtAnalysisData.StockDayDataAccess.DoGetRecords; tmpRule_Cyht_Price.OnGetPriceOpen := fCyhtAnalysisData.StockDayDataAccess.DoGetStockOpenPrice; tmpRule_Cyht_Price.OnGetPriceClose := fCyhtAnalysisData.StockDayDataAccess.DoGetStockClosePrice; tmpRule_Cyht_Price.OnGetPriceHigh := fCyhtAnalysisData.StockDayDataAccess.DoGetStockHighPrice; tmpRule_Cyht_Price.OnGetPriceLow := fCyhtAnalysisData.StockDayDataAccess.DoGetStockLowPrice; tmpRule_Cyht_Price.Execute; tmpSK := tmpRule_Cyht_Price.SK[fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1]; AOutput.AddObject(tmpSK, TObject(ADealItem)); tmpOutput := TStringList.Create; try for i := 0 to fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1 do begin tmpSK := tmpRule_Cyht_Price.SK[i]; tmpDayData := fCyhtAnalysisData.StockDayDataAccess.DayDataByIndex(i); tmpStr := FormatDateTime('yyyymmdd', tmpDayData.DealDate.Value); tmpStr := tmpStr + 'SK:' + FormatFloat('0.00', tmpRule_Cyht_Price.SK[i]); tmpStr := tmpStr + 'SD:' + FormatFloat('0.00', tmpRule_Cyht_Price.SD[i]); tmpOutput.Add(tmpStr); end; tmpOutput.SaveToFile(ADealItem.sCode + '_' + FormatDateTime('yyyymmdd', now) + '_cyht.txt'); finally tmpOutput.Free; end; finally FreeAndNil(tmpRule_Cyht_Price); end; end; finally FreeAndNil(fCyhtAnalysisData.StockDayDataAccess); end; end; end; procedure TfrmCyhtAnalysis.ComputeCYHT(ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode; AStockPackCode: integer); var i: integer; tmpStockItem: PRT_DealItem; tmpCyht: TALDoubleList; tmpResultOutput: TStringList; begin tmpCyht := TALDoubleList.Create; try tmpCyht.Duplicates := lstDupAccept; if src_unknown <> src_unknown then begin tmpStockItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(IntToStr(AStockPackCode)); ComputeCYHT(ADataSrc, tmpStockItem, AWeightMode, tmpCyht); end else begin for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do begin tmpStockItem := TBaseStockApp(App).StockItemDB.DealItemByIndex(i); ComputeCYHT(ADataSrc, tmpStockItem, AWeightMode, tmpCyht); Break; end; end; tmpCyht.Sort; tmpResultOutput := TStringList.Create; try for i := 0 to tmpCyht.Count - 1 do begin tmpStockItem := PRT_DealItem(tmpCyht.Objects[i]); tmpResultOutput.Add(FloatToStr(tmpCyht[i]) + ' -- ' + tmpStockItem.sCode); end; tmpResultOutput.SaveToFile('Cyht' + FormatDateTime('yyyymmdd_hhnnss', now) + '.txt'); finally tmpResultOutput.Free; end; finally tmpCyht.Free; end; end; procedure TfrmCyhtAnalysis.ComputeBDZX(ADataSrc: TDealDataSource; ADealItem: PRT_DealItem; AWeightMode: TRT_WeightMode; AOutput: TALDoubleList); var tmpAK: double; tmpAD: double; tmpAJ: double; tmpOutput: TStringList; i: Integer; tmpStr: string; tmpDayData: PRT_Quote_Day; tmpRule_BDZX_Price: TRule_BDZX_Price; begin if nil = ADealItem then exit; if 0 = ADealItem.EndDealDate then begin if nil <> fCyhtAnalysisData.StockDayDataAccess then begin fCyhtAnalysisData.StockDayDataAccess.Free; end; fCyhtAnalysisData.StockDayDataAccess := TStockDayDataAccess.Create(ADealItem, ADataSrc, AWeightMode); try StockDayData_Load.LoadStockDayData(App, fCyhtAnalysisData.StockDayDataAccess); if (0 < fCyhtAnalysisData.StockDayDataAccess.RecordCount) then begin tmpRule_BDZX_Price := TRule_BDZX_Price.Create(); try tmpRule_BDZX_Price.OnGetDataLength := fCyhtAnalysisData.StockDayDataAccess.DoGetRecords; tmpRule_BDZX_Price.OnGetPriceOpen := fCyhtAnalysisData.StockDayDataAccess.DoGetStockOpenPrice; tmpRule_BDZX_Price.OnGetPriceClose := fCyhtAnalysisData.StockDayDataAccess.DoGetStockClosePrice; tmpRule_BDZX_Price.OnGetPriceHigh := fCyhtAnalysisData.StockDayDataAccess.DoGetStockHighPrice; tmpRule_BDZX_Price.OnGetPriceLow := fCyhtAnalysisData.StockDayDataAccess.DoGetStockLowPrice; tmpRule_BDZX_Price.Execute; tmpAK := GetArrayDoubleValue(tmpRule_BDZX_Price.Ret_AK_Float, fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1); tmpAJ := GetArrayDoubleValue(tmpRule_BDZX_Price.Ret_AJ, fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1); AOutput.AddObject(tmpAK, TObject(ADealItem)); tmpOutput := TStringList.Create; try for i := 0 to fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1 do begin tmpAK := GetArrayDoubleValue(tmpRule_BDZX_Price.Ret_AK_Float, i); tmpAD := tmpRule_BDZX_Price.Ret_AD1_EMA.ValueF[i]; tmpAJ := GetArrayDoubleValue(tmpRule_BDZX_Price.Ret_AJ, i); tmpDayData := fCyhtAnalysisData.StockDayDataAccess.DayDataByIndex(i); tmpStr := FormatDateTime('yyyymmdd', tmpDayData.DealDate.Value) + #32 + '-'; tmpStr := tmpStr + 'AK:' + FormatFloat('0.00', tmpAK) + ' - '; tmpStr := tmpStr + 'AD:' + FormatFloat('0.00', tmpAD) + ' - '; tmpStr := tmpStr + 'AJ:' + FormatFloat('0.00', tmpAJ); tmpOutput.Add(tmpStr); end; tmpOutput.SaveToFile(ADealItem.sCode + '_' + FormatDateTime('yyyymmdd', now) + '_bdzx.txt'); finally tmpOutput.Free; end; finally FreeAndNil(tmpRule_BDZX_Price); end; end; finally FreeAndNil(fCyhtAnalysisData.StockDayDataAccess); end; end; end; procedure TfrmCyhtAnalysis.ComputeBDZX(ADataSrc: TDealDataSource; AWeightMode: TRT_WeightMode; AStockPackCode: integer); var i: integer; tmpStockItem: PRT_DealItem; tmpCyht: TALDoubleList; tmpResultOutput: TStringList; begin tmpCyht := TALDoubleList.Create; try tmpCyht.Duplicates := lstDupAccept; if src_unknown <> src_unknown then begin tmpStockItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(IntToStr(AStockPackCode)); ComputeBDZX(ADataSrc, tmpStockItem, AWeightMode, tmpCyht); end else begin for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do begin tmpStockItem := TBaseStockApp(App).StockItemDB.DealItemByIndex(i); ComputeBDZX(ADataSrc, tmpStockItem, AWeightMode, tmpCyht); Break; end; end; tmpCyht.Sort; tmpResultOutput := TStringList.Create; try for i := 0 to tmpCyht.Count - 1 do begin tmpStockItem := PRT_DealItem(tmpCyht.Objects[i]); tmpResultOutput.Add(FloatToStr(tmpCyht[i]) + ' -- ' + tmpStockItem.sCode); end; tmpResultOutput.SaveToFile('Bdzx' + FormatDateTime('yyyymmdd_hhnnss', now) + '.txt'); finally tmpResultOutput.Free; end; finally tmpCyht.Free; end; end; end.
unit ssWinVer; interface function IsWin95: Boolean; function IsWin98: Boolean; function IsWinMe: Boolean; function IsWinNT: Boolean; function IsWin2k: Boolean; function IsWinXP: Boolean; function IsNTPlatform: Boolean; implementation uses Windows; function IsWin98: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 10) and (WInfo.dwMajorVersion = 4); end; function IsWin95: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 0) and (WInfo.dwMajorVersion = 4); end; function IsWinNT: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 51) and (WInfo.dwMajorVersion = 3); end; function IsWin2k: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 0) and (WInfo.dwMajorVersion = 5); end; function IsWinXP: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 1) and (WInfo.dwMajorVersion = 5); end; function IsWinMe: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := (WInfo.dwMinorVersion = 90) and (WInfo.dwMajorVersion = 4); end; function IsNTPlatform: Boolean; var WInfo: _OSVERSIONINFO; begin Result := False; WInfo.dwOSVersionInfoSize := SizeOf(WInfo); if GetVersionEx(WInfo) then Result := WInfo.dwPlatformId = VER_PLATFORM_WIN32_NT; end; end.
unit IWMainForm; {PUBDIST} interface uses IWAppForm, IWApplication, IWTypes, IWCompListbox, IWCompEdit, Classes, Controls, IWControl, IWCompButton, Menus, IWCompMenu, IWGrids, IWAnotherForm; type TformMain = class(TIWAppForm) IWGrid1: TIWGrid; btnShowGraphic: TIWButton; btnCloseMain: TIWButton; procedure btnShowGraphicClick(Sender: TObject); procedure btnCloseMainClick(Sender: TObject); procedure IWAppFormCreate(Sender: TObject); public // per session data: even better save it in TUserSession anotherform: TAnotherForm; end; implementation {$R *.dfm} uses ServerController, IWHTMLControls, SysUtils; procedure TformMain.btnShowGraphicClick(Sender: TObject); begin anotherform := TAnotherForm.Create(WebApplication); anotherform.Show; end; procedure TformMain.btnCloseMainClick(Sender: TObject); begin // show a message // WebApplication.Terminate('Hello'); // redirect user to another page/site WebApplication.TerminateAndRedirect('http://www.marcocantu.com'); end; procedure TformMain.IWAppFormCreate(Sender: TObject); var i: Integer; link: TIWURL; begin // set grid titles IWGrid1.Cell[0, 0].Text := 'Row'; IWGrid1.Cell[0, 1].Text := 'Owner'; IWGrid1.Cell[0, 2].Text := 'Web Site'; // set grid contents for i := 1 to IWGrid1.RowCount - 1 do begin IWGrid1.Cell [i,0].Text := 'Row ' + IntToStr (i+1); IWGrid1.Cell [i,1].Text := 'IWTwoForms by Marco Cantý'; link := TIWURL.Create(self); link.Text := 'Click here'; link.URL := 'http://www.marcocantu.com'; // link.FriendlyName := '/link'; IWGrid1.Cell [i,2].Control := link; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.10 2/8/05 5:29:16 PM RLebeau { Updated GetHToNBytes() to use CopyTIdWord() instead of AppendBytes() for IPv6 { addresses. } { { Rev 1.9 28.09.2004 20:54:32 Andreas Hausladen { Removed unused functions that were moved to IdGlobal } { Rev 1.8 6/11/2004 8:48:20 AM DSiders Added "Do not Localize" comments. } { Rev 1.7 5/19/2004 10:44:34 PM DSiders Corrected spelling for TIdIPAddress.MakeAddressObject method. } { { Rev 1.6 14/04/2004 17:35:38 HHariri { Removed IP6 for BCB temporarily } { { Rev 1.5 2/11/2004 5:10:40 AM JPMugaas { Moved IPv6 address definition to System package. } { { Rev 1.4 2004.02.03 4:17:18 PM czhower { For unit name changes. } { { Rev 1.3 2/2/2004 12:22:24 PM JPMugaas { Now uses IdGlobal IPVersion Type. Added HToNBytes for things that need { to export into NetworkOrder for structures used in protocols. } { { Rev 1.2 1/3/2004 2:13:56 PM JPMugaas { Removed some empty function code that wasn't used. { Added some value comparison functions. { Added a function in the IPAddress object for comparing the value with another { IP address. Note that this comparison is useful as an IP address will take { several forms (especially common with IPv6). { Added a property for returning the IP address as a string which works for { both IPv4 and IPv6 addresses. } { { Rev 1.1 1/3/2004 1:03:14 PM JPMugaas { Removed Lo as it was not needed and is not safe in NET. } { { Rev 1.0 1/1/2004 4:00:18 PM JPMugaas { An object for handling both IPv4 and IPv6 addresses. This is a proposal with { some old code for conversions. } unit IdIPAddress; interface uses IdGlobal, IdSys; type TIdIPAddress = class(TObject) protected FIPv4 : Cardinal; FIPv6 : TIdIPv6Address; FAddrType : TIdIPVersion; class function IPv4MakeCardInRange(const AInt : Int64; const A256Power : Integer) : Cardinal; //general conversion stuff class function IPv6ToIdIPv6Address(const AIPAddress : String; var VErr : Boolean) : TIdIPv6Address; class function IPv4ToCardinal(const AIPAddress : String; var VErr : Boolean) : Cardinal; class function MakeCanonicalIPv6Address(const AAddr: string): string; class function MakeCanonicalIPv4Address(const AAddr: string): string; //property as String Get methods function GetIPv4AsString : String; function GetIPv6AsString : String; function GetIPAddress : String; public function GetHToNBytes: TIdBytes; public constructor Create; virtual; class function MakeAddressObject(const AIP : String) : TIdIPAddress; function CompareAddress(const AIP : String; var Err : Boolean) : Integer; property IPv4 : Cardinal read FIPv4 write FIPv4; property IPv4AsString : String read GetIPv4AsString; {$IFNDEF BCB} property IPv6 : TIdIPv6Address read FIPv6 write FIPv6; {$ENDIF} property IPv6AsString : String read GetIPv6AsString; property AddrType : TIdIPVersion read FAddrType write FAddrType; property IPAsString : String read GetIPAddress; property HToNBytes : TIdBytes read GetHToNBytes; end; implementation uses IdStack; //The power constants are for processing IP addresses //They are powers of 255. const POWER_1 = $000000FF; POWER_2 = $0000FFFF; POWER_3 = $00FFFFFF; POWER_4 = $FFFFFFFF; //IPv4 address conversion //Much of this is based on http://www.pc-help.org/obscure.htm function OctalToInt64(const AValue: string): Int64; //swiped from: //http://www.swissdelphicenter.ch/torry/showcode.php?id=711 var i: Integer; begin Result := 0; for i := 1 to Length(AValue) do begin Result := Result * 8 + Sys.StrToInt(Copy(AValue, i, 1),0); end; end; function CompareWord(const AWord1, AWord2 : Word) : Integer; { AWord1 > AWord2 > 0 AWord1 < AWord2 < 0 AWord1 = AWord2 = 0 } begin Result := 0; if AWord1 > AWord2 then begin Result := 1; end else begin if AWord1 < AWord2 then begin Result := -1; end; end; end; function CompareCardinal(const ACard1, ACard2 : Cardinal) : Integer; { ACard1 > ACard2 > 0 ACard1 < ACard2 < 0 ACard1 = ACard2 = 0 } begin Result := 0; if ACard1 > ACard2 then begin Result := 1; end else begin if ACard1 < ACard2 then begin Result := -1; end; end; end; { TIdIPAddress } function TIdIPAddress.CompareAddress(const AIP: String; var Err: Boolean): Integer; var LIP2 : TIdIPAddress; i : Integer; { Note that the IP address in the object is S1. S1 > S2 > 0 S1 < S2 < 0 S1 = S2 = 0 } begin Result := 0; //LIP2 may be nil if the IP address is invalid LIP2 := MakeAddressObject(AIP); Err := not Assigned(LIP2); if not Err then begin try //we can't compare an IPv4 address with an IPv6 address Err := FAddrType <> LIP2.FAddrType; if not Err then begin if FAddrType = Id_IPv4 then begin Result := CompareCardinal(FIPv4,LIP2.FIPv4); end else begin for i := 0 to 7 do begin Result := CompareWord(FIPv6[i],LIP2.FIPv6[i]); if Result <> 0 then begin Break; end; end; end; end; finally Sys.FreeAndNil(LIP2); end; end; end; constructor TIdIPAddress.Create; begin inherited Create; FAddrType := Id_IPv4; FIPv4 := 0; //'0.0.0.0' end; function TIdIPAddress.GetHToNBytes: TIdBytes; var i : Integer; begin SetLength(Result, 0); case Self.FAddrType of Id_IPv4 : begin Result := ToBytes(GStack.HostToNetwork(FIPv4)); end; Id_IPv6 : begin SetLength(Result, 16); for i := 0 to 7 do begin CopyTIdWord(GStack.HostToNetwork(FIPv6[i]), Result, 2*i); end; end; end; end; function TIdIPAddress.GetIPAddress: String; begin if FAddrType = Id_IPv4 then begin Result := GetIPv4AsString; end else begin Result := GetIPv6AsString; end; end; function TIdIPAddress.GetIPv4AsString: String; begin Result := ''; if FAddrType = Id_IPv4 then begin Result := Sys.IntToStr((FIPv4 shr 24) and $FF)+'.'; Result := Result + Sys.IntToStr((FIPv4 shr 16) and $FF)+'.'; Result := Result + Sys.IntToStr((FIPv4 shr 8) and $FF)+'.'; Result := Result + Sys.IntToStr(FIPv4 and $FF); end; end; function TIdIPAddress.GetIPv6AsString: String; var i:integer; begin Result := ''; if FAddrType = Id_IPv6 then begin Result := Sys.IntToHex(FIPv6[0], 4); for i := 1 to 7 do begin Result := Result + ':' + Sys.IntToHex(FIPv6[i], 4); end; end; end; class function TIdIPAddress.IPv4MakeCardInRange(const AInt: Int64; const A256Power: Integer): Cardinal; begin case A256Power of 4 : Result := (AInt and POWER_4); 3 : Result := (AInt and POWER_3); 2 : Result := (AInt and POWER_2); else Result := (AInt and POWER_1); end; end; class function TIdIPAddress.IPv4ToCardinal(const AIPAddress: String; var VErr: Boolean): Cardinal; var LBuf, LBuf2 : String; L256Power : Integer; LParts : Integer; //how many parts should we process at a time begin // S.G. 11/8/2003: Added overflow checking disabling and change multiplys by SHLs. // Locally disable overflow checking so we can safely use SHL and SHR {$ifopt Q+} // detect previous setting {$define _QPlusWasEnabled} {$Q-} {$endif} VErr := True; L256Power := 4; LBuf2 := AIPAddress; Result := 0; repeat LBuf := Fetch(LBuf2,'.'); if LBuf = '' then begin break; end; //We do things this way because we have to treat //IP address parts differently than a whole number //and sometimes, there can be missing periods. if (LBuf2='') and (L256Power > 1) then begin LParts := L256Power; Result := Result shl (L256Power SHL 3); end else begin LParts := 1; result := result SHL 8; end; if (Copy(LBuf,1,2)=HEXPREFIX) then begin //this is a hexideciaml number if IsHexidecimal(Copy(LBuf,3,MaxInt))=False then begin Exit; end else begin Result := Result + IPv4MakeCardInRange(Sys.StrToInt64(LBuf,0), LParts); end; end else begin if IsNumeric(LBuf) then begin if (LBuf[1]='0') and IsOctal(LBuf) then begin //this is octal Result := Result + IPv4MakeCardInRange(OctalToInt64(LBuf),LParts); end else begin //this must be a decimal Result := Result + IPv4MakeCardInRange(Sys.StrToInt64(LBuf,0), LParts); end; end else begin //There was an error meaning an invalid IP address Exit; end; end; Dec(L256Power); until False; VErr := False; // Restore overflow checking {$ifdef _QPlusWasEnabled} // detect previous setting {$undef _QPlusWasEnabled} {$Q-} {$endif} end; class function TIdIPAddress.IPv6ToIdIPv6Address(const AIPAddress: String; var VErr: Boolean): TIdIPv6Address; var LAddress:string; i:integer; begin LAddress := MakeCanonicalIPv6Address(AIPAddress); VErr := (LAddress=''); if not VErr then begin for i := 0 to 7 do begin Result[i]:=Sys.StrToInt('$'+fetch(LAddress,':'),0); end; end; end; class function TIdIPAddress.MakeAddressObject( const AIP: String): TIdIPAddress; var LErr : Boolean; begin Result := TIdIPAddress.Create; Result.FIPv6 := Result.IPv6ToIdIPv6Address(AIP,LErr); if LErr then begin Result.FIPv4 := Result.IPv4ToCardinal(AIP,LErr); if LErr then begin //this is not a valid IPv4 address Sys.FreeAndNil(Result); end else begin Result.FAddrType := Id_IPv4; end; end else begin Result.FAddrType := Id_IPv6; end; end; class function TIdIPAddress.MakeCanonicalIPv4Address( const AAddr: string): string; var LErr : Boolean; LIP : Cardinal; begin LIP := IPv4ToDWord(AAddr,LErr); if LErr then begin Result := ''; end else begin Result := MakeDWordIntoIPv4Address(LIP); end; end; class function TIdIPAddress.MakeCanonicalIPv6Address( const AAddr: string): string; // return an empty string if the address is invalid, // for easy checking if its an address or not. var p, i: integer; dots, colons: integer; colonpos: array[1..8] of integer; dotpos: array[1..3] of integer; LAddr: string; num: integer; haddoublecolon: boolean; fillzeros: integer; begin Result := ''; // error LAddr := AAddr; if Length(LAddr) = 0 then exit; if LAddr[1] = ':' then begin LAddr := '0'+LAddr; end; if LAddr[Length(LAddr)] = ':' then begin LAddr := LAddr + '0'; end; dots := 0; colons := 0; for p := 1 to Length(LAddr) do begin case LAddr[p] of '.' : begin inc(dots); if dots < 4 then begin dotpos[dots] := p; end else begin exit; // error in address end; end; ':' : begin inc(colons); if colons < 8 then begin colonpos[colons] := p; end else begin exit; // error in address end; end; 'a'..'f', 'A'..'F': if dots>0 then exit; // allow only decimal stuff within dotted portion, ignore otherwise '0'..'9': ; // do nothing else exit; // error in address end; // case end; // for if not (dots in [0,3]) then begin exit; // you have to write 0 or 3 dots... end; if dots = 3 then begin if not (colons in [2..6]) then begin exit; // must not have 7 colons if we have dots end; if colonpos[colons] > dotpos[1] then begin exit; // x:x:x.x:x:x is not valid end; end else begin if not (colons in [2..7]) then begin exit; // must at least have two colons end; end; // now start :-) num := Sys.StrToInt('$'+Copy(LAddr, 1, colonpos[1]-1), -1); if (num<0) or (num>65535) then begin exit; // huh? odd number... end; Result := Sys.IntToHex(num,1)+':'; haddoublecolon := false; for p := 2 to colons do begin if colonpos[p-1] = colonpos[p]-1 then begin if haddoublecolon then begin Result := ''; exit; // only a single double-dot allowed! end; haddoublecolon := true; fillzeros := 8 - colons; if dots>0 then dec(fillzeros,2); for i := 1 to fillzeros do begin Result := Result + '0:'; {do not localize} end; end else begin num := Sys.StrToInt('$'+Copy(LAddr, colonpos[p-1]+1, colonpos[p]-colonpos[p-1]-1), -1); if (num<0) or (num>65535) then begin Result := ''; exit; // huh? odd number... end; Result := Result + Sys.IntToHex(num,1)+':'; end; end; // end of colon separated part if dots = 0 then begin num := Sys.StrToInt('$'+Copy(LAddr, colonpos[colons]+1, MaxInt), -1); if (num<0) or (num>65535) then begin Result := ''; exit; // huh? odd number... end; Result := Result + Sys.IntToHex(num,1)+':'; end; if dots > 0 then begin num := Sys.StrToInt(Copy(LAddr, colonpos[colons]+1, dotpos[1]-colonpos[colons]-1),-1); if (num < 0) or (num>255) then begin Result := ''; exit; end; Result := Result + Sys.IntToHex(num, 2); num := Sys.StrToInt(Copy(LAddr, dotpos[1]+1, dotpos[2]-dotpos[1]-1),-1); if (num < 0) or (num>255) then begin Result := ''; exit; end; Result := Result + Sys.IntToHex(num, 2)+':'; num := Sys.StrToInt(Copy(LAddr, dotpos[2]+1, dotpos[3]-dotpos[2]-1),-1); if (num < 0) or (num>255) then begin Result := ''; exit; end; Result := Result + Sys.IntToHex(num, 2); num := Sys.StrToInt(Copy(LAddr, dotpos[3]+1, 3), -1); if (num < 0) or (num>255) then begin Result := ''; exit; end; Result := Result + Sys.IntToHex(num, 2)+':'; end; SetLength(Result, Length(Result)-1); end; end.
unit ncsReplyDescription; // Модуль: "w:\common\components\rtl\Garant\cs\ncsReplyDescription.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsReplyDescription" MUID: (5461D6C30025) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , l3ProtoObject , ncsMessage , SyncObjs , Windows ; type TncsReplyDescription = class(Tl3ProtoObject) private f_Event: TEvent; f_Message: TncsMessage; f_Reply: TncsMessage; protected procedure pm_SetReply(aValue: TncsMessage); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aMessage: TncsMessage); reintroduce; procedure RequestEvent; function WaitForReply(aTimeOut: LongWord = Windows.INFINITE): Boolean; procedure AbortWait; public property Message: TncsMessage read f_Message; property Reply: TncsMessage read f_Reply write pm_SetReply; end;//TncsReplyDescription {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , SysUtils , l3Base , l3Utils //#UC START# *5461D6C30025impl_uses* //#UC END# *5461D6C30025impl_uses* ; procedure TncsReplyDescription.pm_SetReply(aValue: TncsMessage); //#UC START# *5461D977016B_5461D6C30025set_var* //#UC END# *5461D977016B_5461D6C30025set_var* begin //#UC START# *5461D977016B_5461D6C30025set_impl* Assert(f_Reply = nil); aValue.SetRefTo(f_Reply); if Assigned(f_Event) then f_Event.SetEvent; //#UC END# *5461D977016B_5461D6C30025set_impl* end;//TncsReplyDescription.pm_SetReply constructor TncsReplyDescription.Create(aMessage: TncsMessage); //#UC START# *5461D8CE0020_5461D6C30025_var* //#UC END# *5461D8CE0020_5461D6C30025_var* begin //#UC START# *5461D8CE0020_5461D6C30025_impl* inherited Create; aMessage.SetRefTo(f_Message) //#UC END# *5461D8CE0020_5461D6C30025_impl* end;//TncsReplyDescription.Create procedure TncsReplyDescription.RequestEvent; //#UC START# *5463220800C9_5461D6C30025_var* //#UC END# *5463220800C9_5461D6C30025_var* begin //#UC START# *5463220800C9_5461D6C30025_impl* if f_Event = nil then f_Event := TEvent.Create(nil, True, False, l3CreateStringGUID); //#UC END# *5463220800C9_5461D6C30025_impl* end;//TncsReplyDescription.RequestEvent function TncsReplyDescription.WaitForReply(aTimeOut: LongWord = Windows.INFINITE): Boolean; //#UC START# *546335030341_5461D6C30025_var* //#UC END# *546335030341_5461D6C30025_var* begin //#UC START# *546335030341_5461D6C30025_impl* if Assigned(Reply) then begin Result := True; end else begin RequestEvent; Result := f_Event.WaitFor(aTimeout) = wrSignaled; end; //#UC END# *546335030341_5461D6C30025_impl* end;//TncsReplyDescription.WaitForReply procedure TncsReplyDescription.AbortWait; //#UC START# *5464AAB30031_5461D6C30025_var* //#UC END# *5464AAB30031_5461D6C30025_var* begin //#UC START# *5464AAB30031_5461D6C30025_impl* FreeAndNil(f_Reply); if Assigned(f_Event) then f_Event.SetEvent; //#UC END# *5464AAB30031_5461D6C30025_impl* end;//TncsReplyDescription.AbortWait procedure TncsReplyDescription.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5461D6C30025_var* //#UC END# *479731C50290_5461D6C30025_var* begin //#UC START# *479731C50290_5461D6C30025_impl* AbortWait; FreeAndNil(f_Event); FreeAndNil(f_Reply); FreeAndNil(f_Message); inherited; //#UC END# *479731C50290_5461D6C30025_impl* end;//TncsReplyDescription.Cleanup {$IfEnd} // NOT Defined(Nemesis) end.
unit MVC_Blog.Model.Conexao; interface uses System.Classes,FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, System.SysUtils,FireDAC.DApt; type iModelQuery = interface; iModelConexao = interface function Connection : TObject; end; iModelConexaoFactory = interface function Conexao : iModelConexao; function Query : iModelQuery; end; iModelQuery = interface function Query : TObject; function Open(aSQL : String) : iModelQuery; function ExecSQL(aSQL : String) : iModelQuery; end; iModelEntidade = interface function DataSet ( aValue : TDataSource ) : iModelEntidade; procedure Open; end; iModelEntidadeFactory = interface function Produto : iModelEntidade; end; Type TModelFiredacConexao = class(TInterfacedObject, iModelConexao) private FConexao : TFDConnection; public constructor Create; destructor Destroy; override; class function New : iModelConexao; function Connection : TObject; end; Type TModelFiredacQuery = class(TInterfacedObject, iModelQuery) private FQuery : TFDQuery; FConexao : iModelConexao; public constructor Create(aValue : iModelConexao); destructor Destroy; override; class function New(aValue : iModelConexao) : iModelQuery; function Query : TObject; function Open(aSQL : String) : iModelQuery; function ExecSQL(aSQL : String) : iModelQuery; end; Type TModelConexaoFactory = class(TInterfacedObject, iModelConexaoFactory) private public constructor Create; destructor Destroy; override; class function New : iModelConexaoFactory; function Conexao : iModelConexao; function Query : iModelQuery; end; Type TModelEntidadeProduto = class(TInterfacedObject, iModelEntidade) private FQuery : iModelQuery; public constructor Create; destructor Destroy; override; class function New : iModelEntidade; function DataSet ( aValue : TDataSource ) : iModelEntidade; procedure Open; end; type TModelEntidadesFactory = class(TInterfacedObject, iModelEntidadeFactory) private FProduto : iModelEntidade; public constructor Create; destructor Destroy; override; class function New : iModelEntidadeFactory; function Produto : iModelEntidade; end; implementation { TModelFiredacConexao } function TModelFiredacConexao.Connection: TObject; begin Result := FConexao; end; constructor TModelFiredacConexao.Create; begin FConexao := TFDConnection.Create(nil); FConexao.Params.DriverID := 'FB'; FConexao.Params.Database := 'localhost/3050:C:\Projetos\DUP_Aula1\Database\PDVUPDATES.FDB'; FConexao.Params.UserName := 'SYSDBA'; FConexao.Params.Password := 'masterkey'; FConexao.Connected := true; end; destructor TModelFiredacConexao.Destroy; begin FreeAndNil(FConexao); inherited; end; class function TModelFiredacConexao.New: iModelConexao; begin Result := Self.Create; end; { TModelFiredacQuery } constructor TModelFiredacQuery.Create(aValue: iModelConexao); begin FConexao := aValue; FQuery := TFDQuery.Create(nil); FQuery.Connection := TFDConnection(FConexao.Connection); end; destructor TModelFiredacQuery.Destroy; begin FreeAndNil(FQuery); inherited; end; function TModelFiredacQuery.ExecSQL(aSQL: String): iModelQuery; begin Result := Self; FQuery.ExecSQL(aSQL); end; class function TModelFiredacQuery.New(aValue: iModelConexao): iModelQuery; begin Result := Self.Create(aValue); end; function TModelFiredacQuery.Open(aSQL: String): iModelQuery; begin Result := Self; FQuery.Open(aSQL); end; function TModelFiredacQuery.Query: TObject; begin Result := FQuery; end; { TModelConexaoFactory } function TModelConexaoFactory.Conexao: iModelConexao; begin Result := TModelFiredacConexao.New; end; constructor TModelConexaoFactory.Create; begin end; destructor TModelConexaoFactory.Destroy; begin inherited; end; class function TModelConexaoFactory.New: iModelConexaoFactory; begin Result := Self.Create; end; function TModelConexaoFactory.Query: iModelQuery; begin Result := TModelFiredacQuery.New(Self.Conexao); end; { TModelEntidadeProduto } constructor TModelEntidadeProduto.Create; begin FQuery := TModelConexaoFactory.New.Query; end; function TModelEntidadeProduto.DataSet(aValue: TDataSource): iModelEntidade; begin Result := Self; aValue.DataSet := TDataSet(FQuery.Query); end; destructor TModelEntidadeProduto.Destroy; begin inherited; end; class function TModelEntidadeProduto.New: iModelEntidade; begin Result := Self.Create; end; procedure TModelEntidadeProduto.Open; begin FQuery.Open('SELECT * FROM PRODUTO'); end; { TModelEntidadesFactory } constructor TModelEntidadesFactory.Create; begin end; destructor TModelEntidadesFactory.Destroy; begin inherited; end; class function TModelEntidadesFactory.New: iModelEntidadeFactory; begin Result := Self.Create; end; function TModelEntidadesFactory.Produto: iModelEntidade; begin if not Assigned(FProduto) then FProduto := TModelEntidadeProduto.New; Result := FProduto; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clEmailValidator; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils,{$IFDEF DEMO} Forms, Windows, clEncoder, clCertificate, clMailMessage,{$ENDIF} {$ELSE} System.Classes, System.SysUtils,{$IFDEF DEMO} Vcl.Forms, Winapi.Windows, clEncoder, clCertificate, clMailMessage,{$ENDIF} {$ENDIF} clDnsQuery, clTcpClient, clSmtp, clSocketUtils, clUtils; type TclEmailValidationLevel = ( vlBlacklist, vlSyntax, vlDomain, vlSmtp, vlMailbox ); TclEmailValidationResult = (vrInvalid, vrBlacklistOk, vrSyntaxOk, vrDomainOk, vrSmtpOk, vrMailboxOk); EclEmailValidatorError = class(Exception); TclValidatorBase = class private FNext: TclValidatorBase; protected function ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; virtual; abstract; public constructor Create(ANext: TclValidatorBase); destructor Destroy; override; function Validate(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; end; TclBlacklistValidator = class(TclValidatorBase) private FBlackList: TStrings; protected function ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; override; public constructor Create(ANext: TclValidatorBase; ABlackList: TStrings); end; TclSyntaxValidator = class(TclValidatorBase) private FPattern: string; protected function ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; override; public constructor Create(ANext: TclValidatorBase; const APattern: string); end; TclDomainValidator = class(TclValidatorBase) private FDns: TclDnsQuery; protected function ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; override; public constructor Create(ANext: TclValidatorBase; ADns: TclDnsQuery); property Dns: TclDnsQuery read FDns; end; TclEmailValidatorClient = class(TclCustomSmtp) protected procedure OpenSession; override; procedure CloseSession; override; public procedure ValidateMailbox(const AEmailFrom, AEmailToValidate: string); procedure Hello; procedure Quit; end; TclSmtpValidator = class(TclDomainValidator) private FClient: TclEmailValidatorClient; protected function ValidateServer(const AEmailToValidate, AServer: string; AErrors: TclErrorList): TclEmailValidationResult; virtual; function ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; override; public constructor Create(ANext: TclValidatorBase; ADns: TclDnsQuery; AClient: TclEmailValidatorClient); property Client: TclEmailValidatorClient read FClient; end; TclMailboxValidator = class(TclSmtpValidator) private FEmailFrom: string; protected function ValidateServer(const AEmailToValidate, AServer: string; AErrors: TclErrorList): TclEmailValidationResult; override; public constructor Create(ANext: TclValidatorBase; ADns: TclDnsQuery; AClient: TclEmailValidatorClient; const AEmailFrom: string); end; TclCreateValidatorEvent = procedure (Sender: TObject; const AEmailToValidate: string; AValidationLevel: TclEmailValidationLevel; var AValidator: TclValidatorBase) of object; TclEmailValidator = class(TComponent) private FOnCreateValidator: TclCreateValidatorEvent; FBlackList: TStrings; FSyntaxPattern: string; FEmailFrom: string; FValidationLevel: TclEmailValidationLevel; FSmtpClient: TclEmailValidatorClient; FDns: TclDnsQuery; FErrors: TclErrorList; procedure SetBlackList(const Value: TStrings); function GetHostName: string; procedure SetHostName(const Value: string); function GetTimeOut: Integer; procedure SetTimeOut(const Value: Integer); function GetDnsServer: string; procedure SetDnsServer(const Value: string); function GetValidator(const AEmail: string): TclValidatorBase; protected procedure DoCreateValidator(const AEmailToValidate: string; AValidationLevel: TclEmailValidationLevel; var AValidator: TclValidatorBase); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Validate(const AEmail: string): TclEmailValidationResult; property Dns: TclDnsQuery read FDns; property SmtpClient: TclEmailValidatorClient read FSmtpClient; property Errors: TclErrorList read FErrors; published property ValidationLevel: TclEmailValidationLevel read FValidationLevel write FValidationLevel default vlSmtp; property DnsServer: string read GetDnsServer write SetDnsServer; property TimeOut: Integer read GetTimeOut write SetTimeOut default 60000; property HostName: string read GetHostName write SetHostName; property EmailFrom: string read FEmailFrom write FEmailFrom; property SyntaxPattern: string read FSyntaxPattern write FSyntaxPattern; property BlackList: TStrings read FBlackList write SetBlackList; property OnCreateValidator: TclCreateValidatorEvent read FOnCreateValidator write FOnCreateValidator; end; const DefaultSyntaxPattern = '\w+(([-]*|[+.])\w+)*@\w+(([-]*|[.])\w+)*\.\w+(([-]*|[.])\w+)*'; resourcestring cEmailInvalid = 'Email must not be empty'; implementation uses clSocket, clSspi, clRegex, clMailUtils, clIdnTranslator; { TclValidatorBase } constructor TclValidatorBase.Create(ANext: TclValidatorBase); begin inherited Create(); FNext := ANext; end; destructor TclValidatorBase.Destroy; begin FNext.Free(); inherited Destroy(); end; function TclValidatorBase.Validate(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; var nextResult: TclEmailValidationResult; begin Result := ValidateEmail(AEmailToValidate, AErrors); if (vrInvalid <> result) and (FNext <> nil) then begin nextResult := FNext.Validate(AEmailToValidate, AErrors); if (vrInvalid <> nextResult) then begin Result := nextResult; end; end; end; { TclBlacklistValidator } constructor TclBlacklistValidator.Create(ANext: TclValidatorBase; ABlackList: TStrings); begin inherited Create(ANext); FBlackList := ABlackList; end; function TclBlacklistValidator.ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; begin if FBlackList.IndexOf(AEmailToValidate) > -1 then begin Result := vrInvalid; end else begin Result := vrBlacklistOk; end; end; { TclSyntaxValidator } constructor TclSyntaxValidator.Create(ANext: TclValidatorBase; const APattern: string); begin inherited Create(ANext); FPattern := APattern; end; function TclSyntaxValidator.ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; begin if TclRegEx.ExactMatch(AEmailToValidate, FPattern, [rxoIgnoreCase]) or TclRegEx.ExactMatch(GetIdnEmail(AEmailToValidate), FPattern, [rxoIgnoreCase]) then begin Result := vrSyntaxOk; end else begin Result := vrInvalid; end; end; { TclDomainValidator } constructor TclDomainValidator.Create(ANext: TclValidatorBase; ADns: TclDnsQuery); begin inherited Create(ANext); FDns := ADns; end; function TclDomainValidator.ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; begin try Dns.ResolveMX(AEmailToValidate); if (Dns.MailServers.Count > 0) then begin Result := vrDomainOk; end else begin Result := vrInvalid; end; except on E: EclSocketError do begin Result := vrInvalid; AErrors.AddError(E.Message, E.ErrorCode); end; end; end; { TclEmailValidatorClient } procedure TclEmailValidatorClient.CloseSession; begin end; procedure TclEmailValidatorClient.Hello; begin SendHelo(); end; procedure TclEmailValidatorClient.OpenSession; begin end; procedure TclEmailValidatorClient.Quit; begin SendQuit(); end; procedure TclEmailValidatorClient.ValidateMailbox(const AEmailFrom, AEmailToValidate: string); var list: TStrings; from: string; begin SendReset(); from := AEmailFrom; if (Trim(from) = '') then begin from := AEmailToValidate; end; if (from = '') then begin raise EclEmailValidatorError.Create(cEmailInvalid); end; SendMailFrom(from); list := TStringList.Create(); try list.Add(AEmailToValidate); SendRecipients(list); finally list.Free(); end; end; { TclSmtpValidator } constructor TclSmtpValidator.Create(ANext: TclValidatorBase; ADns: TclDnsQuery; AClient: TclEmailValidatorClient); begin inherited Create(ANext, ADns); FClient := AClient; end; function TclSmtpValidator.ValidateEmail(const AEmailToValidate: string; AErrors: TclErrorList): TclEmailValidationResult; var i: Integer; begin Result := inherited ValidateEmail(AEmailToValidate, AErrors); if (Result = vrInvalid) then Exit; for i := 0 to Dns.MailServers.Count - 1 do begin Result := ValidateServer(AEmailToValidate, Dns.MailServers[i].Name, AErrors); if (Result <> vrInvalid) then Exit; end; Result := vrInvalid; end; function TclSmtpValidator.ValidateServer(const AEmailToValidate, AServer: string; AErrors: TclErrorList): TclEmailValidationResult; begin Result := vrInvalid; try try Client.Server := AServer; Client.Open(); Result := vrSmtpOk; except on E: EclSspiError do begin AErrors.AddError(E.Message, E.ErrorCode); end; on E: EclSocketError do begin AErrors.AddError(E.Message, E.ErrorCode); end; end; finally Client.Close(); end; end; { TclMailboxValidator } constructor TclMailboxValidator.Create(ANext: TclValidatorBase; ADns: TclDnsQuery; AClient: TclEmailValidatorClient; const AEmailFrom: string); begin inherited Create(ANext, ADns, AClient); FEmailFrom := AEmailFrom; end; function TclMailboxValidator.ValidateServer(const AEmailToValidate, AServer: string; AErrors: TclErrorList): TclEmailValidationResult; begin Result := vrInvalid; try try Client.Server := AServer; Client.Open(); Result := vrSmtpOk; Client.Hello(); try Client.ValidateMailbox(FEmailFrom, AEmailToValidate); Result := vrMailboxOk; finally Client.Quit(); end; except on E: EclSspiError do begin AErrors.AddError(E.Message, E.ErrorCode); end; on E: EclSocketError do begin AErrors.AddError(E.Message, E.ErrorCode); end; end; finally Client.Close(); end; end; { TclEmailValidator } constructor TclEmailValidator.Create(AOwner: TComponent); begin inherited Create(AOwner); FErrors := TclErrorList.Create(); FBlackList := TStringList.Create(); FSmtpClient := TclEmailValidatorClient.Create(nil); FDns := TclDnsQuery.Create(nil); FSyntaxPattern := DefaultSyntaxPattern; FValidationLevel := vlSmtp; end; destructor TclEmailValidator.Destroy; begin FDns.Free(); FSmtpClient.Free(); FBlackList.Free(); FErrors.Free(); inherited Destroy(); end; procedure TclEmailValidator.DoCreateValidator(const AEmailToValidate: string; AValidationLevel: TclEmailValidationLevel; var AValidator: TclValidatorBase); begin if Assigned(OnCreateValidator) then begin OnCreateValidator(Self, AEmailToValidate, AValidationLevel, AValidator); end; end; function TclEmailValidator.GetDnsServer: string; begin Result := Dns.Server; end; function TclEmailValidator.GetHostName: string; begin Result := SmtpClient.HostName; end; function TclEmailValidator.GetTimeOut: Integer; begin Result := SmtpClient.TimeOut; end; function TclEmailValidator.GetValidator(const AEmail: string): TclValidatorBase; begin Result := nil; DoCreateValidator(AEmail, ValidationLevel, Result); if (Result <> nil) then Exit; case ValidationLevel of vlBlacklist: begin Result := TclBlacklistValidator.Create(Result, BlackList); end; vlSyntax: begin Result := TclSyntaxValidator.Create(Result, SyntaxPattern); Result := TclBlacklistValidator.Create(Result, BlackList); end; vlDomain: begin Result := TclDomainValidator.Create(Result, Dns); Result := TclSyntaxValidator.Create(Result, SyntaxPattern); Result := TclBlacklistValidator.Create(Result, BlackList); end; vlSmtp: begin Result := TclSmtpValidator.Create(Result, Dns, SmtpClient); Result := TclSyntaxValidator.Create(Result, SyntaxPattern); Result := TclBlacklistValidator.Create(Result, BlackList); end; vlMailbox: begin Result := TclMailboxValidator.Create(Result, Dns, SmtpClient, EmailFrom); Result := TclSyntaxValidator.Create(Result, SyntaxPattern); Result := TclBlacklistValidator.Create(Result, BlackList); end else Assert(False, 'Not Implemented'); end; end; procedure TclEmailValidator.SetBlackList(const Value: TStrings); begin FBlackList.Assign(Value); end; procedure TclEmailValidator.SetDnsServer(const Value: string); begin Dns.Server := Value; end; procedure TclEmailValidator.SetHostName(const Value: string); begin SmtpClient.HostName := Value; end; procedure TclEmailValidator.SetTimeOut(const Value: Integer); begin SmtpClient.TimeOut := Value; end; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} function TclEmailValidator.Validate(const AEmail: string): TclEmailValidationResult; var validator: TclValidatorBase; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) and (not IsSmtpDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsMailMessageDemoDisplayed) and (not IsDnsDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; IsSmtpDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsCertDemoDisplayed := True; IsMailMessageDemoDisplayed := True; IsDnsDemoDisplayed := True; {$ENDIF} end; {$ENDIF} FErrors.Clear(); validator := GetValidator(AEmail); try Result := validator.Validate(AEmail, FErrors); finally validator.Free(); end; end; end.
unit clProdutos; interface type TProdutos = class(TObject) private function getCodigo(): String; function getDescricao(): String; procedure setCodigo(const Value: String); procedure setDescricao(const Value: String); function getOperacao: String; procedure setOperacao(const Value: String); protected _codigo: String; _descricao: String; _operacao: String; public property Codigo: String read getCodigo write setCodigo; property Descricao: String read getDescricao write setDescricao; property Operacao: String read getOperacao write setOperacao; function Validar(): Boolean; function getObject(id, coluna: String): Boolean; function getObjects(): Boolean; function getField(campo, coluna: String): String; function Delete(filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; end; const TABLENAME = 'JOR_PRODUTOS'; implementation uses System.Variants, System.SysUtils, udm, clUtil, Math, Dialogs, Data.DB, ZAbstractRODataset, ZDataset; { TProdutos } function TProdutos.getCodigo: String; begin Result := _codigo; end; function TProdutos.getDescricao: String; begin Result := _descricao; end; function TProdutos.getOperacao: String; begin Result := _operacao; end; function TProdutos.Validar(): Boolean; begin try Result := False; if TUtil.Empty(Self.Codigo) then begin MessageDlg('Informe o código do Produto!', mtWarning, [mbOK], 0); Exit; end; if Self.Operacao = 'I' then begin if not(TUtil.Empty(getField('COD_PRODUTO', 'CODIGO'))) then begin MessageDlg('Código já cadastrado.', mtWarning, [mbOK], 0); Exit; end; end; if TUtil.Empty(Self.Descricao) then begin MessageDlg('Informe a descrição do Produto.', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.Insert(): Boolean; begin try Result := False; dm.qryCRUD1.Close; dm.qryCRUD1.SQL.Clear; dm.qryCRUD1.SQL.Text := 'INSERT INTO ' + TABLENAME + '(COD_PRODUTO, ' + 'DES_PRODUTO) ' + 'VALUES (' + ':CODIGO, ' + ':DESCRICAO);'; dm.qryCRUD1.ParamByName('CODIGO').AsString := Self.Codigo; dm.qryCRUD1.ParamByName('DESCRICAO').AsString := Self.Descricao; dm.ZConn1.PingServer; dm.qryCRUD1.ExecSQL; dm.qryCRUD1.Close; dm.qryCRUD1.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.Update(): Boolean; begin try Result := False; with dm.qryCRUD1 do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_PRODUTO = :DESCRICAO ' + 'WHERE COD_PRODUTO = :CODIGO'; ParamByName('CODIGO').AsString := Self.Codigo; ParamByName('DESCRICAO').AsString := Self.Descricao; dm.ZConn1.PingServer; ExecSQL; dm.ZConn1.Commit; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.Delete(filtro: String): Boolean; begin Try Result := False; with dm.qryCRUD1 do begin Close; SQL.Clear; SQL.Text := 'DELETE FROM ' + TABLENAME; if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_PRODUTO = :CODIGO'); ParamByName('CODIGO').AsString := Self.Codigo; end else if filtro = 'DESCRICAO' then begin SQL.Add('WHERE DES_PRODUTO = :DESCRICAO'); ParamByName('DESCRICAO').AsString := Self.Descricao; end; dm.ZConn1.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.getObject(id, coluna: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then begin Exit; end; with dm.QryGetObject1 do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_PRODUTO = :CODIGO'); ParamByName('CODIGO').AsString := id; end else if coluna = 'DESCRICAO' then begin if Pos('%', id) > 0 then begin SQL.Add(' WHERE DES_PRODUTO LIKE :DESCRICAO'); ParamByName('DESCRICAO').AsString := id; end else begin SQL.Add(' WHERE DES_PRODUTO = :DESCRICAO'); ParamByName('DESCRICAO').AsString := id; end; end; dm.ZConn1.PingServer; Open; if not(IsEmpty) then begin First; if RecordCount = 1 then begin Self.Codigo := FieldByName('COD_PRODUTO').AsString; Self.Descricao := FieldByName('DES_PRODUTO').AsString; Close; SQL.Clear; end; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.getObjects(): Boolean; begin try Result := False; with dm.QryGetObject1 do begin Close; SQL.Clear; SQL.Text := 'SELECT * FROM ' + TABLENAME; dm.ZConn1.PingServer; Open; if not(IsEmpty) then begin First; end else begin ShowMessage('Nenhum Registro não encontrado!'); Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TProdutos.getField(campo, coluna: String): String; begin try Result := ''; with dm.qryFields1 do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_PRODUTO = :CODIGO '); ParamByName('CODIGO').AsString := Self.Codigo; end else if coluna = 'DESCRICAO' then begin SQL.Add(' WHERE DES_PRODUTO = :DESCRICAO '); ParamByName('DESCRICAO').AsString := Self.Descricao; end; dm.ZConn1.PingServer; Open; if not(IsEmpty) then begin First; Result := FieldByName(campo).AsString; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TProdutos.setCodigo(const Value: String); begin _codigo := Value; end; procedure TProdutos.setDescricao(const Value: String); begin _descricao := Value; end; procedure TProdutos.setOperacao(const Value: String); begin _operacao := Value; end; end.
unit CustomersControllerU; interface uses MVCFramework, CustomersTDGU, ControllersBase; type [MVCPath('/api')] TCustomersController = class(TBaseController) private FCustomersTDG: TCustomersTDG; protected function GetDAL: TCustomersTDG; procedure MVCControllerBeforeDestroy; override; public [MVCPath('/customers')] [MVCHTTPMethod([httpGET])] procedure GetCustomers; [MVCPath('/customers/($ID)')] [MVCHTTPMethod([httpGET])] procedure GetCustomer(const ID: UInt64); [MVCDoc('Updates the customer with the specified id and return "200: OK"')] [MVCPath('/customers/($id)')] [MVCHTTPMethod([httpPUT])] procedure UpdateCustomerByID(id: Integer); [MVCDoc('Creates a new customer and returns "201: Created"')] [MVCPath('/customers')] [MVCHTTPMethod([httpPOST])] procedure CreateCustomer(Context: TWebContext); [MVCDoc('Deletes the customer with the specified id')] [MVCPath('/customers/($id)')] [MVCHTTPMethod([httpDelete])] procedure DeleteCustomerByID(id: Integer); [MVCPath('/customers/($limit)/($page)')] [MVCHTTPMethod([httpGET])] procedure GetCustomersLimit(const limit, page:Integer); procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; end; implementation { TCustomersController } uses CustomersServices, Customer, Commons, mvcframework.Commons; procedure TCustomersController.CreateCustomer(Context: TWebContext); var Customer: TCustomer; begin Customer := Context.Request.BodyAs<TCustomer>; try GetCustomersService.Add(Customer); Render(201, 'Customer Created'); finally Customer.Free; end; end; procedure TCustomersController.UpdateCustomerByID(id: Integer); var Customer: TCustomer; begin Customer := Context.Request.BodyAs<TCustomer>; try Customer.id := Context.Request.ParamsAsInteger['id']; GetCustomersService.Update(Customer); Render(200, 'Customer Updated'); finally Customer.Free; end; end; procedure TCustomersController.DeleteCustomerByID(id: Integer); var Customer: TCustomer; begin GetCustomersService.StartTransaction; try Customer := GetCustomersService.GetByID (Context.Request.ParamsAsInteger['id']); try GetCustomersService.Delete(Customer); finally Customer.Free; end; GetCustomersService.Commit; Render(200, 'Customer deleted!'); except GetCustomersService.Rollback; raise; end; end; procedure TCustomersController.GetCustomer(const ID: UInt64); begin Render(GetDAL.GetCustomerById(ID), true, true); end; procedure TCustomersController.GetCustomers; begin Render(GetDAL.GetCustomers, true); end; procedure TCustomersController.GetCustomersLimit(const limit, page:Integer); begin Render(GetDAL.GetCustomersLimit(limit, page), true); end; function TCustomersController.GetDAL: TCustomersTDG; begin if not Assigned(FCustomersTDG) then FCustomersTDG := TCustomersTDG.Create(nil); Result := FCustomersTDG; end; procedure TCustomersController.MVCControllerBeforeDestroy; begin inherited; FCustomersTDG.Free; end; procedure TCustomersController.OnAfterAction(Context: TWebContext; const AActionName: string); begin { Executed after each action } inherited; end; procedure TCustomersController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin { Executed before each action if handled is true (or an exception is raised) the actual action will not be called } inherited; end; end.
unit SpeedButtonMenu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, menus; type TSpeedButtonMenu = class(TSpeedButton) private { Private declarations } fSpeedMenu : TPopupMenu; fItems : TStrings; fItemIndex : integer; fSelected : string; fSelcaption : string; protected { Protected declarations } procedure SetItems(value:TStrings); procedure click;override; public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; procedure handleclick(Sender: TObject); published { Published declarations } property Items : TStrings read fItems write SetItems; property ItemIndex : integer read fItemIndex; property Selected : string read fSelected; property selCaption : string read fselCaption; end; procedure Register; implementation constructor TSpeedButtonMenu.create(AOwner:TComponent); begin inherited; fSpeedMenu := TPopupMenu.Create(self); fItems := TStringList.Create; tstringlist(fitems).Duplicates := dupIgnore; fItemIndex := -1; fSelected := ''; end; destructor TSpeedButtonMenu.destroy; begin fItems.Free; fSpeedMenu.free; inherited; end; procedure TSpeedButtonMenu.SetItems(value:TStrings); begin (fItems as TStringList).Assign(Value); end; procedure TSpeedButtonMenu.handleclick(sender:TObject); var x : integer; s : string; found : boolean; p : integer; begin s := TMenuItem(sender).caption; x := 0; found := false; while (not found) and (x < fItems.count) do begin p := pos(s,fItems[x]); if p = 1 then found := true else inc(x); end; if found then begin fItemIndex := x; p := pos(';',fitems[x]); fSelected := copy(fitems[x],p+1,length(fitems[x])); fSelCaption := copy(fitems[x],1,p-1); if assigned(OnClick) then OnClick(self); end; end; procedure TSpeedButtonMenu.Click; var mitem : TMenuItem; x : integer; s : string; p : integer; xy : TPoint; begin while fSpeedMenu.Items.Count > 0 do fSpeedMenu.Items.Remove(fspeedmenu.items[0]); for x := 0 to fItems.Count - 1 do begin mitem := tmenuItem.Create(fSpeedMenu); p := pos(';',fitems[x]); s := copy(fitems[x],1,p-1); mitem.Caption := s; mitem.OnClick := handleClick; fSpeedMenu.Items.Add(mitem); end; xy.x := left; xy.y := top; xy := ClienttoScreen(xy); fspeedmenu.Popup(xy.x-left,xy.y-top+height); end; procedure Register; begin RegisterComponents('FFS Common', [TSpeedButtonMenu]); end; end.
{ Date Created: 5/25/00 5:01:02 PM } unit InfoPAYECODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoPAYECODERecord = record PCode: String[4]; PDescription: String[30]; PAddress: String[30]; PCityState: String[25]; PZipCode: String[10]; PContact: String[30]; PPhone: String[30]; PTaxID: String[12]; PExpCode: String[5]; End; TInfoPAYECODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoPAYECODERecord end; TEIInfoPAYECODE = (InfoPAYECODEPrimaryKey); TInfoPAYECODETable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFAddress: TStringField; FDFCityState: TStringField; FDFZipCode: TStringField; FDFContact: TStringField; FDFPhone: TStringField; FDFTaxID: TStringField; FDFExpCode: TStringField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPAddress(const Value: String); function GetPAddress:String; procedure SetPCityState(const Value: String); function GetPCityState:String; procedure SetPZipCode(const Value: String); function GetPZipCode:String; procedure SetPContact(const Value: String); function GetPContact:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPTaxID(const Value: String); function GetPTaxID:String; procedure SetPExpCode(const Value: String); function GetPExpCode:String; procedure SetEnumIndex(Value: TEIInfoPAYECODE); function GetEnumIndex: TEIInfoPAYECODE; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoPAYECODERecord; procedure StoreDataBuffer(ABuffer:TInfoPAYECODERecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFAddress: TStringField read FDFAddress; property DFCityState: TStringField read FDFCityState; property DFZipCode: TStringField read FDFZipCode; property DFContact: TStringField read FDFContact; property DFPhone: TStringField read FDFPhone; property DFTaxID: TStringField read FDFTaxID; property DFExpCode: TStringField read FDFExpCode; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PAddress: String read GetPAddress write SetPAddress; property PCityState: String read GetPCityState write SetPCityState; property PZipCode: String read GetPZipCode write SetPZipCode; property PContact: String read GetPContact write SetPContact; property PPhone: String read GetPPhone write SetPPhone; property PTaxID: String read GetPTaxID write SetPTaxID; property PExpCode: String read GetPExpCode write SetPExpCode; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoPAYECODE read GetEnumIndex write SetEnumIndex; end; { TInfoPAYECODETable } procedure Register; implementation procedure TInfoPAYECODETable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFAddress := CreateField( 'Address' ) as TStringField; FDFCityState := CreateField( 'CityState' ) as TStringField; FDFZipCode := CreateField( 'ZipCode' ) as TStringField; FDFContact := CreateField( 'Contact' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFTaxID := CreateField( 'TaxID' ) as TStringField; FDFExpCode := CreateField( 'ExpCode' ) as TStringField; end; { TInfoPAYECODETable.CreateFields } procedure TInfoPAYECODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPAYECODETable.SetActive } procedure TInfoPAYECODETable.Validate; begin { Enter Validation Code Here } end; { TInfoPAYECODETable.Validate } procedure TInfoPAYECODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoPAYECODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoPAYECODETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoPAYECODETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoPAYECODETable.SetPAddress(const Value: String); begin DFAddress.Value := Value; end; function TInfoPAYECODETable.GetPAddress:String; begin result := DFAddress.Value; end; procedure TInfoPAYECODETable.SetPCityState(const Value: String); begin DFCityState.Value := Value; end; function TInfoPAYECODETable.GetPCityState:String; begin result := DFCityState.Value; end; procedure TInfoPAYECODETable.SetPZipCode(const Value: String); begin DFZipCode.Value := Value; end; function TInfoPAYECODETable.GetPZipCode:String; begin result := DFZipCode.Value; end; procedure TInfoPAYECODETable.SetPContact(const Value: String); begin DFContact.Value := Value; end; function TInfoPAYECODETable.GetPContact:String; begin result := DFContact.Value; end; procedure TInfoPAYECODETable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TInfoPAYECODETable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TInfoPAYECODETable.SetPTaxID(const Value: String); begin DFTaxID.Value := Value; end; function TInfoPAYECODETable.GetPTaxID:String; begin result := DFTaxID.Value; end; procedure TInfoPAYECODETable.SetPExpCode(const Value: String); begin DFExpCode.Value := Value; end; function TInfoPAYECODETable.GetPExpCode:String; begin result := DFExpCode.Value; end; procedure TInfoPAYECODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 4, N'); Add('Description, String, 30, N'); Add('Address, String, 30, N'); Add('CityState, String, 25, N'); Add('ZipCode, String, 10, N'); Add('Contact, String, 30, N'); Add('Phone, String, 30, N'); Add('TaxID, String, 12, N'); Add('ExpCode, String, 5, N'); end; end; procedure TInfoPAYECODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoPAYECODETable.SetEnumIndex(Value: TEIInfoPAYECODE); begin case Value of InfoPAYECODEPrimaryKey : IndexName := ''; end; end; function TInfoPAYECODETable.GetDataBuffer:TInfoPAYECODERecord; var buf: TInfoPAYECODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PAddress := DFAddress.Value; buf.PCityState := DFCityState.Value; buf.PZipCode := DFZipCode.Value; buf.PContact := DFContact.Value; buf.PPhone := DFPhone.Value; buf.PTaxID := DFTaxID.Value; buf.PExpCode := DFExpCode.Value; result := buf; end; procedure TInfoPAYECODETable.StoreDataBuffer(ABuffer:TInfoPAYECODERecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFAddress.Value := ABuffer.PAddress; DFCityState.Value := ABuffer.PCityState; DFZipCode.Value := ABuffer.PZipCode; DFContact.Value := ABuffer.PContact; DFPhone.Value := ABuffer.PPhone; DFTaxID.Value := ABuffer.PTaxID; DFExpCode.Value := ABuffer.PExpCode; end; function TInfoPAYECODETable.GetEnumIndex: TEIInfoPAYECODE; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoPAYECODEPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoPAYECODETable, TInfoPAYECODEBuffer ] ); end; { Register } function TInfoPAYECODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PAddress; 4 : result := @Data.PCityState; 5 : result := @Data.PZipCode; 6 : result := @Data.PContact; 7 : result := @Data.PPhone; 8 : result := @Data.PTaxID; 9 : result := @Data.PExpCode; end; end; end. { InfoPAYECODETable }
unit MvvmInterfaces; {$mode objfpc}{$H+} interface type IEventSource = interface end; IBindingSource = interface(IEventSource) function GetProperty(const PropertyName: string) : string; end; IBoundControl = interface ['{3704CD3E-27FF-48FC-9CE6-C8623D52716C}'] function GetBindingName() : string; procedure SetBindingName(const Value: string); property BindingName : string read GetBindingName write SetBindingName; procedure BindingSourceChanged(Source: IBindingSource); end; IView = interface ['{E94D8F36-B652-4AAC-B9B6-C4FFA5CE34AB}'] function GetBindingSource() : IBindingSource; procedure SetBindingSource(const Value: IBindingSource); property BindingSource : IBindingSource read GetBindingSource write SetBindingSource; end; IViewModel = interface ['{B733C14F-620C-4B71-8A49-E0B427C23807}'] end; IEventListener = interface end; implementation end.
//Exercicio 52: Faça um algoritmo para calcular a série Fibonacci até 0 N-ésimo termo. //A série tem a seguinte forma: 1,1,2,3,5,8,13,21,34,… { Solução em Portugol // A série de Fibonacci tem os 2 primeiros termos iguais a 1 e, a partir do Algoritmo Exercicio 52; // terceiro termo, o número é formado pela soma dos dois anteriores. // Exemplo: terceiro termo = segundo termo + primeiro termo = 1 + 1 = 2 Var termo, contador,penultimo,ultimo,atual: inteiro; Inicio exiba("Programa que determina o valor do N-ésimo termo da série de Fibonacci."); exiba("Digite qual termo você quer conhecer: "); leia(termo); para contador <- 1 até termo faça se(contador = 1 ou contador = 2) então inicio ultimo <- 1; penultimo <- 1; atual <- 1; fim senão inicio atual <- ultimo + penultimo; //Calcula o valor atual e depois atualiza o valor do último e penultimo <- ultimo; //penúltimo para a próxima iteração do loop. ultimo <- atual; fim; fimse; fimpara; exiba("O valor do termo é: ", atual); Fim. } // Solução em Pascal Program Exercicio52; uses crt; var termo, contador,penultimo,ultimo,atual: integer; begin clrscr; writeln('Programa que determina o valor do N-ésimo termo da série de Fibonacci.'); writeln('Digite qual termo você quer conhecer: '); readln(termo); for contador := 1 to termo do Begin if((contador = 1) or (contador = 2)) then Begin ultimo := 1; penultimo := 1; atual := 1; End else Begin atual := ultimo + penultimo; penultimo := ultimo; ultimo := atual; End; End; writeln('O valor do termo é: ', atual); repeat until keypressed; end.
unit UTLBMembers; interface uses Winapi.ActiveX, System.SysUtils, System.Generics.Collections, UTLBClasses; type TAliasList = class strict private type TItem = record Idx: Integer; OldName: string; end; strict private FList: TDictionary<string, TItem>; public constructor Create; destructor Destroy; override; procedure AddAlias(const ANewName, AOldName: string); overload; function AddAlias(const AName: string; ARefCnt: Integer; AStdUnit: TStdUnits): string; overload; function AddAlias(const AType: TPasTypeInfo): string; overload; procedure Print(AOut: TCustomOut); end; TIntfItem = class strict private FName: string; FComment: string; public constructor Create(const AName: string); function Print(AOut: TCustomOut): Boolean; virtual; procedure RequireUnits(AUnitManager: TUnitManager); virtual; procedure RegisterAliases(AList: TAliasList); virtual; public property Name: string read FName; end; TTLBMember = class; TTLBMemberDict = class(TDictionary<string, TTLBMember>); TTLBMember = class(TIntfItem) strict private FMembers: TTLBMemberDict; FPrinted: Boolean; strict protected procedure ParseTypeInfo(const ATypeInfo: ITypeInfo); virtual; procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); virtual; procedure PrintRecursive(AOut: TCustomOut); virtual; public constructor CreateTLB(const ATypeLib: ITypeLib; AIdx: Integer); constructor Create(const ATypeInfo: ITypeInfo); virtual; function Print(AOut: TCustomOut): Boolean; override; public property Members: TTLBMemberDict read FMembers write FMembers; end; TAlias = class(TTLBMember) strict private FAlias: TPasTypeInfo; FWriteType: string; strict protected procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; public function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RegisterAliases(AList: TAliasList); override; end; TTypeMember = class(TIntfItem) public constructor Create(const ATypeInfo: ITypeInfo; AMemberID: TMemberID); end; TMethodArg = class(TIntfItem) strict private const CFlagIn = $01; CFlagOut = $02; CFlagRetVal = $04; strict private FType: TPasTypeInfo; FWriteType: string; FFlag: Byte; public constructor Create(const ATypeInfo: ITypeInfo; const AName: string; const ADesc: TElemDesc); function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; function ToString: string; override; function IsRetVal: Boolean; procedure RegisterAliases(AList: TAliasList); override; public property Type_: TPasTypeInfo read FType; property WriteType: string read FWriteType; end; TPrintMethodMode = (pmmIntf, pmmDisp, pmmDelphi); TIntfMethod = class(TTypeMember) strict private type TCallingConv = (ccRegister, ccPascal, ccCdecl, ccStdcall, ccSafecall); TPropInfo = (piNone, piGet, piSet); TBrackets = (bRound, bSquare); const CCallinvConvNames: array[TCallingConv] of string = ( 'register', 'pascal', 'cdecl', 'stdcall', 'safecall' ); strict private FRetType: TPasTypeInfo; FWriteRetType: string; FArgs: TObjectList<TMethodArg>; FCallingConv: TCallingConv; FUseSafeCall: Boolean; FPropInfo: TPropInfo; FDispID: TMemberID; strict private function GetArgCount: Integer; function GetArg(AIdx: Integer): TMethodArg; strict private function DecodeCallingConv(ACallingConv: TCallConv): TCallingConv; function IsRetHRes: Boolean; public constructor Create(const ATypeInfo: ITypeInfo; AIdx: Integer; AUseSafecall: Boolean); destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure PrintForDisp(AOut: TCustomOut; AMode: TPrintMethodMode; const AClassName: string; out AIsFunc: Boolean); overload; procedure PrintForDisp(AOut: TCustomOut; AMode: TPrintMethodMode; const AClassName: string = ''); overload; /// <returns>Return True if need AOut.DecIdent</returns> function PrintArgs(AOut: TCustomOut; ABuilder: TStringBuilder; ACnt: Integer; ABrackets: TBrackets; AIsCall: Boolean = False): Boolean; procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RegisterAliases(AList: TAliasList); override; function IsSafecall: Boolean; function GetEventType: string; class function IsVoid(const AType: TPasTypeInfo): Boolean; static; public property RetType: TPasTypeInfo read FRetType; property WriteRetType: string read FWriteRetType; property DispID: TMemberID read FDispID; property PropInfo: TPropInfo read FPropInfo; property ArgCount: Integer read GetArgCount; property Args[AIdx: Integer]: TMethodArg read GetArg; end; TGUIDMember = class(TTLBMember) strict private FUUID: TGUID; strict protected property UUID: TGUID read FUUID; strict protected procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; function GetIIDPrefix: string; virtual; abstract; public procedure PrintIID(AOut: TCustomOut); procedure PrintForward(AOut: TCustomOut); virtual; abstract; end; TPropMember = record Read: TIntfMethod; Write: TIntfMethod; Index: Integer; end; TPropList = class(TDictionary<TMemberID, TPropMember>) public type TPropPair = TPair<TMemberID, TPropMember>; TPropArray = TArray<TPropPair>; strict private function GetPropMethod(const AProp: TPropMember): TIntfMethod; inline; function PrintHeaderProp(AOut: TCustomOut; ABuilder: TStringBuilder; const AProp: TPropMember; out AIdxCnt: Integer): Boolean; function CheckProcessProp(const AProp: TPropMember): Boolean; public function ToSortedArray: TPropArray; procedure PrintMethods(AOut: TCustomOut); procedure PrintProps(AOut: TCustomOut); procedure PrintDispProps(AOut: TCustomOut); end; TCustomInterface = class(TGUIDMember) strict protected function GetIIDPrefix: string; override; public procedure PrintForward(AOut: TCustomOut); override; procedure PrintMethods(AOut: TCustomOut; APropList: TPropList; AMode: TPrintMethodMode; const AClassName: string = ''); virtual; end; TInterface = class(TCustomInterface) strict private FMethods: TObjectList<TIntfMethod>; FParent: TCustomInterface; FFlags: Word; strict private function GetForwardDecl: string; strict protected property Flags: Word read FFlags; strict protected class function GetIsDisp(AFlags: Word): Boolean; overload; function GetIsDisp: Boolean; overload; strict protected procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; procedure ParseTypeInfo(const ATypeInfo: ITypeInfo); override; procedure InternalPrint(AOut: TCustomOut; const AHeader: string; APrintDisp: Boolean); function CreateParent(const ATypeInfo: ITypeInfo): TCustomInterface; virtual; procedure PrintSelf(AOut: TCustomOut); virtual; procedure PrintRecursive(AOut: TCustomOut); override; public constructor Create(const ATypeInfo: ITypeInfo); override; destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure PrintForward(AOut: TCustomOut); override; procedure PrintMethods(AOut: TCustomOut; APropList: TPropList; AMode: TPrintMethodMode; const AClassName: string = ''); override; procedure PrintImplMethods(AOut: TCustomOut; const AClassName: string); procedure PrintAsEvents(AOut: TCustomOut); procedure PrintAsInvokeEvents(AOut: TCustomOut); procedure PrintAsProps(AOut: TCustomOut); procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RegisterAliases(AList: TAliasList); override; public property UUID; end; TDispInterface = class(TInterface) strict private function GetDispName: string; function GetForwardDecl: string; strict protected function GetIIDPrefix: string; override; function CreateParent(const ATypeInfo: ITypeInfo): TCustomInterface; override; procedure PrintSelf(AOut: TCustomOut); override; public constructor Create(const ATypeInfo: ITypeInfo); override; procedure PrintForward(AOut: TCustomOut); override; end; TCoClass = class(TGUIDMember) strict private FInterfaces: TObjectList<TInterface>; FEvents: TObjectList<TInterface>; FDefaultIntf: TInterface; strict private // Service methods procedure PrintGetDefaultInterface(AOut: TCustomOut); procedure PrintInitServerData(AOut: TCustomOut); procedure PrintInvokeEvent(AOut: TCustomOut); procedure PrintConnect(AOut: TCustomOut); procedure PrintConnectTo(AOut: TCustomOut); procedure PrintDisconnect(AOut: TCustomOut); strict private function GetCoClassName: string; function GetOleClassName: string; procedure PrintCoClass(AOut: TCustomOut); procedure PrintOleClass(AOut: TCustomOut); procedure PrintCoClassImpl(AOut: TCustomOut); procedure PrintOlePropImpl(AOut: TCustomOut); procedure PrintOleSvcMethodsImpl(AOut: TCustomOut); procedure PrintOleClassImpl(AOut: TCustomOut); /// <returns>Return True if need AOut.DecIdent</returns> function PrintIntfPropImpl(AOut: TCustomOut; AMethod: TIntfMethod; ABuilder: TStringBuilder): Boolean; strict protected function GetIIDPrefix: string; override; procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; public constructor Create(const ATypeInfo: ITypeInfo); override; destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure PrintForward(AOut: TCustomOut); override; procedure RegisterAliases(AList: TAliasList); override; procedure PrintImpl(AOut: TCustomOut); procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RequireImplUnits(AUnitManager: TUnitManager); end; TEnumItem = class(TTypeMember) strict private FValue: Integer; FValueFmt: string; public constructor Create(const ATypeInfo: ITypeInfo; AIdx: Integer); function Print(AOut: TCustomOut): Boolean; override; public property ValueFmt: string read FValueFmt write FValueFmt; end; TEnum = class(TTLBMember) strict private FItems: TObjectList<TEnumItem>; FShowEnum: Boolean; FShowHex: Boolean; strict private procedure PrintItem(AOut: TCustomOut; AItem: TEnumItem; const AFmt: string); strict protected procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; public constructor Create(const ATypeInfo: ITypeInfo); override; destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; end; TVariable = class(TTypeMember) strict private FType: TPasTypeInfo; FWriteType: string; public constructor Create(const ATypeInfo: ITypeInfo; AIdx: Integer); function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RegisterAliases(AList: TAliasList); override; public property WriteType: string read FWriteType; end; TRecord = class(TTLBMember) strict private FFields: TObjectList<TVariable>; FAlign: Word; strict protected procedure ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); override; procedure PrintRecursive(AOut: TCustomOut); override; public constructor Create(const ATypeInfo: ITypeInfo); override; destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RegisterAliases(AList: TAliasList); override; end; TTLBMemberList<T: TTLBMember> = class(TObjectList<T>) strict private type TPrintProc = reference to procedure(AOut: TCustomOut; AItem: T); public constructor Create; procedure Print(AOut: TCustomOut; const AComment: string; AAddEmptyLine: Boolean); procedure CustomPrint(AOut: TCustomOut; const AComment: string; AAddEmptyLine: Boolean; const APrintProc: TPrintProc); procedure RequireUnits(AUnitManager: TUnitManager); procedure RegisterAliases(AList: TAliasList); function Add(const AItem: T; ADict: TTLBMemberDict = nil): T; end; TTLBInfo = class(TIntfItem) strict private FMajorVersion: Integer; FMinorVersion: Integer; FUUID: TGUID; FMemberList: TObjectList<TTLBMemberList<TTLBMember>>; FEnums: TTLBMemberList<TEnum>; FRecords: TTLBMemberList<TRecord>; FInterfaces: TTLBMemberList<TInterface>; FCoClasses: TTLBMemberList<TCoClass>; FAliases: TTLBMemberList<TAlias>; FRecordDict: TTLBMemberDict; FIntfDict: TTLBMemberDict; strict private function GetPasUnitName: string; strict private function CreateMemberList<T: TTLBMember>: TTLBMemberList<T>; procedure Parse(const ATypeLib: ITypeLib); procedure PrintHeaderConst(AOut: TCustomOut); procedure PrintClassIDs(AOut: TCustomOut); procedure PrintIIDs(AOut: TCustomOut); procedure PrintForward<T: TGUIDMember>(AOut: TCustomOut; AItem: T); procedure PrintClassImpl(AOut: TCustomOut); public constructor Create(const AFileName: string); destructor Destroy; override; function Print(AOut: TCustomOut): Boolean; override; procedure RequireUnits(AUnitManager: TUnitManager); override; procedure RequireImplUnits(AUnitManager: TUnitManager); procedure RegisterAliases(AList: TAliasList); override; public property PasUnitName: string read GetPasUnitName; end; implementation uses System.Win.ComObj, System.Generics.Defaults; const CEmpty = ''; CSpace = ' '; CSemicolon = ';'; CDefaultInterfaceFld = 'DefaultInterface'; type TUnitSections = record const CUnit = 'unit'; CInterface = 'interface'; CImplementation = 'implementation'; CType = 'type'; CConst = 'const'; CVar = 'var'; CBegin = 'begin'; CEnd = 'end.'; CComment = '// '; end; TClassSections = record const CClass = 'class'; CPrivate = 'private'; CProtected = 'protected'; CPublic = 'public'; CPublished = 'published'; CProperty = 'property'; CRead = 'read'; CWrite = 'write'; CDefault = 'default'; CGetPrfx = 'Get_'; CSetPrfx = 'Set_'; CProcedure = 'procedure'; CFunction = 'function'; COut = 'out'; CEnd = 'end;'; end; function __TypeDescToPasType(const ATypeDesc: TTypeDesc; out AHRef: HRefType; var APasType: TPasTypeInfo): Boolean; begin Result := True; APasType.VarType := ATypeDesc.vt; case ATypeDesc.vt of VT_EMPTY: APasType.Name := '!!!UNKNOWN Type VT_EMPTY!!!'; VT_NULL: APasType.Name := '!!!UNKNOWN Type VT_NULL!!!'; VT_I2: APasType.Name := 'SmallInt'; VT_I4: APasType.Name := 'Integer'; VT_R4: APasType.Name := 'Single'; VT_R8: APasType.Name := 'Double'; VT_CY: APasType.Name := 'Currency'; VT_DATE: APasType.Name := 'TDateTime'; VT_BSTR: APasType.Name := 'WideString'; VT_DISPATCH: APasType.Name := 'IDispatch'; VT_ERROR: begin APasType.Name := 'SCODE'; APasType.StdUnit := suActiveX; end; VT_BOOL: APasType.Name := 'WordBool'; VT_VARIANT: APasType.Name := 'OleVariant'; VT_UNKNOWN: APasType.Name := 'IUnknown'; VT_DECIMAL: APasType.Name := '!!!UNKNOWN Type VT_DECIMAL!!!'; VT_I1: APasType.Name := 'ShortInt'; VT_UI1: APasType.Name := 'Byte'; VT_UI2: APasType.Name := 'Word'; VT_UI4: APasType.Name := 'Cardinal'; VT_I8: APasType.Name := 'Int64'; VT_UI8: APasType.Name := 'UInt64'; VT_INT: begin APasType.Name := 'SYSINT'; APasType.StdUnit := suActiveX; end; VT_UINT: begin APasType.Name := 'SYSUINT'; APasType.StdUnit := suActiveX; end; VT_VOID: APasType.Name := 'VOID'; VT_HRESULT: APasType.Name := 'HRESULT'; VT_PTR: begin Inc(APasType.Ref); Result := __TypeDescToPasType(ATypeDesc.ptdesc^, AHRef, APasType); end; VT_SAFEARRAY: APasType.Name := '!!!UNKNOWN Type VT_SAFEARRAY!!!'; VT_CARRAY: APasType.Name := '!!!UNKNOWN Type VT_CARRAY!!!'; VT_USERDEFINED: begin AHRef := ATypeDesc.hreftype; APasType.Name := ''; APasType.StdUnit := suCustom; Result := False; end; VT_LPSTR: APasType.Name := 'PAnsiChar'; VT_LPWSTR: APasType.Name := 'PWideChar'; VT_RECORD: APasType.Name := '!!!UNKNOWN Type VT_RECORD!!!'; VT_INT_PTR: begin APasType.Name := 'LPARAM'; APasType.StdUnit := suWindows; end; VT_UINT_PTR: begin APasType.Name := 'WPARAM'; APasType.StdUnit := suWindows; end; VT_FILETIME: begin APasType.Name := 'FILETIME'; APasType.StdUnit := suWindows; end; VT_BLOB: APasType.Name := '!!!UNKNOWN Type VT_BLOB!!!'; VT_STREAM: APasType.Name := '!!!UNKNOWN Type VT_STREAM!!!'; VT_STORAGE: APasType.Name := '!!!UNKNOWN Type VT_STORAGE!!!'; VT_STREAMED_OBJECT: APasType.Name := '!!!UNKNOWN Type VT_STREAMED_OBJECT!!!'; VT_STORED_OBJECT: APasType.Name := '!!!UNKNOWN Type VT_STORED_OBJECT!!!'; VT_BLOB_OBJECT: APasType.Name := '!!!UNKNOWN Type VT_BLOB_OBJECT!!!'; VT_CF: APasType.Name := '!!!UNKNOWN Type VT_CF!!!'; VT_CLSID: APasType.Name := '!!!UNKNOWN Type VT_CLSID!!!'; // VT_VERSIONED_STREAM: APasType.Name := '!!!UNKNOWN Type VT_VERSIONED_STREAM!!!'; else APasType.Name := Format('!!!UNKNOWN Type desc. VT: %.4x!!!', [ATypeDesc.vt]); end; end; function TypeDescToPasType(const ATypeDesc: TTypeDesc; out AHRef: HRefType; out APasType: TPasTypeInfo): Boolean; begin APasType.Ref := 0; APasType.StdUnit := suSystem; APasType.CustomUnit := CEmpty; Result := __TypeDescToPasType(ATypeDesc, AHRef, APasType); APasType.RefBase := APasType.Ref; end; procedure GetHRefName(const ATypeInfo: ITypeInfo; AHRef: HRefType; var AType: TPasTypeInfo); forward; function ElemDescToTypeStr(const ATypeInfo: ITypeInfo; const ADesc: TTypeDesc): TPasTypeInfo; overload; var LHref: HRefType; begin if not TypeDescToPasType(ADesc, LHref, Result) then GetHRefName(ATypeInfo, LHref, Result); if (Result.VarType = VT_VOID) and (Result.Ref > 0) then begin Result.Name := 'Pointer'; Result.VarType := VT_PTR; Dec(Result.Ref); Dec(Result.RefBase); end; end; function ElemDescToTypeStr(const ATypeInfo: ITypeInfo; const ADesc: TElemDesc): TPasTypeInfo; overload; begin Result := ElemDescToTypeStr(ATypeInfo, ADesc.tdesc); end; procedure GetHRefName(const ATypeInfo: ITypeInfo; AHRef: HRefType; var AType: TPasTypeInfo); var LType: ITypeInfo; LAttr: PTypeAttr; LStr: WideString; LPasType: TPasTypeInfo; begin OleCheck(ATypeInfo.GetRefTypeInfo(AHRef, LType)); OleCheck(LType.GetDocumentation(MEMBERID_NIL, @LStr, nil, nil, nil)); AType.Name := TReservedWords.Escape(LStr); OleCheck(LType.GetTypeAttr(LAttr)); try case LAttr^.typekind of TKIND_ENUM: AType.VarType := VT_I4; TKIND_RECORD: begin AType.VarType := VT_RECORD; if (LAttr^.cVars = 4) and (AType.Name = 'GUID') then begin AType.Name := 'TGUID'; AType.StdUnit := suSystem; end; end; TKIND_INTERFACE: AType.VarType := VT_UNKNOWN; TKIND_DISPATCH: AType.VarType := VT_DISPATCH; TKIND_ALIAS: begin LPasType := ElemDescToTypeStr(ATypeInfo, LAttr^.tdescAlias); AType.VarType := LPasType.VarType; Inc(AType.RefBase, LPasType.Ref); end; end; finally LType.ReleaseTypeAttr(LAttr); end; if AType.VarType in [VT_UNKNOWN, VT_DISPATCH] then begin Dec(AType.Ref); Dec(AType.RefBase); end; end; { TAliasList } constructor TAliasList.Create; begin inherited Create; FList := TDictionary<string, TItem>.Create; end; destructor TAliasList.Destroy; begin FList.Free; inherited Destroy; end; procedure TAliasList.AddAlias(const ANewName, AOldName: string); var LItem: TItem; begin if not FList.TryGetValue(ANewName, LItem) then begin LItem.Idx := FList.Count; LItem.OldName := AOldName; FList.Add(ANewName, LItem); end; end; function TAliasList.AddAlias(const AName: string; ARefCnt: Integer; AStdUnit: TStdUnits): string; const CTypePrfx = 'T'; CPtrPrfx = 'P'; CPtrSign = '^'; var LPrevName: string; begin if AName = CEmpty then raise Exception.Create('Type must be not empty'); if ARefCnt <= 0 then Result := AName else if ARefCnt = 1 then begin Result := AName; if Result[1] = CTypePrfx then Result[1] := CPtrPrfx else Result := CPtrPrfx + Result; if AStdUnit = suCustom then AddAlias(Result, CPtrSign + AName); end else begin LPrevName := AddAlias(AName, ARefCnt - 1, AStdUnit); Result := CPtrPrfx + LPrevName; AddAlias(Result, CPtrSign + LPrevName); end; end; function TAliasList.AddAlias(const AType: TPasTypeInfo): string; begin Result := AddAlias(AType.Name, AType.Ref, AType.StdUnit); end; procedure TAliasList.Print(AOut: TCustomOut); type TItemPair = TPair<string, TItem>; var LData: TArray<TItemPair>; Li: Integer; begin if FList.Count = 0 then Exit; LData := FList.ToArray; TArray.Sort<TItemPair>(LData, TComparer<TItemPair>.Construct( function (const ALeft, ARight: TItemPair): Integer begin Result := CompareInt(ALeft.Value.Idx, ARight.Value.Idx); end )); AOut.Write(TUnitSections.CComment + 'Custom aliaces'); for Li := 0 to Length(LData) - 1 do AOut.WriteFmt('%s = %s;', [LData[Li].Key, LData[Li].Value.OldName]); AOut.EmptyLine; end; { TIntfItem } constructor TIntfItem.Create(const AName: string); begin inherited Create; FName := TReservedWords.Escape(AName); end; function TIntfItem.Print(AOut: TCustomOut): Boolean; begin Result := True; end; procedure TIntfItem.RequireUnits(AUnitManager: TUnitManager); begin // Abstract end; procedure TIntfItem.RegisterAliases(AList: TAliasList); begin // Abstract end; { TTLBMember } constructor TTLBMember.CreateTLB(const ATypeLib: ITypeLib; AIdx: Integer); var LType: ITypeInfo; begin OleCheck(ATypeLib.GetTypeInfo(AIdx, LType)); Create(LType); end; constructor TTLBMember.Create(const ATypeInfo: ITypeInfo); var LStr: WideString; begin OleCheck(ATypeInfo.GetDocumentation(MEMBERID_NIL, @LStr, nil, nil, nil)); inherited Create(LStr); ParseTypeInfo(ATypeInfo); end; procedure TTLBMember.ParseTypeInfo(const ATypeInfo: ITypeInfo); var LAttr: PTypeAttr; begin OleCheck(ATypeInfo.GetTypeAttr(LAttr)); try ParseTypeAttr(ATypeInfo, LAttr^); finally ATypeInfo.ReleaseTypeAttr(LAttr); end; end; procedure TTLBMember.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); begin // Abstract end; procedure TTLBMember.PrintRecursive(AOut: TCustomOut); begin // Abstract end; function TTLBMember.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; if FMembers <> nil then begin if FPrinted then Exit(False); FPrinted := True; PrintRecursive(AOut); end; end; { TAlias } procedure TAlias.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); FAlias := ElemDescToTypeStr(ATypeInfo, ATypeAttr.tdescAlias); end; function TAlias.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; AOut.WriteFmt('%s = type %s;', [Name, FWriteType]); end; procedure TAlias.RequireUnits(AUnitManager: TUnitManager); begin inherited RequireUnits(AUnitManager); AUnitManager.AddPasType(FAlias); end; procedure TAlias.RegisterAliases(AList: TAliasList); begin inherited RegisterAliases(AList); FWriteType := AList.AddAlias(FAlias); end; { TTypeMember } constructor TTypeMember.Create(const ATypeInfo: ITypeInfo; AMemberID: TMemberID); var LStr: WideString; begin ATypeInfo.GetDocumentation(AMemberID, @LStr, nil, nil, nil); inherited Create(LStr); end; { TMethodArg } constructor TMethodArg.Create(const ATypeInfo: ITypeInfo; const AName: string; const ADesc: TElemDesc); begin inherited Create(AName); FType := ElemDescToTypeStr(ATypeInfo, ADesc); if ADesc.paramdesc.wParamFlags and PARAMFLAG_FIN = PARAMFLAG_FIN then FFlag := FFlag or CFlagIn; if ADesc.paramdesc.wParamFlags and PARAMFLAG_FOUT = PARAMFLAG_FOUT then FFlag := FFlag or CFlagOut; if ADesc.paramdesc.wParamFlags and PARAMFLAG_FRETVAL = PARAMFLAG_FRETVAL then FFlag := FFlag or CFlagRetVal; end; function TMethodArg.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; AOut.Write(ToString); end; procedure TMethodArg.RequireUnits(AUnitManager: TUnitManager); begin inherited RequireUnits(AUnitManager); AUnitManager.AddPasType(FType); end; function TMethodArg.ToString: string; var LPrfx: string; begin if (FType.Ref > 0) and (FFlag and CFlagOut = CFlagOut) then begin if FFlag and CFlagIn = CFlagIn then LPrfx := TUnitSections.CVar else LPrfx := TClassSections.COut; end else begin if FType.Ref = 0 then begin if FType.VarType in [VT_BSTR, VT_UNKNOWN, VT_DISPATCH, VT_RECORD, VT_VARIANT] then LPrfx := TUnitSections.CConst else LPrfx := CEmpty; end else LPrfx := TUnitSections.CVar; end; if LPrfx <> CEmpty then LPrfx := LPrfx + CSpace; Result := Format('%s%s: %s', [LPrfx, Name, FWriteType]); end; function TMethodArg.IsRetVal: Boolean; const CTestFlag = CFlagOut or CFlagRetVal; begin Result := FFlag and CTestFlag = CTestFlag; end; procedure TMethodArg.RegisterAliases(AList: TAliasList); begin inherited RegisterAliases(AList); FWriteType := AList.AddAlias(FType.Name, FType.Ref - 1, FType.StdUnit); end; { TIntfMethod } constructor TIntfMethod.Create(const ATypeInfo: ITypeInfo; AIdx: Integer; AUseSafecall: Boolean); var LDesc: PFuncDesc; Li: Integer; LParamNames: array of WideString; LCnt: Integer; LPrmName: string; begin FUseSafeCall := AUseSafecall; FArgs := TObjectList<TMethodArg>.Create(True); OleCheck(ATypeInfo.GetFuncDesc(AIdx, LDesc)); try inherited Create(ATypeInfo, LDesc^.memid); FDispID := LDesc^.memid; FRetType := ElemDescToTypeStr(ATypeInfo, LDesc^.elemdescFunc); FCallingConv := DecodeCallingConv(LDesc^.callconv); case LDesc^.invkind of INVOKE_PROPERTYGET: FPropInfo := piGet; INVOKE_PROPERTYPUT, INVOKE_PROPERTYPUTREF: FPropInfo := piSet; else FPropInfo := piNone; end; if LDesc^.cParams > 0 then begin SetLength(LParamNames, LDesc^.cParams + 1); OleCheck(ATypeInfo.GetNames(LDesc^.memid, @LParamNames[0], LDesc^.cParams + 1, LCnt)); for Li := 0 to LDesc^.cParams - 1 do begin LPrmName := LParamNames[Li + 1]; if LPrmName = CEmpty then LPrmName := 'Param' + IntToStr(Li + 1); FArgs.Add(TMethodArg.Create(ATypeInfo, LPrmName, LDesc^.lprgelemdescParam^[Li])); end; end; finally ATypeInfo.ReleaseFuncDesc(LDesc); end; end; destructor TIntfMethod.Destroy; begin FArgs.Free; inherited Destroy; end; function TIntfMethod.GetArgCount: Integer; begin Result := FArgs.Count; end; function TIntfMethod.GetArg(AIdx: Integer): TMethodArg; begin Result := FArgs[AIdx]; end; function TIntfMethod.DecodeCallingConv(ACallingConv: TCallConv): TCallingConv; begin case ACallingConv of CC_SAFECALL: Result := ccSafecall; CC_CDECL, CC_MPWCDECL: Result := ccCdecl; CC_PASCAL, CC_MACPASCAL, CC_MPWPASCAL: Result := ccPascal; CC_STDCALL: Result := ccStdcall; CC_FPFASTCALL: Result := ccRegister; CC_SYSCALL: Result := ccCdecl; else Result := ccCdecl; end; end; function TIntfMethod.IsRetHRes: Boolean; begin Result := (FRetType.RefBase = 0) and (FRetType.VarType = VT_HRESULT); end; function TIntfMethod.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; PrintForDisp(AOut, pmmIntf); end; procedure TIntfMethod.PrintForDisp(AOut: TCustomOut; AMode: TPrintMethodMode; const AClassName: string; out AIsFunc: Boolean); var LIsIdent: Boolean; LUseSafeCall: Boolean; LCallConv: TCallingConv; LRetType: TPasTypeInfo; LRetTypeName: string; LLastArg: TMethodArg; LBuilder: TStringBuilder; LArgCnt: Integer; begin if AMode <> pmmIntf then LUseSafeCall := IsRetHRes else LUseSafeCall := IsSafecall; LLastArg := nil; LRetType := FRetType; LRetTypeName := FWriteRetType; LArgCnt := FArgs.Count; if LUseSafeCall then begin if LArgCnt > 0 then begin LLastArg := FArgs.Last; if LLastArg.IsRetVal then begin LRetType := LLastArg.Type_; LRetTypeName := LLastArg.WriteType; Dec(LArgCnt); end else LLastArg := nil; end; LCallConv := ccSafecall; end else LCallConv := FCallingConv; AIsFunc := (LLastArg <> nil) or (not LUseSafeCall and not IsVoid(FRetType)); // if AUseDisp and (LLastArg = nil) then // LUseSafeCall := False; LBuilder := TStringBuilder.Create; try if AIsFunc then LBuilder.Append(TClassSections.CFunction) else begin LBuilder.Append(TClassSections.CProcedure); LRetType.Ref := 0; LRetType.VarType := VT_VOID; end; LBuilder.Append(CSpace); if AClassName <> CEmpty then begin LBuilder.Append(AClassName); LBuilder.Append('.'); end; case FPropInfo of piGet: LBuilder.Append(TClassSections.CGetPrfx); piSet: LBuilder.Append(TClassSections.CSetPrfx); end; LBuilder.Append(Name); LIsIdent := PrintArgs(AOut, LBuilder, LArgCnt, bRound); if AIsFunc then begin LBuilder.Append(': '); LBuilder.Append(LRetTypeName); end; LBuilder.Append(CSemicolon); if (FCallingConv <> ccRegister) and (AMode <> pmmDelphi) then begin LBuilder.Append(CSpace); if AMode = pmmDisp then LBuilder.AppendFormat('dispid %d', [FDispID]) else LBuilder.Append(CCallinvConvNames[LCallConv]); LBuilder.Append(CSemicolon); end; AOut.Write(LBuilder.ToString); finally LBuilder.Free; end; if LIsIdent then AOut.DecIdent; end; procedure TIntfMethod.PrintForDisp(AOut: TCustomOut; AMode: TPrintMethodMode; const AClassName: string); var LIsFunc: Boolean; begin PrintForDisp(AOut, AMode, AClassName, LIsFunc); end; function TIntfMethod.PrintArgs(AOut: TCustomOut; ABuilder: TStringBuilder; ACnt: Integer; ABrackets: TBrackets; AIsCall: Boolean): Boolean; const COpenBrackets: array[TBrackets] of Char = ('(', '['); CCloseBrackets: array[TBrackets] of Char = (')', ']'); var Li: Integer; LDelim: string; LArgStr: string; begin Result := False; if ACnt > 0 then begin ABuilder.Append(COpenBrackets[ABrackets]); if AIsCall then LDelim := ', ' else LDelim := CSemicolon + CSpace; for Li := 0 to ACnt - 1 do begin if AIsCall then LArgStr := FArgs[Li].Name else LArgStr := FArgs[Li].ToString; if (ABuilder.Length + Length(LArgStr) + Length(LDelim) >= 176) and (ABuilder.Length <> 0) then begin AOut.Write(TrimRight(ABuilder.ToString)); ABuilder.Clear; if not Result then begin AOut.IncIdent; Result := True; end; end; ABuilder.Append(LArgStr); ABuilder.Append(LDelim); end; ABuilder.Length := ABuilder.Length - Length(LDelim); ABuilder.Append(CCloseBrackets[ABrackets]); end; end; procedure TIntfMethod.RequireUnits(AUnitManager: TUnitManager); var Li: Integer; begin inherited RequireUnits(AUnitManager); AUnitManager.AddPasType(FRetType); for Li := 0 to FArgs.Count - 1 do FArgs[Li].RequireUnits(AUnitManager); end; procedure TIntfMethod.RegisterAliases(AList: TAliasList); var Li: Integer; begin inherited RegisterAliases(AList); FWriteRetType := AList.AddAlias(FRetType); for Li := 0 to FArgs.Count - 1 do FArgs[Li].RegisterAliases(AList); end; function TIntfMethod.IsSafecall: Boolean; begin Result := FUseSafeCall and (FCallingConv = ccStdcall) and IsRetHRes; end; function TIntfMethod.GetEventType: string; var Li: Integer; LBld: TStringBuilder; LIsProc: Boolean; begin LIsProc := IsVoid(FRetType) or IsRetHRes; if LIsProc and (FArgs.Count = 0) then Exit('TNotifyEvent'); LBld := TStringBuilder.Create; try for Li := 0 to FArgs.Count - 1 do LBld.Append(FArgs[Li].Name); if not LIsProc then begin LBld.Append('Func'); LBld.Append(FRetType.Name); end else LBld.Append('Proc'); Result := LBld.ToString; finally LBld.Free; end; end; class function TIntfMethod.IsVoid(const AType: TPasTypeInfo): Boolean; begin Result := (AType.RefBase = 0) and (AType.VarType = VT_VOID); end; { TGUIDMember } procedure TGUIDMember.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); FUUID := ATypeAttr.guid; end; procedure TGUIDMember.PrintIID(AOut: TCustomOut); begin AOut.WriteFmt('%s_%s: TGUID = ''%s'';', [GetIIDPrefix, Name, GUIDToString(FUUID)]); end; { TPropList } function TPropList.GetPropMethod(const AProp: TPropMember): TIntfMethod; begin if AProp.Read <> nil then Result := AProp.Read else Result := AProp.Write; end; function TPropList.PrintHeaderProp(AOut: TCustomOut; ABuilder: TStringBuilder; const AProp: TPropMember; out AIdxCnt: Integer): Boolean; var LMethod: TIntfMethod; LArgCnt: Integer; begin LMethod := GetPropMethod(AProp); ABuilder.Append(TClassSections.CProperty + CSpace); ABuilder.Append(LMethod.Name); LArgCnt := LMethod.ArgCount; Result := LMethod.PrintArgs(AOut, ABuilder, LArgCnt - 1, bSquare); ABuilder.Append(': '); AIdxCnt := LArgCnt; if LArgCnt > 0 then begin ABuilder.Append(LMethod.Args[LArgCnt - 1].WriteType); Dec(AIdxCnt); end else ABuilder.Append(LMethod.WriteRetType); ABuilder.Append(CSpace); end; function TPropList.CheckProcessProp(const AProp: TPropMember): Boolean; var LArg: TMethodArg; LRetType: TPasTypeInfo; LType: TPasTypeInfo; Li: Integer; begin Result := False; if AProp.Read <> nil then begin if AProp.Read.IsSafecall then begin if AProp.Read.ArgCount = 0 then Exit; LArg := AProp.Read.Args[AProp.Read.ArgCount - 1]; if not LArg.IsRetVal then Exit; LRetType := LArg.Type_; if LRetType.Ref <= 0 then Exit; Dec(LRetType.Ref); end else begin // not Safecall LRetType := AProp.Read.RetType; if AProp.Read.IsVoid(LRetType) then Exit; end; end; if AProp.Write <> nil then begin if AProp.Write.ArgCount = 0 then Exit; LArg := AProp.Write.Args[AProp.Write.ArgCount - 1]; if AProp.Write.IsSafecall then begin if LArg.IsRetVal then Exit; end else begin // not Safecall LType := AProp.Write.RetType; if not AProp.Write.IsVoid(LType) then Exit; end; if AProp.Read <> nil then begin if not LRetType.IsEqual(LArg.Type_) then Exit; for Li := 0 to AProp.Write.ArgCount - 2 do begin if not AProp.Write.Args[Li].Type_.IsEqual(AProp.Read.Args[Li].Type_) then Exit; end; end; end; Result := True; end; function TPropList.ToSortedArray: TPropArray; begin Result := ToArray; TArray.Sort<TPropPair>(Result, TComparer<TPropPair>.Construct( function (const ALeft, ARight: TPropPair): Integer begin Result := CompareInt(ALeft.Value.Index, ARight.Value.Index); end )); end; procedure TPropList.PrintMethods(AOut: TCustomOut); var LProps: TPropArray; Li: Integer; LProp: TPropMember; begin if Count = 0 then Exit; LProps := ToSortedArray; for Li := 0 to Length(LProps) - 1 do begin LProp := LProps[Li].Value; if LProp.Read <> nil then LProp.Read.PrintForDisp(AOut, pmmDelphi); if LProp.Write <> nil then LProp.Write.PrintForDisp(AOut, pmmDelphi); end; end; procedure TPropList.PrintProps(AOut: TCustomOut); var LProps: TPropArray; LBuilder: TStringBuilder; Li: Integer; LProp: TPropMember; LIdxCnt: Integer; LIsIdent: Boolean; begin if Count = 0 then Exit; LProps := ToSortedArray; LBuilder := TStringBuilder.Create; try for Li := 0 to Length(LProps) - 1 do begin LProp := LProps[Li].Value; if not CheckProcessProp(LProp) then LBuilder.Append(TUnitSections.CComment); LIsIdent := PrintHeaderProp(AOut, LBuilder, LProp, LIdxCnt); if LProp.Read <> nil then begin LBuilder.Append(TClassSections.CRead); LBuilder.Append(CSpace); LBuilder.Append(TClassSections.CGetPrfx); LBuilder.Append(LProp.Read.Name); LBuilder.Append(CSpace); end; if LProp.Write <> nil then begin LBuilder.Append(TClassSections.CWrite); LBuilder.Append(CSpace); LBuilder.Append(TClassSections.CSetPrfx); LBuilder.Append(LProp.Write.Name); LBuilder.Append(CSpace); end; LBuilder.Chars[LBuilder.Length - 1] := ';'; if (LProps[Li].Key = 0) and (LIdxCnt > 0) then begin LBuilder.Append(CSpace); LBuilder.Append(TClassSections.CDefault); LBuilder.Append(CSemicolon); end; AOut.Write(LBuilder.ToString); LBuilder.Clear; if LIsIdent then AOut.DecIdent; end; finally LBuilder.Free; end; end; procedure TPropList.PrintDispProps(AOut: TCustomOut); var LProps: TPropArray; LBuilder: TStringBuilder; Li: Integer; LProp: TPropMember; LIdxCnt: Integer; LIsIdent: Boolean; begin if Count = 0 then Exit; LProps := ToSortedArray; LBuilder := TStringBuilder.Create; try for Li := 0 to Length(LProps) - 1 do begin LProp := LProps[Li].Value; LIsIdent := PrintHeaderProp(AOut, LBuilder, LProp, LIdxCnt); if LProp.Read <> nil then begin if LProp.Write = nil then LBuilder.Append('readonly '); end else LBuilder.Append('writeonly '); LBuilder.AppendFormat('dispid %d;', [LProps[Li].Key]); AOut.Write(LBuilder.ToString); LBuilder.Clear; if LIsIdent then AOut.DecIdent; end; finally LBuilder.Free; end; end; { TCustomInterface } function TCustomInterface.GetIIDPrefix: string; begin Result := 'IID'; end; procedure TCustomInterface.PrintForward(AOut: TCustomOut); begin // Abstract end; procedure TCustomInterface.PrintMethods(AOut: TCustomOut; APropList: TPropList; AMode: TPrintMethodMode; const AClassName: string); begin // Abstract end; { TInterface } constructor TInterface.Create(const ATypeInfo: ITypeInfo); begin FMethods := TObjectList<TIntfMethod>.Create(True); inherited Create(ATypeInfo); end; destructor TInterface.Destroy; begin FParent.Free; FMethods.Free; inherited Destroy; end; function TInterface.GetForwardDecl: string; begin Result := Name + ' = interface'; end; class function TInterface.GetIsDisp(AFlags: Word): Boolean; begin Result := AFlags and TYPEFLAG_FDUAL = TYPEFLAG_FDUAL end; function TInterface.GetIsDisp: Boolean; begin Result := GetIsDisp(FFlags); end; procedure TInterface.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); var Li: Integer; begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); FFlags := ATypeAttr.wTypeFlags; for Li := 0 to ATypeAttr.cFuncs - 1 do FMethods.Add(TIntfMethod.Create(ATypeInfo, Li, GetIsDisp)); end; procedure TInterface.ParseTypeInfo(const ATypeInfo: ITypeInfo); var LRef: HRefType; LInfo: ITypeInfo; begin inherited ParseTypeInfo(ATypeInfo); OleCheck(ATypeInfo.GetRefTypeOfImplType(0, LRef)); OleCheck(ATypeInfo.GetRefTypeInfo(LRef, LInfo)); FParent := CreateParent(LInfo); end; procedure TInterface.InternalPrint(AOut: TCustomOut; const AHeader: string; APrintDisp: Boolean); const CModes: array[Boolean] of TPrintMethodMode = (pmmIntf, pmmDisp); var LProps: TPropList; begin AOut.Write(AHeader); AOut.IncIdent; try AOut.WriteFmt('[''%s'']', [GUIDToString(UUID)]); LProps := TPropList.Create; try {$IFOPT D+} if APrintDisp then begin FMethods.Sort(TComparer<TIntfMethod>.Construct( function (const ALeft, ARight: TIntfMethod): Integer begin Result := CompareInt(ALeft.DispID, ARight.DispID); end )); end; {$ENDIF} PrintMethods(AOut, LProps, CModes[APrintDisp]); if APrintDisp then LProps.PrintDispProps(AOut) else LProps.PrintProps(AOut); finally LProps.Free; end; finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; function TInterface.CreateParent(const ATypeInfo: ITypeInfo): TCustomInterface; begin Result := TCustomInterface.Create(ATypeInfo); end; procedure TInterface.PrintSelf(AOut: TCustomOut); var LHeader: string; begin LHeader := Format('%s(%s)', [GetForwardDecl, FParent.Name]); InternalPrint(AOut, LHeader, False); end; procedure TInterface.PrintRecursive(AOut: TCustomOut); var LMem: TTLBMember; begin inherited PrintRecursive(AOut); if Members.TryGetValue(FParent.Name, LMem) then LMem.Print(AOut); end; function TInterface.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; PrintSelf(AOut); end; procedure TInterface.PrintForward(AOut: TCustomOut); begin AOut.Write(GetForwardDecl + CSemicolon); end; procedure TInterface.PrintMethods(AOut: TCustomOut; APropList: TPropList; AMode: TPrintMethodMode; const AClassName: string); var Li: Integer; LMethod: TIntfMethod; LPropMember: TPropMember; begin inherited PrintMethods(AOut, APropList, AMode); for Li := 0 to FMethods.Count - 1 do begin LMethod := FMethods[Li]; if LMethod.PropInfo <> piNone then begin if not APropList.TryGetValue(LMethod.DispID, LPropMember) then begin LPropMember.Read := nil; LPropMember.Write := nil; LPropMember.Index := APropList.Count; end; if LMethod.PropInfo = piGet then LPropMember.Read := LMethod else LPropMember.Write := LMethod; APropList.AddOrSetValue(LMethod.DispID, LPropMember); end; if (AMode = pmmIntf) or (LMethod.PropInfo = piNone) then LMethod.PrintForDisp(AOut, AMode, AClassName); end; if AMode = pmmDisp then begin // AOut.Write(TUnitSections.CComment + 'Parent ' + FParent.Name); FParent.PrintMethods(AOut, APropList, AMode, AClassName); end; end; procedure TInterface.PrintImplMethods(AOut: TCustomOut; const AClassName: string); var Li: Integer; LMethod: TIntfMethod; LBuilder: TStringBuilder; LIsFunc: Boolean; LNeedDecIdent: Boolean; begin for Li := 0 to FMethods.Count - 1 do begin LMethod := FMethods[Li]; if LMethod.PropInfo = piNone then begin LMethod.PrintForDisp(AOut, pmmDelphi, AClassName, LIsFunc); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try LBuilder := TStringBuilder.Create; try if LIsFunc then LBuilder.Append('Result := '); LBuilder.Append(CDefaultInterfaceFld + '.'); LBuilder.Append(LMethod.Name); LNeedDecIdent := LMethod.PrintArgs(AOut, LBuilder, LMethod.ArgCount - Ord(LIsFunc), bRound, True); LBuilder.Append(CSemicolon); AOut.Write(LBuilder.ToString); if LNeedDecIdent then AOut.DecIdent; finally LBuilder.Free; end; finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; end; end; procedure TInterface.PrintAsEvents(AOut: TCustomOut); var Li: Integer; LMethod: TIntfMethod; begin for Li := 0 to FMethods.Count - 1 do begin LMethod := FMethods[Li]; AOut.WriteFmt('FOn%s: %s;', [LMethod.Name, LMethod.GetEventType]); end; end; procedure TInterface.PrintAsInvokeEvents(AOut: TCustomOut); var Li: Integer; LMethod: TIntfMethod; begin for Li := 0 to FMethods.Count - 1 do begin LMethod := FMethods[Li]; AOut.WriteFmt('%d: begin', [LMethod.DispID]); AOut.IncIdent; try AOut.WriteFmt('if Assigned(FOn%s) then', [LMethod.Name]); AOut.WriteIdentFmt('FOn%s(Self);', [LMethod.Name]); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); end; end; procedure TInterface.PrintAsProps(AOut: TCustomOut); var Li: Integer; begin for Li := 0 to FMethods.Count - 1 do begin AOut.WriteFmt( 'property On%s: %s read FOn%0:s write FOn%0:s;', [FMethods[Li].Name, FMethods[Li].GetEventType] ); end; end; procedure TInterface.RequireUnits(AUnitManager: TUnitManager); var Li: Integer; begin inherited RequireUnits(AUnitManager); FParent.RequireUnits(AUnitManager); for Li := 0 to FMethods.Count - 1 do FMethods[Li].RequireUnits(AUnitManager); end; procedure TInterface.RegisterAliases(AList: TAliasList); var Li: Integer; begin inherited RegisterAliases(AList); FParent.RegisterAliases(AList); for Li := 0 to FMethods.Count - 1 do FMethods[Li].RegisterAliases(AList); end; { TDispInterface } constructor TDispInterface.Create(const ATypeInfo: ITypeInfo); var LAttr: PTypeAttr; LHref: HRefType; LType: ITypeInfo; LKind: TTypeKind; begin OleCheck(ATypeInfo.GetTypeAttr(LAttr)); try LKind := LAttr^.typekind; if (LKind = TKIND_DISPATCH) and GetIsDisp(LAttr^.wTypeFlags) then begin OleCheck(ATypeInfo.GetRefTypeOfImplType(-1, LHref)); OleCheck(ATypeInfo.GetRefTypeInfo(LHref, LType)); end else LType := ATypeInfo; finally ATypeInfo.ReleaseTypeAttr(LAttr); end; inherited Create(LType); end; function TDispInterface.GetDispName: string; begin Result := Name; if GetIsDisp then Result := Result + 'Disp'; end; function TDispInterface.GetForwardDecl: string; begin Result :=Format('%s = dispinterface', [GetDispName]); end; function TDispInterface.GetIIDPrefix: string; begin Result := inherited GetIIDPrefix; if not GetIsDisp then Result := 'D' + Result; end; function TDispInterface.CreateParent( const ATypeInfo: ITypeInfo): TCustomInterface; var LAttr: PTypeAttr; begin if GetIsDisp then begin OleCheck(ATypeInfo.GetTypeAttr(LAttr)); try if not IsEqualGUID(LAttr^.guid, IDispatch) and not IsEqualGUID(LAttr^.guid, IUnknown) then Result := TDispInterface.Create(ATypeInfo) else Result := inherited CreateParent(ATypeInfo); finally ATypeInfo.ReleaseTypeAttr(LAttr); end; end else Result := inherited CreateParent(ATypeInfo); end; procedure TDispInterface.PrintSelf(AOut: TCustomOut); begin if GetIsDisp then inherited PrintSelf(AOut); InternalPrint(AOut, GetForwardDecl, True); end; procedure TDispInterface.PrintForward(AOut: TCustomOut); begin if GetIsDisp then inherited PrintForward(AOut); AOut.Write(GetForwardDecl + CSemicolon); end; { TCoClass } constructor TCoClass.Create(const ATypeInfo: ITypeInfo); begin FInterfaces := TObjectList<TInterface>.Create(True); FEvents := TObjectList<TInterface>.Create(True); inherited Create(ATypeInfo); end; destructor TCoClass.Destroy; begin FEvents.Free; FInterfaces.Free; inherited Destroy; end; procedure TCoClass.PrintGetDefaultInterface(AOut: TCustomOut); begin AOut.WriteFmt('function %s.Get%s: %s;', [GetOleClassName, CDefaultInterfaceFld, FDefaultIntf.Name]); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('if FIntf = nil then'); AOut.WriteIdent('Connect;'); AOut.Write('Assert('); AOut.IncIdent; try AOut.Write('FIntf <> nil,'); AOut.Write('''DefaultInterface is NULL. Component is not connected to Server. You must call "Connect" or "ConnectTo" before this operation'''); finally AOut.DecIdent; end; AOut.Write(');'); AOut.Write('Result := FIntf;'); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintInitServerData(AOut: TCustomOut); var LStr: string; begin AOut.WriteFmt('procedure %s.InitServerData;', [GetOleClassName]); AOut.Write(TUnitSections.CConst); AOut.IncIdent; try AOut.Write('CServerData: TServerData = ('); AOut.IncIdent; try AOut.WriteFmt('ClassID: ''%s'';', [GUIDToString(UUID)]); AOut.WriteFmt('IntfIID: ''%s'';', [GUIDToString(FDefaultIntf.UUID)]); if FEvents.Count > 0 then LStr := GUIDToString(FEvents[0].UUID) else LStr := CEmpty; AOut.WriteFmt('EventIID: ''%s'';', [LStr]); AOut.Write('LicenseKey: nil;'); AOut.Write('Version: 500'); finally AOut.DecIdent; end; AOut.Write(');'); finally AOut.DecIdent; end; AOut.Write(TUnitSections.CBegin); AOut.WriteIdent('ServerData := @CServerData;'); AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintInvokeEvent(AOut: TCustomOut); var Li: Integer; begin AOut.WriteFmt('procedure %s.InvokeEvent(ADispID: TDispID; var AParams: TVariantArray);', [GetOleClassName]); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('case ADispID of'); AOut.IncIdent; try AOut.Write('DISPID_UNKNOWN: Exit;'); for Li := 0 to FEvents.Count - 1 do FEvents[Li].PrintAsInvokeEvents(AOut); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintConnect(AOut: TCustomOut); begin AOut.WriteFmt('procedure %s.Connect;', [GetOleClassName]); AOut.Write(TUnitSections.CVar); AOut.WriteIdent('LServer: IInterface;'); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('if FIntf = nil then begin'); AOut.IncIdent; try AOut.Write('LServer := GetServer;'); AOut.Write('ConnectEvents(LServer);'); AOut.WriteFmt('FIntf:= LServer as %s;', [FDefaultIntf.Name]); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintConnectTo(AOut: TCustomOut); begin AOut.WriteFmt('procedure %s.ConnectTo(const ASrvIntf: %s);', [GetOleClassName, FDefaultIntf.Name]); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('Disconnect;'); AOut.Write('FIntf := ASrvIntf;'); AOut.Write('ConnectEvents(FIntf);'); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintDisconnect(AOut: TCustomOut); begin AOut.WriteFmt('procedure %s.Disconnect;', [GetOleClassName]); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('if FIntf <> nil then begin'); AOut.IncIdent; try AOut.Write('DisconnectEvents(FIntf);'); AOut.Write('FIntf := nil;'); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; function TCoClass.GetCoClassName: string; begin Result := 'Co' + Name; end; function TCoClass.GetOleClassName: string; begin Result := 'T' + Name; end; procedure TCoClass.PrintCoClass(AOut: TCustomOut); begin AOut.WriteFmt('%s = class', [GetCoClassName]); AOut.IncIdent; try AOut.WriteFmt('class function Create: %s;', [FDefaultIntf.Name]); AOut.WriteFmt('class function CreateRemote(const AMachineName: string): %s;', [FDefaultIntf.Name]); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintOleClass(AOut: TCustomOut); var Li: Integer; LProps: TPropList; LOutBuf: TOutBuffer; begin AOut.WriteFmt('%s = class(TOleServer)', [GetOleClassName]); AOut.Write('private'); AOut.IncIdent; try AOut.WriteFmt('FIntf: %s;', [FDefaultIntf.Name]); finally AOut.DecIdent; end; if FEvents.Count > 0 then begin AOut.Write(TClassSections.CPrivate); AOut.IncIdent; try for Li := 0 to FEvents.Count - 1 do FEvents[Li].PrintAsEvents(AOut); finally AOut.DecIdent; end; end; LOutBuf := TOutBuffer.Create; try LOutBuf.Ident := AOut.Ident; LOutBuf.Write(TClassSections.CPrivate); LOutBuf.IncIdent; try LOutBuf.WriteFmt('function Get%s: %s;', [CDefaultInterfaceFld, FDefaultIntf.Name]); finally LOutBuf.DecIdent; end; LOutBuf.Write(TClassSections.CProtected); LOutBuf.IncIdent; try LOutBuf.Write('procedure InitServerData; override;'); if FEvents.Count > 0 then LOutBuf.Write('procedure InvokeEvent(ADispID: TDispID; var AParams: TVariantArray); override;'); finally LOutBuf.DecIdent; end; LOutBuf.Write(TClassSections.CPublic); LOutBuf.IncIdent; try LOutBuf.Write('procedure Connect; override;'); LOutBuf.WriteFmt('procedure ConnectTo(const ASrvIntf: %s);', [FDefaultIntf.Name]); LOutBuf.Write('procedure Disconnect; override;'); finally LOutBuf.DecIdent; end; LOutBuf.WriteFmt('public // Implements %s', [FDefaultIntf.Name]); LOutBuf.IncIdent; try LProps := TPropList.Create; try FDefaultIntf.PrintMethods(LOutBuf, LProps, pmmDelphi); if LProps.Count > 0 then begin LProps.PrintProps(LOutBuf); AOut.Write(TClassSections.CPrivate); AOut.IncIdent; LProps.PrintMethods(AOut); end; finally LProps.Free; end; finally LOutBuf.DecIdent; end; LOutBuf.Flush(AOut); finally LOutBuf.Free; end; AOut.Write(TClassSections.CPublic); AOut.IncIdent; try AOut.WriteFmt('property %s: %s read Get%0:s;', [CDefaultInterfaceFld, FDefaultIntf.Name]); finally AOut.DecIdent; end; if FEvents.Count > 0 then begin AOut.Write(TClassSections.CPublished); AOut.IncIdent; try for Li := 0 to FEvents.Count - 1 do FEvents[Li].PrintAsProps(AOut); finally AOut.DecIdent; end; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintCoClassImpl(AOut: TCustomOut); var LClassName: string; LIntfName: string; LSfxFunc: string; begin LClassName := GetCoClassName; LIntfName := FDefaultIntf.Name; LSfxFunc := Format('%s_%s) as %s;', [GetIIDPrefix, Name, LIntfName]); AOut.WriteFmt('{ %s }', [LClassName]); AOut.EmptyLine; AOut.WriteFmt('class function %s.Create: %s;', [LClassName, LIntfName]); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('Result := CreateComObject(' + LSfxFunc); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; AOut.WriteFmt( 'class function %s.CreateRemote(const AMachineName: string): %s;', [LClassName, LIntfName] ); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try AOut.Write('Result := CreateRemoteComObject(AMachineName, ' + LSfxFunc); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TCoClass.PrintOlePropImpl(AOut: TCustomOut); var LClassName: string; LProps: TPropList; LBuf: TOutBuffer; LBuilder: TStringBuilder; LPropList: TPropList.TPropArray; LProp: TPropList.TPropPair; LMethod: TIntfMethod; LIsIdent: Boolean; begin LClassName := GetOleClassName; AOut.WriteFmt('{ %s }', [LClassName]); AOut.EmptyLine; LProps := TPropList.Create; try LBuf := TOutBuffer.Create; try LBuilder := TStringBuilder.Create; try FDefaultIntf.PrintMethods(LBuf, LProps, pmmDelphi, LClassName); LPropList := LProps.ToSortedArray; for LProp in LPropList do begin LMethod := LProp.Value.Read; if LMethod <> nil then begin LMethod.PrintForDisp(AOut, pmmDelphi, LClassName); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try LBuilder.Append('Result := '); LIsIdent := PrintIntfPropImpl(AOut, LMethod, LBuilder); LBuilder.Append(CSemicolon); AOut.Write(LBuilder.ToString); if LIsIdent then AOut.DecIdent; LBuilder.Clear; finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; LMethod := LProp.Value.Write; if LMethod <> nil then begin LMethod.PrintForDisp(AOut, pmmDelphi, LClassName); AOut.Write(TUnitSections.CBegin); AOut.IncIdent; try LIsIdent := PrintIntfPropImpl(AOut, LMethod, LBuilder); LBuilder.Append(' := '); if LMethod.ArgCount > 0 then LBuilder.Append(LMethod.Args[LMethod.ArgCount - 1].Name) else LBuilder.Append('???'); LBuilder.Append(CSemicolon); AOut.Write(LBuilder.ToString); if LIsIdent then AOut.DecIdent; LBuilder.Clear; finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; end; // for LProp in LPropList do begin finally LBuilder.Free end; finally LBuf.Free; end; finally LProps.Free; end; end; procedure TCoClass.PrintOleSvcMethodsImpl(AOut: TCustomOut); begin PrintGetDefaultInterface(AOut); PrintInitServerData(AOut); if FEvents.Count > 0 then PrintInvokeEvent(AOut); PrintConnect(AOut); PrintConnectTo(AOut); PrintDisconnect(AOut); AOut.WriteFmt('// Implements %s', [FDefaultIntf.Name]); FDefaultIntf.PrintImplMethods(AOut, GetOleClassName); end; procedure TCoClass.PrintOleClassImpl(AOut: TCustomOut); begin PrintOlePropImpl(AOut); PrintOleSvcMethodsImpl(AOut); end; function TCoClass.PrintIntfPropImpl(AOut: TCustomOut; AMethod: TIntfMethod; ABuilder: TStringBuilder): Boolean; begin ABuilder.Append(CDefaultInterfaceFld); ABuilder.Append('.'); ABuilder.Append(AMethod.Name); Result := AMethod.PrintArgs(AOut, ABuilder, AMethod.ArgCount - 1, bSquare, True); end; function TCoClass.GetIIDPrefix: string; begin Result := 'CLASS'; end; procedure TCoClass.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); var Li: Integer; LFlag: Integer; LRefType: HRefType; LInfo: ITypeInfo; LAttr: PTypeAttr; LIntf: TInterface; begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); for Li := 0 to ATypeAttr.cImplTypes - 1 do begin OleCheck(ATypeInfo.GetImplTypeFlags(Li, LFlag)); OleCheck(ATypeInfo.GetRefTypeOfImplType(Li, LRefType)); OleCheck(ATypeInfo.GetRefTypeInfo(LRefType, LInfo)); OleCheck(LInfo.GetTypeAttr(LAttr)); try if LAttr^.typekind = TKIND_DISPATCH then LIntf := TDispInterface.Create(LInfo) else LIntf := TInterface.Create(LInfo); if LFlag and IMPLTYPEFLAG_FSOURCE = IMPLTYPEFLAG_FSOURCE then FEvents.Add(LIntf) else FInterfaces.Add(LIntf); if (FDefaultIntf = nil) and (LFlag and IMPLTYPEFLAG_FDEFAULT = IMPLTYPEFLAG_FDEFAULT) then FDefaultIntf := LIntf; finally LInfo.ReleaseTypeAttr(LAttr); end; end; end; function TCoClass.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; PrintCoClass(AOut); PrintOleClass(AOut); end; procedure TCoClass.PrintForward(AOut: TCustomOut); begin AOut.WriteFmt('%s = %s;', [Name, FDefaultIntf.Name]); end; procedure TCoClass.RegisterAliases(AList: TAliasList); begin inherited RegisterAliases(AList); FDefaultIntf.RegisterAliases(AList); end; procedure TCoClass.PrintImpl(AOut: TCustomOut); begin PrintCoClassImpl(AOut); PrintOleClassImpl(AOut); end; procedure TCoClass.RequireUnits(AUnitManager: TUnitManager); begin inherited RequireUnits(AUnitManager); AUnitManager.AddStdUnit(suOleServer); if FEvents.Count > 0 then AUnitManager.AddStdUnit(suClasses); end; procedure TCoClass.RequireImplUnits(AUnitManager: TUnitManager); begin AUnitManager.AddStdUnit(suComObj); end; { TEnumItem } constructor TEnumItem.Create(const ATypeInfo: ITypeInfo; AIdx: Integer); var LVarDesc: PVarDesc; begin OleCheck(ATypeInfo.GetVarDesc(AIdx, LVarDesc)); try FValue := LVarDesc^.lpvarValue^; inherited Create(ATypeInfo, LVarDesc^.memid); finally ATypeInfo.ReleaseVarDesc(LVarDesc); end; end; function TEnumItem.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; AOut.WriteFmt('%s = ' + FValueFmt, [Name, FValue]); end; { TEnum } constructor TEnum.Create(const ATypeInfo: ITypeInfo); begin FItems := TObjectList<TEnumItem>.Create(True); FShowEnum := False; FShowHex := True; inherited Create(ATypeInfo); end; destructor TEnum.Destroy; begin FItems.Free; inherited Destroy; end; procedure TEnum.PrintItem(AOut: TCustomOut; AItem: TEnumItem; const AFmt: string); begin AItem.ValueFmt := AFmt; AItem.Print(AOut); end; procedure TEnum.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); var Li: Integer; begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); for Li := 0 to ATypeAttr.cVars - 1 do FItems.Add(TEnumItem.Create(ATypeInfo, Li)); end; function TEnum.Print(AOut: TCustomOut): Boolean; var Li: Integer; LFmt: string; begin Result := inherited Print(AOut); if not Result then Exit; if AOut.Level[-1] <> TUnitSections.CType then begin AOut.DecIdent; try AOut.Write(TUnitSections.CType); finally AOut.IncIdent; end; end; if FShowHex then LFmt := '$%.8x' else LFmt := '%d'; if FShowEnum then begin AOut.WriteFmt('%s = (', [Name]); LFmt := LFmt + ','; AOut.IncIdent; end else begin AOut.WriteFmt('%s = type TOleEnum;', [Name]); LFmt := Format('%s(%s);', [Name, LFmt]); AOut.DecIdent; AOut.Write(TUnitSections.CConst); AOut.IncIdent; end; for Li := 0 to FItems.Count - 2 do PrintItem(AOut, FItems[Li], LFmt); if FShowEnum then SetLength(LFmt, Length(LFmt) - 1); PrintItem(AOut, FItems.Last, LFmt); if FShowEnum then begin AOut.DecIdent; AOut.Write(');'); end; AOut.EmptyLine; end; procedure TEnum.RequireUnits(AUnitManager: TUnitManager); begin inherited RequireUnits(AUnitManager); if not FShowEnum then AUnitManager.AddStdUnit(suActiveX); end; { TVariable } constructor TVariable.Create(const ATypeInfo: ITypeInfo; AIdx: Integer); var LVarDesc: PVarDesc; begin OleCheck(ATypeInfo.GetVarDesc(AIdx, LVarDesc)); try FType := ElemDescToTypeStr(ATypeInfo, LVarDesc^.elemdescVar); inherited Create(ATypeInfo, LVarDesc^.memid); finally ATypeInfo.ReleaseVarDesc(LVarDesc); end; end; function TVariable.Print(AOut: TCustomOut): Boolean; begin Result := inherited Print(AOut); if not Result then Exit; AOut.WriteFmt('%s: %s;', [Name, FWriteType]); end; procedure TVariable.RequireUnits(AUnitManager: TUnitManager); begin inherited RequireUnits(AUnitManager); AUnitManager.AddPasType(FType); end; procedure TVariable.RegisterAliases(AList: TAliasList); begin inherited RegisterAliases(AList); FWriteType := AList.AddAlias(FType); end; { TRecord } constructor TRecord.Create(const ATypeInfo: ITypeInfo); begin FFields := TObjectList<TVariable>.Create(True); inherited Create(ATypeInfo); end; destructor TRecord.Destroy; begin FFields.Free; inherited Destroy; end; procedure TRecord.ParseTypeAttr(const ATypeInfo: ITypeInfo; const ATypeAttr: TTypeAttr); var Li: Integer; begin inherited ParseTypeAttr(ATypeInfo, ATypeAttr); FAlign := ATypeAttr.cbAlignment; for Li := 0 to ATypeAttr.cVars - 1 do FFields.Add(TVariable.Create(ATypeInfo, Li)); end; procedure TRecord.PrintRecursive(AOut: TCustomOut); var Li: Integer; LMem: TTLBMember; begin inherited PrintRecursive(AOut); for Li := 0 to FFields.Count - 1 do begin if Members.TryGetValue(FFields[Li].WriteType, LMem) then LMem.Print(AOut); end; end; function TRecord.Print(AOut: TCustomOut): Boolean; var Li: Integer; begin Result := inherited Print(AOut); if not Result then Exit; // AOut.WriteFmt('{$A %d}', [FAlign]); AOut.WriteFmt('{$ALIGN %d}', [FAlign]); AOut.WriteFmt('%s = record', [Name]); AOut.IncIdent; try for Li := 0 to FFields.Count - 1 do FFields[Li].Print(AOut); finally AOut.DecIdent; end; AOut.Write(TClassSections.CEnd); AOut.EmptyLine; end; procedure TRecord.RequireUnits(AUnitManager: TUnitManager); var Li: Integer; begin inherited RequireUnits(AUnitManager); for Li := 0 to FFields.Count - 1 do FFields[Li].RequireUnits(AUnitManager); end; procedure TRecord.RegisterAliases(AList: TAliasList); var Li: Integer; begin inherited RegisterAliases(AList); for Li := 0 to FFields.Count - 1 do FFields[Li].RegisterAliases(AList); end; { TTLBMemberList<T> } constructor TTLBMemberList<T>.Create; begin inherited Create(True); end; procedure TTLBMemberList<T>.Print(AOut: TCustomOut; const AComment: string; AAddEmptyLine: Boolean); begin CustomPrint( AOut, AComment, AAddEmptyLine, procedure(AOut: TCustomOut; AItem: T) begin AItem.Print(AOut); end ); end; procedure TTLBMemberList<T>.CustomPrint(AOut: TCustomOut; const AComment: string; AAddEmptyLine: Boolean; const APrintProc: TPrintProc); var Li: Integer; begin if Count > 0 then begin if AComment <> '' then AOut.Write(TUnitSections.CComment + AComment); for Li := 0 to Count - 1 do APrintProc(AOut, Items[Li]); if AAddEmptyLine then AOut.EmptyLine; end; end; procedure TTLBMemberList<T>.RequireUnits(AUnitManager: TUnitManager); var Li: Integer; begin for Li := 0 to Count - 1 do Items[Li].RequireUnits(AUnitManager); end; procedure TTLBMemberList<T>.RegisterAliases(AList: TAliasList); var Li: Integer; begin for Li := 0 to Count - 1 do Items[Li].RegisterAliases(AList); end; function TTLBMemberList<T>.Add(const AItem: T; ADict: TTLBMemberDict): T; begin inherited Add(AItem); Result := AItem; if ADict <> nil then begin ADict.Add(Result.Name, Result); Result.Members := ADict; end; end; { TTLBInfo } constructor TTLBInfo.Create(const AFileName: string); var LTlb: ITypeLib; LStr: WideString; begin OleCheck(LoadTypeLibEx(PChar(AFileName), REGKIND_NONE, LTlb)); OleCheck(LTlb.GetDocumentation(MEMBERID_NIL, @LStr, nil, nil, nil)); inherited Create(LStr); FMemberList := TObjectList<TTLBMemberList<TTLBMember>>.Create(True); FEnums := CreateMemberList<TEnum>; FRecords := CreateMemberList<TRecord>; FInterfaces := CreateMemberList<TInterface>; FCoClasses := CreateMemberList<TCoClass>; FAliases := CreateMemberList<TAlias>; FRecordDict := TTLBMemberDict.Create; FIntfDict := TTLBMemberDict.Create; Parse(LTlb); end; destructor TTLBInfo.Destroy; begin FIntfDict.Free; FRecordDict.Free; FMemberList.Free; inherited Destroy; end; function TTLBInfo.GetPasUnitName: string; begin Result := Name + '_TLB'; end; function TTLBInfo.CreateMemberList<T>: TTLBMemberList<T>; begin Result := TTLBMemberList<T>.Create; FMemberList.Add(TTLBMemberList<TTLBMember>(Result)); end; procedure TTLBInfo.Parse(const ATypeLib: ITypeLib); var LAttr: PTLibAttr; Li: Integer; LTypeKind: TTypeKind; begin OleCheck(ATypeLib.GetLibAttr(LAttr)); try FMajorVersion := LAttr^.wMajorVerNum; FMinorVersion := LAttr^.wMinorVerNum; FUUID := LAttr^.guid; finally ATypeLib.ReleaseTLibAttr(LAttr); end; for Li := 0 to ATypeLib.GetTypeInfoCount - 1 do begin OleCheck(ATypeLib.GetTypeInfoType(Li, LTypeKind)); case LTypeKind of TKIND_ENUM: FEnums.Add(TEnum.CreateTLB(ATypeLib, Li)); TKIND_RECORD: FRecords.Add(TRecord.CreateTLB(ATypeLib, Li), FRecordDict); TKIND_MODULE:; TKIND_INTERFACE: FInterfaces.Add(TInterface.CreateTLB(ATypeLib, Li), FIntfDict); TKIND_DISPATCH: FInterfaces.Add(TDispInterface.CreateTLB(ATypeLib, Li), FIntfDict); TKIND_COCLASS: FCoClasses.Add(TCoClass.CreateTLB(ATypeLib, Li)); TKIND_ALIAS: FAliases.Add(TAlias.CreateTLB(ATypeLib, Li)); TKIND_UNION:; end; end; end; procedure TTLBInfo.PrintHeaderConst(AOut: TCustomOut); begin AOut.WriteFmt('%sMajorVersion = %d;', [Name, FMajorVersion]); AOut.WriteFmt('%sMinorVersion = %d;', [Name, FMinorVersion]); AOut.EmptyLine; AOut.WriteFmt('LIBID_%s: TGUID = ''%s'';', [Name, GUIDToString(FUUID)]); AOut.EmptyLine; end; procedure TTLBInfo.PrintClassIDs(AOut: TCustomOut); var Li: Integer; begin if FCoClasses.Count > 0 then begin AOut.Write('// CLASSID constants'); for Li := 0 to FCoClasses.Count - 1 do FCoClasses[Li].PrintIID(AOut); AOut.EmptyLine; end; end; procedure TTLBInfo.PrintIIDs(AOut: TCustomOut); var Li: Integer; begin if FInterfaces.Count > 0 then begin AOut.Write('// IID constants'); for Li := 0 to FInterfaces.Count - 1 do FInterfaces[Li].PrintIID(AOut); AOut.EmptyLine; end; end; procedure TTLBInfo.PrintForward<T>(AOut: TCustomOut; AItem: T); begin AItem.PrintForward(AOut); end; procedure TTLBInfo.PrintClassImpl(AOut: TCustomOut); var Li: Integer; begin for Li := 0 to FCoClasses.Count - 1 do FCoClasses[Li].PrintImpl(AOut); end; function TTLBInfo.Print(AOut: TCustomOut): Boolean; var LUnits: TUnitManager; LAliaces: TAliasList; begin Result := inherited Print(AOut); if not Result then Exit; LUnits := TUnitManager.Create(True); try AOut.WriteFmt(TUnitSections.CUnit + ' %s;', [PasUnitName]); AOut.EmptyLine; AOut.Write(TUnitSections.CInterface); AOut.EmptyLine; RequireUnits(LUnits); LUnits.Print(AOut); AOut.Write(TUnitSections.CConst); AOut.IncIdent; try PrintHeaderConst(AOut); PrintClassIDs(AOut); PrintIIDs(AOut); finally AOut.DecIdent; end; if FEnums.Count > 0 then begin AOut.Write('// Enumerators'); // AOut.Write('{$Z 4}'); AOut.Write('{$MINENUMSIZE 4}'); AOut.EmptyLine; AOut.Write(TUnitSections.CType); AOut.IncIdent; try FEnums.Print(AOut, CEmpty, False); finally AOut.DecIdent; end; end; if (FInterfaces.Count > 0) or (FCoClasses.Count > 0) or (FAliases.Count > 0) or (FRecords.Count > 0) then begin AOut.Write(TUnitSections.CType); AOut.IncIdent; try FInterfaces.CustomPrint(AOut, 'Interfaces forward declarations', True, PrintForward<TInterface>); FCoClasses.CustomPrint(AOut, 'CoClasses as default interface', True, PrintForward<TCoClass>); LAliaces := TAliasList.Create; try RegisterAliases(LAliaces); LAliaces.Print(AOut); finally LAliaces.Free; end; FAliases.Print(AOut, 'Aliaces', True); FRecords.Print(AOut, 'Records', False); FInterfaces.Print(AOut, 'Interfaces', False); FCoClasses.Print(AOut, 'CoClasses', False); finally AOut.DecIdent; end; end; AOut.Write(TUnitSections.CImplementation); AOut.EmptyLine; LUnits.Clear; RequireImplUnits(LUnits); LUnits.Print(AOut); PrintClassImpl(AOut); AOut.Write(TUnitSections.CEnd); finally LUnits.Free; end; end; procedure TTLBInfo.RequireUnits(AUnitManager: TUnitManager); var Li: Integer; begin for Li := 0 to FMemberList.Count - 1 do FMemberList[Li].RequireUnits(AUnitManager); end; procedure TTLBInfo.RequireImplUnits(AUnitManager: TUnitManager); var Li: Integer; begin for Li := 0 to FCoClasses.Count - 1 do FCoClasses[Li].RequireImplUnits(AUnitManager); end; procedure TTLBInfo.RegisterAliases(AList: TAliasList); var Li: Integer; begin for Li := 0 to FMemberList.Count - 1 do FMemberList[Li].RegisterAliases(AList); end; end.
unit PPMdSubAllocatorVariantI; {$mode objfpc}{$H+} {$packrecords c} {$inline on} interface uses Classes, SysUtils, CTypes, PPMdSubAllocator; const N1 = 4; N2 = 4; N3 = 4; N4 = ((128 + 3 - 1 * N1 - 2 * N2 - 3 * N3) div 4); UNIT_SIZE = 12; N_INDEXES = (N1 + N2 + N3 + N4); type PPPMdMemoryBlockVariantI = ^TPPMdMemoryBlockVariantI; TPPMdMemoryBlockVariantI = packed record Stamp: cuint32; next: cuint32; NU: cuint32; end; PPPMdSubAllocatorVariantI = ^TPPMdSubAllocatorVariantI; TPPMdSubAllocatorVariantI = record core: TPPMdSubAllocator; GlueCount, SubAllocatorSize: cuint32; Index2Units: array[0..37] of cuint8; // constants Units2Index: array[0..127] of cuint8; // constants pText, UnitsStart, LowUnit, HighUnit: pcuint8; BList: array[0..37] of TPPMdMemoryBlockVariantI; HeapStart: array[0..0] of cuint8; end; function CreateSubAllocatorVariantI(size: cint): PPPMdSubAllocatorVariantI; procedure FreeSubAllocatorVariantI(self: PPPMdSubAllocatorVariantI); function GetUsedMemoryVariantI(self: PPPMdSubAllocatorVariantI): cuint32; procedure SpecialFreeUnitVariantI(self: PPPMdSubAllocatorVariantI; offs: cuint32); function MoveUnitsUpVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; num: cint): cuint32; procedure ExpandTextAreaVariantI(self: PPPMdSubAllocatorVariantI); implementation function NextBlock(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI): PPPMdMemoryBlockVariantI; forward; procedure SetNextBlock(self: PPPMdMemoryBlockVariantI; newnext: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); forward; function AreBlocksAvailable(self: PPPMdMemoryBlockVariantI): cbool; forward; procedure LinkBlockAfter(self: PPPMdMemoryBlockVariantI; p: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); forward; procedure UnlinkBlockAfter(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); forward; function RemoveBlockAfter(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI): Pointer; forward; procedure InsertBlockAfter(self: PPPMdMemoryBlockVariantI; pv: Pointer; NU: cint; alloc: PPPMdSubAllocatorVariantI); forward; function I2B(self: PPPMdSubAllocatorVariantI; index: cint): cuint; forward; procedure SplitBlock(self: PPPMdSubAllocatorVariantI; pv: Pointer; oldindex: cint; newindex: cint); forward; procedure InitVariantI(self: PPPMdSubAllocatorVariantI); forward; function AllocContextVariantI(self: PPPMdSubAllocatorVariantI): cuint32; forward; function AllocUnitsVariantI(self: PPPMdSubAllocatorVariantI; num: cint): cuint32; forward; function _AllocUnits(self: PPPMdSubAllocatorVariantI; index: cint): cuint32; forward; function ExpandUnitsVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; oldnum: cint): cuint32; forward; function ShrinkUnitsVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; oldnum: cint; newnum: cint): cuint32; forward; procedure FreeUnitsVariantI(self: PPPMdSubAllocatorVariantI; offs: cuint32; num: cint); forward; procedure GlueFreeBlocks(self: PPPMdSubAllocatorVariantI); forward; function _OffsetToPointer(self: PPPMdSubAllocatorVariantI; offset: cuint32): Pointer; inline; begin Result:= pcuint8(self) + offset; end; function _PointerToOffset(self: PPPMdSubAllocatorVariantI; pointer: Pointer): cuint32; inline; begin Result:= ptruint(pointer) - ptruint(self); end; function CreateSubAllocatorVariantI(size: cint): PPPMdSubAllocatorVariantI; var self: PPPMdSubAllocatorVariantI; begin self:= GetMem(sizeof(TPPMdSubAllocatorVariantI) + size); if (self = nil) then Exit(nil); Pointer(self^.core.Init):= @InitVariantI; Pointer(self^.core.AllocContext):= @AllocContextVariantI; Pointer(self^.core.AllocUnits):= @AllocUnitsVariantI; Pointer(self^.core.ExpandUnits):= @ExpandUnitsVariantI; Pointer(self^.core.ShrinkUnits):= @ShrinkUnitsVariantI; Pointer(self^.core.FreeUnits):= @FreeUnitsVariantI; self^.SubAllocatorSize:= size; Result:= self; end; procedure FreeSubAllocatorVariantI(self: PPPMdSubAllocatorVariantI); begin FreeMem(self); end; procedure InitVariantI(self: PPPMdSubAllocatorVariantI); var i, k: cint; diff: cuint; begin FillChar(self^.BList, sizeof(self^.BList), 0); self^.pText:= self^.HeapStart; self^.HighUnit:= @self^.HeapStart[0] + self^.SubAllocatorSize; diff:= UNIT_SIZE * (self^.SubAllocatorSize div 8 div UNIT_SIZE * 7); self^.LowUnit:= self^.HighUnit - diff; self^.UnitsStart:= self^.LowUnit; self^.GlueCount:= 0; for i:= 0 to N1 - 1 do self^.Index2Units[i]:= 1 + i; for i:= 0 to N2 - 1 do self^.Index2Units[N1 + i]:= 2 + N1 + i * 2; for i:= 0 to N3 - 1 do self^.Index2Units[N1 + N2 + i]:= 3 + N1 + 2 * N2 + i * 3; for i:= 0 to N4 - 1 do self^.Index2Units[N1 + N2 + N3 + i]:= 4 + N1 + 2 * N2 + 3 * N3 + i * 4; i:= 0; for k:= 0 to 127 do begin if (self^.Index2Units[i] < k + 1) then Inc(i); self^.Units2Index[k]:= i; end; end; function AllocContextVariantI(self: PPPMdSubAllocatorVariantI): cuint32; begin if (self^.HighUnit <> self^.LowUnit) then begin self^.HighUnit -= UNIT_SIZE; Result:= _PointerToOffset(self, self^.HighUnit); end else if (AreBlocksAvailable(@self^.BList[0])) then Result:= _PointerToOffset(self, RemoveBlockAfter(@self^.BList[0], self)) else Result:= _AllocUnits(self, 0); end; function AllocUnitsVariantI(self: PPPMdSubAllocatorVariantI; num: cint): cuint32; var index: cint; units: Pointer; begin index:= self^.Units2Index[num - 1]; if (AreBlocksAvailable(@self^.BList[index])) then Exit(_PointerToOffset(self, RemoveBlockAfter(@self^.BList[index], self))); units:= self^.LowUnit; self^.LowUnit += I2B(self, index); if (self^.LowUnit <= self^.HighUnit) then Exit(_PointerToOffset(self, units)); self^.LowUnit -= I2B(self, index); Result:= _AllocUnits(self, index); end; function _AllocUnits(self: PPPMdSubAllocatorVariantI; index: cint): cuint32; var i: cint; units: Pointer; begin if (self^.GlueCount = 0) then begin GlueFreeBlocks(self); if (AreBlocksAvailable(@self^.BList[index])) then Exit(_PointerToOffset(self, RemoveBlockAfter(@self^.BList[index], self))); end; for i:= index + 1 to N_INDEXES - 1 do begin if (AreBlocksAvailable(@self^.BList[i])) then begin units:= RemoveBlockAfter(@self^.BList[i], self); SplitBlock(self, units, i, index); Exit(_PointerToOffset(self, units)); end; end; Dec(self^.GlueCount); i:= I2B(self, index); if (self^.UnitsStart - self^.pText > i) then begin self^.UnitsStart -= i; Exit(_PointerToOffset(self, self^.UnitsStart)); end; Result:= 0; end; function ExpandUnitsVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; oldnum: cint): cuint32; var offs: cuint32; oldptr: Pointer; oldindex, newindex: cint; begin oldptr:= _OffsetToPointer(self, oldoffs); oldindex:= self^.Units2Index[oldnum - 1]; newindex:= self^.Units2Index[oldnum]; if (oldindex = newindex) then Exit(oldoffs); offs:= AllocUnitsVariantI(self, oldnum + 1); if (offs <> 0) then begin Move(oldptr^, _OffsetToPointer(self, offs)^, oldnum * UNIT_SIZE); InsertBlockAfter(@self^.BList[oldindex], oldptr, oldnum, self); end; Result:= offs; end; function ShrinkUnitsVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; oldnum: cint; newnum: cint): cuint32; var ptr, oldptr: Pointer; oldindex, newindex: cint; begin oldptr:= _OffsetToPointer(self, oldoffs); oldindex:= self^.Units2Index[oldnum - 1]; newindex:= self^.Units2Index[newnum - 1]; if (oldindex = newindex) then Exit(oldoffs); if (AreBlocksAvailable(@self^.BList[newindex])) then begin ptr:= RemoveBlockAfter(@self^.BList[newindex], self); Move(oldptr^, ptr^, newnum * UNIT_SIZE); InsertBlockAfter(@self^.BList[oldindex], oldptr, self^.Index2Units[oldindex], self); Result:= _PointerToOffset(self, ptr); end else begin SplitBlock(self, oldptr, oldindex, newindex); Result:= oldoffs; end; end; procedure FreeUnitsVariantI(self: PPPMdSubAllocatorVariantI; offs: cuint32; num: cint); var index: cint; begin index:= self^.Units2Index[num - 1]; InsertBlockAfter(@self^.BList[index], _OffsetToPointer(self, offs), self^.Index2Units[index], self); end; function GetUsedMemoryVariantI(self: PPPMdSubAllocatorVariantI): cuint32; var i: cint; size: cuint32; begin size:= self^.SubAllocatorSize - (self^.HighUnit - self^.LowUnit) - (self^.UnitsStart - self^.pText); for i:= 0 to N_INDEXES - 1 do size -= UNIT_SIZE * self^.Index2Units[i] * self^.BList[i].Stamp; Result:= size; end; procedure SpecialFreeUnitVariantI(self: PPPMdSubAllocatorVariantI; offs: cuint32); var ptr: Pointer; begin ptr:= _OffsetToPointer(self, offs); if (pcuint8(ptr) = self^.UnitsStart) then begin pcuint32(ptr)^:= $ffffffff; self^.UnitsStart += UNIT_SIZE; end else InsertBlockAfter(@self^.BList[0], ptr, 1, self); end; function MoveUnitsUpVariantI(self: PPPMdSubAllocatorVariantI; oldoffs: cuint32; num: cint): cuint32; var newnum, index: cint; ptr, oldptr: Pointer; begin oldptr:= _OffsetToPointer(self, oldoffs); index:= self^.Units2Index[num - 1]; if (pcuint8(oldptr) > self^.UnitsStart + 16 * 1024) or (oldoffs > self^.BList[index].next) then Exit(oldoffs); ptr:= RemoveBlockAfter(@self^.BList[index], self); Move(oldptr^, ptr^, num * UNIT_SIZE); newnum:= self^.Index2Units[index]; if(pcuint8(oldptr) <> self^.UnitsStart) then InsertBlockAfter(@self^.BList[index], oldptr, newnum, self) else self^.UnitsStart += newnum * UNIT_SIZE; Result:= _PointerToOffset(self, ptr); end; procedure ExpandTextAreaVariantI(self: PPPMdSubAllocatorVariantI); var i: cint; p, pm: PPPMdMemoryBlockVariantI; Count: array[0..N_INDEXES - 1] of cuint; begin FillChar(Count, sizeof(Count), 0); p:= PPPMdMemoryBlockVariantI(self^.UnitsStart); while (p^.Stamp = $ffffffff) do begin pm:= p; self^.UnitsStart:= pcuint8(pm + pm^.NU); Inc(Count[self^.Units2Index[pm^.NU - 1]]); pm^.Stamp:= 0; p:= PPPMdMemoryBlockVariantI(self^.UnitsStart); end; for i:= 0 to N_INDEXES - 1 do begin p:= @self^.BList[i]; while Count[i] <> 0 do begin while (NextBlock(p,self)^.Stamp = 0) do begin UnlinkBlockAfter(p, self); Dec(self^.BList[i].Stamp); Dec(Count[i]); if (Count[i] = 0) then break; end; p:= NextBlock(p, self) end; end; end; procedure GlueFreeBlocks(self: PPPMdSubAllocatorVariantI); var i, k, sz: cint; s0: TPPMdMemoryBlockVariantI; p, p0, p1: PPPMdMemoryBlockVariantI; begin if (self^.LowUnit <> self^.HighUnit) then self^.LowUnit^:= 0; p0:= @s0; s0.next:= 0; for i:= 0 to N_INDEXES - 1 do begin while (AreBlocksAvailable(@self^.BList[i])) do begin p:= PPPMdMemoryBlockVariantI(RemoveBlockAfter(@self^.BList[i], self)); if (p^.NU = 0) then continue; p1:= p + p^.NU; while (p1^.Stamp = $ffffffff) do begin p^.NU += p1^.NU; p1^.NU:= 0; p1:= p + p^.NU; end; LinkBlockAfter(p0, p, self); p0:= p; end; end; while (AreBlocksAvailable(@s0)) do begin p:= RemoveBlockAfter(@s0, self); sz:= p^.NU; if (sz = 0) then continue; while (sz > 128) do begin InsertBlockAfter(@self^.BList[N_INDEXES - 1], p, 128, self); sz -= 128; p += 128; end; i:= self^.Units2Index[sz - 1]; if (self^.Index2Units[i] <> sz) then begin Dec(i); k:= sz - self^.Index2Units[i]; InsertBlockAfter(@self^.BList[k - 1], p + (sz - k), k, self); end; InsertBlockAfter(@self^.BList[i], p, self^.Index2Units[i], self); end; self^.GlueCount:= 1 shl 13; end; function NextBlock(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI): PPPMdMemoryBlockVariantI; begin Result:= OffsetToPointer(@alloc^.core, self^.next); end; procedure SetNextBlock(self: PPPMdMemoryBlockVariantI; newnext: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); begin self^.next:= PointerToOffset(@alloc^.core, newnext); end; function AreBlocksAvailable(self: PPPMdMemoryBlockVariantI): cbool; begin Result:= self^.next <> 0; end; procedure LinkBlockAfter(self: PPPMdMemoryBlockVariantI; p: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); begin SetNextBlock(p, NextBlock(self, alloc), alloc); SetNextBlock(self, p, alloc); end; procedure UnlinkBlockAfter(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI); begin SetNextBlock(self, NextBlock(NextBlock(self, alloc), alloc), alloc); end; function RemoveBlockAfter(self: PPPMdMemoryBlockVariantI; alloc: PPPMdSubAllocatorVariantI): Pointer; var p: PPPMdMemoryBlockVariantI; begin p:= NextBlock(self, alloc); UnlinkBlockAfter(self, alloc); Dec(self^.Stamp); Result:= p; end; procedure InsertBlockAfter(self: PPPMdMemoryBlockVariantI; pv: Pointer; NU: cint; alloc: PPPMdSubAllocatorVariantI); var p: PPPMdMemoryBlockVariantI; begin p:= PPPMdMemoryBlockVariantI(pv); LinkBlockAfter(self, p, alloc); p^.Stamp:= $ffffffff; p^.NU:= NU; Inc(self^.Stamp); end; function I2B(self: PPPMdSubAllocatorVariantI; index: cint): cuint; begin Result:= UNIT_SIZE * self^.Index2Units[index]; end; procedure SplitBlock(self: PPPMdSubAllocatorVariantI; pv: Pointer; oldindex: cint; newindex: cint); var p: pcuint8; i, k, diff: cint; begin p:= pcuint8(pv) + I2B(self, newindex); diff:= self^.Index2Units[oldindex] - self^.Index2Units[newindex]; i:= self^.Units2Index[diff - 1]; if (self^.Index2Units[i] <> diff) then begin Dec(i); k:= self^.Index2Units[i]; InsertBlockAfter(@self^.BList[i], p, k, self); p += k * UNIT_SIZE; diff -= k; end; InsertBlockAfter(@self^.BList[self^.Units2Index[diff - 1]], p, diff, self); end; end.
unit fmPasswordReset; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ActiveDs_TLB, ADC.GlobalVar, ADC.Types, ADC.Common, ADC.DC, ADC.ADObject; const LockoutStatus: string = 'Состояние блокировки учетной записи на данном контроллере домена: %s'; type TForm_ResetPassword = class(TForm) Edit_Password1: TEdit; CheckBox_ChangeOnLogon: TCheckBox; Edit_Password2: TEdit; Label15: TLabel; Label14: TLabel; Button_Cancel: TButton; Button_OK: TButton; CheckBox_Unblock: TCheckBox; Label1: TLabel; Label2: TLabel; Bevel1: TBevel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button_CancelClick(Sender: TObject); procedure Button_OKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CheckBox_ChangeOnLogonClick(Sender: TObject); private { Private declarations } FObj: TADObject; FCallingForm: TForm; FOnPwdChange: TPwdChangeProc; procedure SetObject(const Value: TADObject); procedure SetDefaultPassword(const Value: string); public { Public declarations } property CallingForm: TForm read FCallingForm write FCallingForm; property UserObject: TADObject read FObj write SetObject; property DefaultPassword: string write SetDefaultPassword; property OnPasswordChange: TPwdChangeProc read FOnPwdChange write FOnPwdChange; end; var Form_ResetPassword: TForm_ResetPassword; implementation {$R *.dfm} uses fmMainForm; procedure TForm_ResetPassword.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_ResetPassword.Button_OKClick(Sender: TObject); var MsgBoxParam: TMsgBoxParams; hr: HRESULT; begin with MsgBoxParam do begin cbSize := SizeOf(MsgBoxParam); hwndOwner := Self.Handle; hInstance := 0; case apAPI of ADC_API_LDAP: lpszCaption := PChar('LDAP Exception'); ADC_API_ADSI: lpszCaption := PChar('ADSI Exception'); end; lpszIcon := MAKEINTRESOURCE(32513); dwStyle := MB_OK or MB_ICONHAND; dwContextHelpId := 0; lpfnMsgBoxCallback := nil; dwLanguageId := LANG_NEUTRAL; end; if Edit_Password1.Text = '' then begin MsgBoxParam.lpszText := PChar('Установите пароль пользователя.'); MessageBoxIndirect(MsgBoxParam); Edit_Password1.SetFocus; Exit; end; if not string(Edit_Password1.Text).Equals(Edit_Password2.Text) then begin MsgBoxParam.lpszText := PChar('Пароли не совпадают.'); MessageBoxIndirect(MsgBoxParam); Edit_Password2.SetFocus; Exit; end; if not ADCheckPasswordComplexity(SelectedDC.DomainDnsName, Edit_Password1.Text) then begin MsgBoxParam.lpszText := PChar('Пароль не отвечает требованиям политики.' + #13#10 + 'Проверьте минимальную длинну пароля, его сложность, отличие от ранее использованных паролей.'); MessageBoxIndirect(MsgBoxParam); Edit_Password1.SetFocus; Exit; end; try case apAPI of ADC_API_LDAP: begin // FObj.SetUserPassword( // LDAPBinding, // Edit_Password1.Text, // CheckBox_ChangeOnLogon.Checked, // CheckBox_Unblock.Checked // ); FObj.SetUserPassword( Edit_Password1.Text, CheckBox_ChangeOnLogon.Checked, CheckBox_Unblock.Checked ); end; ADC_API_ADSI: begin FObj.SetUserPassword( Edit_Password1.Text, CheckBox_ChangeOnLogon.Checked, CheckBox_Unblock.Checked ); end; end; if Assigned(FOnPwdChange) then FOnPwdChange(FObj, CheckBox_ChangeOnLogon.Checked); Close; except on e: Exception do begin MsgBoxParam.lpszText := PChar(e.Message); MessageBoxIndirect(MsgBoxParam); end; end; end; procedure TForm_ResetPassword.CheckBox_ChangeOnLogonClick(Sender: TObject); var MsgBoxParam: TMsgBoxParams; begin if ((FObj.userAccountControl and ADS_UF_DONT_EXPIRE_PASSWD) <> 0) and (CheckBox_ChangeOnLogon.Checked) then begin with MsgBoxParam do begin cbSize := SizeOf(MsgBoxParam); hwndOwner := Self.Handle; hInstance := 0; lpszText := PChar( 'Установлен параметр "Срок действия пароля не ограничен".'+ #13#10 + 'От пользователя не требуется изменять пароль при следующем входе в систему.' ); lpszCaption := PChar('AD Commander'); lpszIcon := MAKEINTRESOURCE(32516); dwStyle := MB_OK or MB_ICONASTERISK; dwContextHelpId := 0; lpfnMsgBoxCallback := nil; dwLanguageId := LANG_NEUTRAL; end; MessageBoxIndirect(MsgBoxParam); CheckBox_ChangeOnLogon.Checked := False; end; end; procedure TForm_ResetPassword.FormClose(Sender: TObject; var Action: TCloseAction); begin Edit_Password1.Clear; Edit_Password2.Clear; CheckBox_ChangeOnLogon.Checked := False; CheckBox_Unblock.Checked := False; FObj := nil; FOnPwdChange := nil; if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; end; procedure TForm_ResetPassword.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin Close; end; end; end; procedure TForm_ResetPassword.FormShow(Sender: TObject); begin Edit_Password1.SetFocus; end; procedure TForm_ResetPassword.SetDefaultPassword(const Value: string); begin Edit_Password1.Text := Value; Edit_Password2.Text := Value; end; procedure TForm_ResetPassword.SetObject(const Value: TADObject); begin FObj := Value; CheckBox_ChangeOnLogon.Checked := FObj.userAccountControl and ADS_UF_DONT_EXPIRE_PASSWD = 0; case FObj.IsAccountLocked of True : Label2.Caption := Format(LockoutStatus, ['Заблокирована']); False : Label2.Caption := Format(LockoutStatus, ['Разблокирована']); end; end; end.
unit TTSLDOCTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSLDOCRecord = record PLenderNum: String[4]; PCifFlag: String[1]; PLoanNum: String[20]; PDocCount: Integer; PDescription: String[30]; PDateStamp: String[10]; End; TTTSLDOCBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSLDOCRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSLDOC = (TTSLDOCPrimaryKey); TTTSLDOCTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFDocCount: TIntegerField; FDFDescription: TStringField; FDFDateStamp: TStringField; FDFImage: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPDocCount(const Value: Integer); function GetPDocCount:Integer; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPDateStamp(const Value: String); function GetPDateStamp:String; procedure SetEnumIndex(Value: TEITTSLDOC); function GetEnumIndex: TEITTSLDOC; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSLDOCRecord; procedure StoreDataBuffer(ABuffer:TTTSLDOCRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFDocCount: TIntegerField read FDFDocCount; property DFDescription: TStringField read FDFDescription; property DFDateStamp: TStringField read FDFDateStamp; property DFImage: TBlobField read FDFImage; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PDocCount: Integer read GetPDocCount write SetPDocCount; property PDescription: String read GetPDescription write SetPDescription; property PDateStamp: String read GetPDateStamp write SetPDateStamp; published property Active write SetActive; property EnumIndex: TEITTSLDOC read GetEnumIndex write SetEnumIndex; end; { TTTSLDOCTable } procedure Register; implementation procedure TTTSLDOCTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFDocCount := CreateField( 'DocCount' ) as TIntegerField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFDateStamp := CreateField( 'DateStamp' ) as TStringField; FDFImage := CreateField( 'Image' ) as TBlobField; end; { TTTSLDOCTable.CreateFields } procedure TTTSLDOCTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSLDOCTable.SetActive } procedure TTTSLDOCTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSLDOCTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSLDOCTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSLDOCTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSLDOCTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSLDOCTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSLDOCTable.SetPDocCount(const Value: Integer); begin DFDocCount.Value := Value; end; function TTTSLDOCTable.GetPDocCount:Integer; begin result := DFDocCount.Value; end; procedure TTTSLDOCTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSLDOCTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSLDOCTable.SetPDateStamp(const Value: String); begin DFDateStamp.Value := Value; end; function TTTSLDOCTable.GetPDateStamp:String; begin result := DFDateStamp.Value; end; procedure TTTSLDOCTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('DocCount, Integer, 0, N'); Add('Description, String, 30, N'); Add('DateStamp, String, 10, N'); Add('Image, Blob, 0, N'); end; end; procedure TTTSLDOCTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CifFlag;LoanNum;DocCount, Y, Y, N, Y'); end; end; procedure TTTSLDOCTable.SetEnumIndex(Value: TEITTSLDOC); begin case Value of TTSLDOCPrimaryKey : IndexName := ''; end; end; function TTTSLDOCTable.GetDataBuffer:TTTSLDOCRecord; var buf: TTTSLDOCRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PDocCount := DFDocCount.Value; buf.PDescription := DFDescription.Value; buf.PDateStamp := DFDateStamp.Value; result := buf; end; procedure TTTSLDOCTable.StoreDataBuffer(ABuffer:TTTSLDOCRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFDocCount.Value := ABuffer.PDocCount; DFDescription.Value := ABuffer.PDescription; DFDateStamp.Value := ABuffer.PDateStamp; end; function TTTSLDOCTable.GetEnumIndex: TEITTSLDOC; var iname : string; begin result := TTSLDOCPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSLDOCPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSLDOCTable, TTTSLDOCBuffer ] ); end; { Register } function TTTSLDOCBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('LENDERNUM','CIFFLAG','LOANNUM','DOCCOUNT','DESCRIPTION','DATESTAMP' ); 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 TTTSLDOCBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftString; end; end; function TTTSLDOCBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCifFlag; 3 : result := @Data.PLoanNum; 4 : result := @Data.PDocCount; 5 : result := @Data.PDescription; 6 : result := @Data.PDateStamp; end; end; end.
unit ReqPlanerForma; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, PlannersEh, SpreadGridsEh, PlannerCalendarPickerEh, EhLibVCL, GridsEh, DBAxisGridsEh, DBGridEh, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, DBCtrlsEh, PlannerDataEh, MemTableDataEh, Data.DB, MemTableEh, FIBDataSet, pFIBDataSet, DataDriverEh, pFIBDataDriverEh, FIBDatabase, pFIBDatabase, Vcl.DBCtrls; type TReqPlanerForm = class(TForm) pnlCalPickerPanel: TPanel; gridResouce: TDBGridEh; plnrclndrpckrhCalendarPickerEh1: TPlannerCalendarPickerEh; PlannerControl: TPlannerControlEh; PlannerDayViewEh1: TPlannerDayViewEh; PlannerWeekViewEh1: TPlannerWeekViewEh; PlannerMonthViewEh1: TPlannerMonthViewEh; PlannerVertHourslineViewEh1: TPlannerVertHourslineViewEh; PlannerHorzHourslineViewEh1: TPlannerHorzHourslineViewEh; PlannerVertDayslineViewEh1: TPlannerVertDayslineViewEh; PlannerHorzDayslineViewEh1: TPlannerHorzDayslineViewEh; pnl1: TPanel; cbbPlanerViewMode: TDBComboBoxEh; pldsPlanner: TPlannerDataSourceEh; mtPlannerData: TMemTableEh; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; drvPlan: TpFIBDataDriverEh; srcPlan: TDataSource; dsRequest: TpFIBDataSet; edtEndWorkTime: TDBDateTimeEditEh; edtStartWorkTime: TDBDateTimeEditEh; chkWorkOnly: TCheckBox; bFillPlanner: TButton; NewPlanItem: TButton; cbbGroupBy: TDBComboBoxEh; dsFilter: TpFIBDataSet; srcFilter: TDataSource; mmoItem: TDBMemoEh; spl1: TSplitter; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbbPlanerViewModeChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure bFillPlannerClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure cbbGroupByChange(Sender: TObject); procedure pldsPlannerPrepareItemsReader(PlannerDataSource: TPlannerDataSourceEh; RequriedStartDate, RequriedFinishDate, LoadedBorderDate: TDateTime; var PreparedReadyStartDate, PreparedFinishDate: TDateTime); procedure FormShow(Sender: TObject); procedure PlannerControlPlannerItemInteractiveChanged(PlannerControl: TPlannerControlEh; PlannerView: TCustomPlannerViewEh; Item, OldValuesItem: TPlannerDataItemEh); procedure PlannerControlShowPlanItemDialog(PlannerControl: TPlannerControlEh; PlannerView: TCustomPlannerViewEh; Item: TPlannerDataItemEh; ChangeMode: TPlanItemChangeModeEh); procedure PlannerViewEhSelectionChanged(Sender: TObject); private FRFull: Boolean; FREdit: Boolean; FRGive: Boolean; FRAdd: Boolean; procedure FillPlanner(const StartDate: TDate; const EndDate: TDate); procedure PrepareFilter(const TypeID: Integer = -1); function GetItemText: String; function GetTitleText: String; procedure SetItemColor(PlanItem: TPlannerDataItemEh); public { Public declarations } end; var ReqPlanerForm: TReqPlanerForm; implementation {$R *.dfm} uses System.DateUtils, Generics.Collections, DM, RequestForma, RequestNewForma, pFIBQuery, PrjConst; function TReqPlanerForm.GetItemText: String; var s: string; begin s := dsRequest['CONTETNT']; s := s + sLineBreak; if not dsRequest.FieldByName('ACCOUNT_NO').IsNull then begin if not dsRequest.FieldByName('FIO').IsNull then s := s + 'ФИО ' + dsRequest['FIO'] + ' '; s := s + 'лицевой ' + dsRequest['ACCOUNT_NO']; end; if (not dsRequest.FieldByName('WORKERS').IsNull) and (dsRequest['WORKERS'] <> '') then s := s + sLineBreak + 'Исп.: ' + dsRequest['WORKERS']; result := s; end; function TReqPlanerForm.GetTitleText: String; var s: string; begin s := '[' + IntToStr(dsRequest['RQ_ID']) + '] ' + dsRequest['RT_NAME'] + sLineBreak; if (not dsRequest.FieldByName('Subarea_Name').IsNull) and (dsRequest['Subarea_Name'] <> '') then s := s + '[' + dsRequest['Subarea_Name']+']'; s := s + dsRequest['STREET_NAME'] + ' д.' + dsRequest['HOUSE_NO'] + ' ' + dsRequest['FLAT_NO']; result := s; end; procedure TReqPlanerForm.PlannerControlPlannerItemInteractiveChanged(PlannerControl: TPlannerControlEh; PlannerView: TCustomPlannerViewEh; Item, OldValuesItem: TPlannerDataItemEh); var Query: TpFIBQuery; begin if not FREdit then Exit; if (Item.StartTime <> OldValuesItem.StartTime) or (Item.EndTime <> OldValuesItem.EndTime) then begin if Application.MessageBox(PChar(Format('Новое время заявки %s - %s', [FormatDateTime('dd.mm.yy hh:nn', Item.StartTime), FormatDateTime('dd.mm.yy hh:nn', Item.EndTime)])), PChar('Перенос времени'), MB_YESNO + MB_ICONQUESTION) = IDYES then begin Query := TpFIBQuery.Create(self); try Query.Database := dmMain.dbTV; Query.Transaction := trWrite; Query.SQL.Text := 'update Request set Rq_Plan_Date = :Rq_Plan_Date, Rq_Time_From = :Rq_Time_From, Rq_Time_To = :Rq_Time_To'; Query.SQL.Add(' where (Rq_Id = :Rq_Id)'); Query.ParamByName('Rq_Plan_Date').AsDate := Item.StartTime; Query.ParamByName('Rq_Time_From').AsTime := Item.StartTime; Query.ParamByName('Rq_Time_To').AsTime := Item.EndTime; Query.ParamByName('Rq_Id').AsInteger := Item.ItemID; Query.Transaction.StartTransaction; Query.ExecQuery; Query.Transaction.Commit; finally FreeAndNil(Query); end; FillPlanner(Item.StartTime, Item.StartTime); // PlannerControl.CurrentTime := Item.StartTime; end; end; end; procedure TReqPlanerForm.PlannerControlShowPlanItemDialog(PlannerControl: TPlannerControlEh; PlannerView: TCustomPlannerViewEh; Item: TPlannerDataItemEh; ChangeMode: TPlanItemChangeModeEh); var StartTime, EndTime: TDateTime; AResource: TPlannerResourceEh; i: Integer; begin if not(FREdit or FRAdd or FRGive) then Exit; i := -1; PlannerControl.NewItemParams(StartTime, EndTime, AResource); if ChangeMode = picmModifyEh then begin if not(FREdit or FRGive) then Exit; i := ReguestExecute(Item.ItemID, -2); end else begin if not(FRAdd) then Exit; if Assigned(AResource) then i := AResource.ResourceID; i := NewRequestFromPlaner(StartTime, i); end; if i > 0 then begin FillPlanner(Today, Today); PlannerControl.CurrentTime := StartTime; end; end; procedure TReqPlanerForm.PlannerViewEhSelectionChanged(Sender: TObject); begin if PlannerControl.ActivePlannerView.SelectedPlanItem <> nil then begin mmoItem.Lines.Text := PlannerControl.ActivePlannerView.SelectedPlanItem.Title; mmoItem.Lines.Add(PlannerControl.ActivePlannerView.SelectedPlanItem.Body); end else mmoItem.Lines.Text := ''; end; procedure TReqPlanerForm.SetItemColor(PlanItem: TPlannerDataItemEh); var c: TColor; begin // c := clDefault; if (dsRequest['REQ_RESULT'] < 1) and (PlanItem.EndTime < now()) then begin c := clRed; end else begin if not dsRequest.FieldByName('RT_COLOR').IsNull then c := StringToColor(dsRequest['RT_COLOR']) else c := clWhite; // если выполнена. отметим его if (dsRequest['REQ_RESULT'] > 1) then c := clMoneyGreen; end; PlanItem.FillColor := c; end; procedure TReqPlanerForm.FillPlanner(const StartDate: TDate; const EndDate: TDate); var i: Integer; PlanItem: TPlannerDataItemEh; ResList: TList<Integer>; TypeID: Integer; STime, ETime : TDateTime; begin ResList := TList<Integer>.Create; pldsPlanner.BeginUpdate; pldsPlanner.Resources.Clear; pldsPlanner.ClearItems; if dsRequest.Active then dsRequest.Close; TypeID := 0; if not VarIsNull(cbbGroupBy.Value) then TypeID := cbbGroupBy.Value; if TypeID > 0 then begin for i := 0 to gridResouce.SelectedRows.Count - 1 do begin with pldsPlanner.Resources.Add do begin dsFilter.Bookmark := gridResouce.SelectedRows[i]; Name := dsFilter.FieldByName('NAME').AsString; ResourceID := dsFilter.FieldByName('ID').AsString; if not dsFilter.FieldByName('COLOR').IsNull then Color := StringToColor(dsFilter['COLOR']); ResList.Add(dsFilter['ID']); end; end; end; dsRequest.ParamByName('BDATE').AsDate := Today - 7; // StartDate; dsRequest.ParamByName('EDATE').AsDate := Today + 30; // EndDate; dsRequest.DisableControls; dsRequest.Open; dsRequest.First; while not dsRequest.Eof do begin if (TypeID = 0) or ((TypeID = 1) and (ResList.IndexOf(dsRequest['RQ_TYPE']) > -1)) then begin if not dsRequest.FieldByName('RQ_TIME_FROM').IsNull then STime := dsRequest['RQ_PLAN_DATE'] + dsRequest['RQ_TIME_FROM'] else STime := dsRequest['RQ_PLAN_DATE']; if not dsRequest.FieldByName('RQ_TIME_TO').IsNull then ETime := dsRequest['RQ_PLAN_DATE'] + dsRequest['RQ_TIME_TO'] else ETime := dsRequest['RQ_PLAN_DATE'] + 0.9999; PlanItem := pldsPlanner.NewItem(); PlanItem.ItemID := dsRequest['RQ_ID']; if STime < ETime then begin PlanItem.StartTime := STime; PlanItem.EndTime := ETime; end else begin PlanItem.StartTime := ETime; PlanItem.EndTime := STime; end; PlanItem.Title := GetTitleText; PlanItem.Body := GetItemText; PlanItem.AllDay := False; SetItemColor(PlanItem); case TypeID of 1: PlanItem.ResourceID := dsRequest['RQ_TYPE']; end; pldsPlanner.FetchTimePlanItem(PlanItem); end; dsRequest.Next; end; dsRequest.EnableControls; // dsRequest.Close; pldsPlanner.EndUpdate; PlannerControl.CurrentTime := Today; FreeAndNil(ResList); end; procedure TReqPlanerForm.bFillPlannerClick(Sender: TObject); begin FillPlanner(PlannerControl.CurrentTime - 30, PlannerControl.CurrentTime + 30); end; procedure TReqPlanerForm.cbbGroupByChange(Sender: TObject); var t: Integer; begin // FillPlanner(Today - 7, Today + 7); t := -1; if not VarIsNull(cbbGroupBy.Value) then t := cbbGroupBy.Value; PrepareFilter(t); end; procedure TReqPlanerForm.cbbPlanerViewModeChange(Sender: TObject); begin case StrToInt(cbbPlanerViewMode.Value) of 1: PlannerControl.ActivePlannerView := PlannerWeekViewEh1; 2: PlannerControl.ActivePlannerView := PlannerMonthViewEh1; 3: begin PlannerControl.ActivePlannerView := PlannerVertHourslineViewEh1; PlannerVertHourslineViewEh1.TimeRange := hlrDayEh; end; 4: begin PlannerControl.ActivePlannerView := PlannerVertHourslineViewEh1; PlannerVertHourslineViewEh1.TimeRange := hlrWeekEh; end; 5: begin PlannerControl.ActivePlannerView := PlannerVertDayslineViewEh1; PlannerVertDayslineViewEh1.TimeRange := dlrWeekEh; end; 6: begin PlannerControl.ActivePlannerView := PlannerVertDayslineViewEh1; PlannerVertDayslineViewEh1.TimeRange := dlrMonthEh; end; 7: begin PlannerControl.ActivePlannerView := PlannerHorzHourslineViewEh1; PlannerHorzHourslineViewEh1.TimeRange := hlrDayEh; end; 8: begin PlannerControl.ActivePlannerView := PlannerHorzHourslineViewEh1; PlannerHorzHourslineViewEh1.TimeRange := hlrWeekEh; end; 9: begin PlannerControl.ActivePlannerView := PlannerHorzDayslineViewEh1; PlannerHorzDayslineViewEh1.TimeRange := dlrWeekEh; end; 10: begin PlannerControl.ActivePlannerView := PlannerHorzDayslineViewEh1; PlannerHorzDayslineViewEh1.TimeRange := dlrMonthEh; end; else PlannerControl.ActivePlannerView := PlannerDayViewEh1; end; PlannerControl.ActivePlannerView.OnSelectionChanged := PlannerViewEhSelectionChanged; PlannerControl.WorkingTimeStart := edtStartWorkTime.Value; PlannerControl.WorkingTimeEnd := edtEndWorkTime.Value; PlannerDayViewEh1.ShowWorkingTimeOnly := chkWorkOnly.Checked; PlannerWeekViewEh1.ShowWorkingTimeOnly := chkWorkOnly.Checked; end; procedure TReqPlanerForm.FormActivate(Sender: TObject); begin bFillPlannerClick(Sender); end; procedure TReqPlanerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if dsRequest.Active then dsRequest.Close; Action := caFree; ReqPlanerForm := nil; end; procedure TReqPlanerForm.FormCreate(Sender: TObject); begin FRFull := dmMain.AllowedAction(rght_Request_full); FREdit := dmMain.AllowedAction(rght_Request_edit); FRGive := dmMain.AllowedAction(rght_Request_Give); FRAdd := dmMain.AllowedAction(rght_Request_add); FREdit := FREdit or FRFull; FRAdd := FRAdd or FRFull; FRGive := FRGive or FRFull; chkWorkOnly.Checked := True; edtStartWorkTime.Value := TTime(EncodeTime(8, 0, 0, 0)); edtEndWorkTime.Value := TTime(EncodeTime(17, 0, 0, 0)); cbbPlanerViewMode.Value := 0; end; procedure TReqPlanerForm.FormShow(Sender: TObject); var i: Integer; Font_size : Integer; Font_name : string; begin if TryStrToInt(dmMain.GetIniValue('FONT_SIZE'), i) then begin Font_size := i; Font_name := dmMain.GetIniValue('FONT_NAME'); for i := 0 to ComponentCount - 1 do begin if Components[i] is TDBGridEh then begin (Components[i] as TDBGridEh).Font.Name := Font_name; (Components[i] as TDBGridEh).Font.Size := Font_size; end; end; PlannerControl.Font.Name := Font_name; PlannerControl.Font.Size := Font_size; end; end; procedure TReqPlanerForm.pldsPlannerPrepareItemsReader(PlannerDataSource: TPlannerDataSourceEh; RequriedStartDate, RequriedFinishDate, LoadedBorderDate: TDateTime; var PreparedReadyStartDate, PreparedFinishDate: TDateTime); begin // if (LoadedBorderDate < StartDate) or (LoadedBorderDate > FinishDate) if ((RequriedStartDate <> 0) and (RequriedFinishDate <> 0)) then begin FillPlanner(RequriedStartDate, RequriedFinishDate); PreparedReadyStartDate := RequriedStartDate; PreparedFinishDate := RequriedFinishDate; end; end; procedure TReqPlanerForm.PrepareFilter(const TypeID: Integer = -1); begin dsFilter.Close; case TypeID of 1: begin dsFilter.SQLs.SelectSQL.Clear; dsFilter.SQLs.SelectSQL.Add ('select RT.RT_ID as ID, RT.RT_NAME as NAME, rt.Rt_Color as COLOR from REQUEST_TYPES RT ORDER BY 2'); end; end; dsFilter.Active := (TypeID > 0); if dsFilter.Active then begin dsFilter.First; while not dsFilter.Eof do begin gridResouce.SelectedRows.CurrentRowSelected := True; dsFilter.Next; end; dsFilter.First; end; gridResouce.Visible := (dsFilter.Active); end; end.
{ Subroutine SST_R_PAS_STATEMENT (STAT) * * Process STATEMENT construction. STAT is returned with EOD status when end of * data is encountered. } module sst_r_pas_STATEMENT; define sst_r_pas_statement; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_statement ( {process STATEMENT construction} out stat: sys_err_t); var tag: sys_int_machine_t; {tag number from .syn file} str_h: syo_string_t; {handle to string for current tag} begin sys_error_none (stat); {init STAT to indicate no error} syo_level_down; {down into STATEMENT construction} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_bad', nil, 0); case tag of { * CONST } 1: begin sst_r_pas_sment_const; {process CONST_STATEMENT} end; { * TYPE } 2: begin sst_r_pas_sment_type; {process TYPE_STATEMENT} end; { * VAR } 3: begin sst_r_pas_sment_var; {process VAR_STATEMENT} end; { * LABEL } 4: begin sst_r_pas_sment_label; {process LABEL_STATEMENT syntax} end; { * DEFINE } 5: begin sst_r_pas_sment_define; {process DEFINE_STATEMENT syntax} end; { * Routine heading } 6: begin sst_r_pas_sment_rout (str_h); {process ROUTINE_HEADING syntax} end; { * Executable block } 7: begin sst_opcode_new; {make opcode descriptor for executable block} sst_opc_p^.opcode := sst_opc_exec_k; {opcode is chain of executable statements} sst_opc_p^.str_h := str_h; {save source file char range handle} sst_opcode_pos_push (sst_opc_p^.exec_p); {executable opcodes get chained on here} syo_level_down; {down into EXECUTABLE_BLOCK syntax} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'statement_bad', nil, 0); sst_r_pas_statements; {build opcodes from STATEMENTS syntax} syo_level_up; {back up from EXECUTABLE_BLOCK syntax} sst_opcode_pos_pop; {end of block of executable code} sst_opcode_pos_pop; {end of program/subroutine} sst_scope_old; {pop back to parent scope from prog/subr} nest_level := nest_level - 1; {one less layer deep in nested blocks} end; { * PROGRAM } 8: begin sst_r_pas_sment_prog (str_h); {process PROGRAM_STATEMENT syntax} end; { * MODULE } 9: begin sst_r_pas_sment_module (str_h); {process MODULE_STATEMENT syntax} end; { * End of data. } 10: begin sys_stat_set (sst_subsys_k, sst_stat_eod_k, stat); {indicate end of data condition} end; otherwise syo_error_tag_unexp (tag, str_h); end; {done with all the statement type cases} end;
// islip - IneQuation's Simple LOLCODE Interpreter in Pascal // Written by Leszek "IneQuation" Godlewski <leszgod081@student.polsl.pl> // Variable class unit unit variable; {$IFDEF fpc} {$MODE objfpc} {$ENDIF} interface uses typedefs; type islip_type = (VT_UNTYPED, VT_INT, VT_FLOAT, VT_STRING, VT_BOOL, VT_ARRAY); pislip_var = ^islip_var; islip_var = class public constructor create; overload; constructor create(var v : islip_var); overload; constructor create(i : int); overload; constructor create(f : float); overload; constructor create(s : string); overload; constructor create(b : boolean); overload; {constructor create(id : string; arr_type : islip_var_type; s : size_t); overload;} destructor destroy; // copies the variable from other procedure copy(other : pislip_var); // prints the variable to stdout or stderr procedure echo(to_stderr : boolean); // returns variable type function get_type : islip_type; // does a cast to target type function cast(target : islip_type) : boolean; // evaluates the variable to a bool and returns function get_bool : boolean; // math operation; assumes "self" as the first operand and // destination of result; op is the opcode function math(other : pislip_var; op : byte) : boolean; // logical operation; assumes "self" as the first operand and // destination of result; op is the opcode function logic(other : pislip_var; op : byte) : boolean; // string concatenation; results in a cast to string procedure concat(other : pislip_var); // frees the value pointed to by m_valptr procedure reset_value; private m_type : islip_type; m_valptr : pointer; end; implementation uses convert, bytecode, SysUtils; // untyped constructor constructor islip_var.create; begin m_valptr := nil; m_type := VT_UNTYPED; end; // copy constructor constructor islip_var.create(var v : islip_var); begin copy(@v); end; // integer constructor constructor islip_var.create(i : int); var p : ^int; begin new(p); p^ := i; m_valptr := p; m_type := VT_INT; end; // float constructor constructor islip_var.create(f : float); var p : ^float; begin new(p); p^ := f; m_valptr := p; m_type := VT_FLOAT; end; // string constructor constructor islip_var.create(s : string); var p : ^string; begin new(p); p^ := s; m_valptr := p; m_type := VT_STRING; end; // boolean constructor constructor islip_var.create(b : boolean); var p : ^boolean; begin new(p); p^ := b; m_valptr := p; m_type := VT_BOOL; end; // array constructor {constructor islip_var.create(id : string; arr_type : islip_var_type; s : size_t); var p : array of islip_var; i : int; begin setlength(p, s); for i := 1 to s do begin case arr_type of VT_INT: p[i].create(id + '[' + i + ']', int(0)); break; VT_FLOAT: p[i].create(id + '[' + i + ']', float(0.0)); break; VT_STRING: p[i].create(id + '[' + i + ']', ''); break; end; end; p^ := f; m_valptr := p; m_type := VT_ARRAY; end;} // universal destructor destructor islip_var.destroy; begin reset_value; end; procedure islip_var.reset_value; var pi : ^int; pf : ^float; ps : ^string; pb : ^boolean; //pa : ^islip_var; begin if m_valptr = nil then exit; case m_type of VT_INT: begin pi := m_valptr; dispose(pi); end; VT_FLOAT: begin pf := m_valptr; dispose(pf); end; VT_STRING: begin ps := m_valptr; dispose(ps); end; VT_BOOL: begin pb := m_valptr; dispose(pb); end; {VT_ARRAY: begin end;} end; m_valptr := nil; end; procedure islip_var.copy(other : pislip_var); var pi1, pi2 : ^int; pf1, pf2 : ^float; ps1, ps2 : ^string; pb1, pb2 : ^boolean; begin reset_value; m_type := other^.m_type; case m_type of VT_INT: begin new(pi1); pi2 := other^.m_valptr; pi1^ := pi2^; m_valptr := pi1; end; VT_FLOAT: begin new(pf1); pf2 := other^.m_valptr; pf1^ := pf2^; m_valptr := pf1; end; VT_STRING: begin new(ps1); ps2 := other^.m_valptr; ps1^ := ps2^; m_valptr := ps1; end; VT_BOOL: begin new(pb1); pb2 := other^.m_valptr; pb1^ := pb2^; m_valptr := pb1; end; end; end; procedure islip_var.echo(to_stderr : boolean); var pi : ^int; pf : ^float; ps : ^string; pb : ^boolean; begin case m_type of VT_INT: begin pi := m_valptr; if to_stderr then write(stderr, pi^) else write(pi^); end; VT_FLOAT: begin pf := m_valptr; if to_stderr then write(stderr, pf^:0:2) else write(pf^:0:2); end; VT_STRING: begin ps := m_valptr; if to_stderr then write(stderr, ps^) else write(ps^); end; VT_BOOL: begin pb := m_valptr; if to_stderr then begin if pb^ then write(stderr, 'WIN') else write(stderr, 'FAIL'); end else begin if pb^ then write('WIN') else write('FAIL'); end; end; end; end; function islip_var.get_type : islip_type; begin get_type := m_type; end; function islip_var.cast(target : islip_type) : boolean; var pi : ^int; pf : ^float; ps : ^string; pb : ^boolean; begin if target = m_type then begin cast := true; exit; end; cast := false; case m_type of VT_UNTYPED: case target of VT_INT: begin new(pi); pi^ := 0; m_valptr := pi; end; VT_FLOAT: begin new(pf); pf^ := 0; m_valptr := pf; end; VT_BOOL: begin new(pb); pb^ := false; m_valptr := pb; end; VT_STRING: begin new(ps); ps^ := ''; m_valptr := ps; end; end; VT_INT: begin pi := m_valptr; case target of VT_FLOAT: begin new(pf); pf^ := float(pi^); m_valptr := pf; end; VT_BOOL: begin new(pb); pb^ := (pi^ <> 0); m_valptr := pb; end; VT_STRING: begin new(ps); ps^ := IntToStr(pi^); m_valptr := ps; end; end; if target <> VT_INT then dispose(pi); end; VT_FLOAT: begin pf := m_valptr; case target of VT_INT: begin new(pi); pi^ := trunc(pf^); m_valptr := pi; end; VT_BOOL: begin new(pb); pb^ := (pf^ <> 0.0); m_valptr := pb; end; VT_STRING: begin new(ps); ps^ := FloatToStr(pf^); m_valptr := ps; end; end; if target <> VT_FLOAT then dispose(pf); end; VT_BOOL: begin pb := m_valptr; case target of VT_INT: begin new(pi); pi^ := int(pb^); m_valptr := pi; end; VT_FLOAT: begin new(pf); if pb^ then pf^ := 1.0 else pf^ := 0.0; m_valptr := pf; end; VT_STRING: begin new(ps); if pb^ then ps^ := 'WIN' else ps^ := 'FAIL'; m_valptr := ps; end; end; if target <> VT_BOOL then dispose(pb); end; VT_STRING: begin ps := m_valptr; case target of VT_INT: begin new(pi); try pi^ := StrToInt(ps^); except on E : Exception do begin dispose(pi); exit; end; end; m_valptr := pi; end; VT_FLOAT: begin new(pf); if not atof(ps^, pf) then begin dispose(pf); exit; end; m_valptr := pf; end; VT_BOOL: begin new(pb); pb^ := (length(ps^) > 0); m_valptr := pb; end; end; if target <> VT_STRING then dispose(ps); end; end; m_type := target; cast := true; end; function islip_var.math(other : pislip_var; op : byte) : boolean; var pi1, pi2 : ^int; pf1, pf2 : ^float; begin math := false; if (m_type = VT_UNTYPED) or (other^.m_type = VT_UNTYPED) or (m_type = VT_STRING) or (other^.m_type = VT_STRING) then exit; if m_type = VT_INT then begin pi1 := m_valptr; // int + int if other^.m_type = VT_INT then begin pi2 := other^.m_valptr; case op of OP_ADD: pi1^ := pi1^ + pi2^; OP_SUB: pi1^ := pi1^ - pi2^; OP_MUL: pi1^ := pi1^ * pi2^; OP_DIV: pi1^ := pi1^ div pi2^; OP_MOD: pi1^ := pi1^ mod pi2^; OP_MIN: if pi1^ > pi2^ then pi1^ := pi2^; OP_MAX: if pi1^ < pi2^ then pi1^ := pi2^; else exit; end; // int + float end else begin pf2 := other^.m_valptr; // special case for modulo if op = OP_MOD then pi1^ := pi1^ mod trunc(pf2^) else begin self.cast(VT_FLOAT); pf1 := m_valptr; case op of OP_ADD: pf1^ := pf1^ + pf2^; OP_SUB: pf1^ := pf1^ - pf2^; OP_MUL: pf1^ := pf1^ * pf2^; OP_DIV: pf1^ := pf1^ / pf2^; OP_MIN: if pf1^ > pf2^ then pf1^ := pf2^; OP_MAX: if pf1^ < pf2^ then pf1^ := pf2^; else exit; end; end; end; end else begin pf1 := m_valptr; // float + int if other^.m_type = VT_INT then begin pi2 := other^.m_valptr; case op of OP_ADD: pf1^ := pf1^ + float(pi2^); OP_SUB: pf1^ := pf1^ - float(pi2^); OP_MUL: pf1^ := pf1^ * float(pi2^); OP_DIV: pf1^ := pf1^ / float(pi2^); OP_MOD: begin self.cast(VT_INT); pi1 := m_valptr; pi1^ := pi1^ mod pi2^; end; OP_MIN: if pf1^ > float(pi2^) then pf1^ := float(pi2^); OP_MAX: if pf1^ < float(pi2^) then pf1^ := float(pi2^); else exit; end; // float + float end else begin // special case for modulo if op = OP_MOD then begin self.cast(VT_INT); pi1 := m_valptr; pi1^ := pi1^ mod trunc(pf2^); end else begin pf2 := other^.m_valptr; case op of OP_ADD: pf1^ := pf1^ + pf2^; OP_SUB: pf1^ := pf1^ - pf2^; OP_MUL: pf1^ := pf1^ * pf2^; OP_DIV: pf1^ := pf1^ / pf2^; OP_MIN: if pf1^ > pf2^ then pf1^ := pf2^; OP_MAX: if pf1^ < pf2^ then pf1^ := pf2^; else exit; end; end; end; end; math := true; end; function islip_var.logic(other : pislip_var; op : byte) : boolean; var pb1, pb2 : ^boolean; pi1, pi2 : ^int; pf1, pf2 : ^float; ps1, ps2 : ^string; comparison : islip_type; temp : boolean; begin logic := false; case op of OP_NEG: begin self.cast(VT_BOOL); pb1 := m_valptr; pb1^ := not pb1^; end; OP_AND, OP_OR, OP_XOR: begin self.cast(VT_BOOL); other^.cast(VT_BOOL); pb1 := m_valptr; pb2 := other^.m_valptr; case op of OP_AND: pb1^ := pb1^ and pb2^; OP_OR: pb1^ := pb1^ or pb2^; OP_XOR: pb1^ := pb1^ xor pb2^; end; end; OP_EQ, OP_NEQ: begin // select comparison mode and perform necessary casts case m_type of VT_INT: case other^.m_type of VT_INT: comparison := VT_INT; VT_FLOAT: begin self.cast(VT_FLOAT); comparison := VT_FLOAT; end; VT_BOOL: begin other^.cast(VT_INT); comparison := VT_INT; end; VT_STRING: begin self.cast(VT_STRING); comparison := VT_STRING; end; else begin self.cast(VT_BOOL); other^.cast(VT_BOOL); comparison := VT_BOOL; end; end; VT_FLOAT: case other^.m_type of VT_INT, VT_BOOL: begin other^.cast(VT_FLOAT); comparison := VT_FLOAT; end; VT_FLOAT: comparison := VT_FLOAT; VT_STRING: begin self.cast(VT_STRING); comparison := VT_STRING; end; else begin self.cast(VT_BOOL); other^.cast(VT_BOOL); comparison := VT_BOOL; end; end; VT_BOOL: case other^.m_type of VT_INT, VT_FLOAT, VT_STRING: begin self.cast(other^.m_type); comparison := other^.m_type; end; VT_BOOL: comparison := VT_BOOL; else begin other^.cast(VT_BOOL); comparison := VT_BOOL; end; end; VT_STRING: case other^.m_type of VT_INT, VT_FLOAT, VT_BOOL: begin other^.cast(VT_STRING); comparison := VT_STRING; end; VT_STRING: comparison := VT_STRING; else begin self.cast(VT_BOOL); other^.cast(VT_BOOL); comparison := VT_BOOL; end; end; else begin self.cast(VT_BOOL); other^.cast(VT_BOOL); comparison := VT_BOOL; end; end; // now compare case comparison of VT_INT: begin pi1 := m_valptr; pi2 := other^.m_valptr; temp := ((pi1^ = pi2^) and (op = OP_EQ)) or ((pi1^ <> pi2^) and (op = OP_NEQ)); end; VT_FLOAT: begin pf1 := m_valptr; pf2 := other^.m_valptr; temp := ((pf1^ = pf2^) and (op = OP_EQ)) or ((pf1^ <> pf2^) and (op = OP_NEQ)); end; VT_BOOL: begin pb1 := m_valptr; pb2 := other^.m_valptr; temp := ((pb1^ = pb2^) and (op = OP_EQ)) or ((pb1^ <> pb2^) and (op = OP_NEQ)); end; VT_STRING: begin ps1 := m_valptr; ps2 := other^.m_valptr; temp := ((ps1^ = ps2^) and (op = OP_EQ)) or ((ps1^ <> ps2^) and (op = OP_NEQ)); end; end; // write down the result self.cast(VT_BOOL); pb1 := m_valptr; pb1^ := temp; end; end; logic := true; end; procedure islip_var.concat(other : pislip_var); var ps1, ps2 : ^string; begin self.cast(VT_STRING); other^.cast(VT_STRING); ps1 := m_valptr; ps2 := other^.m_valptr; ps1^ := ps1^ + ps2^; end; function islip_var.get_bool : boolean; var pb : ^boolean; pi : ^int; pf : ^float; ps : ^string; begin if m_type = VT_BOOL then begin pb := m_valptr; get_bool := pb^; end else case m_type of VT_UNTYPED: get_bool := false; VT_INT: begin pi := m_valptr; get_bool := pi^ <> 0; end; VT_FLOAT: begin pf := m_valptr; get_bool := pf^ <> 0.0; end; VT_STRING: begin ps := m_valptr; get_bool := ps^ <> ''; end; end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, Windows, jwatlhelp32, iniFiles; type { TForm1 } TForm1 = class(TForm) miAbout: TMenuItem; miExit: TMenuItem; PopupMenu1: TPopupMenu; Timer1: TTimer; TrayIcon1: TTrayIcon; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure miExitClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; cpu_time_old: real; process_name: String; path_to_file: String; timeout: Integer; percents_of_cpu_to_kill: Integer; implementation {$R *.lfm} function RunApp(my_app : string; my_wait : bool) : bool; var si : TStartupInfo; pi : TProcessInformation; begin Result := false; try ZeroMemory(@si,SizeOf(si)); si.cb := SizeOf(si); si.dwFlags := STARTF_USESHOWWINDOW; si.wShowWindow := SW_HIDE; if CreateProcess(nil,PChar(my_app),nil,nil,False,0,nil,nil,si,pi{%H-})=true then Result := true; try CloseHandle(pi.hThread); except ; end; if my_wait = true then WaitForSingleObject(pi.hProcess, INFINITE); try CloseHandle(pi.hProcess); except ; end; except Result := false; end; end; function GetProcID(name:string):Cardinal; var SnapShot:THandle; process:TProcessEntry32; begin result := 0; SnapShot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS,0); process.dwSize := SizeOf(Process); Process32First(SnapShot,Process); repeat if LowerCase(process.szExeFile) = LowerCase(name) then begin result := process.th32ProcessID; CloseHandle(SnapShot); exit; end; until Process32Next(SnapShot,Process) <> true; CloseHandle(SnapShot); end; function GetTimeByName(name: String): real; var cpu_time: real; pid: cardinal; timeCreate,timeExit,timeKernel,timeUser: TFileTime; ProcessHandle: handle; begin result:=0; pid:=GetProcID(name); if pid<>0 then begin ProcessHandle:=OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_ALL_ACCESS,false,pid); if ProcessHandle<>0 then begin if GetProcessTimes(ProcessHandle,timeCreate{%H-},timeExit{%H-},timeKernel{%H-},timeUser{%H-}) then begin cpu_time := timeUser.dwHighDateTime*(4294967296/10000000)+timeUser.dwLowDateTime/10000000; cpu_time := cpu_time + timeKernel.dwHighDateTime*(4294967296/10000000)+timeKernel.dwLowDateTime/10000000; result:=cpu_time; end; end; end; end; function TerminateProcessByName(name: string): boolean; var pid: cardinal; ProcessHandle: handle; begin result:=false; pid:=GetProcID(name); if pid<>0 then begin ProcessHandle:=OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_ALL_ACCESS,false,pid); if ProcessHandle<>0 then begin Result:=TerminateProcess(ProcessHandle,0); end; end; end; procedure ReadSettings(); var ininame: string; ini: TIniFile; begin ininame:=paramstr(0); //get current path\exe-name SetLength(ininame, Length(ininame)-4); // cut '.exe' ininame:=ininame+'.ini'; ini:=TIniFile.Create(ininame); try //process_name := ini.ReadString('Settings', 'process_name', 'ETDCtrl.exe'); path_to_file := ini.ReadString('Settings', 'path_to_file', 'C:\Program Files\Elantech\ETDCtrl.exe'); timeout := ini.ReadInteger('Settings', 'timeout', 30); percents_of_cpu_to_kill := ini.ReadInteger('Settings', 'percents_of_cpu_to_kill', 40); //of 1 core finally ini.Free; end; process_name := ExtractFileName(path_to_file); if not FileExists(path_to_file) then begin ShowMessage('File not found:'+#10+'"'+path_to_file+'"'+#10+'Press Ok to exit...'); Application.Terminate; end; end; procedure WriteSettings(); var ininame: string; ini: TIniFile; begin ininame:=paramstr(0); //get current path\exe-name SetLength(ininame, Length(ininame)-4); // cut '.exe' ininame:=ininame+'.ini'; ini:=TIniFile.Create(ininame); try //ini.WriteString('Settings', 'process_name', process_name); ini.WriteString('Settings', 'path_to_file', path_to_file); ini.WriteInteger('Settings', 'timeout', timeout); ini.WriteInteger('Settings', 'percents_of_cpu_to_kill', percents_of_cpu_to_kill); //of 1 core finally ini.Free; end; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin ReadSettings(); Timer1.Interval:=TIMEOUT*1000; cpu_time_old:=GetTimeByName(PROCESS_NAME); Timer1.Enabled:=true; if GetProcID(process_name)=0 then RunApp(path_to_file, false); end; procedure TForm1.FormShow(Sender: TObject); begin Form1.Hide; end; procedure TForm1.miAboutClick(Sender: TObject); var info: string; begin info:='ETDCtrlRestarter'+ #10+''+ #10+'Created by Str@y (2013)'; MessageBox(0, PChar(info), '', MB_OK); end; procedure TForm1.miExitClick(Sender: TObject); begin WriteSettings(); Application.Terminate; end; procedure TForm1.Timer1Timer(Sender: TObject); var cpu_time: real; begin cpu_time:=GetTimeByName(PROCESS_NAME); if cpu_time<>0 then begin if ( (cpu_time - cpu_time_old) > (timeout * percents_of_cpu_to_kill/100) ) then begin TerminateProcessByName(PROCESS_NAME); cpu_time:=0; RunApp(path_to_file, false); end; cpu_time_old:=cpu_time; end; end; end.
unit uFormSelectSource_FMX; {$I DelphiTwain.inc} interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox, FMX.Objects {$IFDEF DELPHI_XE4_UP}, FMX.StdCtrls{$ENDIF} {$IFDEF DELPHI_XE5_UP}, FMX.Graphics{$ENDIF} ; type TFormSelectSource = class(TForm) protected {$IFDEF DELPHI_XE5_UP} procedure DoShow; override; {$ENDIF} public {$IFDEF DELPHI_XE5_UP} LblCaption: TLabel; {$ENDIF} LBSources: TListBox; BtnOk: TButton; BtnCancel: TButton; procedure LBSourcesDblClick(Sender: TObject); procedure FormResize(Sender: TObject); public constructor CreateNew(AOwner: TComponent; Dummy: {$IFDEF DELPHI_XE5_UP}NativeInt{$ELSE}Integer{$ENDIF} = 0); override; end; implementation uses DelphiTwainLang; constructor TFormSelectSource.CreateNew(AOwner: TComponent; Dummy: {$IFDEF DELPHI_XE5_UP}NativeInt{$ELSE}Integer{$ENDIF} = 0); begin inherited; Caption := DELPHITWAIN_SelectSource; Position := TFormPosition.poOwnerFormCenter; Width := 300; Height := 200; BorderIcons := [TBorderIcon.biSystemMenu]; {$IFDEF DELPHI_XE5_UP} LblCaption := TLabel.Create(Self); LblCaption.Parent := Self; LblCaption.Text := Caption; LblCaption.Font.Size := 15; LblCaption.StyledSettings := LblCaption.StyledSettings - [TStyledSetting.ssFamily, TStyledSetting.ssSize]; LblCaption.Position.X := 3; LblCaption.Position.Y := 3; {$ENDIF} LBSources := TListBox.Create(Self); LBSources.Parent := Self; LBSources.OnDblClick := LBSourcesDblClick; BtnOk := TButton.Create(Self); BtnOk.Parent := Self; BtnOk.ModalResult := mrOk; {$IFDEF DELPHI_XE3_UP} BtnOk.Text := DELPHITWAIN_OK; {$ELSE} BtnOk.Text := StringReplace(DELPHITWAIN_OK, '&', '', [rfReplaceAll]); {$ENDIF} BtnOk.Default := True; BtnCancel := TButton.Create(Self); BtnCancel.Parent := Self; BtnCancel.ModalResult := mrCancel; {$IFDEF DELPHI_XE3_UP} BtnCancel.Text := DELPHITWAIN_Cancel; {$ELSE} BtnCancel.Text := StringReplace(DELPHITWAIN_Cancel, '&', '', [rfReplaceAll]); {$ENDIF} OnResize := FormResize; FormResize(nil); end; procedure TFormSelectSource.LBSourcesDblClick(Sender: TObject); begin ModalResult := mrOk; end; {$IFDEF DELPHI_XE5_UP} procedure TFormSelectSource.DoShow; begin inherited; Width := 300;//BUG WORKAROUND: XE5 Height := 200;//BUG WORKAROUND: XE5 //BUG WORKAROUND XE5 -> FORM HEADER IS NOT SHOWN, SET COLOR BACKGROUND AT LEAST Fill.Kind := TBrushKind.bkSolid; Fill.Color := $FFDDDDFF; end; {$ENDIF} procedure TFormSelectSource.FormResize(Sender: TObject); begin LBSources.Position.X := 3; LBSources.Position.Y := 3 {$IFDEF DELPHI_XE5_UP}+ LblCaption.Height + 3{$ENDIF}; LBSources.Width := Self.ClientWidth - 6; LBSources.Height := Self.ClientHeight - (41+LBSources.Position.Y); BtnCancel.Position.X := Self.ClientWidth - BtnCancel.Width - 6; BtnOK.Position.X := BtnCancel.Position.X - BtnOK.Width - 6; BtnCancel.Position.Y := LBSources.ParentedRect.Bottom + (41 - BtnCancel.Height) / 2; BtnOK.Position.Y := BtnCancel.Position.Y; end; end.
unit clTipoContrato; interface uses clConexao, Vcl.Dialogs, System.SysUtils, clCentroCusto; type TTipoContrato = class(TObject) protected FContrato: Integer; FCCusto: Integer; FDescricao: String; conexao: TConexao; centrocusto: TCentroCusto; private procedure SetDescricao(val: String); procedure SetContrato(val: Integer); procedure SetCCusto(val: Integer); public constructor Create; property Descricao: String read FDescricao write SetDescricao; property Contrato: Integer read FContrato write SetContrato; property CCusto: Integer read FCCusto write SetCCusto; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getObjects: Boolean; function getField(sCampo: String; sColuna: String): String; destructor Destroy; override; end; const TABLENAME = 'FIN_TIPO_CONTRATO'; implementation uses udm; constructor TTipoContrato.Create; begin inherited Create; conexao := TConexao.Create; centrocusto := TCentroCusto.Create; end; procedure TTipoContrato.SetDescricao(val: String); begin FDescricao := val; end; procedure TTipoContrato.SetContrato(val: Integer); begin FContrato := val; end; procedure TTipoContrato.SetCCusto(val: Integer); begin FCCusto := val; end; function TTipoContrato.Validar: Boolean; begin Result := False; if Self.Contrato = 0 then begin MessageDlg('Informe o código do Contrato!', mtWarning, [mbCancel], 0); Exit; end; if Self.Contrato = 0 then begin MessageDlg('Informe a Descrição Contrato!', mtWarning, [mbCancel], 0); Exit; end; if Self.CCusto > 0 then begin if (not centrocusto.getObject(IntToStr(Self.CCusto),'CODIGO')) then begin MessageDlg('Código de Centro de Custo não cadastrado!', mtWarning, [mbCancel], 0); Exit; end else begin dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; end; end; Result := True; end; function TTipoContrato.Insert: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_TIPO_CONTRATO, ' + 'DES_TIPO_CONTRATO, ' + 'COD_CENTRO_CUSTO) ' + 'VALUES(' + ':CODIGO, ' + ':DESCRICAO, ' + ':CUSTO)'; ParamByName('CODIGO').AsInteger := Self.Contrato; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('CUSTO').AsDate := Self.CCusto; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTipoContrato.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO_CONTRATO = :DESCRICAO, ' + 'COD_CENTRO_CUSTO = :CUSTO ' + 'WHERE COD_TIPO_CONTRATO - :CODIGO'; ParamByName('CODIGO').AsInteger := Self.Contrato; ParamByName('DESCRICAO').AsString := Self.Descricao; ParamByName('CUSTO').AsDate := Self.CCusto; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTipoContrato.Delete(sFiltro: String): Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add('WHERE COD_TIPO_CONTRATO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Contrato; end else if sFiltro = 'CUSTP' then begin SQL.Add('WHERE COD_CENTRO_CUSTO = :CUSTO'); ParamByName('CUSTO').AsInteger := Self.CCusto; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTipoContrato.getObject(sId: String; sFiltro: String): Boolean; begin try Result := False; if sId.IsEmpty then begin Exit; end; if sFiltro.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add('WHERE COD_TIPO_CONTRATO = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(sId); end else if sFiltro = 'DESCRICAO' then begin SQL.Add('WHERE DES_TIPO_CONTRATO LIKE :DESCRICAO'); ParamByName('DESCRICAO').AsString := QuotedStr('%' + sId + '%'); end else if sFiltro = 'CUSTO' then begin SQL.Add('WHERE COD_CENTRO_CUSTO = :CUSTO'); ParamByName('CUSTO').AsInteger := StrToInt(sId); end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Self.Contrato := FieldByName('COD_TIPO_CONTRATO').AsInteger; Self.Descricao := FieldByName('DES_TIPO_CONTRATO').AsString; Self.CCusto := FieldByName('COD_CENTRO_CUSTO').AsInteger; Result := True; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTipoContrato.getObjects: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Result := True; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TTipoContrato.getField(sCampo: String; sColuna: String): String; begin try Result := ''; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.qryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if sColuna = 'CODIGO' then begin SQL.Add('WHERE COD_TIPO_CONTRATO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Contrato; end else if sColuna = 'DESCRICAO' then begin SQL.Add('WHERE DES_TIPO_CONTRATO = :DESCRICAO'); ParamByName('DESCRICAO').AsString := Self.Descricao; end else if sColuna = 'CUSTO' then begin SQL.Add('WHERE COD_CENTRO_CUSTO = :CUSTO'); ParamByName('CUSTO').AsInteger := Self.CCusto; end; dm.ZConn.PingServer; Open; if (not IsEmpty) then begin First; Result := FieldByName(sCampo).AsString; Exit; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; destructor TTipoContrato.Destroy; begin conexao.Free; inherited Destroy; end; end.
unit RTTIUtils; interface uses Data.DB, Vcl.Forms; type Bind = class(TCustomAttribute) private FField: String; FDisplayLabel: String; FDisplayWidth: Integer; procedure SetField(const Value: String); procedure SetDisplayLabel(const Value: String); procedure SetDisplayWidth(const Value: Integer); public constructor Create ( aField : String; aDisplayLabel : String; aDisplayWidth : Integer ); property Field : String read FField write SetField; property DisplayLabel : String read FDisplayLabel write SetDisplayLabel; property DisplayWidth : Integer read FDisplayWidth write SetDisplayWidth; end; TRTTIUtils = class private public class procedure DataSetToForm(aDataSet : TDataSet; aForm : TForm); end; implementation uses System.RTTI, System.Classes, Vcl.StdCtrls; { TRTTIUtils } class procedure TRTTIUtils.DataSetToForm(aDataSet: TDataSet; aForm: TForm); var ctxContext : TRTTIContext; typRtti : TRttiType; fldRtti : TRttiField; cusAttr : TCustomAttribute; Component : TComponent; begin ctxContext := TRTTIContext.Create; try typRtti := ctxContext.GetType(aForm.ClassType); for fldRtti in typRtti.GetFields do for cusAttr in fldRtti.GetAttributes do begin if cusAttr is Bind then begin Component := aForm.FindComponent(fldRtti.Name); if Component is TEdit then TEdit(Component).Text := aDataSet.FieldByName(Bind(cusAttr).Field).AsString; aDataSet.FieldByName(Bind(cusAttr).Field).DisplayLabel := Bind(cusAttr).DisplayLabel; aDataSet.FieldByName(Bind(cusAttr).Field).DisplayWidth := Bind(cusAttr).DisplayWidth; end; end; finally ctxContext.Free; end; end; { Bind } constructor Bind.Create( aField : String; aDisplayLabel : String; aDisplayWidth : Integer ); begin FField := aField; FDisplayLabel := aDisplayLabel; FDisplayWidth := aDisplayWidth; end; procedure Bind.SetDisplayLabel(const Value: String); begin FDisplayLabel := Value; end; procedure Bind.SetDisplayWidth(const Value: Integer); begin FDisplayWidth := Value; end; procedure Bind.SetField(const Value: String); begin FField := Value; end; end.
Unit ZMMsg; // Built by ZipResMaker // DO NOT MODIFY // ZMMsg.pas - default messages and compressed tables (* ************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2015 delphizip Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. contact: problems AT delphizip DOT org updates: http://www.delphizip.org ************************************************** *) //Generated 2015-07-15 Interface Uses {$IFDEF VERDXE2up} System.Classes; {$ELSE} Classes; {$ENDIF} Const ZS_Success = 0; // "Success" ZE_UnknownError = 1; // "Unknown Error" ZA_Author = 2; // "R.Peters" ZA_Desc = 3; // "Language Neutral" ZA_ID = 4; // "$0409" ZA_Language = 5; // "US: default" ZC_Abort = 6; // "&Abort" ZC_Cancel = 7; // "&Cancel" ZC_CancelAll = 8; // "CancelAll" ZC_Caption = 9; // "Password" ZC_FileConflict = 10; // "File conflict!" ZC_Ignore = 11; // "&Ignore" ZC_Merge = 12; // "'%s'\nwill overwrite\n '%s'\nRename to '%s'?" ZC_MessageConfirm = 13; // "Confirm Password " ZC_MessageEnter = 14; // "Enter Password " ZC_No = 15; // "&No" ZC_NoToAll = 16; // "NoToAll" ZC_OK = 17; // "&OK" ZC_Retry = 18; // "&Retry" ZC_Yes = 19; // "&Yes" ZC_YesToAll = 20; // "YesToAll" ZE_AAA = 23; // "." ZE_AccessDenied = 24; // "Access denied opening: '%s'" ZE_AutoSFXWrong = 25; // "Error %.1d occurred during Auto SFX creation." ZE_BadCRC = 26; // "CRC error" ZE_BadDll = 27; // "Unable to load %s - It is old or corrupt" ZE_BadFileName = 28; // "Invalid Filename: '%s'" ZE_Blocked = 29; // "Busy or not Active" ZE_BrowseError = 30; // "Error while browsing resources." ZE_BuildBaseError = 31; // "Error building extract base path '%s'" ZE_BuildPathError = 32; // "Error building path '%s'" ZE_CannotAddToItself = 33; // "'Cannot add zip to itself'" ZE_CEHBadRead = 34; // "Error while reading a central header" ZE_CEHBadWrite = 35; // "Error while writing a central header" ZE_CEHDataSize = 36; // "Central Directory Entry too big" ZE_CEHWrongSig = 37; // "A central header signature is wrong" ZE_CopyError = 38; // "File copy error" ZE_CopyFailed = 39; // "Copying a file from '%s' to '%s' failed" ZE_CryptError = 40; // "Crypt error" ZE_DataCopy = 41; // "Error copying compressed data: '%s'" ZE_DataDesc = 42; // "Error while reading/writing a data descriptor area: '%s'" ZE_DetachedHeaderTooBig = 43; // "Detached SFX Header too large" ZE_DLLCritical = 44; // "critical DLL Error %d" ZE_DriveNoMount = 45; // "Drive %s is NOT defined" ZE_DuplFileName = 46; // "Duplicate Filename: '%s'" ZE_EntryCancelled = 47; // "Entry cancelled" ZE_EOCBadRead = 48; // "Error while reading the End Of Central Directory" ZE_EOCBadWrite = 49; // "Error while writing the End Of Central Directory" ZE_ErrorUnknown = 50; // "UnKnown error in function" ZE_EventEx = 51; // "Exception in Event '%s'" ZE_Except = 52; // "Exception in Event handler %s" ZE_ExceptErr = 53; // "Error Exception: " ZE_ExeSections = 54; // "Error while reading executable sections." ZE_Existing = 55; // "File exists: '%s'" ZE_FailedSeek = 56; // "Seek error in input file" ZE_FatalZip = 57; // "Fatal Error in DLL: abort exception" ZE_FileChanged = 58; // "File changed" ZE_FileCreate = 59; // "Error: Could not create file '%s'" ZE_FileError = 60; // "File Error: '%s'" ZE_FileOpen = 61; // "Zip file could not be opened" ZE_Inactive = 62; // "not Active" ZE_InIsOutStream = 63; // "Input stream may not be set to the output stream" ZE_InputNotExe = 64; // "Error: input file is not an .EXE file" ZE_InternalError = 65; // "Internal error" ZE_InvalidArguments = 66; // "Invalid Arguments" ZE_InvalidDateTime = 67; // "Invalid date/time argument for file: " ZE_InvalidEntry = 68; // "Invalid zip entry!" ZE_InvalidParameter = 69; // "Invalid Parameter! '%s'" ZE_InvalidZip = 70; // "Invalid zip file" ZE_InvalLangFile = 71; // "Invalid language file" ZE_LoadErr = 72; // "Error [%d %s] loading %s" ZE_LockViolation = 73; // "Lock violation opening: '%s'" ZE_LogicError = 74; // "Internal logic error!" ZE_LOHBadRead = 75; // "Error while reading a local header" ZE_LOHBadWrite = 76; // "Error while writing a local header" ZE_LOHWrongName = 77; // "Local and Central names different : %s" ZE_NoAppend = 78; // "Append failed" ZE_NoChangeDir = 79; // "Cannot change path" ZE_NoCopyIcon = 80; // "Cannot copy icon." ZE_NoDestDir = 81; // "Destination directory '%s' must exist!" ZE_NoDiskSpace = 82; // "This disk has not enough free space available" ZE_NoDll = 83; // "Failed to load %s%s" ZE_NoEncrypt = 84; // "encryption not supported" ZE_NoExeIcon = 85; // "No icon resources found in executable." ZE_NoExeResource = 86; // "No resources found in executable." ZE_NoExtrDir = 87; // "Extract directory '%s' must exist" ZE_NoIcon = 88; // "No icon found." ZE_NoIconFound = 89; // "No matching icon found." ZE_NoInFile = 90; // "Input file does not exist" ZE_NoInStream = 91; // "No input stream" ZE_NoMem = 92; // "Requested memory not available" ZE_NoneFound = 93; // "No files found for '%s'" ZE_NoneSelected = 94; // "No files selected for '%s'" ZE_NoOpen = 95; // "Could not open: '%s'" ZE_NoOutFile = 96; // "Creation of output file failed" ZE_NoOutStream = 97; // "No output stream" ZE_NoOverwrite = 98; // "Cannot overwrite existing file" ZE_NoProcess = 99; // "Cannot process invalid zip" ZE_NoProtected = 100; // "Cannot change details of Encrypted file" ZE_NoRenamePart = 101; // "Last part left as : %s" ZE_NoSkipping = 102; // "Skipping not allowed" ZE_NoStreamSpan = 103; // "Multi-parts not supported on streams!" ZE_NotChangeable = 104; // "Cannot write to %s" ZE_NoTempFile = 105; // "Temporary file could not be created" ZE_NotFound = 106; // "File not found!" ZE_NothingToDel = 107; // "Error - no files selected for deletion" ZE_NothingToDo = 108; // "Nothing to do" ZE_NothingToZip = 109; // "Error - no files to zip!" ZE_NoUnattSpan = 110; // "Unattended disk spanning not implemented" ZE_NoValidZip = 111; // "This archive is not a valid Zip archive" ZE_NoVolume = 112; // "Volume label could not be set" ZE_NoWrite = 113; // "Write error in output file" ZE_NoZipSFXBin = 114; // "Error: SFX stub '%s' not found!" ZE_NoZipSpecified = 115; // "Error - no zip file specified!" ZE_PasswordCancel = 116; // "Password cancelled!" ZE_PasswordFail = 117; // "Password failed!" ZE_RangeError = 118; // "Index (%d) outside range 0..%d" ZE_ReadError = 119; // "Error reading file" ZE_ReadZipError = 120; // "Seek error reading Zip archive!" ZE_SameAsSource = 121; // "source and destination on same removable drive" ZE_SeekError = 122; // "File seek error" ZE_SeekFailed = 123; // "Seek error: %s" ZE_SetDateError = 124; // "Error setting file date" ZE_SetFileAttributes = 125; // "Error setting file attributes" ZE_SetFileInformation = 126; // "Error setting file information" ZE_SetFileTimes = 127; // "Error setting file times" ZE_SFXBadRead = 128; // "Error reading SFX" ZE_SFXCopyError = 129; // "Error while copying the SFX data" ZE_ShareViolation = 130; // "Sharing violation opening: '%s'" ZE_SourceIsDest = 131; // "Source archive is the same as the destination archive!" ZE_StreamNoSupport = 132; // "Operation not supported on streams" ZE_StringTooLong = 133; // "Error: Combined SFX strings unreasonably long!" ZE_TooManyParts = 134; // "More than 999 parts in multi volume archive" ZE_UnatAddPWMiss = 135; // "Error - no add password given" ZE_UnatExtPWMiss = 136; // "Error - no extract password given" ZE_UnattPassword = 137; // "Unattended action not possible without a password" ZE_Unknown = 138; // " Unknown error %d" ZE_Unsupported = 139; // "Unsupported zip version" ZE_WildName = 140; // "Wildcards are not allowed in Filename or file specification" ZE_WriteError = 141; // "Error writing file" ZE_WrongLength = 142; // "Wrong length" ZE_WrongPassword = 143; // "Error - passwords do NOT match\nPassword ignored" ZE_Zip64FieldError = 144; // "Error reading Zip64 field" ZE_ZipDataError = 145; // "Zip data error" ZE_ZipSeekError = 146; // "Seek error in Zip archive: %s" ZE_ZLib = 147; // "ZLib error: %d %s" ZE_ZZZ = 148; // "." ZS_Abort = 154; // "User Abort" ZS_Adding = 155; // " adding: %s" ZS_AddingAs = 156; // " adding: %s as %s" ZS_AnotherDisk = 157; // "This disk is part of a backup set,\nplease insert another disk" ZS_AskDeleteFile = 158; // "There is already a file %s\nDo you want to overwrite this file" ZS_AskPrevFile = 159; // "ATTENTION: This is previous disk no %d!!!\nAre you sure you want to overwrite the contents" ZS_Canceled = 160; // "User canceled operation" ZS_Confirm = 161; // "Confirm" ZS_CopyCentral = 162; // "Central directory" ZS_Copying = 163; // "Copying: %s" ZS_Deleting = 164; // "EraseFloppy - Deleting %s" ZS_DllLoaded = 165; // "Loaded %s" ZS_DllUnloaded = 166; // "Unloaded %s" ZS_Erase = 167; // "Erase %s" ZS_Erasing = 168; // "EraseFloppy - Removing %s" ZS_GetNewDisk = 169; // "GetNewDisk Opening: %s" ZS_InDrive = 170; // "\nin drive: %s" ZS_InsertAVolume = 171; // "Please insert disk volume %.1d" ZS_InsertDisk = 172; // "Please insert last disk" ZS_InsertVolume = 173; // "Please insert disk volume %.1d of %.1d" ZS_InvalidPath = 174; // "Invalid or illegal path" ZS_Keeping = 175; // "Keeping: '%s'" ZS_Skipped = 176; // "Skipped '%s' %d" ZS_TempZip = 177; // "Temporary zipfile: %s" ZS_Updating = 178; // "Updating: '%s' from '%s'" ZS_Zipping = 179; // "Zipping: %s" ZW_EOCCommentLen = 185; // "EOC comment length error" ZW_WrongZipStruct = 186; // "Warning - Error in zip structure!" ZZ_ZLibData = 187; // "ZLib Error: Data error" ZZ_ZLibFile = 188; // "ZLib Error: File error" ZZ_ZLibIncompatible = 189; // "ZLib Error: Incompatible version" ZZ_ZLibNoMem = 190; // "ZLib Error: Insufficient memory" ZZ_ZLibStream = 191; // "ZLib Error: Stream error" ZZ_ZLibUnknown = 192; // "ZLib Error: Unknown error" ZP_Archive = 198; // "*Resetting Archive bit" ZP_CopyZipFile = 199; // "*Copying Zip File" ZP_SFX = 200; // "*SFX" ZP_Header = 201; // "*??" ZP_Finish = 202; // "*Finalising" ZP_Copying = 203; // "*Copying" ZP_CentrlDir = 204; // "*Writing Central Directory" ZP_Checking = 205; // "*Checking" ZP_Loading = 206; // "*Loading Directory" ZP_Joining = 207; // "*Joining split zip file" ZP_Splitting = 208; // "*Splitting zip file" ZP_Writing = 209; // "*Writing zip file" ZP_PreCalc = 210; // "*Precalculating CRC" ZP_Processing = 211; // "*Processing" ZP_Merging = 212; // "*Merging" ZP_Zipping = 213; // "*Zipping" ZD_GOOD = 214; // "Good" ZD_CANCELLED = 215; // "Cancelled" ZD_ABORT = 216; // "Aborted by User!" ZD_CALLBACK = 217; // "Callback exception" ZD_MEMORY = 218; // "No memory" ZD_STRUCT = 219; // "Invalid structure" ZD_ERROR = 220; // "Fatal error" ZD_PASSWORD_FAIL = 221; // "Password failed!" ZD_PASSWORD_CANCEL = 222; // "Password cancelled!" ZD_INVAL_ZIP = 223; // "Invalid zip structure!" ZD_NO_CENTRAL = 224; // "No Central directory!" ZD_ZIP_EOF = 225; // "Unexpected end of Zip file!" ZD_ZIP_END = 226; // "Premature end of file!" ZD_ZIP_NOOPEN = 227; // "Error opening Zip file!" ZD_ZIP_MULTI = 228; // "Multi-part Zips not supported!" ZD_NOT_FOUND = 229; // "File not found!" ZD_LOGIC_ERROR = 230; // "Internal logic error!" ZD_NOTHING_TO_DO = 231; // "Nothing to do!" ZD_BAD_OPTIONS = 232; // "Bad Options specified!" ZD_TEMP_FAILED = 233; // "Temporary file failure!" ZD_NO_FILE_OPEN = 234; // "File not found or no permission!" ZD_ERROR_READ = 235; // "Error reading file!" ZD_ERROR_CREATE = 236; // "Error creating file!" ZD_ERROR_WRITE = 237; // "Error writing file!" ZD_ERROR_SEEK = 238; // "Error seeking in file!" ZD_EMPTY_ZIP = 239; // "Missing or empty zip file!" ZD_INVAL_NAME = 240; // "Invalid characters in filename!" ZD_GENERAL = 241; // "Error " ZD_MISS = 242; // "Nothing found" ZD_WARNING = 243; // "Warning: " ZD_ERROR_DELETE = 244; // "Delete failed" ZD_FATAL_IMPORT = 245; // "Fatal Error - could not import symbol!" ZD_SKIPPING = 246; // "Skipping: " ZD_LOCKED = 247; // "File locked" ZD_DENIED = 248; // "Access denied" ZD_DUPNAME = 249; // "Duplicate internal name" ZD_SKIPPED = 250; // "Skipped files" Const MSG_ID_MASK = $0FF; MAX_ID = 250; ZS_NoLanguage = 251; // names of compressed resource data const DZRES_Lng = 'DZResLng'; // compressed language strings DZRES_SFX = 'DZResSFX'; // stored UPX Dll version as string DZRES_Dll = 'DZResDll'; // stored UPX Dll // names of resource strings data const DZRES_Trace = 'DZResTrc'; // stored Trace message strings DZRES_Inform = 'DZResInf'; // stored Inform message strings DZRES_Defaults = 'DZResDef'; // stored Default message strings DZRES_Hashed = 'DZIdHash'; // stored identifier name hashes // Extended error codes // 0fFF FFFF LLLL LLLL LLLL mmTI EEEE EEEE {31 .. 0} // F _ file number [ 7 bits = 0..127] // L _ line number [12 bits = 0..4095] // m _ unused [ 2 bits = 0..3] // T _ Trace // I _ Inform // E _ error [ 8 bits = 0..255] const ZERR_UNIT_MASK_SHIFTED = $7FF; ZERR_LINE_MASK_SHIFTED = $FFF; ZERR_UNIT_SHIFTS = 24; ZERR_LINE_SHIFTS = 12; ZERR_UNIT_MASK = $7F000000; ZERR_LINE_MASK = $00FFF000; ZERR_ERROR_MASK = MSG_ID_MASK; ZERR_DIAG_MASK = $300; implementation end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 10/26/2004 10:51:40 PM JPMugaas Updated ref. Rev 1.4 7/6/2004 4:53:46 PM DSiders Corrected spelling of Challenge in properties, methods, types. Rev 1.3 2004.02.03 5:44:40 PM czhower Name changes Rev 1.2 2004.01.22 2:05:16 PM czhower TextIsSame Rev 1.1 1/21/2004 4:21:08 PM JPMugaas InitComponent Rev 1.0 11/13/2002 08:04:16 AM JPMugaas } unit IdUserAccounts; { Original Author: Sergio Perry Date: 24/04/2001 2002-05-03 - Andrew P.Rybin - TIdCustomUserManager,TIdSimpleUserManager,UserId - universal TIdUserManagerAuthenticationEvent> Sender: TObject } interface {$i IdCompilerDefines.inc} uses Classes, IdException, IdGlobal, IdBaseComponent, IdComponent, IdStrings; type TIdUserHandle = Cardinal;//ptr,object,collection.item.id or THandle TIdUserAccess = Integer; //<0-denied, >=0-accept; ex: 0-guest,1-user,2-power user,3-admin var IdUserHandleNone: TIdUserHandle = High(Cardinal)-1; //Special handle: empty handle IdUserHandleBroadcast: TIdUserHandle = High(Cardinal); //Special handle IdUserAccessDenied: TIdUserAccess = Low(Integer); //Special access type TIdCustomUserManagerOption = (umoCaseSensitiveUsername, umoCaseSensitivePassword); TIdCustomUserManagerOptions = set of TIdCustomUserManagerOption; TIdUserManagerAuthenticationEvent = procedure(Sender: TObject; {TIdCustomUserManager, TIdPeerThread, etc} const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess) of object; TIdUserManagerLogoffEvent = procedure(Sender: TObject; var VUserHandle: TIdUserHandle) of object; TIdCustomUserManager = class(TIdBaseComponent) protected FDomain: String; FOnAfterAuthentication: TIdUserManagerAuthenticationEvent; //3 FOnBeforeAuthentication: TIdUserManagerAuthenticationEvent;//1 FOnLogoffUser: TIdUserManagerLogoffEvent;//4 // procedure DoBeforeAuthentication(const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); virtual; // Descendants must override this method: procedure DoAuthentication (const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); virtual; abstract; procedure DoAfterAuthentication (const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); virtual; procedure DoLogoffUser(var VUserHandle: TIdUserHandle); virtual; function GetOptions: TIdCustomUserManagerOptions; virtual; procedure SetDomain(const AValue: String); virtual; procedure SetOptions(const AValue: TIdCustomUserManagerOptions); virtual; // props property Domain: String read FDomain write SetDomain; property Options: TIdCustomUserManagerOptions read GetOptions write SetOptions; // events property OnBeforeAuthentication: TIdUserManagerAuthenticationEvent read FOnBeforeAuthentication write FOnBeforeAuthentication; property OnAfterAuthentication: TIdUserManagerAuthenticationEvent read FOnAfterAuthentication write FOnAfterAuthentication; property OnLogoffUser: TIdUserManagerLogoffEvent read FOnLogoffUser write FOnLogoffUser; public //Challenge user is a nice backdoor for some things we will do in a descendent class function ChallengeUser(var VIsSafe : Boolean; const AUserName : String) : String; virtual; function AuthenticateUser(const AUsername, APassword: String): Boolean; overload; function AuthenticateUser(const AUsername, APassword: String; var VUserHandle: TIdUserHandle): TIdUserAccess; overload; class function IsRegisteredUser(AUserAccess: TIdUserAccess): Boolean; procedure LogoffUser(AUserHandle: TIdUserHandle); virtual; procedure UserDisconnected(const AUser : String); virtual; function SendsChallange : Boolean; virtual; End;//TIdCustomUserManager //============================================================================= // * TIdSimpleUserManager * //============================================================================= TIdSimpleUserManager = class(TIdCustomUserManager) protected FOptions: TIdCustomUserManagerOptions; FOnAuthentication: TIdUserManagerAuthenticationEvent; // procedure DoAuthentication (const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); override; function GetOptions: TIdCustomUserManagerOptions; override; procedure SetOptions(const AValue: TIdCustomUserManagerOptions); override; published property Domain; property Options; // events property OnBeforeAuthentication; property OnAuthentication: TIdUserManagerAuthenticationEvent read FOnAuthentication write FOnAuthentication; property OnAfterAuthentication; property OnLogoffUser; End;//TIdSimpleUserManager //============================================================================= // * TIdUserManager * //============================================================================= const IdUserAccountDefaultAccess = 0;//guest type TIdUserManager = class; TIdUserAccount = class(TCollectionItem) protected FAttributes: TStrings; FData: TObject; FUserName: string; FPassword: string; FRealName: string; FAccess: TIdUserAccess; // procedure SetAttributes(const AValue: TStrings); procedure SetPassword(const AValue: String); virtual; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; // function CheckPassword(const APassword: String): Boolean; virtual; // property Data: TObject read FData write FData; published property Access: TIdUserAccess read FAccess write FAccess default IdUserAccountDefaultAccess; property Attributes: TStrings read FAttributes write SetAttributes; property UserName: string read FUserName write FUserName; property Password: string read FPassword write SetPassword; property RealName: string read FRealName write FRealName; End;//TIdUserAccount TIdUserAccounts = class(TOwnedCollection) protected FCaseSensitiveUsernames: Boolean; FCaseSensitivePasswords: Boolean; // function GetAccount(const AIndex: Integer): TIdUserAccount; function GetByUsername(const AUsername: String): TIdUserAccount; procedure SetAccount(const AIndex: Integer; AAccountValue: TIdUserAccount); public function Add: TIdUserAccount; reintroduce; constructor Create(AOwner: TIdUserManager); // property CaseSensitiveUsernames: Boolean read FCaseSensitiveUsernames write FCaseSensitiveUsernames; property CaseSensitivePasswords: Boolean read FCaseSensitivePasswords write FCaseSensitivePasswords; property UserNames[const AUserName: String]: TIdUserAccount read GetByUsername; default; property Items[const AIndex: Integer]: TIdUserAccount read GetAccount write SetAccount; end;//TIdUserAccounts TIdUserManager = class(TIdCustomUserManager) protected FAccounts: TIdUserAccounts; // procedure DoAuthentication (const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); override; function GetOptions: TIdCustomUserManagerOptions; override; procedure SetAccounts(AValue: TIdUserAccounts); procedure SetOptions(const AValue: TIdCustomUserManagerOptions); override; procedure InitComponent; override; public destructor Destroy; override; published property Accounts: TIdUserAccounts read FAccounts write SetAccounts; property Options; // events property OnBeforeAuthentication; property OnAfterAuthentication; End;//TIdUserManager implementation uses SysUtils; { How add UserAccounts to your component: 1) property UserAccounts: TIdCustomUserManager read FUserAccounts write SetUserAccounts; 2) procedure SetUserAccounts(const AValue: TIdCustomUserManager); begin if FUserAccounts <> AValue then begin if Assigned(FUserAccounts) then begin FUserAccounts.RemoveFreeNotification(Self); end; FUserAccounts := AValue; if Assigned(FUserAccounts) then begin FUserAccounts.FreeNotification(Self); end; end; end; 3) procedure Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); ... if (Operation = opRemove) and (AComponent = FUserAccounts) then begin FUserAccounts := nil; end; end; 4) ... if Assigned(FUserAccounts) then begin FAuthenticated := FUserAccounts.AuthenticateUser(FUsername, ASender.UnparsedParams); if FAuthenticated then else } { TIdCustomUserManager } function TIdCustomUserManager.AuthenticateUser(const AUsername, APassword: String): Boolean; var LUserHandle: TIdUserHandle; Begin Result := IsRegisteredUser(AuthenticateUser(AUsername, APassword, LUserHandle)); LogoffUser(LUserHandle); End;//AuthenticateUser function TIdCustomUserManager.AuthenticateUser(const AUsername, APassword: String; var VUserHandle: TIdUserHandle): TIdUserAccess; var LPassword: String; Begin LPassword := APassword; VUserHandle := IdUserHandleNone; Result := IdUserAccessDenied; DoBeforeAuthentication(AUsername, LPassword, VUserHandle, Result); DoAuthentication(AUsername, LPassword, VUserHandle, Result); DoAfterAuthentication(AUsername, LPassword, VUserHandle, Result); End;// class function TIdCustomUserManager.IsRegisteredUser(AUserAccess: TIdUserAccess): Boolean; Begin Result := AUserAccess>=0; End; procedure TIdCustomUserManager.DoBeforeAuthentication(const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); Begin if Assigned(FOnBeforeAuthentication) then begin FOnBeforeAuthentication(SELF,AUsername,VPassword,VUserHandle,VUserAccess); end; End;// procedure TIdCustomUserManager.DoAfterAuthentication(const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); Begin if Assigned(FOnAfterAuthentication) then begin FOnAfterAuthentication(SELF,AUsername,VPassword,VUserHandle,VUserAccess); end; End;// function TIdCustomUserManager.GetOptions: TIdCustomUserManagerOptions; Begin Result := []; End;// procedure TIdCustomUserManager.SetOptions(const AValue: TIdCustomUserManagerOptions); Begin End; procedure TIdCustomUserManager.SetDomain(const AValue: String); begin if FDomain<>AValue then begin FDomain := AValue; end; end; procedure TIdCustomUserManager.LogoffUser(AUserHandle: TIdUserHandle); Begin DoLogoffUser(AUserHandle); End;//free resources, unallocate handles, etc... //============================================================================= procedure TIdCustomUserManager.DoLogoffUser(var VUserHandle: TIdUserHandle); Begin if Assigned(FOnLogoffUser) then begin FOnLogoffUser(SELF, VUserHandle); end; End;// function TIdCustomUserManager.ChallengeUser(var VIsSafe : Boolean; const AUserName: String): String; begin VIsSafe := True; Result := ''; end; procedure TIdCustomUserManager.UserDisconnected(const AUser: String); begin end; function TIdCustomUserManager.SendsChallange : Boolean; begin Result := False; end; { TIdUserAccount } function TIdUserAccount.CheckPassword(const APassword: String): Boolean; begin if (Collection as TIdUserAccounts).CaseSensitivePasswords then begin Result := Password = APassword; end else begin Result := TextIsSame(Password, APassword); end; end; constructor TIdUserAccount.Create(ACollection: TCollection); begin inherited Create(ACollection); FAttributes := TStringList.Create; FAccess := IdUserAccountDefaultAccess; end; destructor TIdUserAccount.Destroy; begin FreeAndNil(FAttributes); inherited Destroy; end; procedure TIdUserAccount.SetAttributes(const AValue: TStrings); begin FAttributes.Assign(AValue); end; procedure TIdUserAccount.SetPassword(const AValue: String); begin FPassword := AValue; end; { TIdUserAccounts } constructor TIdUserAccounts.Create(AOwner: TIdUserManager); begin inherited Create(AOwner, TIdUserAccount); end; function TIdUserAccounts.GetAccount(const AIndex: Integer): TIdUserAccount; begin Result := TIdUserAccount(inherited Items[AIndex]); end; function TIdUserAccounts.GetByUsername(const AUsername: String): TIdUserAccount; var i: Integer; begin Result := nil; if CaseSensitiveUsernames then begin for i := 0 to Count - 1 do begin if AUsername = Items[i].UserName then begin Result := Items[i]; Break; end; end; end else begin for i := 0 to Count - 1 do begin if TextIsSame(AUsername, Items[i].UserName) then begin Result := Items[i]; Break; end; end; end; end; procedure TIdUserAccounts.SetAccount(const AIndex: Integer; AAccountValue: TIdUserAccount); begin inherited SetItem(AIndex, AAccountValue); end; function TIdUserAccounts.Add: TIdUserAccount; begin Result := inherited Add as TIdUserAccount; end; { IdUserAccounts - Main Component } procedure TIdUserManager.InitComponent; begin inherited; FAccounts := TIdUserAccounts.Create(Self); end; destructor TIdUserManager.Destroy; begin FreeAndNil(FAccounts); inherited Destroy; end; procedure TIdUserManager.DoAuthentication(const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); var LUser: TIdUserAccount; begin VUserHandle := IdUserHandleNone; VUserAccess := IdUserAccessDenied; LUser := Accounts[AUsername]; if Assigned(LUser) then begin if LUser.CheckPassword(VPassword) then begin VUserHandle := LUser.ID; VUserAccess := LUser.Access; end; end; end; procedure TIdUserManager.SetAccounts(AValue: TIdUserAccounts); begin FAccounts.Assign(AValue); end; function TIdUserManager.GetOptions: TIdCustomUserManagerOptions; Begin Result := []; if FAccounts.CaseSensitiveUsernames then begin Include(Result, umoCaseSensitiveUsername); end; if FAccounts.CaseSensitivePasswords then begin Include(Result, umoCaseSensitivePassword); end; End;// procedure TIdUserManager.SetOptions(const AValue: TIdCustomUserManagerOptions); Begin FAccounts.CaseSensitiveUsernames := umoCaseSensitiveUsername in AValue; FAccounts.CaseSensitivePasswords := umoCaseSensitivePassword in AValue; End;// { TIdSimpleUserManager } procedure TIdSimpleUserManager.DoAuthentication(const AUsername: String; var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); Begin if Assigned(FOnAuthentication) then begin FOnAuthentication(SELF,AUsername,VPassword,VUserHandle,VUserAccess); end; End;// function TIdSimpleUserManager.GetOptions: TIdCustomUserManagerOptions; Begin Result := FOptions; End;// procedure TIdSimpleUserManager.SetOptions( const AValue: TIdCustomUserManagerOptions); Begin FOptions := AValue; End;// end.
{$I ACBr.inc} unit pciotOperacaoTransporteW; interface uses SysUtils, Classes, pcnAuxiliar, pcnConversao, pciotCIOT, ASCIOTUtil; type TGeradorOpcoes = class; TOperacaoTransporteW = class(TPersistent) private FGerador: TGerador; FOperacaoTransporte: TOperacaoTransporte; FOperacao: TpciotOperacao; FOpcoes: TGeradorOpcoes; public constructor Create(AOwner: TOperacaoTransporte; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function GerarXML: boolean; published property Gerador: TGerador read FGerador write FGerador; property OperacaoTransporte: TOperacaoTransporte read FOperacaoTransporte write FOperacaoTransporte; property Opcoes: TGeradorOpcoes read FOpcoes write FOpcoes; end; TGeradorOpcoes = class(TPersistent) private FAjustarTagNro: boolean; FNormatizarMunicipios: boolean; FGerarTagAssinatura: TpcnTagAssinatura; FPathArquivoMunicipios: string; FValidarInscricoes: boolean; FValidarListaServicos: boolean; published property AjustarTagNro: boolean read FAjustarTagNro write FAjustarTagNro; property NormatizarMunicipios: boolean read FNormatizarMunicipios write FNormatizarMunicipios; property GerarTagAssinatura: TpcnTagAssinatura read FGerarTagAssinatura write FGerarTagAssinatura; property PathArquivoMunicipios: string read FPathArquivoMunicipios write FPathArquivoMunicipios; property ValidarInscricoes: boolean read FValidarInscricoes write FValidarInscricoes; property ValidarListaServicos: boolean read FValidarListaServicos write FValidarListaServicos; end; implementation { TOperacaoTransporteW } uses ASCIOT; constructor TOperacaoTransporteW.Create(AOwner: TOperacaoTransporte; AOperacao: TpciotOperacao); begin FOperacaoTransporte := AOwner; FOperacao := AOperacao; FGerador := TGerador.Create; FGerador.FIgnorarTagNivel := '|?xml version|CTe xmlns|infCTe versao|obsCont|obsFisco|'; FOpcoes := TGeradorOpcoes.Create; FOpcoes.FAjustarTagNro := True; FOpcoes.FNormatizarMunicipios := False; FOpcoes.FGerarTagAssinatura := taSomenteSeAssinada; FOpcoes.FValidarInscricoes := False; FOpcoes.FValidarListaServicos := False; end; destructor TOperacaoTransporteW.Destroy; begin FGerador.Free; FOpcoes.Free; inherited Destroy; end; function TOperacaoTransporteW.GerarXML: boolean; var chave: AnsiString; Gerar: boolean; xProtCTe : String; I, J: integer; begin Gerador.Opcoes.IdentarXML := True; Gerador.Opcoes.TagVaziaNoFormatoResumido := False; Gerador.ArquivoFormatoXML := ''; case FOperacao of opObter: begin Gerador.wGrupo('ObterOperacaoTransportePdfRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wTexto('<Integrador ' + NAME_SPACE_EFRETE_OBJECTS + '>' + TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao + '</Integrador>'); Gerador.wTexto('<Versao ' + NAME_SPACE_EFRETE_OBJECTS + '>1</Versao>'); Gerador.wCampo(tcStr, '', 'CodigoIdentificacaoOperacao', 001, 030, 1, FOperacaoTransporte.NumeroCIOT, ''); // <DocumentoViagem>string</DocumentoViagem> //caso seja TAC Agregado Gerador.wGrupo('/ObterOperacaoTransportePdfRequest'); end; opAdicionar: begin Gerador.wGrupo('AdicionarOperacaoTransporteRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP01'); Gerador.wCampo(tcStr, 'AP77', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP131', 'Versao', 001, 001, 1, 3, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP02', 'CodigoIdentificacaoOperacaoPrincipal', 001, 001, 1, FOperacaoTransporte.CodigoIdentificacaoOperacaoPrincipal, ''); if FOperacaoTransporte.TipoViagem = Padrao then Gerador.wCampo(tcInt, 'AP03', 'CodigoNCMNaturezaCarga', 001, 004, 1, FOperacaoTransporte.CodigoNCMNaturezaCarga); //0001 if FOperacaoTransporte.Consignatario.CpfOuCnpj <> '' then begin Gerador.wGrupo('Consignatario', 'AP04'); Gerador.wCampo(tcStr, 'AP05', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Consignatario.CpfOuCnpj, 'CPF ou CNPJ do Consignatário'); Gerador.wCampo(tcStr, 'AP06', 'EMail', 001, 001, 1, FOperacaoTransporte.Consignatario.EMail, 'Email do consignatário.'); with FOperacaoTransporte.Consignatario do begin Gerador.wGrupo('Endereco', 'AP07'); Gerador.wCampo(tcStr, 'AP08', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP09', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP10', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP11', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP12', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP13', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'AP14', 'Nome', 001, 001, 1, FOperacaoTransporte.Consignatario.NomeOuRazaoSocial, 'Nome ou Razão Social do Consignatário.'); Gerador.wCampo(tcStr, 'AP15', 'ResponsavelPeloPagamento', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.Consignatario.ResponsavelPeloPagamento, true)), 'Informar se é o responsável pelo pagamento da Operação de Transporte. True = Sim. False = Não'); with FOperacaoTransporte.Consignatario.Telefones do begin Gerador.wGrupo('Telefones', 'AP16'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'AP17'); Gerador.wCampo(tcInt, 'AP18', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'AP19', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'AP20'); Gerador.wCampo(tcInt, 'AP21', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'AP22', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'AP23'); Gerador.wCampo(tcInt, 'AP24', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'AP25', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/Consignatario'); end else Gerador.wCampo(tcStr, 'AP04', 'Consignatario', 001, 001, 1, ''); {TomadorServico} if FOperacaoTransporte.TomadorServico.CpfOuCnpj <> '' then begin Gerador.wGrupo('TomadorServico', 'AP178'); Gerador.wCampo(tcStr, 'AP179', 'NomeOuRazaoSocial', 001, 001, 1, FOperacaoTransporte.TomadorServico.NomeOuRazaoSocial, 'Nome ou Razão Social do Tomador.'); Gerador.wCampo(tcStr, 'AP180', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.TomadorServico.CpfOuCnpj, 'CPF ou CNPJ do Tomador'); with FOperacaoTransporte.TomadorServico do begin Gerador.wGrupo('Endereco', 'AP181'); Gerador.wCampo(tcStr, 'AP182', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP183', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP184', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP185', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP186', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP187', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'AP188', 'EMail', 001, 001, 1, FOperacaoTransporte.TomadorServico.EMail, 'Email do Tomador.'); //Gerador.wCampo(tcStr, 'AP189', 'ResponsavelPeloPagamento', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.TomadorServico.ResponsavelPeloPagamento, true)), 'O Tomador é slçidário ao Contratante ao pagamento do TAC, não sendo necessário o preenchimento desse campo'); with FOperacaoTransporte.TomadorServico.Telefones do begin Gerador.wGrupo('Telefones', 'AP190'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'AP191'); Gerador.wCampo(tcInt, 'AP192', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'AP193', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'AP194'); Gerador.wCampo(tcInt, 'AP195', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'AP196', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'AP197'); Gerador.wCampo(tcInt, 'AP198', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'AP199', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/TomadorServico'); end else Gerador.wCampo(tcStr, 'AP178', 'TomadorServico', 001, 001, 1, ''); Gerador.wGrupo('Contratado ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP26'); Gerador.wCampo(tcStr, 'AP27', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Contratado.CpfOuCnpj, ''); Gerador.wCampo(tcStr, 'AP28', 'RNTRC', 001, 001, 1, FOperacaoTransporte.Contratado.RNTRC, ''); Gerador.wGrupo('/Contratado'); Gerador.wGrupo('Contratante', 'AP29'); Gerador.wCampo(tcStr, 'AP30', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Contratante.CpfOuCnpj); Gerador.wCampo(tcStr, 'AP31', 'EMail', 001, 001, 1, FOperacaoTransporte.Contratante.EMail); with FOperacaoTransporte.Contratante do begin Gerador.wGrupo('Endereco', 'AP32'); Gerador.wCampo(tcStr, 'AP33', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP34', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP35', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP36', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP37', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP38', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'AP39', 'NomeOuRazaoSocial', 001, 001, 1, FOperacaoTransporte.Contratante.NomeOuRazaoSocial, 'Nome ou Razão Social do Contratante.'); Gerador.wCampo(tcStr, 'AP40', 'ResponsavelPeloPagamento', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.Contratante.ResponsavelPeloPagamento, true)), 'Informar se é o responsável pelo pagamento da Operação de Transporte. True = Sim. False = Não'); with FOperacaoTransporte.Consignatario.Telefones do begin Gerador.wGrupo('Telefones', 'AP41'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'AP42'); Gerador.wCampo(tcInt, 'AP43', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'AP44', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'AP45'); Gerador.wCampo(tcInt, 'AP46', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'AP47', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'AP48'); Gerador.wCampo(tcInt, 'AP49', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'AP50', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wCampo(tcStr, '', 'RNTRC', 001, 001, 1, FOperacaoTransporte.Contratante.RNTRC); Gerador.wGrupo('/Contratante'); Gerador.wCampo(tcDat, 'AP51', 'DataFimViagem', 001, 001, 1, FOperacaoTransporte.DataFimViagem, 'Data prevista para o fim de viagem.'); if FOperacaoTransporte.TipoViagem = Padrao then begin Gerador.wCampo(tcDat, 'AP52', 'DataInicioViagem', 001, 001, 1, FOperacaoTransporte.DataInicioViagem, 'Data de início da viagem. Operação do tipo 1 seu preenchimento é obrigatório.'); Gerador.wGrupo('Destinatario', 'AP53'); Gerador.wCampo(tcStr, 'AP54', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Destinatario.CpfOuCnpj); Gerador.wCampo(tcStr, 'AP55', 'EMail', 001, 001, 1, FOperacaoTransporte.Destinatario.EMail); with FOperacaoTransporte.Destinatario do begin Gerador.wGrupo('Endereco', 'AP56'); Gerador.wCampo(tcStr, 'AP57', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP58', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP59', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP60', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP61', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP62', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'AP63', 'NomeOuRazaoSocial', 001, 001, 1, FOperacaoTransporte.Destinatario.NomeOuRazaoSocial, 'Nome ou Razão Social do Contratante.'); Gerador.wCampo(tcStr, 'AP64', 'ResponsavelPeloPagamento', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.Destinatario.ResponsavelPeloPagamento, true)), 'Informar se é o responsável pelo pagamento da Operação de Transporte. True = Sim. False = Não'); with FOperacaoTransporte.Destinatario.Telefones do begin Gerador.wGrupo('Telefones', 'AP65'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'AP66'); Gerador.wCampo(tcInt, 'AP67', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'AP68', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'AP69'); Gerador.wCampo(tcInt, 'AP70', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'AP71', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'AP72'); Gerador.wCampo(tcInt, 'AP73', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'AP74', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/Destinatario'); end; Gerador.wCampo(tcStr, 'AP75', 'FilialCNPJ', 001, 001, 1, FOperacaoTransporte.FilialCNPJ, 'CPNJ da filial do Contratante, que está realizando a operação de transporte, se necessário.'); Gerador.wCampo(tcStr, 'AP76', 'IdOperacaoCliente', 001, 001, 1, FOperacaoTransporte.IdOperacaoCliente, 'Id / Chave primária da operação de transporte no sistema do Cliente.'); Gerador.wGrupo('Impostos', 'AP78'); Gerador.wCampo(tcStr, 'AP79', 'DescricaoOutrosImpostos', 001, 001, 1, FOperacaoTransporte.Impostos.DescricaoOutrosImpostos); Gerador.wCampo(tcDe2, 'AP80', 'INSS', 001, 020, 1, FOperacaoTransporte.Impostos.INSS, 'Valor destinado ao INSS. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP81', 'IRRF', 001, 020, 1, FOperacaoTransporte.Impostos.IRRF, 'Valor destinado ao IRRF. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP82', 'ISSQN', 001, 020, 1, FOperacaoTransporte.Impostos.ISSQN, 'Valor destinado ao ISSQN. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP83', 'OutrosImpostos', 001, 020, 1, FOperacaoTransporte.Impostos.OutrosImpostos, 'Valor destinado a outros impostos não previstos. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP84', 'SestSenat', 001, 020, 1, FOperacaoTransporte.Impostos.SestSenat, 'Valor destinado ao SEST / SENAT. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wGrupo('/Impostos'); Gerador.wCampo(tcStr, 'AP85', 'MatrizCNPJ', 001, 001, 1, FOperacaoTransporte.MatrizCNPJ, 'CNPJ da Matriz da Transportadora.'); Gerador.wGrupo('Motorista ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP86'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP87'); with FOperacaoTransporte.Motorista do begin Gerador.wCampo(tcInt, 'AP88', 'DDD', 001, 002, 1, Celular.DDD, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcInt, 'AP89', 'Numero', 001, 009, 1, Celular.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); end; Gerador.wGrupo('/Celular'); Gerador.wCampo(tcStr, 'AP90', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Motorista.CpfOuCnpj, 'CPF ou CNPJ do Motorista.'); Gerador.wCampo(tcInt, 'AP', 'CNH', 001, 007, 1, FOperacaoTransporte.Motorista.CNH, ''); Gerador.wGrupo('/Motorista'); if FOperacaoTransporte.TipoViagem = Padrao then begin for I := 0 to FOperacaoTransporte.Pagamentos.Count -1 do begin with FOperacaoTransporte.Pagamentos.Items[I] do begin Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP91'); //Pagamentos registrados. - Pode existir mais de 1 pagamento com uma mesma categoria (exceto para Quitacao). - A soma dos pagamentos c/ categoria Adiantamento, deverá ter o mesmo valor apontado na tag TotalAdiantamento da tag Viagem/Valores, e neste caso, a tag Documento do pagamento deverá conter o mesmo valor da tag DocumentoViagem da tag Viagem . - Se a viagem possuir a tag TotalQuitacao maior que zero, deverá ter um pagamento correspondente, com Categoria Quitacao e com o Documento o mesmo valor apontado na tag DocumentoViagem . Gerador.wCampo(tcStr, 'AP92', 'Categoria', 001, 001, 1, TpCatPagToStr(Categoria), 'Categoria relacionada ao pagamento realizado. Restrita aos membros da ENUM: -Adiantamento, -Estadia, Quitacao, -SemCategoria ', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDat, 'AP93', 'DataDeLiberacao', 001, 001, 1, DataDeLiberacao); Gerador.wCampo(tcStr, 'AP94', 'Documento', 001, 020, 1, Documento, 'Documento relacionado a viagem.'); Gerador.wCampo(tcStr, 'AP94', 'IdPagamentoCliente', 001, 020, 1, IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); Gerador.wCampo(tcStr, 'AP95', 'InformacaoAdicional', 001, 000, 0, InformacaoAdicional, ''); Gerador.wGrupo('InformacoesBancarias ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP97'); with InformacoesBancarias do begin Gerador.wCampo(tcStr, 'AP98', 'Agencia', 001, 001, 1, Agencia); Gerador.wCampo(tcStr, 'AP99', 'Conta', 001, 001, 1, Conta); Gerador.wCampo(tcStr, 'AP100', 'InstituicaoBancaria', 001, 001, 1, InstituicaoBancaria); end; Gerador.wGrupo('/InformacoesBancarias'); Gerador.wCampo(tcStr, 'AP101', 'TipoPagamento', 001, 020, 1, TpPagamentoToStr(TipoPagamento), 'Tipo de pagamento que será usado pelo contratante. Restrito aos itens da enum: -TransferenciaBancaria -eFRETE', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDe2, 'AP102', 'Valor', 001, 020, 1, Valor, 'Valor do pagamento.'); Gerador.wGrupo('/Pagamentos'); end; end; end; // if FOperacaoTransporte.TipoViagem = Padrao then if (FOperacaoTransporte.PesoCarga > 0) and (FOperacaoTransporte.TipoViagem = Padrao) then Gerador.wCampo(tcDe6, 'AP103', 'PesoCarga', 001, 001, 1, FOperacaoTransporte.PesoCarga, 'Peso total da carga.'); // else // Gerador.wCampo(tcStr, 'AP103', 'PesoCarga', 001, 001, 1, '', 'Peso total da carga.'); Gerador.wCampo(tcStr, 'AP104', 'TipoEmbalagem', 001, 001, 1, TpCiotTipoEmbalagemToStr(FOperacaoTransporte.TipoEmbalagem)); if FOperacaoTransporte.Subcontratante.CpfOuCnpj <> '' then begin Gerador.wGrupo('Subcontratante', 'AP105'); Gerador.wCampo(tcStr, 'AP106', 'CpfOuCnpj', 001, 001, 1, FOperacaoTransporte.Subcontratante.CpfOuCnpj); Gerador.wCampo(tcStr, 'AP107', 'EMail', 001, 001, 1, FOperacaoTransporte.Subcontratante.EMail); with FOperacaoTransporte.Subcontratante do begin Gerador.wGrupo('Endereco', 'AP108'); Gerador.wCampo(tcStr, 'AP109', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP110', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP111', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP112', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP113', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'AP114', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'AP115', 'NomeOuRazaoSocial', 001, 001, 1, FOperacaoTransporte.Subcontratante.NomeOuRazaoSocial, 'Nome ou Razão Social do Contratante.'); Gerador.wCampo(tcStr, 'AP116', 'ResponsavelPeloPagamento', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.Subcontratante.ResponsavelPeloPagamento, true)), 'Informar se é o responsável pelo pagamento da Operação de Transporte. True = Sim. False = Não'); with FOperacaoTransporte.Subcontratante.Telefones do begin Gerador.wGrupo('Telefones', 'AP117'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'AP118'); Gerador.wCampo(tcInt, 'AP119', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'AP120', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'AP121'); Gerador.wCampo(tcInt, 'AP122', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'AP123', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'AP124'); Gerador.wCampo(tcInt, 'AP125', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'AP126', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/Subcontratante'); end else Gerador.wCampo(tcStr, 'AP104', 'Subcontratante', 001, 001, 1, ''); Gerador.wCampo(tcStr, 'AP127', 'TipoViagem', 001, 001, 1, TpViagemToStr(FOperacaoTransporte.TipoViagem), 'Restrito aos itens da enum: -SemVinculoANTT -Padrao -TAC_Agregado'); Gerador.wGrupo('Veiculos ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP129'); for I := 0 to FOperacaoTransporte.Veiculos.Count -1 do begin with FOperacaoTransporte.Veiculos.Items[I] do Gerador.wCampo(tcStr, 'AP130', 'Placa', 001, 001, 1, Placa, 'Placa do veículo conforme exemplo: AAA1234.'); end; Gerador.wGrupo('/Veiculos'); if FOperacaoTransporte.TipoViagem = Padrao then begin Gerador.wGrupo('Viagens ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP132'); for I := 0 to FOperacaoTransporte.Viagens.Count -1 do begin with FOperacaoTransporte.Viagens.Items[I] do begin Gerador.wCampo(tcInt, 'AP133', 'CodigoMunicipioDestino', 001, 007, 1, CodigoMunicipioDestino); Gerador.wCampo(tcInt, 'AP134', 'CodigoMunicipioOrigem', 001, 007, 1, CodigoMunicipioOrigem); Gerador.wCampo(tcStr, 'AP135', 'DocumentoViagem', 001, 001, 1, DocumentoViagem, 'Exemplo: CT-e / Serie, CTRC / Serie, Ordem de Serviço.'); Gerador.wGrupo('NotasFiscais', 'AP136'); for J := 0 to NotasFiscais.Count -1 do begin with NotasFiscais.Items[J] do begin Gerador.wGrupo('NotaFiscal'); Gerador.wCampo(tcInt, 'AP137', 'CodigoNCMNaturezaCarga', 001, 004, 1, CodigoNCMNaturezaCarga); Gerador.wCampo(tcDat, 'AP138', 'Data', 001, 004, 1, Data); Gerador.wCampo(tcStr, 'AP139', 'DescricaoDaMercadoria', 001, 060, 1, DescricaoDaMercadoria, 'Descrição adicional ao código NCM.'); Gerador.wCampo(tcStr, 'AP140', 'Numero', 001, 010, 1, Numero); Gerador.wCampo(tcDe3, 'AP141', 'QuantidadeDaMercadoriaNoEmbarque', 001, 010, 1, QuantidadeDaMercadoriaNoEmbarque); Gerador.wCampo(tcStr, 'AP142', 'Serie', 001, 001, 1, Serie); Gerador.wCampo(tcStr, 'AP143', 'TipoDeCalculo', 001, 001, 1, TpVgTipoCalculoToStr(TipoDeCalculo)); Gerador.wGrupo('ToleranciaDePerdaDeMercadoria', 'AP144'); Gerador.wCampo(tcStr, 'AP145', 'Tipo', 001, 001, 1, TpProporcaoToStr(ToleranciaDePerdaDeMercadoria.Tipo)); Gerador.wCampo(tcDe2, 'AP146', 'Valor', 001, 001, 1, ToleranciaDePerdaDeMercadoria.Valor); Gerador.wGrupo('/ToleranciaDePerdaDeMercadoria'); if DiferencaDeFrete.Tipo <> SemDiferenca then begin Gerador.wGrupo('DiferencaDeFrete', 'AP147'); Gerador.wCampo(tcStr, 'AP148', 'Tipo', 001, 001, 1, TpDifFreteToStr(DiferencaDeFrete.Tipo)); Gerador.wCampo(tcStr, 'AP149', 'Base', 001, 001, 1, TpDiferencaFreteBCToStr(DiferencaDeFrete.Base)); Gerador.wGrupo('Tolerancia', 'AP150'); Gerador.wCampo(tcStr, 'AP151', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.Tolerancia.Tipo)); Gerador.wCampo(tcDe2, 'AP152', 'Valor', 001, 001, 1, DiferencaDeFrete.Tolerancia.Valor); Gerador.wGrupo('/Tolerancia'); Gerador.wGrupo('MargemGanho', 'AP153'); Gerador.wCampo(tcStr, 'AP154', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemGanho.Tipo)); Gerador.wCampo(tcDe2, 'AP155', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemGanho.Valor); Gerador.wGrupo('/MargemGanho'); Gerador.wGrupo('MargemPerda', 'AP156'); Gerador.wCampo(tcStr, 'AP157', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemPerda.Tipo)); Gerador.wCampo(tcDe2, 'AP158', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemPerda.Valor); Gerador.wGrupo('/MargemPerda'); Gerador.wGrupo('/DiferencaDeFrete'); end; Gerador.wCampo(tcStr, 'AP159', 'UnidadeDeMedidaDaMercadoria', 001, 001, 1, TpUnMedMercToStr(UnidadeDeMedidaDaMercadoria)); Gerador.wCampo(tcDe2, 'AP159', 'ValorDaMercadoriaPorUnidade', 001, 001, 1, ValorDaMercadoriaPorUnidade); Gerador.wCampo(tcDe2, 'AP159', 'ValorDoFretePorUnidadeDeMercadoria', 001, 001, 1, ValorDoFretePorUnidadeDeMercadoria); Gerador.wCampo(tcDe2, 'AP159', 'ValorTotal', 001, 001, 1, ValorTotal); Gerador.wGrupo('/NotaFiscal'); end; end; Gerador.wGrupo('/NotasFiscais'); Gerador.wGrupo('Valores ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP163'); with Valores do begin Gerador.wCampo(tcDe2, 'AP164', 'Combustivel', 001, 001, 1, Combustivel); Gerador.wCampo(tcStr, 'AP165', 'JustificativaOutrosCreditos', 001, 001, 1, JustificativaOutrosCreditos); Gerador.wCampo(tcStr, 'AP166', 'JustificativaOutrosDebitos', 001, 001, 1, JustificativaOutrosDebitos); Gerador.wCampo(tcDe2, 'AP167', 'OutrosCreditos', 001, 001, 1, OutrosCreditos); Gerador.wCampo(tcDe2, 'AP168', 'OutrosDebitos', 001, 001, 1, OutrosDebitos); Gerador.wCampo(tcDe2, 'AP169', 'Pedagio', 001, 001, 1, Pedagio); Gerador.wCampo(tcDe2, 'AP170', 'Seguro', 001, 001, 1, Seguro); Gerador.wCampo(tcDe2, 'AP171', 'TotalDeAdiantamento', 001, 001, 1, TotalDeAdiantamento); Gerador.wCampo(tcDe2, 'AP172', 'TotalDeQuitacao', 001, 001, 1, TotalDeQuitacao); Gerador.wCampo(tcDe2, 'AP173', 'TotalOperacao', 001, 001, 1, TotalOperacao); Gerador.wCampo(tcDe2, 'AP174', 'TotalViagem', 001, 001, 1, TotalViagem); end; Gerador.wGrupo('/Valores'); end; end; Gerador.wGrupo('/Viagens'); end; Gerador.wCampo(tcStr, 'AP175', 'EmissaoGratuita', 001, 001, 1, LowerCase(BoolToStr(FOperacaoTransporte.EmissaoGratuita, True))); Gerador.wCampo(tcStr, 'AP176', 'ObservacoesAoTransportador', 001, 001, 1, FOperacaoTransporte.ObservacoesAoTransportador); Gerador.wCampo(tcStr, 'AP177', 'ObservacoesAoCredenciado', 001, 001, 1, FOperacaoTransporte.ObservacoesAoCredenciado); Gerador.wGrupo('/AdicionarOperacaoTransporteRequest'); end; opRetificar: begin Gerador.wGrupo('RetificarOperacaoTransporteRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'WP01'); Gerador.wCampo(tcStr, 'WP08', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'WP13', 'Versao', 001, 001, 1, 1, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'WP02', 'CodigoIdentificacaoOperacao', 001, 001, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wCampo(tcInt, 'WP03', 'CodigoMunicipioDestino', 001, 007, 1, FOperacaoTransporte.Viagens.Items[0].CodigoMunicipioDestino); //0001 Gerador.wCampo(tcInt, 'WP04', 'CodigoMunicipioOrigem', 001, 007, 1, FOperacaoTransporte.Viagens.Items[0].CodigoMunicipioOrigem); //0001 Gerador.wCampo(tcInt, 'WP05', 'CodigoNCMNaturezaCarga', 001, 004, 1, FOperacaoTransporte.CodigoNCMNaturezaCarga); //0001 Gerador.wCampo(tcDat, 'WP06', 'DataFimViagem', 001, 001, 1, FOperacaoTransporte.DataFimViagem); //0001 Gerador.wCampo(tcDat, 'WP07', 'DataInicioViagem', 001, 001, 1, FOperacaoTransporte.DataInicioViagem); //0001 Gerador.wCampo(tcDe6, 'WP09', 'PesoCarga', 001, 001, 1, FOperacaoTransporte.PesoCarga); //0001 Gerador.wGrupo('Veiculos ' + NAME_SPACE_EFRETE_PEFRETIFICAR_OBJECTS, 'WP11'); for I := 0 to FOperacaoTransporte.Veiculos.Count -1 do begin with FOperacaoTransporte.Veiculos.Items[I] do Gerador.wCampo(tcStr, 'WP12', 'Placa', 001, 001, 1, Placa, 'Placa do veículo conforme exemplo: AAA1234.'); end; Gerador.wGrupo('/Veiculos'); Gerador.wGrupo('/RetificarOperacaoTransporteRequest'); end; opCancelar: begin Gerador.wGrupo('CancelarOperacaoTransporteRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'KP01'); Gerador.wCampo(tcStr, 'KP03', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'KP06', 'Versao', 001, 001, 1, 1, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'KP02', 'CodigoIdentificacaoOperacao', 001, 001, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wCampo(tcStr, 'KP04', 'Motivo', 001, 001, 1, FOperacaoTransporte.Cancelamento.Motivo, ''); Gerador.wGrupo('/CancelarOperacaoTransporteRequest'); end; opAdicionarViagem: begin if FOperacaoTransporte.TipoViagem = TAC_Agregado then begin Gerador.wGrupo('AdicionarViagemRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcStr, '', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'Versao', 001, 001, 1, 2, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'CodigoIdentificacaoOperacao', 001, 030, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wGrupo('Viagens ' + NAME_SPACE_EFRETE_PEFADICIONAR_VIAGEM, ''); for I := 0 to FOperacaoTransporte.Viagens.Count -1 do begin Gerador.wGrupo('Viagem'); with FOperacaoTransporte.Viagens.Items[I] do begin Gerador.wCampo(tcInt, 'AP133', 'CodigoMunicipioDestino', 001, 007, 1, CodigoMunicipioDestino); Gerador.wCampo(tcInt, 'AP134', 'CodigoMunicipioOrigem', 001, 007, 1, CodigoMunicipioOrigem); Gerador.wCampo(tcStr, 'AP135', 'DocumentoViagem', 001, 001, 1, DocumentoViagem, 'Exemplo: CT-e / Serie, CTRC / Serie, Ordem de Serviço.'); // Gerador.wGrupo('NotasFiscais', 'AP136'); for J := 0 to NotasFiscais.Count -1 do begin with NotasFiscais.Items[J] do begin Gerador.wGrupo('NotasFiscais'); Gerador.wCampo(tcInt, 'AP137', 'CodigoNCMNaturezaCarga', 001, 004, 1, CodigoNCMNaturezaCarga); Gerador.wCampo(tcDat, 'AP138', 'Data', 001, 004, 1, Data); Gerador.wCampo(tcStr, 'AP139', 'DescricaoDaMercadoria', 001, 060, 1, DescricaoDaMercadoria, 'Descrição adicional ao código NCM.'); Gerador.wCampo(tcStr, 'AP140', 'Numero', 001, 010, 1, Numero); Gerador.wCampo(tcDe3, 'AP141', 'QuantidadeDaMercadoriaNoEmbarque', 001, 010, 1, QuantidadeDaMercadoriaNoEmbarque); Gerador.wCampo(tcStr, 'AP142', 'Serie', 001, 001, 1, Serie); Gerador.wCampo(tcStr, 'AP143', 'TipoDeCalculo', 001, 001, 1, TpVgTipoCalculoToStr(TipoDeCalculo)); Gerador.wGrupo('ToleranciaDePerdaDeMercadoria', 'AP144'); Gerador.wCampo(tcStr, 'AP145', 'Tipo', 001, 001, 1, TpProporcaoToStr(ToleranciaDePerdaDeMercadoria.Tipo)); Gerador.wCampo(tcDe2, 'AP146', 'Valor', 001, 001, 1, ToleranciaDePerdaDeMercadoria.Valor); Gerador.wGrupo('/ToleranciaDePerdaDeMercadoria'); if DiferencaDeFrete.Tipo <> SemDiferenca then begin Gerador.wGrupo('DiferencaDeFrete', 'AP147'); Gerador.wCampo(tcStr, 'AP148', 'Tipo', 001, 001, 1, TpDifFreteToStr(DiferencaDeFrete.Tipo)); Gerador.wCampo(tcStr, 'AP149', 'Base', 001, 001, 1, TpDiferencaFreteBCToStr(DiferencaDeFrete.Base)); Gerador.wGrupo('Tolerancia', 'AP150'); Gerador.wCampo(tcStr, 'AP151', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.Tolerancia.Tipo)); Gerador.wCampo(tcDe2, 'AP152', 'Valor', 001, 001, 1, DiferencaDeFrete.Tolerancia.Valor); Gerador.wGrupo('/Tolerancia'); Gerador.wGrupo('MargemGanho', 'AP153'); Gerador.wCampo(tcStr, 'AP154', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemGanho.Tipo)); Gerador.wCampo(tcDe2, 'AP155', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemGanho.Valor); Gerador.wGrupo('/MargemGanho'); Gerador.wGrupo('MargemPerda', 'AP156'); Gerador.wCampo(tcStr, 'AP157', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemPerda.Tipo)); Gerador.wCampo(tcDe2, 'AP158', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemPerda.Valor); Gerador.wGrupo('/MargemPerda'); Gerador.wGrupo('/DiferencaDeFrete'); end; Gerador.wCampo(tcStr, 'AP159', 'UnidadeDeMedidaDaMercadoria', 001, 001, 1, TpUnMedMercToStr(UnidadeDeMedidaDaMercadoria)); Gerador.wCampo(tcDe2, 'AP159', 'ValorDaMercadoriaPorUnidade', 001, 001, 1, ValorDaMercadoriaPorUnidade); Gerador.wCampo(tcDe2, 'AP159', 'ValorDoFretePorUnidadeDeMercadoria', 001, 001, 1, ValorDoFretePorUnidadeDeMercadoria); Gerador.wCampo(tcDe2, 'AP159', 'ValorTotal', 001, 001, 1, ValorTotal); Gerador.wGrupo('/NotasFiscais'); // Gerador.wGrupo('/NotaFiscal'); end; end; // Gerador.wGrupo('/NotasFiscais'); Gerador.wGrupo('Valores ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP163'); with Valores do begin Gerador.wCampo(tcDe2, 'AP164', 'Combustivel', 001, 001, 1, Combustivel); Gerador.wCampo(tcStr, 'AP165', 'JustificativaOutrosCreditos', 001, 001, 1, JustificativaOutrosCreditos); Gerador.wCampo(tcStr, 'AP166', 'JustificativaOutrosDebitos', 001, 001, 1, JustificativaOutrosDebitos); Gerador.wCampo(tcDe2, 'AP167', 'OutrosCreditos', 001, 001, 1, OutrosCreditos); Gerador.wCampo(tcDe2, 'AP168', 'OutrosDebitos', 001, 001, 1, OutrosDebitos); Gerador.wCampo(tcDe2, 'AP169', 'Pedagio', 001, 001, 1, Pedagio); Gerador.wCampo(tcDe2, 'AP170', 'Seguro', 001, 001, 1, Seguro); Gerador.wCampo(tcDe2, 'AP171', 'TotalDeAdiantamento', 001, 001, 1, TotalDeAdiantamento); Gerador.wCampo(tcDe2, 'AP172', 'TotalDeQuitacao', 001, 001, 1, TotalDeQuitacao); Gerador.wCampo(tcDe2, 'AP173', 'TotalOperacao', 001, 001, 1, TotalOperacao); Gerador.wCampo(tcDe2, 'AP174', 'TotalViagem', 001, 001, 1, TotalViagem); end; Gerador.wGrupo('/Valores'); end; Gerador.wGrupo('/Viagem'); end; Gerador.wGrupo('/Viagens'); Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFADICIONAR_VIAGEM, ''); for I := 0 to FOperacaoTransporte.Pagamentos.Count -1 do begin with FOperacaoTransporte.Pagamentos.Items[I] do begin // Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'AP91'); //Pagamentos registrados. - Pode existir mais de 1 pagamento com uma mesma categoria (exceto para Quitacao). - A soma dos pagamentos c/ categoria Adiantamento, deverá ter o mesmo valor apontado na tag TotalAdiantamento da tag Viagem/Valores, e neste caso, a tag Documento do pagamento deverá conter o mesmo valor da tag DocumentoViagem da tag Viagem . - Se a viagem possuir a tag TotalQuitacao maior que zero, deverá ter um pagamento correspondente, com Categoria Quitacao e com o Documento o mesmo valor apontado na tag DocumentoViagem . Gerador.wGrupo('Pagamento'); Gerador.wCampo(tcStr, 'AP92', 'Categoria', 001, 001, 1, TpCatPagToStr(Categoria), 'Categoria relacionada ao pagamento realizado. Restrita aos membros da ENUM: -Adiantamento, -Estadia, Quitacao, -SemCategoria ', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDat, 'AP93', 'DataDeLiberacao', 001, 001, 1, DataDeLiberacao); Gerador.wCampo(tcStr, 'AP94', 'Documento', 001, 020, 1, Documento, 'Documento relacionado a viagem.'); Gerador.wCampo(tcStr, 'AP94', 'IdPagamentoCliente', 001, 020, 1, IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); Gerador.wCampo(tcStr, 'AP95', 'InformacaoAdicional', 001, 000, 0, InformacaoAdicional, ''); Gerador.wGrupo('InformacoesBancarias ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP97'); with InformacoesBancarias do begin Gerador.wCampo(tcStr, 'AP98', 'Agencia', 001, 001, 1, Agencia); Gerador.wCampo(tcStr, 'AP99', 'Conta', 001, 001, 1, Conta); Gerador.wCampo(tcStr, 'AP100', 'InstituicaoBancaria', 001, 001, 1, InstituicaoBancaria); end; Gerador.wGrupo('/InformacoesBancarias'); Gerador.wCampo(tcStr, 'AP101', 'TipoPagamento', 001, 020, 1, TpPagamentoToStr(TipoPagamento), 'Tipo de pagamento que será usado pelo contratante. Restrito aos itens da enum: -TransferenciaBancaria -eFRETE', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDe2, 'AP102', 'Valor', 001, 020, 1, Valor, 'Valor do pagamento.'); Gerador.wGrupo('/Pagamento'); // Gerador.wGrupo('/Pagamentos'); end; end; Gerador.wGrupo('/Pagamentos'); Gerador.wCampo(tcStr, '', 'NaoAdicionarParcialmente', 001, 001, 1, 'false', ''); Gerador.wGrupo('/AdicionarViagemRequest'); end; end; opAdicionarPagamento: begin if FOperacaoTransporte.TipoViagem = TAC_Agregado then begin Gerador.wGrupo('AdicionarPagamentoRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcStr, '', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'Versao', 001, 001, 1, 2, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'CodigoIdentificacaoOperacao', 001, 030, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFADICIONAR_PAGAMENTOS, ''); for I := 0 to FOperacaoTransporte.Pagamentos.Count -1 do begin with FOperacaoTransporte.Pagamentos.Items[I] do begin Gerador.wGrupo('Pagamento'); Gerador.wCampo(tcStr, 'AP92', 'Categoria', 001, 001, 1, TpCatPagToStr(Categoria), 'Categoria relacionada ao pagamento realizado. Restrita aos membros da ENUM: -Adiantamento, -Estadia, Quitacao, -SemCategoria ', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDat, 'AP93', 'DataDeLiberacao', 001, 001, 1, DataDeLiberacao); Gerador.wCampo(tcStr, 'AP94', 'Documento', 001, 020, 1, Documento, 'Documento relacionado a viagem.'); Gerador.wCampo(tcStr, 'AP94', 'IdPagamentoCliente', 001, 020, 1, IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); Gerador.wCampo(tcStr, 'AP95', 'InformacaoAdicional', 001, 000, 0, InformacaoAdicional, ''); Gerador.wGrupo('InformacoesBancarias ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP97'); with InformacoesBancarias do begin Gerador.wCampo(tcStr, 'AP98', 'Agencia', 001, 001, 1, Agencia); Gerador.wCampo(tcStr, 'AP99', 'Conta', 001, 001, 1, Conta); Gerador.wCampo(tcStr, 'AP100', 'InstituicaoBancaria', 001, 001, 1, InstituicaoBancaria); end; Gerador.wGrupo('/InformacoesBancarias'); Gerador.wCampo(tcStr, 'AP101', 'TipoPagamento', 001, 020, 1, TpPagamentoToStr(TipoPagamento), 'Tipo de pagamento que será usado pelo contratante. Restrito aos itens da enum: -TransferenciaBancaria -eFRETE', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDe2, 'AP102', 'Valor', 001, 020, 1, Valor, 'Valor do pagamento.'); Gerador.wGrupo('/Pagamento'); end; end; Gerador.wGrupo('/Pagamentos'); Gerador.wGrupo('/AdicionarPagamentoRequest'); end; end; opCancelarPagamento: begin if FOperacaoTransporte.TipoViagem = TAC_Agregado then begin Gerador.wGrupo('CancelarPagamentoRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcStr, '', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'Versao', 001, 001, 1, 1, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'CodigoIdentificacaoOperacao', 001, 030, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wCampo(tcStr, '', 'IdPagamentoCliente', 001, 020, 1, FOperacaoTransporte.Cancelamento.IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); Gerador.wCampo(tcStr, 'KP04', 'Motivo', 001, 001, 1, FOperacaoTransporte.Cancelamento.Motivo, ''); Gerador.wGrupo('/CancelarPagamentoRequest'); end; end; opEncerrar: begin Gerador.wGrupo('EncerrarOperacaoTransporteRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcStr, '', 'Integrador', 001, 001, 1, TAmsCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'Versao', 001, 001, 1, 1, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, '', 'CodigoIdentificacaoOperacao', 001, 030, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wCampo(tcDe6, '', 'PesoCarga', 001, 001, 1, FOperacaoTransporte.PesoCarga, 'Peso total da carga.'); // Gerador.wGrupo('Viagens ' + NAME_SPACE_EFRETE_PEFENCERRAR_OPERACAO, ''); // // for I := 0 to FOperacaoTransporte.Viagens.Count -1 do // begin // Gerador.wGrupo('Viagem'); // with FOperacaoTransporte.Viagens.Items[I] do // begin // Gerador.wCampo(tcInt, 'AP133', 'CodigoMunicipioDestino', 001, 007, 1, CodigoMunicipioDestino); // Gerador.wCampo(tcInt, 'AP134', 'CodigoMunicipioOrigem', 001, 007, 1, CodigoMunicipioOrigem); // Gerador.wCampo(tcStr, 'AP135', 'DocumentoViagem', 001, 001, 1, DocumentoViagem, 'Exemplo: CT-e / Serie, CTRC / Serie, Ordem de Serviço.'); // //// Gerador.wGrupo('NotasFiscais', 'AP136'); // // for J := 0 to NotasFiscais.Count -1 do // begin // with NotasFiscais.Items[J] do // begin // Gerador.wGrupo('NotasFiscais'); // Gerador.wCampo(tcInt, 'AP137', 'CodigoNCMNaturezaCarga', 001, 004, 1, CodigoNCMNaturezaCarga); // Gerador.wCampo(tcDat, 'AP138', 'Data', 001, 004, 1, Data); // Gerador.wCampo(tcStr, 'AP139', 'DescricaoDaMercadoria', 001, 060, 1, DescricaoDaMercadoria, 'Descrição adicional ao código NCM.'); // Gerador.wCampo(tcStr, 'AP140', 'Numero', 001, 010, 1, Numero); // Gerador.wCampo(tcDe3, 'AP141', 'QuantidadeDaMercadoriaNoEmbarque', 001, 010, 1, QuantidadeDaMercadoriaNoEmbarque); // Gerador.wCampo(tcStr, 'AP142', 'Serie', 001, 001, 1, Serie); // Gerador.wCampo(tcStr, 'AP143', 'TipoDeCalculo', 001, 001, 1, TpVgTipoCalculoToStr(TipoDeCalculo)); // Gerador.wGrupo('ToleranciaDePerdaDeMercadoria', 'AP144'); // Gerador.wCampo(tcStr, 'AP145', 'Tipo', 001, 001, 1, TpProporcaoToStr(ToleranciaDePerdaDeMercadoria.Tipo)); // Gerador.wCampo(tcDe2, 'AP146', 'Valor', 001, 001, 1, ToleranciaDePerdaDeMercadoria.Valor); // Gerador.wGrupo('/ToleranciaDePerdaDeMercadoria'); // // if DiferencaDeFrete.Tipo <> SemDiferenca then // begin // Gerador.wGrupo('DiferencaDeFrete', 'AP147'); // Gerador.wCampo(tcStr, 'AP148', 'Tipo', 001, 001, 1, TpDifFreteToStr(DiferencaDeFrete.Tipo)); // Gerador.wCampo(tcStr, 'AP149', 'Base', 001, 001, 1, TpDiferencaFreteBCToStr(DiferencaDeFrete.Base)); // Gerador.wGrupo('Tolerancia', 'AP150'); // Gerador.wCampo(tcStr, 'AP151', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.Tolerancia.Tipo)); // Gerador.wCampo(tcDe2, 'AP152', 'Valor', 001, 001, 1, DiferencaDeFrete.Tolerancia.Valor); // Gerador.wGrupo('/Tolerancia'); // Gerador.wGrupo('MargemGanho', 'AP153'); // Gerador.wCampo(tcStr, 'AP154', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemGanho.Tipo)); // Gerador.wCampo(tcDe2, 'AP155', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemGanho.Valor); // Gerador.wGrupo('/MargemGanho'); // Gerador.wGrupo('MargemPerda', 'AP156'); // Gerador.wCampo(tcStr, 'AP157', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemPerda.Tipo)); // Gerador.wCampo(tcDe2, 'AP158', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemPerda.Valor); // Gerador.wGrupo('/MargemPerda'); // Gerador.wGrupo('/DiferencaDeFrete'); // end; // // Gerador.wCampo(tcStr, 'AP159', 'UnidadeDeMedidaDaMercadoria', 001, 001, 1, TpUnMedMercToStr(UnidadeDeMedidaDaMercadoria)); // Gerador.wCampo(tcDe2, 'AP159', 'ValorDaMercadoriaPorUnidade', 001, 001, 1, ValorDaMercadoriaPorUnidade); // Gerador.wCampo(tcDe2, 'AP159', 'ValorDoFretePorUnidadeDeMercadoria', 001, 001, 1, ValorDoFretePorUnidadeDeMercadoria); // Gerador.wCampo(tcDe2, 'AP159', 'ValorTotal', 001, 001, 1, ValorTotal); // // Gerador.wGrupo('/NotasFiscais'); //// Gerador.wGrupo('/NotaFiscal'); // end; // end; //// Gerador.wGrupo('/NotasFiscais'); // // Gerador.wGrupo('Valores ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP163'); // with Valores do // begin // Gerador.wCampo(tcDe2, 'AP164', 'Combustivel', 001, 001, 1, Combustivel); // Gerador.wCampo(tcStr, 'AP165', 'JustificativaOutrosCreditos', 001, 001, 1, JustificativaOutrosCreditos); // Gerador.wCampo(tcStr, 'AP166', 'JustificativaOutrosDebitos', 001, 001, 1, JustificativaOutrosDebitos); // Gerador.wCampo(tcDe2, 'AP167', 'OutrosCreditos', 001, 001, 1, OutrosCreditos); // Gerador.wCampo(tcDe2, 'AP168', 'OutrosDebitos', 001, 001, 1, OutrosDebitos); // Gerador.wCampo(tcDe2, 'AP169', 'Pedagio', 001, 001, 1, Pedagio); // Gerador.wCampo(tcDe2, 'AP170', 'Seguro', 001, 001, 1, Seguro); // Gerador.wCampo(tcDe2, 'AP171', 'TotalDeAdiantamento', 001, 001, 1, TotalDeAdiantamento); // Gerador.wCampo(tcDe2, 'AP172', 'TotalDeQuitacao', 001, 001, 1, TotalDeQuitacao); // Gerador.wCampo(tcDe2, 'AP173', 'TotalOperacao', 001, 001, 1, TotalOperacao); // Gerador.wCampo(tcDe2, 'AP174', 'TotalViagem', 001, 001, 1, TotalViagem); // end; // Gerador.wGrupo('/Valores'); // end; // // Gerador.wGrupo('/Viagem'); // end; // Gerador.wGrupo('/Viagens'); // // // Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFENCERRAR_OPERACAO, ''); // for I := 0 to FOperacaoTransporte.Pagamentos.Count -1 do // begin // with FOperacaoTransporte.Pagamentos.Items[I] do // begin // Gerador.wGrupo('Pagamento'); // Gerador.wCampo(tcStr, 'AP92', 'Categoria', 001, 001, 1, TpCatPagToStr(Categoria), 'Categoria relacionada ao pagamento realizado. Restrita aos membros da ENUM: -Adiantamento, -Estadia, Quitacao, -SemCategoria ', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); // Gerador.wCampo(tcDat, 'AP93', 'DataDeLiberacao', 001, 001, 1, DataDeLiberacao); // Gerador.wCampo(tcStr, 'AP94', 'Documento', 001, 020, 1, Documento, 'Documento relacionado a viagem.'); // Gerador.wCampo(tcStr, 'AP94', 'IdPagamentoCliente', 001, 020, 1, IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); // Gerador.wCampo(tcStr, 'AP95', 'InformacaoAdicional', 001, 000, 0, InformacaoAdicional, ''); // // Gerador.wGrupo('InformacoesBancarias ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'AP97'); // with InformacoesBancarias do // begin // Gerador.wCampo(tcStr, 'AP98', 'Agencia', 001, 001, 1, Agencia); // Gerador.wCampo(tcStr, 'AP99', 'Conta', 001, 001, 1, Conta); // Gerador.wCampo(tcStr, 'AP100', 'InstituicaoBancaria', 001, 001, 1, InstituicaoBancaria); // end; // Gerador.wGrupo('/InformacoesBancarias'); // // Gerador.wCampo(tcStr, 'AP101', 'TipoPagamento', 001, 020, 1, TpPagamentoToStr(TipoPagamento), 'Tipo de pagamento que será usado pelo contratante. Restrito aos itens da enum: -TransferenciaBancaria -eFRETE', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); // Gerador.wCampo(tcDe2, 'AP102', 'Valor', 001, 020, 1, Valor, 'Valor do pagamento.'); // Gerador.wGrupo('/Pagamento'); // end; // end; // Gerador.wGrupo('/Pagamentos'); Gerador.wGrupo('Impostos', 'AP78'); Gerador.wCampo(tcStr, 'AP79', 'DescricaoOutrosImpostos', 001, 001, 1, FOperacaoTransporte.Impostos.DescricaoOutrosImpostos); Gerador.wCampo(tcDe2, 'AP80', 'INSS', 001, 020, 1, FOperacaoTransporte.Impostos.INSS, 'Valor destinado ao INSS. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP81', 'IRRF', 001, 020, 1, FOperacaoTransporte.Impostos.IRRF, 'Valor destinado ao IRRF. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP82', 'ISSQN', 001, 020, 1, FOperacaoTransporte.Impostos.ISSQN, 'Valor destinado ao ISSQN. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP83', 'OutrosImpostos', 001, 020, 1, FOperacaoTransporte.Impostos.OutrosImpostos, 'Valor destinado a outros impostos não previstos. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wCampo(tcDe2, 'AP84', 'SestSenat', 001, 020, 1, FOperacaoTransporte.Impostos.SestSenat, 'Valor destinado ao SEST / SENAT. Este valor deverá fazer parte do valor de Adiantamento ou do valor de Quitação.'); Gerador.wGrupo('/Impostos'); Gerador.wGrupo('/EncerrarOperacaoTransporteRequest'); end; end; Result := (Gerador.ListaDeAlertas.Count = 0); end; end.
unit InfoXTRANTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoXTRANRecord = record PCode: String[2]; PDescription: String[30]; PGroup: String[1]; PCertificateCoverage: Boolean; PActive: Boolean; PModCount: SmallInt; End; TInfoXTRANClass2 = class public PCode: String[2]; PDescription: String[30]; PGroup: String[1]; PCertificateCoverage: Boolean; PActive: Boolean; PModCount: SmallInt; End; // function CtoRInfoXTRAN(AClass:TInfoXTRANClass):TInfoXTRANRecord; // procedure RtoCInfoXTRAN(ARecord:TInfoXTRANRecord;AClass:TInfoXTRANClass); TInfoXTRANBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoXTRANRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoXTRAN = (InfoXTRANPrimaryKey); TInfoXTRANTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TStringField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; FDFModCount: TSmallIntField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoXTRAN); function GetEnumIndex: TEIInfoXTRAN; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoXTRANRecord; procedure StoreDataBuffer(ABuffer:TInfoXTRANRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TStringField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property DFModCount: TSmallIntField read FDFModCount; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: String read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoXTRAN read GetEnumIndex write SetEnumIndex; end; { TInfoXTRANTable } TInfoXTRANQuery = class( TDBISAMQueryAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TStringField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; FDFModCount: TSmallIntField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoXTRANRecord; procedure StoreDataBuffer(ABuffer:TInfoXTRANRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TStringField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property DFModCount: TSmallIntField read FDFModCount; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: String read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoXTRANTable } procedure Register; implementation function TInfoXTRANTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoXTRANTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoXTRANTable.GenerateNewFieldName } function TInfoXTRANTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoXTRANTable.CreateField } procedure TInfoXTRANTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TStringField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXTRANTable.CreateFields } procedure TInfoXTRANTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXTRANTable.SetActive } procedure TInfoXTRANTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoXTRANTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoXTRANTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXTRANTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXTRANTable.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoXTRANTable.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoXTRANTable.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoXTRANTable.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoXTRANTable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoXTRANTable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoXTRANTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXTRANTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoXTRANTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 2, N'); Add('Description, String, 30, N'); Add('Group, String, 1, N'); Add('CertificateCoverage, Boolean, 0, N'); Add('Active, Boolean, 0, N'); Add('ModCount, SmallInt, 0, N'); end; end; procedure TInfoXTRANTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoXTRANTable.SetEnumIndex(Value: TEIInfoXTRAN); begin case Value of InfoXTRANPrimaryKey : IndexName := ''; end; end; function TInfoXTRANTable.GetDataBuffer:TInfoXTRANRecord; var buf: TInfoXTRANRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXTRANTable.StoreDataBuffer(ABuffer:TInfoXTRANRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; DFModCount.Value := ABuffer.PModCount; end; function TInfoXTRANTable.GetEnumIndex: TEIInfoXTRAN; var iname : string; begin result := InfoXTRANPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoXTRANPrimaryKey; end; function TInfoXTRANQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoXTRANQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoXTRANQuery.GenerateNewFieldName } function TInfoXTRANQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoXTRANQuery.CreateField } procedure TInfoXTRANQuery.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TStringField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXTRANQuery.CreateFields } procedure TInfoXTRANQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXTRANQuery.SetActive } procedure TInfoXTRANQuery.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoXTRANQuery.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoXTRANQuery.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXTRANQuery.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXTRANQuery.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoXTRANQuery.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoXTRANQuery.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoXTRANQuery.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoXTRANQuery.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoXTRANQuery.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoXTRANQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXTRANQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; function TInfoXTRANQuery.GetDataBuffer:TInfoXTRANRecord; var buf: TInfoXTRANRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXTRANQuery.StoreDataBuffer(ABuffer:TInfoXTRANRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoXTRANTable, TInfoXTRANQuery, TInfoXTRANBuffer ] ); end; { Register } function TInfoXTRANBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('CODE','DESCRIPTION','GROUP','CERTIFICATECOVERAGE','ACTIVE','MODCOUNT' ); 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 TInfoXTRANBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftBoolean; 5 : result := ftBoolean; 6 : result := ftSmallInt; end; end; function TInfoXTRANBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PGroup; 4 : result := @Data.PCertificateCoverage; 5 : result := @Data.PActive; 6 : result := @Data.PModCount; end; end; end.
{ apImgList: Simple image lister and selector Copyright by Andrej Pakhutin } unit apImgList; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ExtDlgs, ExtCtrls, StdCtrls, ActnList, ComCtrls, Menus, xLngManager, {$IFDEF USEDB} DB, DBTables, {$ENDIF} jpeg; type {TapimgListDBProps = class protected FdataSource: TDataSource; FprovLoad, FprovSave: string; FblobFieldName: String; FdefaultFieldName: String; FpostToWebFieldName: String; FonBeforeDBUpdate: TNotifyEvent; FonDBError: TNotifyEvent; published property DBdataSource: TDataSource read FdataSource write FdataSource; property imageFieldName: String read FblobFieldName write FblobFieldName; property defaultFieldName: String read FbdefaultFieldName write FdefaultFieldName; property postToWebFieldName: String read FpostToWebFieldName write FpostToWebFieldName; end; } //----------------------------------------------------------------------- TapImgList = class(TPanel) pmImages: TPopupMenu; miImgAdd: TMenuItem; miImgDefault: TMenuItem; miImgDel: TMenuItem; aImgAdd: TAction; aImgDel: TAction; aImgDefault: TAction; OpenPictureDialog1: TOpenPictureDialog; TrackBarW, TrackBarH: TTrackBar; sbImages: TScrollBox; DefaultMark: TImage; procedure aImgAddExecute(Sender: TObject); procedure aImgDefaultExecute(Sender: TObject); procedure aImgDelExecute(Sender: TObject); procedure Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pmImagesPopup(Sender: TObject); procedure sbImagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure switchDel(Sender: TObject); private imgListOrig: array of TMemoryStream; // originals imgList: array of TImage; // what is displayed imgListDeletedImages: array of TImage; // "delete" buttons imgListSel: array of TImage; // selection overlays imgListWebImages: array of TImage; // buttons: "post to web" imgListID: array of Integer; imgListWebState: array of Boolean; // "post to web" state imgListDeleted: array of Boolean; // "is deleted" state imgListNew: array of Boolean; // "is new" state imgListModified: array of Boolean; // "is modified" state imgListLastClicked: Integer; imgListDefault: Integer; Fcount: Integer; FlangMan: TxLngManager; FiconHeight, FiconWidth: Integer; FLeft, FTop, FWidth, FHeight: Integer; FshowPostToWeb: Boolean; FshowDelete: Boolean; FallowEditing: Boolean; FJPEGsOnly: Boolean; // evants FonChange: TNotifyEvent; FonDefaultSet: TNotifyEvent; FonSelect: TNotifyEvent; FonImageFileLoaded: TNotifyEvent; FonImageFileDeleted: TNotifyEvent; {$IFDEF USEDB} //DB: TapImgListDBProps; FdataSet: TDataSet; FprovLoad, FprovSave: string; FblobFieldName: String; FdefaultFieldName: String; FpostToWebFieldName: String; FonBeforeDBAppend: TNotifyEvent; FonBeforeDBPost: TNotifyEvent; FonDBError: TNotifyEvent; {$ENDIF} procedure SetCaptions; procedure deselectImages; procedure selectImage(const idx: Integer; sel: Boolean); // add another image of product to the viewer. returns image index function AddImage(var img: Timage; APostToWeb: Boolean; var Astream: TMemoryStream; const AID: Integer = -1): Integer; procedure DelImage(idx: Integer; Value: Boolean); procedure SetDefaultImage(const idx: Integer); // add default mark on the image of product @ the viewer procedure tbChanged(Sender: TObject); procedure sbImagesResize(Sender: TObject); procedure panelConstrainedResize(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); procedure switchPostToweb(Sender: TObject); procedure setImagePosition(const idx: Integer); procedure repositionImages; procedure repositionImageButtons(const i: Integer); procedure repaintImage(const idx: Integer); procedure SetCount(const newc: Integer); procedure SetLangMan(const nlm: TxLngManager); procedure SetIconHeight(const h: Integer); procedure SetIconWidth(const w: Integer); function GetNew(idx: Integer): Boolean; function GetModified(idx: Integer): Boolean; function GetPostToWeb(idx: Integer): Boolean; procedure SetPostToWeb(idx: Integer; Value: Boolean); function GetSelected(const idx: Integer): Boolean; procedure SetSelected(const idx: Integer; const Value: Boolean); function Getdeleted(idx: Integer): Boolean; function GetBitmap(idx: Integer): TBitmap; procedure SetBitmap(idx: Integer; Value: TBitmap); function GetStream(idx: Integer): TStream; procedure SetStream(idx: Integer; Value: TStream); function GetID(idx: Integer): Integer; procedure SetID(idx: Integer; Value: Integer); {$IFDEF USEDB} procedure newImage; procedure SetDataSet(Value: TDataSet); {$ENDIF} procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ClearAll; {$IFDEF USEDB} procedure loadDBImages; procedure saveDBImages; {$ENDIF} // returns the index of added image function AddFromStream(const stream: TStream; const AID: Integer = -1): Integer; property DefaultIndex: Integer read imgListDefault write SetDefaultImage; property Count: Integer read FCount;// write SetCount; property PostToWeb[idx: Integer]: Boolean read GetPostToWeb write SetPostToWeb; property isNew[idx: Integer]: Boolean read GetNew; property isDeleted[idx: Integer]: Boolean read GetDeleted write DelImage; property isModified[idx: Integer]: Boolean read GetModified; property Bitmaps[idx: Integer]: TBitmap read GetBitmap write SetBitmap; default; property Stream[idx: Integer]: TStream read GetStream write SetStream; property Selected[const idx: Integer]: Boolean read GetSelected write SetSelected; property ID[idx: Integer]: Integer read GetID write SetID; property DockManager; // from tpanel published property langMan: TxLngManager read FlangMan write SetLangMan; property iconWidth: Integer read FiconWidth write setIconWidth; property iconHeight: Integer read FiconHeight write setIconHeight; property showPostToWeb: Boolean read FshowPostToWeb write FshowPostToWeb; property showDelete: Boolean read FshowDelete write FshowDelete; property allowEditing: Boolean read FallowEditing write FallowEditing; property JPEGsOnly: Boolean read FJPEGsOnly write FJPEGsOnly; property onChange: TNotifyEvent read FonChange write FonChange; property onDefaultSet: TNotifyEvent read FonDefaultSet write FonDefaultSet; property onSelect: TNotifyEvent read FonSelect write FonSelect; property onImageFileLoaded: TNotifyEvent read FonImageFileLoaded write FonImageFileLoaded; property onImageFileDeleted: TNotifyEvent read FonImageFileDeleted write FonImageFileDeleted; {$IFDEF USEDB} //property DB: TapimgListDBProps read DB write DB; property DBdataSet: TDataSet read FdataSet write setDataSet; property DBimageFieldName: String read FblobFieldName write FblobFieldName; property DBdefaultFieldName: String read FdefaultFieldName write FdefaultFieldName; property DBpostToWebFieldName: String read FpostToWebFieldName write FpostToWebFieldName; property onBeforeDBAppend: TNotifyEvent read FonBeforeDBAppend write FonBeforeDBAppend; property onBeforeDBPost: TNotifyEvent read FonBeforeDBPost write FonBeforeDBPost; {$ENDIF} // from TPanel: property Left; property Top; property Width; property Height; property Align; property Alignment; property Anchors; property AutoSize; property BevelInner; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property BorderStyle; property Caption; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property ParentBiDiMode; property ParentBackground; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; //property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; procedure Register; implementation {$R *.res} //============================================================================================== procedure Register; begin RegisterComponents('AP', [TapImgList]); end; //============================================================================================== constructor TapImgList.Create(AOwner: TComponent); begin inherited; FiconHeight := 100; FiconWidth := 100; { Panel := TPanel.Create(Owner); with Panel do begin Width := 200; Height := 200; Parent := pointer(AOwner); OnConstrainedResize := panelConstrainedResize; OnResize := sbImagesResize; end; } TrackBarW := TTrackBar.Create(Self); with TrackBarW do begin Parent := Self; Height := 20; Frequency := 10; Linesize := 10; Pagesize := 50; Orientation := trHorizontal; Max := 300; Min := 100; Position := FiconWidth; ThumbLength := 15; OnChange := tbChanged; end; TrackBarH := TTrackBar.Create(Self); with TrackBarH do begin Parent := Self; Top := 0; Height := 20; Frequency := 10; Linesize := 10; Pagesize := 50; Orientation := trVertical; Max := 300; Min := 100; Position := FiconHeight; ThumbLength := 15; OnChange := tbChanged; end; sbImages := TScrollBox.Create(Self); with sbImages do begin Parent := Self; OnMouseDown := sbImagesMouseDown; end; aImgAdd := TAction.Create(Self); aImgAdd.OnExecute := aImgAddExecute; aImgAdd.Caption := 'Add'; aImgDel := TAction.Create(Self); aImgDel.OnExecute := aImgDelExecute; aImgDel.Caption := 'Del'; aImgDefault := TAction.Create(Self); aImgDefault.OnExecute := aImgDefaultExecute; aImgDefault.Caption := 'Default'; miImgAdd := TMenuItem.Create(pmImages); miImgAdd.Action := aImgAdd; miImgDefault := TMenuItem.Create(pmImages); miImgDefault.Action := aImgdefault; miImgDel := TMenuItem.Create(pmImages); miImgDel.Action := aImgDel; pmImages := TPopupMenu.Create(sbImages); pmImages.OnPopup := pmImagesPopup; pmImages.Items.Add(miImgAdd); pmImages.Items.Add(miImgDefault); pmImages.Items.Add(miImgDel); OpenPictureDialog1 := TOpenPictureDialog.Create(sbImages); DefaultMark := TImage.Create(sbImages); with DefaultMark do begin Parent := sbImages; Picture.Bitmap := TBitmap.Create; Picture.Bitmap.LoadFromResourceName(Hinstance, 'CHECK'); Width := Picture.Bitmap.Width; Height := Picture.Bitmap.Height; Transparent := True; Visible := False; end; imgListLastClicked := -1; imgListDefault := -1; Fcount := 0; FlangMan := nil; {$IFDEF USEDB} FdataSet := nil; FprovLoad := ''; FprovSave := ''; FblobFieldName := ''; FdefaultFieldName := ''; FpostToWebFieldName := ''; FonBeforeDBAppend := nil; FonBeforeDBPost := nil; FonDBError := nil; {$ENDIF} FJPEGsOnly := False; FshowPostToWeb := True; FshowDelete := True; FallowEditing := True; sbImagesResize(nil); // set controls in places end; //============================================================================================== destructor TapImgList.Destroy; var i: integer; begin {DefaultMark.Free; for i := 0 to Fcount - 1 do begin imgList[i].Free; imgListWebImages[i].Free; end; sbImages.Free; } inherited; end; //============================================================================================== function BoolToInt(v: Boolean): Integer; begin if V then Result := 1 else Result := 0; end; //============================================================================================== procedure TapImgList.WMSize(var Message: TWMSize); begin inherited; sbImagesResize(nil); end; //============================================================================================== procedure TapImgList.WMWindowPosChanged(var Message: TWMWindowPosChanged); begin inherited; sbImagesResize(nil); end; //============================================================================================== procedure TapImgList.sbImagesResize(Sender: TObject); var BevelPixels: Integer; begin inherited; BevelPixels := BorderWidth; if BevelInner <> bvNone then Inc(BevelPixels, BevelWidth); if BevelOuter <> bvNone then Inc(BevelPixels, BevelWidth); // setting main buttons // setting trackbars with TrackBarW do begin // horizontal, width setting. at the bottom of panel Left := BevelPixels; Width := Self.Width - 2 * BevelPixels - TrackBarH.Width; Top := Self.Height - Height - BevelPixels; end; with TrackBarH do begin // vertical, height setting. rightmost on the panel Top := BevelPixels; Left := Self.Width - Width - BevelPixels; Height := Self.Height - 2 * BevelPixels - TrackBarW.Height; end; with sbImages do begin Top := BevelPixels; Left := BevelPixels; Width := TrackBarH.Left - 1; Height := TrackBarW.Top - 1; end; {$IFNDEF PKG} repositionImages; {$ENDIF} end; //============================================================================================== procedure TapImgList.panelConstrainedResize(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); begin MinWidth := 120; MinHeight := 120; end; //============================================================================================== procedure TapImgList.ClearAll; var i: Integer; begin for i := 0 to Fcount - 1 do begin imgList[i].Picture.Bitmap.Free; imgList[i].Free; imgListDeletedImages[i].Picture.Bitmap.Free; imgListDeletedImages[i].Free; imgListWebImages[i].Picture.Bitmap.Free; imgListWebImages[i].Free; imgListSel[i].Picture.Bitmap.Free; imgListSel[i].Free; end; SetLength(imgListDeleted, 0); SetLength(imgListWebState, 0); SetLength(imgList, 0); SetLength(imgListDeletedImages, 0); SetLength(imgListSel, 0); SetLength(imgListWebImages, 0); imgListLastClicked := -1; imgListDefault := -1; Fcount := 0; end; //============================================================================================== {$IFDEF USEDB} procedure TapImgList.loadDBImages; var Stream: TStream; begin if (FdataSet = nil){ or (FprovLoad = '')} then Exit; ClearAll; try with FdataSet do begin Open; First; while not Eof do begin newImage; Stream := CreateBlobStream(FieldByName(FblobFieldName) as TBlobField, bmRead); imgList[Fcount - 1].Picture.Bitmap.LoadFromStream(Stream); this is incorrect ! imgListOrig[Fcount - 1] := Stream; inc(Fcount); if FieldByName(FdefaultFieldName).AsInteger <> 0 then SetDefaultImage(Fcount - 1); SetPostToWeb(Fcount - 1, (0 <> FieldByName(FpostToWebFieldName).AsInteger)); Next; end; Close; end; except if assigned(FonDBError) then FonDBError(Self) else raise; end; SetCaptions; end; //============================================================================================== procedure TapImgList.saveDBImages; var Stream: TStream; i: integer; begin if (Fcount <= 0) or (FdataSet = nil){ or (FprovSave = '')} then Exit; if assigned(FonBeforeDBAppend) then FonBeforeDBAppend(Self); try with FdataSet do begin Open; for i := 0 to Fcount - 1 do begin Append; Stream := CreateBlobStream(FieldByName(FblobFieldName) as TBlobField, bmWrite); imgList[i].Picture.Bitmap.SaveToStream(Stream); FieldByName(FdefaultFieldName).AsInteger := BoolToInt(i = imgListDefault); FieldByName(FpostToWebFieldName).AsInteger := BoolToInt(imgListWebState[i]); if assigned(FonBeforeDBPost) then FonBeforeDBPost(Self); Post; Stream.Free; end; Close; end; except if assigned(FonDBError) then FonDBError(Self) else raise; end; end; //============================================================================================== procedure TapImgList.SetDataSet(Value: TDataSet); begin ClearAll; FdataSet := Value; end; {//============================================================================================== procedure TapImgList.SetblobFieldName(Value: String); begin //ClearAll; FblobFieldName := Value; end; } {$ENDIF} //============================================================================================== function TapImgList.GetNew(idx: Integer): Boolean; begin Result := imgListNew[idx]; end; //============================================================================================== function TapImgList.GetModified(idx: Integer): Boolean; begin Result := imgListModified[idx]; end; //============================================================================================== function TapImgList.GetSelected(const idx: Integer): Boolean; begin Result := imgListSel[idx].Visible; end; //============================================================================================== procedure TapImgList.SetSelected(const idx: Integer; const Value: Boolean); begin SelectImage(idx, Value); end; //============================================================================================== function TapImgList.GetPostToWeb(idx: Integer): Boolean; begin Result := imgListWebState[idx]; end; //============================================================================================== procedure TapImgList.SetPostToWeb(idx: Integer; Value: Boolean); begin imgListWebState[idx] := Value; if Value then imgListWebImages[idx].Picture.Bitmap.LoadFromResourceName(Hinstance, 'IE') else imgListWebImages[idx].Picture.Bitmap.LoadFromResourceName(Hinstance, 'IEBW'); end; //============================================================================================== procedure TapImgList.switchPostToweb(Sender: TObject); var idx: Integer; begin if not FallowEditing then Exit; idx := (Sender as TImage).Tag; SetPostToWeb(idx, not imgListWebState[idx]); if Assigned(FonChange) then FonChange(Self); end; //============================================================================================== function TapImgList.GetStream(idx: Integer): TStream; begin if (idx < 0) or (idx >= Fcount) then begin Result := nil; Exit; end; imgListOrig[idx].Position := 0; Result := imgListOrig[idx]; end; //============================================================================================== procedure TapImgList.SetStream(idx: Integer; Value: TStream); begin if (idx < 0) or (idx >= Fcount) then Exit; imgListOrig[idx].Position := 0; imgListOrig[idx].Size := 0; imgListOrig[idx].CopyFrom(Value, Value.Size); if imgList[idx].Picture.Bitmap <> nil then imgList[idx].Picture.Bitmap.Free; Value.Position := 0; imgList[idx].Picture.Bitmap.LoadFromStream(Value); if Assigned(FonChange) then FonChange(Self); end; //============================================================================================== function TapImgList.GetID(idx: Integer): Integer; begin if (idx < 0) or (idx >= Fcount) then Result := -1 else Result := imgListID[idx]; end; //============================================================================================== procedure TapImgList.SetID(idx: Integer; Value: Integer); begin if (idx < 0) or (idx >= Fcount) then Exit; imgListID[idx] := Value; imgListNew[idx] := (Value = -1); // maybe that's wrong, but addImage does the same... end; //============================================================================================== function TapImgList.GetBitmap(idx: Integer): TBitmap; begin if (idx < 0) or (idx >= Fcount) then Result := nil else Result := imgList[idx].Picture.Bitmap; end; //============================================================================================== procedure TapImgList.SetBitmap(idx: Integer; Value: TBitmap); begin if (idx < 0) or (idx >= Fcount) then Exit; if imgList[idx].Picture.Bitmap <> nil then imgList[idx].Picture.Bitmap.Free; imgList[idx].Picture.Bitmap := Value; end; //============================================================================================== procedure TapImgList.SetCount(const newc: Integer); var i: integer; begin { if (newc < 0) or (Fcount = newc) then Exit; if Fcount < newc then begin // removing for i := Fcount - 1 downto newc do begin imgList[i].Picture.Bitmap.Free; imgList[i].Free; imgListDeletedImages[i].Picture.Bitmap.Free; imgListDeletedImages[i].Free; imgListSel[i].Picture.Bitmap.Free; imgListSel[i].Free; imgListWebImages[i].Picture.Bitmap.Free; imgListWebImages[i].Free; end; SetLength(imgListDeleted, newc); SetLength(imgListNew, newc); SetLength(imgListWebState, newc); imgListLastClicked := -1; if imgListDefault >= newc then begin imgListDefault := -1; DefaultMark.Visible := False; end; end else begin // adding blank end; Fcount := newc; SetCaptions; if Assigned(FonChange) then FonChange; } end; //============================================================================================== procedure TapImgList.SetLangMan(const nlm: TxLngManager); begin if FlangMan = nlm then Exit; FlangMan := nlm; SetCaptions; end; //============================================================================================== procedure TapImgList.SetCaptions; var i: Integer; begin {$IFNDEF PKG} if FlangMan = nil then Exit; with FLangMan do begin aImgAdd.Caption := getRS('apImgList', 'Add'); aImgDel.Caption := getRS('apImgList', 'Del'); aImgDefault.Caption := getRS('apImgList', 'Default'); DefaultMark.Hint := getRS('apImgList', 'DefaultHint'); Self.Caption := getRS('apImgList', 'NoImages'); for i := 0 to Fcount - 1 do begin imgListWebImages[i].Hint := getRS('apImgList', 'PostToWebHint'); imgListDeletedImages[i].Hint := getRS('apImgList', 'DeleteHint'); end; end; {$ENDIF} end; //============================================================================================== procedure TapImgList.repaintImage(const idx: Integer); begin imgList[idx].Repaint; imgListWebImages[idx].Repaint; if idx = imgListDefault then DefaultMark.Repaint; end; //============================================================================================== procedure TapImgList.setImagePosition(const idx: Integer); var size,wc: Integer; begin if FiconHeight > FiconWidth then size := FiconWidth else size := FiconHeight; wc := (sbImages.Width - 5) div (FiconWidth + 10); if wc = 0 then wc := 1; imgList[idx].Left := (FiconWidth - size) div 2 + (idx mod wc) * (FiconWidth + 10) + 5; imgList[idx].Top := (FiconHeight - size) div 2 + (idx div wc) * (FiconHeight + 10) + 5; with imgListSel[idx] do begin Left := (idx mod wc) * (FiconWidth + 10) + 5; Top := (idx div wc) * (FiconHeight + 10) + 5; Width := FiconWidth; Height := FiconHeight; Picture.Bitmap.Width := FiconWidth; Picture.Bitmap.Height := FiconHeight; Picture.Bitmap.Canvas.FillRect(Rect(0, 0, FiconWidth, FiconHeight)); end; repositionImageButtons(idx); end; //============================================================================================== procedure TapImgList.repositionImages; var i: Integer; begin for i := 0 to Fcount - 1 do begin setImagePosition(i); end; end; //============================================================================================== procedure TapImgList.repositionImageButtons(const i: Integer); begin with imgListWebImages[i] do begin Top := imgList[i].Top + imgList[i].Height - Height; Left := imgList[i].Left; end; with imgListDeletedImages[i] do begin Top := imgList[i].Top + imgList[i].Height - Height; Left := imgListWebImages[i].Left + imgListWebImages[i].Width + 1; end; if i = imgListDefault then begin DefaultMark.Left := imgList[i].Left; DefaultMark.Top := imgList[i].Top; DefaultMark.Visible := True; end; end; //============================================================================================== procedure TapImgList.SetIconHeight(const h: Integer); var i: Integer; begin FiconHeight := h; for i := 0 to Fcount - 1 do begin imgList[i].Height := h; end; end; //============================================================================================== procedure TapImgList.SetIconWidth(const w: Integer); var i: Integer; begin FiconWidth := w; for i := 0 to Fcount - 1 do begin imgList[i].Width := w; end; end; //============================================================================================== procedure TapImgList.tbChanged(Sender: TObject); begin if Sender = TrackBarH then SetIconHeight(TrackBarH.Position) else SetIconWidth(TrackBarW.Position); repositionImages; end; //============================================================================================== {$IFDEF USEDB} procedure TapImgList.newImage; var img: Timage; begin img := TImage.Create(sbImages); img.Parent := sbImages; img.Picture.Bitmap := TBitmap.Create; AddImage(img, False, nil); end; {$ENDIF} //============================================================================================== function TapImgList.AddFromStream(const stream: TStream; const AID: Integer = -1): Integer; var img: TImage; jpeg: TJpegImage; myStream: TMemoryStream; begin Result := -1; if (stream = nil) or (stream.Size = 0) then Exit; Stream.Position := 0; myStream := TMemoryStream.Create; myStream.CopyFrom(stream, stream.size); img := nil; jpeg := nil; try img := TImage.Create(sbImages); img.Parent := sbImages; jpeg := TJpegImage.create; Stream.Position := 0; jpeg.LoadFromStream(Stream); Img.Picture.Assign(jpeg); jpeg.Free; except if jpeg <> nil then jpeg.Free; if img <> nil then img.Free; myStream.Free; Exit; end; Result := AddImage(img, False, myStream, AID); sbImages.Repaint; end; //============================================================================================== function TapImgList.AddImage(var img: Timage; APostToWeb: Boolean; var AStream: TMemoryStream; const AID: Integer = -1): Integer; var btn: Timage; begin Result := -1; DefaultMark.BringToFront; deselectImages; inc(Fcount); img.Width := FiconWidth; img.Height := FiconHeight; img.Proportional := True; img.Stretch := True; img.Tag := Fcount - 1; img.OnMouseDown := Image1MouseDown; // selection overlays SetLength(imgListSel, Fcount); btn := TImage.Create(sbImages); with btn do begin Parent := sbImages; Visible := False; Tag := Fcount - 1; btn.OnMouseDown := Image1MouseDown; Picture.Bitmap := TBitmap.Create; //Picture.Bitmap.LoadFromResourceName(Hinstance, 'SEL'); Picture.Bitmap.Transparent := True; Transparent := True; //Picture.Bitmap.TransparentColor := clWhite; Picture.Bitmap.Canvas.Brush.Bitmap := TBitmap.Create; Picture.Bitmap.Canvas.Brush.Bitmap.LoadFromResourceName(Hinstance, 'SEL'); end; imgListSel[Fcount - 1] := btn; // making "delete" button SetLength(imgListDeleted, Fcount); imgListDeleted[Fcount - 1] := False; btn := TImage.Create(sbImages); with btn do begin Parent := sbImages; Picture.Bitmap := TBitmap.Create; Picture.Bitmap.LoadFromResourceName(Hinstance, 'DELBW'); Width := Picture.Width; Height := Picture.Height; OnClick := switchDel; Tag := Fcount - 1; Transparent := True; Visible := (FshowDelete and FallowEditing); end; SetLength(imgListDeletedImages, Fcount); imgListDeletedImages[Fcount - 1] := btn; // making "post to web" button SetLength(imgListWebImages, Fcount); SetLength(imgListWebState, Fcount); imgListWebState[Fcount - 1] := APostToWeb; btn := TImage.Create(sbImages); with btn do begin Parent := sbImages; Picture.Bitmap := TBitmap.Create; Picture.Bitmap.LoadFromResourceName(Hinstance, 'IEBW'); Width := Picture.Width; Height := Picture.Height; OnClick := switchPostToWeb; Tag := Fcount - 1; Transparent := True; Visible := FshowPostToWeb; end; imgListWebImages[Fcount - 1] := btn; SetLength(imgListNew, Fcount); imgListNew[Fcount - 1] := (AID = -1); SetLength(imgListModified, Fcount); imgListModified[Fcount - 1] := False; SetLength(imgList, Fcount); imgList[Fcount - 1] := img; setImagePosition(Fcount - 1); repaintImage(Fcount - 1); SetLength(imgListID, Fcount); imgListID[Fcount - 1] := AID; setLength(imgListOrig, Fcount); imgListOrig[Fcount - 1] := AStream; setCaptions; // to load hints, etc... Result := Fcount - 1; end; //============================================================================================== procedure TapImgList.aImgAddExecute(Sender: TObject); var img: TImage; fStream: TFileStream; oStream: TMemoryStream; jpeg: TJPEGImage; begin if FJPEGsOnly then OpenPictureDialog1.Filter := 'JPEG (*.jpg)|*.jpg;*.jpeg'; if not OpenPictureDialog1.Execute then exit; img := nil; jpeg := nil; fStream := nil; try fStream := TFileStream.Create(OpenPictureDialog1.FileName, fmOpenRead); img := TImage.Create(sbImages); img.Parent := sbImages; img.Picture.Bitmap := TBitmap.create; jpeg := TJPEGImage.Create; fStream.Position := 0; jpeg.LoadFromStream(fStream); Img.Picture.Assign(jpeg); jpeg.Free; except if img <> nil then img.Free; if nil <> jpeg then jpeg.Free; if nil <> fStream then fStream.Free; Exit; end; oStream := TMemoryStream.Create; fStream.Position := 0; oStream.CopyFrom(fStream, fStream.Size); fStream.Free; AddImage(img, False, oStream); sbImages.Repaint; if Assigned(FonImageFileLoaded) then FonImageFileLoaded(Self); if Assigned(FonChange) then FonChange(Self); end; //============================================================================================== function TapImgList.GetDeleted(idx: Integer): Boolean; begin Result := imgListDeleted[idx]; end; //============================================================================================== procedure TapImgList.DelImage(idx: Integer; Value: boolean); begin imgListDeleted[idx] := Value; if idx = imgListDefault then begin with DefaultMark do begin Visible := False; end; imgListDefault := -1; end; with imgListDeletedImages[idx] do begin if imgListDeleted[idx] then Picture.Bitmap.LoadFromResourceName(Hinstance, 'DEL') else Picture.Bitmap.LoadFromResourceName(Hinstance, 'DELBW'); Width := Picture.Width; Height := Picture.Height; end; if Assigned(FonImageFileDeleted) then FonImageFileDeleted(Self); if Assigned(FonChange) then FonChange(Self); end; //============================================================================================== procedure TapImgList.switchDel(Sender: TObject); begin if not FallowEditing then Exit; DelImage((Sender as TImage).Tag, not imgListDeleted[(Sender as TImage).Tag]); end; //============================================================================================== procedure TapImgList.aImgDelExecute(Sender: TObject); var i: Integer; begin for i := 0 to Fcount - 1 do if imgListSel[i].Visible then delImage(i, True); end; //============================================================================================== procedure TapImgList.SetDefaultImage(const idx: Integer); begin if not FallowEditing then Exit; if (idx < 0) or (idx >= Fcount) then begin DefaultMark.Visible := False; imgListDefault := -1; Exit; end; if imgListDeleted[idx] then Exit; imgListDefault := idx; DefaultMark.Visible := True; repositionImageButtons(idx); if Assigned(FonChange) then FonChange(Self); if Assigned(FonDefaultSet) then FonDefaultSet(Self); end; //============================================================================================== procedure TapImgList.aImgDefaultExecute(Sender: TObject); begin SetDefaultImage(imgListLastClicked); end; //============================================================================================== procedure TapImgList.deselectImages; var i: integer; begin for i := 0 to Fcount - 1 do if imgListSel[i].Visible then selectImage(i, False); end; //============================================================================================== procedure TapImgList.selectImage(const idx: Integer; sel: Boolean); begin if (idx < 0) or (idx >= Fcount) then Exit; if imgListSel[idx].Visible = sel then Exit; // same state imgListSel[idx].Visible := sel; repaintImage(idx); if assigned(FonSelect) then FonSelect(Self); end; //============================================================================================== procedure TapImgList.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i,f,t: integer; begin case Button of mbLeft: // perform select/unselect begin if ssShift in Shift then begin i := imgListLastClicked; if i = -1 then i := 0; if i <= (Sender as TImage).Tag then begin f := i; t := (Sender as TImage).Tag; end else begin f := (Sender as TImage).Tag; t := i; end; for i := f to t do selectImage(i, True); end else if ssCtrl in Shift then begin i := (Sender as TImage).Tag; selectImage(i, not imgListSel[i].Visible); end else begin// just a click - single image select deselectImages; selectImage((Sender as TImage).Tag, True); end; // shift imgListLastClicked := (Sender as TImage).Tag; // to make shift-click work end; mbRight: // menu popup begin i := (Sender as TImage).Tag; if not imgListSel[i].Visible then begin deselectImages; selectImage(i, True); end; pmImages.Tag := i; pmImages.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); imgListLastClicked := (Sender as TImage).Tag; // to make menu work end; end; end; //============================================================================================== procedure TapImgList.pmImagesPopup(Sender: TObject); begin inherited; miImgDefault.Enabled := pmImages.Tag <> -1; miImgDel.Enabled := pmImages.Tag <> -1; end; //============================================================================================== procedure TapImgList.sbImagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Button = mbLeft then begin deselectImages; Exit; end else if Button = mbRight then begin pmImages.Tag := -1; pmImages.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; //============================================================================================== initialization //============================================================================================== finalization end.
{ *************************************************************************** } { } { } { Copyright (C) Amarildo Lacerda } { } { https://github.com/amarildolacerda } { } { } { *************************************************************************** } { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } { *************************************************************************** } unit Social.Dropbox; interface uses System.Sysutils, System.Classes, System.JSON, IPPeerClient, REST.Client, REST.Authenticator.OAuth, REST.Response.Adapter, REST.types, idHTTP, IdSSL, IdSSLOpenSSL, REST.Social, REST.FDSocial, REST.JSON, System.Generics.Collections, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type {TDropboxAppInfo = record public end;} TDropboxAccountInfo = class(TPersistent) private JSON: string; Femail: string; Fuid: string; Fdisplay_name: string; procedure Setdisplay_name(const Value: string); procedure Setemail(const Value: string); procedure Setuid(const Value: string); public procedure FromJson(aJson: string); procedure LoadFromJson(js: TJsonObject); published property email: string read Femail write Setemail; property display_name: string read Fdisplay_name write Setdisplay_name; property uid: string read Fuid write Setuid; end; TDropboxListFolderItem = class public private Frev: string; Fmodified: string; Fpath: string; Frevision: string; Fthumb_exists: string; Fread_only: string; Ficon: string; Fis_dir: string; Fsize: string; Froot: string; Fbytes: string; procedure Setbytes(const Value: string); procedure Seticon(const Value: string); procedure Setis_dir(const Value: string); procedure Setmodified(const Value: string); procedure Setpath(const Value: string); procedure Setread_only(const Value: string); procedure Setrev(const Value: string); procedure Setrevision(const Value: string); procedure Setroot(const Value: string); procedure Setsize(const Value: string); procedure Setthumb_exists(const Value: string); public procedure FromJson(js: TJsonValue); property rev: string read Frev write Setrev; property thumb_exists: string read Fthumb_exists write Setthumb_exists; property path: string read Fpath write Setpath; property is_dir: string read Fis_dir write Setis_dir; property icon: string read Ficon write Seticon; property read_only: string read Fread_only write Setread_only; property bytes: string read Fbytes write Setbytes; property modified: string read Fmodified write Setmodified; property size: string read Fsize write Setsize; property root: string read Froot write Setroot; property revision: string read Frevision write Setrevision; end; TDropboxListFolderList = class(TObjectList<TDropboxListFolderItem>) public JSON: string; procedure FromJson(aJson: String); end; TSocialDropbox = class(TComponent) private FStatusCode: integer; FDataset: TDataset; FRestClient: TRESTSocialClientDataset; FAuthBase: TCustomSocialAuthBase; FListFolder: TDropboxListFolderList; FAccountInfo: TDropboxAccountInfo; procedure SetAuthBase(const Value: TCustomSocialAuthBase); procedure SetListFolder(const Value: TDropboxListFolderList); procedure SetAccountInfo(const Value: TDropboxAccountInfo); procedure SetAccessToken(const Value: string); function GetAccessToken: string; protected procedure prepare; public //Command: string; Response: string; function DataSet: TDataset; constructor create(ow: TComponent);override; destructor destroy; override; function StatusCode: integer; function GetAccountInfo: TDropboxAccountInfo; function GetListFolder(APath: string; AContinue: boolean = false): boolean; procedure UploadFile(AFileName: string; AFile_To: String); procedure DownloadFile(file_path: string; saveToPath: string); overload; procedure DownloadFile(file_path: string; AStream: TStream); overload; property ListFolder: TDropboxListFolderList read FListFolder write SetListFolder; property AccountInfo: TDropboxAccountInfo read FAccountInfo write SetAccountInfo; published property AuthBase: TCustomSocialAuthBase read FAuthBase write SetAuthBase; // property RestClient: TRESTSocialClientDataset read FRestClient write FRestClient; property AccessToken: string read GetAccessToken write SetAccessToken; end; procedure Register; implementation { TDropbox } // Uses Data.DB.Helper; const authServer = 'https://www.dropbox.com'; apiServer = 'https://api.dropbox.com'; fileServer = 'https://content.dropboxapi.com'; const url_authorize = authServer + '/1/oauth2/authorize'; url_token = apiServer + '/1/oauth2/token'; url_signOut = apiServer + '/1/unlink_access_token'; url_accountInfo = apiServer + '/1/account/info'; url_getFile = fileServer + '/1/files/auto'; url_postFile = fileServer + '/1/files/auto'; url_putFile = fileServer + '/1/files_put/auto'; /// auto url_metadata = apiServer + '/1/metadata/auto'; url_delta = apiServer + '/1/delta'; url_revisions = apiServer + '/1/revisions/auto/'; url_restore = apiServer + '/1/restore/auto/'; url_search = apiServer + '/1/search/auto/'; url_shares = apiServer + '/1/shares/auto'; url_media = apiServer + '/1/media/auto'; url_copyRef = apiServer + '/1/copy_ref/auto'; url_thumbnails = fileServer + '/1/thumbnails/auto'; url_chunkedUpload = fileServer + '/1/chunked_upload'; url_commitChunkedUpload = fileServer + '/1/commit_chunked_upload/auto'; url_fileopsCopy = apiServer + '/1/fileops/copy'; url_fileopsCreateFolder = apiServer + '/1/fileops/create_folder'; url_fileopsDelete = apiServer + '/1/fileops/delete'; url_fileopsMove = apiServer + '/1/fileops/move'; url_list_Folder = apiServer + '/2/files/list_folder/'; procedure Register; begin RegisterClass(TDropboxAccountInfo); RegisterComponents('REST Client', [TSocialDropbox]); end; constructor TSocialDropbox.create(ow: TComponent); begin inherited create(ow); FAccountInfo := TDropboxAccountInfo.create; FAuthBase := TCustomSocialAuthBase.create; FRestClient := TRESTSocialClientDataset.create(self); FRestClient.Name := 'RestClientInternal'; FListFolder := TDropboxListFolderList.create; // (true); end; function TSocialDropbox.DataSet: TDataset; begin result := FDataset; end; destructor TSocialDropbox.destroy; begin FAuthBase.Free; FRestClient.Free; FListFolder.Free; FAccountInfo.Free; inherited; end; procedure TSocialDropbox.DownloadFile(file_path: string; AStream: TStream); begin prepare; FStatusCode := FRestClient.GetStream(url_getFile, file_path, AStream); end; procedure TSocialDropbox.DownloadFile(file_path: string; saveToPath: string); var AStream: TMemoryStream; rsp: boolean; begin AStream := TMemoryStream.create; try DownloadFile(file_path, AStream); if StatusCode = 200 then begin AStream.SaveToFile(saveToPath); end; finally AStream.Free; end; end; function TSocialDropbox.GetAccessToken: string; begin result := AuthBase.AccessToken; end; function TSocialDropbox.GetAccountInfo: TDropboxAccountInfo; var sJson: string; begin prepare; FRestClient.BaseURL := url_accountInfo; Response := FRestClient.Get(); FStatusCode := FRestClient.StatusCode; if StatusCode = 200 then FAccountInfo.FromJson(Response); result := FAccountInfo; end; function TSocialDropbox.GetListFolder(APath: string; AContinue: boolean = false): boolean; var FCommand:string; begin prepare; FRestClient.BaseURL := url_metadata; FRestClient.Resource := APath + '?list'; Response := FRestClient.Get(); FStatusCode := FRestClient.StatusCode; if StatusCode = 200 then begin FRestClient.RootElement := 'contents'; Response := TJson.ObjectToJsonString(FRestClient.DataSet); // .ToJson; FListFolder.FromJson(Response); end; end; procedure TSocialDropbox.prepare; begin FRestClient.Clear; FRestClient.AccessToken := FAuthBase.AccessToken; end; procedure TSocialDropbox.SetAccessToken(const Value: string); begin FRestClient.AccessToken := value; AuthBase.AccessToken := value; end; procedure TSocialDropbox.SetAccountInfo(const Value: TDropboxAccountInfo); begin FAccountInfo := Value; end; procedure TSocialDropbox.SetAuthBase(const Value: TCustomSocialAuthBase); begin FAuthBase := Value; end; procedure TSocialDropbox.SetListFolder(const Value: TDropboxListFolderList); begin FListFolder := Value; end; function TSocialDropbox.StatusCode: integer; begin result := FStatusCode; end; procedure TSocialDropbox.UploadFile(AFileName: string; AFile_To: String); var AStream: TFileStream; FCommand:string; begin prepare; FCommand := url_putFile + AFile_To; AStream := TFileStream.create(AFileName, fmOpenRead); try FStatusCode := FRestClient.SendStream(FCommand, '', AStream); finally AStream.Free; end; end; { TDropboxConfig } { TDropboxAuthBase } { TDropboxAccountInfo } procedure TDropboxAccountInfo.FromJson(aJson: string); var js: TJsonObject; begin js := TJsonObject.ParseJSONValue(aJson) as TJsonObject; try LoadFromJson(js); finally js.Free; end; end; procedure TDropboxAccountInfo.LoadFromJson(js: TJsonObject); begin inherited; JSON := js.ToString; js.TryGetValue<string>('email', Femail); js.TryGetValue<string>('display_name', Fdisplay_name); js.TryGetValue<string>('uid', Fuid); end; procedure TDropboxAccountInfo.Setdisplay_name(const Value: string); begin Fdisplay_name := Value; end; procedure TDropboxAccountInfo.Setemail(const Value: string); begin Femail := Value; end; procedure TDropboxAccountInfo.Setuid(const Value: string); begin Fuid := Value; end; { TDropboxListFolderList } procedure TDropboxListFolderList.FromJson(aJson: String); var J: TJsonArray; A: TJsonValue; it: TDropboxListFolderItem; begin JSON := aJson; J := TJsonObject.ParseJSONValue(aJson) as TJsonArray; for A in J do begin it := TDropboxListFolderItem.create; Add(it); it.FromJson(A); end; end; { TDropboxListFolderItem } procedure TDropboxListFolderItem.FromJson(js: TJsonValue); begin js.TryGetValue<string>('rev', Frev); js.TryGetValue<string>('thumb_exists', Fthumb_exists); js.TryGetValue<string>('path', Fpath); js.TryGetValue<string>('is_dir', Fis_dir); js.TryGetValue<string>('icon', Ficon); js.TryGetValue<string>('read_only', Fread_only); js.TryGetValue<string>('bytes', Fbytes); js.TryGetValue<string>('modified', Fmodified); js.TryGetValue<string>('size', Fsize); js.TryGetValue<string>('root', Froot); js.TryGetValue<string>('revision', Frevision); end; procedure TDropboxListFolderItem.Setbytes(const Value: string); begin Fbytes := Value; end; procedure TDropboxListFolderItem.Seticon(const Value: string); begin Ficon := Value; end; procedure TDropboxListFolderItem.Setis_dir(const Value: string); begin Fis_dir := Value; end; procedure TDropboxListFolderItem.Setmodified(const Value: string); begin Fmodified := Value; end; procedure TDropboxListFolderItem.Setpath(const Value: string); begin Fpath := Value; end; procedure TDropboxListFolderItem.Setread_only(const Value: string); begin Fread_only := Value; end; procedure TDropboxListFolderItem.Setrev(const Value: string); begin Frev := Value; end; procedure TDropboxListFolderItem.Setrevision(const Value: string); begin Frevision := Value; end; procedure TDropboxListFolderItem.Setroot(const Value: string); begin Froot := Value; end; procedure TDropboxListFolderItem.Setsize(const Value: string); begin Fsize := Value; end; procedure TDropboxListFolderItem.Setthumb_exists(const Value: string); begin Fthumb_exists := Value; end; end.
unit WinUtils; interface Uses Windows, SysUtils, Printers, TntClasses, Classes, Registry; procedure SaveOption(Name, Key, Value : String;Root : HKey); function LoadOption(Name, Key, Default : String;Root : HKey) : String; procedure DelOption (Name, Key : String;Root : HKey); implementation procedure SaveOption(Name, Key, Value : String;Root : HKey); Var Reg : TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := root; if Reg.OpenKey(key, True) then begin Reg.WriteString(name,value); Reg.CloseKey; end; finally Reg.Free; end; end; function LoadOption(Name, Key, Default : String;Root : HKey) : String; Var Reg : TRegistry; begin result:=default; Reg := TRegistry.Create; try Reg.RootKey := root; if Reg.OpenKey(Key, True) then begin if Reg.ValueExists(name) then result:=Reg.ReadString(name) else result:=default; Reg.CloseKey; end; finally Reg.Free; end; end; procedure DelOption (Name, Key : String;Root : HKey); Var Reg : TRegistry; begin Reg := TRegistry.Create; try Reg.RootKey := root; if Reg.OpenKey(Key, True) then begin if Reg.ValueExists(name) then Reg.DeleteValue(name); Reg.CloseKey; end; finally Reg.Free; end; end; end.
unit DelForExTestOldNew; {$OPTIMIZATION off} interface uses Windows, Classes, SysUtils, TestFrameWork, GX_CodeFormatterTypes, GX_CodeFormatterSettings, GX_CodeFormatterDefaultSettings, GX_CodeFormatterEngine, GX_GenericUtils; type {Tests that compare the output of the original dll with the output of the current compile.} TTestCompareOldNew = class(TTestCase) private FLastActual: string; FSettings: TCodeFormatterEngineSettings; FNewFormatter: TCodeFormatterEngine; procedure CompareOldNew(const _Input, _Expected: TGxUnicodeString; const _Description: string); virtual; procedure TestFile(const _Filename: string); protected function GetFormatSettings: TCodeFormatterEngineSettings; virtual; abstract; procedure SetUp; override; procedure TearDown; override; published procedure testJustOpeningComment; procedure testJustOpeningStarCommentInAsm; procedure TabBeforeEndInAsm; procedure testEmptyProgram; procedure testEmptyUnit; procedure testPreview; virtual; procedure testProblems; virtual; procedure testProblemRus; procedure testCompilerDirectives; procedure testDelforEngine; procedure testDelforTypes; procedure testDelForStack; procedure testoObjects; procedure testDelforexPackage9; procedure testDelforExpert; procedure testDelforBookmarks; procedure testDelforDefaultSettings; procedure testElseAtEnd; procedure testStrictVisibility; virtual; procedure testLargeUnit1; virtual; procedure testIndentComment; virtual; procedure testUnterminatedString; virtual; procedure testStringWithSingleQuotes; procedure testEmptyStringAssignment; procedure testHashCharStrings; // this crashes the original DLL (fixed in the new one) // procedure testLargeUnit2; end; //type // TTestOldNewHeadworkFormatting = class(TTestCompareOldNew) // protected // function GetFormatSettings: TSettings; override; // published // procedure testPreview; override; // procedure testLargeUnit1; override; // procedure testIndentComment; override; // procedure testDelforexPackage9; // end; type TTestOldNewBorlandFormatting = class(TTestCompareOldNew) protected function GetFormatSettings: TCodeFormatterEngineSettings; override; published end; //type // TTestOldNewDelforFormatting = class(TTestCompareOldNew) // protected // function GetFormatSettings: TSettings; override; // published // procedure testLargeUnit1; override; // procedure testIndentComment; override; // procedure testDelforexPackage9; // end; //type // TTestAlign = class(TTestOldNewDelforFormatting) // protected // function GetFormatSettings: TSettings; override; // published // procedure testPreview; override; // end; //type // TTestCaptializationFile = class(TTestCompareOldNew) // private // {: This list can have one of 3 states: // 1. it is empty -> the results are expected to be the same // 2. it is not empty -> the results are expected to differ at the lines stored in the list // 3. it is NIL -> the files are expected to differ } // FExpectedCapDifferenceLines: TList; // protected // function GetFormatSettings: TSettings; override; // procedure CheckCaptialization(const _Description: string); override; // procedure SetUp; override; // procedure TearDown; override; // published // procedure testProblems; override; // procedure testStrictVisibility; override; // procedure testLargeUnit1; override; // procedure testIndentComment; override; // procedure testDelforexPackage9; // end; implementation uses Dialogs; procedure TTestCompareOldNew.SetUp; begin FSettings := GetFormatSettings; FNewFormatter := TCodeFormatterEngine.Create; FNewFormatter.Settings.Settings := FSettings; end; procedure TTestCompareOldNew.TearDown; begin FNewFormatter.Free; end; procedure TTestCompareOldNew.CompareOldNew(const _Input, _Expected: TGxUnicodeString; const _Description: string); var st: TGxUnicodeStringList; begin st := TGxUnicodeStringList.Create; try st.Text := _Input; Check(FNewFormatter.Execute(st), 'Error in formatter engine'); FLastActual := st.Text; CheckEquals(_Expected, FLastActual, _Description + ' had unexpected differences') finally st.Free; end; end; procedure TTestCompareOldNew.testJustOpeningComment; begin TestFile('OpeningCommentOnly'); end; procedure TTestCompareOldNew.testElseAtEnd; begin TestFile('ElseAtEnd'); end; procedure TTestCompareOldNew.testJustOpeningStarCommentInAsm; begin // I actually thought this would crash... TestFile('OpeningStarCommentInAsm'); end; procedure TTestCompareOldNew.TabBeforeEndInAsm; begin TestFile('TabBeforeEndInAsm'); end; procedure TTestCompareOldNew.testEmptyProgram; begin TestFile('EmptyProgram'); end; procedure TTestCompareOldNew.testEmptyUnit; begin TestFile('EmptyUnit'); end; procedure TTestCompareOldNew.testIndentComment; begin TestFile('IndentComment'); end; procedure TTestCompareOldNew.testUnterminatedString; begin TestFile('UnterminatedString'); end; procedure TTestCompareOldNew.testStringWithSingleQuotes; begin // note this actually contains a string with the TEXT #13#10: // >hello ' #13#10);< TestFile('StringWithSingleQuote'); end; procedure TTestCompareOldNew.testEmptyStringAssignment; begin TestFile('EmptyStringAssignment'); end; procedure TTestCompareOldNew.testHashCharStrings; begin TestFile('HashCharStrings'); end; procedure TTestCompareOldNew.TestFile(const _Filename: string); var InputStr: TStringList; ExpectedStr: TStringList; s: string; begin InputStr := TStringList.Create; ExpectedStr := TStringList.Create; try s := 'unittests\testcases\input\testfile_' + _Filename + '.pas'; InputStr.LoadFromFile(s); s := 'unittests\testcases\expected-' + ClassName + '\testfile_' + _Filename + '.pas'; ExpectedStr.LoadFromFile(s); try CompareOldNew(InputStr.Text, ExpectedStr.Text, _Filename); except InputStr.Text := FLastActual; s := 'unittests\testcases\expected-' + ClassName + '\testfile_' + _Filename + '.out'; InputStr.SaveToFile(s); raise; end; finally ExpectedStr.Free; InputStr.Free; end; end; procedure TTestCompareOldNew.testPreview; begin TestFile('preview'); end; procedure TTestCompareOldNew.testProblems; begin TestFile('problems'); end; procedure TTestCompareOldNew.testProblemRus; begin TestFile('problemrus'); end; procedure TTestCompareOldNew.testCompilerDirectives; begin // the new engine also recognises '(*$' as directives // and since all configurations uppercase them, there are two differences TestFile('compilerdirectives'); end; procedure TTestCompareOldNew.testStrictVisibility; begin // the new dll does not indent "strict private" / "strict protected" TestFile('strictvisibility'); end; procedure TTestCompareOldNew.testLargeUnit1; begin // TestFile('unittests\testcases\input\testunit_xdom_3_1.pas'); end; // this test crashes the old dll (access violation), the new one doesn't //procedure TTestCompareOldNew.testLargeUnit2; //begin // TestFile('unittests\testcases\input\testunit_VirtualTrees.pas'); //end; procedure TTestCompareOldNew.testDelforEngine; begin TestFile('GX_CodeFormatterEngine'); end; procedure TTestCompareOldNew.testDelforTypes; begin TestFile('GX_CodeFormatterTypes'); end; procedure TTestCompareOldNew.testDelForStack; begin TestFile('GX_CodeFormatterStack'); end; procedure TTestCompareOldNew.testoObjects; begin TestFile('GX_CollectionLikeLists'); end; procedure TTestCompareOldNew.testDelforexPackage9; begin TestFile('DelforexPackage9'); end; procedure TTestCompareOldNew.testDelforExpert; begin TestFile('DeforExpert'); end; procedure TTestCompareOldNew.testDelforBookmarks; begin TestFile('GX_CodeFormatterBookmarks'); end; procedure TTestCompareOldNew.testDelforDefaultSettings; begin TestFile('GX_CodeFormatterDefaultSettings'); end; { TTestHeadworkFormatting } //function TTestOldNewHeadworkFormatting.GetFormatSettings: TSettings; //begin // Result := HeadworkDefaults; //end; // //procedure TTestOldNewHeadworkFormatting.testDelforexPackage9; //begin // FExpectDifferentFromInput := False; // inherited; //end; // //procedure TTestOldNewHeadworkFormatting.testIndentComment; //begin // FExpectDifferentFromInput := False; // inherited; //end; // //procedure TTestOldNewHeadworkFormatting.testLargeUnit1; //begin // FExpectedDifferenceLines.Add(pointer(3887)); // inherited; //end; // //procedure TTestOldNewHeadworkFormatting.testPreview; //begin // // headwork formatting is the only one that actually changes the preview file // TestFile('packagewiz\preview.pas'); //end; { TTestBorlandFormatting } function TTestOldNewBorlandFormatting.GetFormatSettings: TCodeFormatterEngineSettings; begin Result := BorlandDefaults; end; { TTestOldNewDelforFormatting } //function TTestOldNewDelforFormatting.GetFormatSettings: TSettings; //begin // Result := DelforDefaults; //end; // //procedure TTestOldNewDelforFormatting.testDelforexPackage9; //begin // FExpectDifferentFromInput := False; // inherited; //end; // //procedure TTestOldNewDelforFormatting.testIndentComment; //begin // FExpectDifferentFromInput := False; // inherited; //end; // //procedure TTestOldNewDelforFormatting.testLargeUnit1; //begin // FExpectedDifferenceLines.Add(pointer(3883)); // inherited; //end; { TTestAlign } //function TTestAlign.GetFormatSettings: TSettings; //begin // Result := inherited GetFormatSettings; // Result.Parser.AlignComments := True; // Result.Parser.AlignVar := True; //end; // //procedure TTestAlign.testPreview; //begin // FExpectDifferentFromInput := True; // TestFile('packagewiz\preview.pas'); //end; { TTestCaptializationFile } //procedure TTestCaptializationFile.CheckCaptialization(const _Description: string); //var // OldCap: TStringList; // NewCap: TStringList; // OldCapFile: string; // NewCapFile: string; // NameOnly: string; //begin // NameOnly := ExtractFileName(_Description); // OldCapFile := NameOnly + '-captialization-failed-' + ClassName + 'OldFormatter'; // NewCapFile := NameOnly + '-captialization-failed-' + ClassName + 'NewFormatter'; // // FOrigFormatter.SaveCapFile(OldCapFile); // FNewFormatter.SaveCapFile(NewCapFile); // // OldCap := TStringList.Create; // NewCap := TStringList.Create; // try // OldCap.LoadFromFile(OldCapFile); // NewCap.LoadFromFile(NewCapFile); // CompareLines(OldCap, NewCap, FExpectedCapDifferenceLines, 'captitalization file'); // DeleteFile(OldCapFile); // DeleteFile(NewCapFile); // finally // NewCap.Free; // OldCap.Free; // end; // inherited; //end; // //function TTestCaptializationFile.GetFormatSettings: TSettings; //begin // Result := DelforDefaults; // Result.Parser.FillNewWords := fmAddNewWord; //end; // //procedure TTestCaptializationFile.SetUp; //begin // inherited; // FExpectedCapDifferenceLines := TList.Create; //end; // //procedure TTestCaptializationFile.TearDown; //begin // FExpectedCapDifferenceLines.Free; // inherited; //end; // //procedure TTestCaptializationFile.testStrictVisibility; //begin // FExpectedDifferenceLines.Add(pointer(6)); // FExpectedDifferenceLines.Add(pointer(7)); // FExpectedDifferenceLines.Add(pointer(8)); // FExpectedDifferenceLines.Add(pointer(9)); // FExpectedCapDifferenceLines.Add(pointer(1)); // TestFile('unittests\testcases\input\testunit_strictvisibility.pas'); //end; // //procedure TTestCaptializationFile.testLargeUnit1; //begin // FExpectedDifferenceLines.Add(pointer(3883)); // FExpectedCapDifferenceLines.Add(pointer(1661)); // inherited; //end; // //procedure TTestCaptializationFile.testProblems; //begin // FExpectedCapDifferenceLines.Add(pointer(22)); // FExpectedCapDifferenceLines.Add(pointer(62)); // inherited; //end; // //procedure TTestCaptializationFile.testIndentComment; //begin // FExpectDifferentFromInput := False; // inherited; //end; // //procedure TTestCaptializationFile.testDelforexPackage9; //begin // FExpectDifferentFromInput := False; // inherited; //end; initialization // RegisterTest('OldNew', TTestOldNewHeadworkFormatting.Suite); // RegisterTest('OldNew', TTestOldNewBorlandFormatting.Suite); // RegisterTest('OldNew', TTestOldNewDelforFormatting.Suite); // RegisterTest('OldNew', TTestAlign.Suite); // RegisterTest('OldNew', TTestCaptializationFile.Suite); // RegisterTest('timing', TTestTimingHeadworkFormatting.Suite); // RegisterTest('timing', TTestTimingBorlandFormatting.Suite); // RegisterTest('timing', TTestTimingDelforFormatting.Suite); end.
unit NotifyUnit; {$Z4} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "GblAdapterLib" // Модуль: "w:/garant6x/implementation/Garant/GblAdapterLib/NotifyUnit.pas" // Delphi интерфейсы для адаптера (.pas) // Generated from UML model, root element: <<Interfaces::Category>> garant6x::GblAdapterLib::Notify // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// interface uses BaseTypesUnit ; type INotification = interface; { - предварительное описание INotification. } INotifyManager = interface; { - предварительное описание INotifyManager. } PNotifyType = ^TNotifyType; TNotifyType = ( NT_LONG_OPERATION_START , NT_LONG_OPERATION_END , NT_MONITORING_UPDATE , NT_SHUTDOWN , NT_LOGOUT , NT_BASE_UPDATE_START , NT_BASE_UPDATE_END , NT_BASE_UPDATE_FAILED , NT_CONSULTATION_RECEIVED // Получен ответ , NT_CONSULTATION_NOT_SENT // Консультация не отправлена , NT_NO_SUBSCRIPTION // Консультация не отправлена, тк не прошла валидация , NT_INTERNET_AVAILABLE // Приходит при успешной связи с удалёнными сервисами (СК или сервер ревизий документов) , NT_NEW_CHAT_MESSAGES_RECEIVED // получены новые сообщения для чата , NT_CHAT_CONTACT_ADDED // добавлен новый контакт для чата , NT_CHAT_CONTACT_REMOVED // удалён контакт чата , NT_INTERNET_NOT_AVAILABLE // нет доступа к серверу ревизий документов ); // Callback на облочке для получения сообщений с адаптера IListener = interface (IInterface) ['{DFAC9F0B-95D4-4E9B-8525-1A10739E41A9}'] procedure Fire ( const aNotify: INotification ); stdcall; end; INotification = interface (IInterface) ['{30BDF2EC-FBC4-4477-AC3B-5BB8CBFC8A4D}'] function DontUseMe: Pointer; procedure GetData (out aRet {: IVariant}); stdcall; function GetId (): TNotifyType; stdcall; end; // Менеджер, обеспечивающий обмен сообщениями между адаптером и оболочкой INotifyManager = interface (IInterface) ['{4E4282C5-1F27-4A9E-8F8D-3CC8B00FDA97}'] function DontUseMe: Pointer; procedure RegisterListenerForNotify ( aNotifyId: TNotifyType; const aListener: IListener ); stdcall; end; implementation end.
unit UFunctions; interface uses SysUtils, Classes, Windows, Sockets; const nl= #13+#10; sep = '***************************'; //send result SR_SENDED = 0; SR_NO_MORE_THEN_15 = 1; SR_UNKNOWN_ERROR = 255; SR_CANT_CONNECT = 2; //ProcessSMSText PSMST_OK = 0; PSMST_BIG_LEN = 1; //SMS-LENGTH SMS_LENGTH_TRANSLIT = 156; SMS_LENGTH_NOTRANSLIT = 66; SPLIT_SMS_IS_ZERO = 1; SPLIT_SMS_IS_BIG = 2; //FormWidth FW_NORMAL = 264; FW_EXTENDED = 563; //поиск по телефонной книге MAX_SMS_CNT_NOTRANS = 3; //максимальное число сообщений MAX_SMS_CNT_TRANS = 1; // MY_ATOM = 'SMS-Sender_ver_1.0_beta'; type //результат CalSymCnt TCalcSymCnt = record sms_cnt: word; sym_cnt: word; end; //результат SplitSMS PTSplitSMSInfo = ^TSplitSMSInfo; TSplitSMSInfo = record sms_cnt: word; sym_cnt_more: word; //количесво оставшихся символов split_res: byte; //результат нарезки max_sms: word end; //запись контакта TContactRec = record name: string[50]; phonenumber: string[11]; end; // TPrepairSMSResult = record new_sms: string; new_len: integer; end; //Запись настроек TSettingsRec = record savethehistory: boolean; signature: string[10]; autosignat: boolean; useProxy: boolean; proxyAddress: String[20]; proxyPort: string[6]; DublicateOnMail: boolean; //для отладки Reserved1: integer; //сюда мы пишем значение параметра флажка автотранслитерации Reserved2: integer; Reserved3: integer; end; //запись истории THistoryRec = record DT: TDateTime; Number: string[11]; MessageText: string[255]; end; //сокет прокис-сервера (HTTP) TConnectionData = record server: TSocketHost; port: TSocketPort; end; //export procedure ShowMyMessage(text: string); function isValidNumber(num: string): boolean; function SplitSMS(sms_text: string; trans_on: boolean; var split_info: TSplitSMSInfo): TStringList; function GetPrefByNumber(var num: string; cut: boolean=false): string; implementation //сообщение procedure ShowMyMessage(text: string); begin MessageBox(0,@text[1],'SMS-Sender',MB_OK); end; //проверяет является ли номер корректным function isValidNumber(num: string): boolean; begin result:= false; if (Length(Trim(num))<11) then exit; if num[1]<>'7' then exit; result:= true; end; //возвращает вес символа function VesSimvola(symb: char; trans_on: boolean): byte; const s_2_sim = 'еЕюЮшШяЯжЖ'; s_3_sim = 'щЩ'; begin result:= 1; if trans_on = false then exit; if pos(symb,s_2_sim)>0 then Result:= 2 else if pos(symb,s_3_sim)>0 then Result:= 3; end; //возвращает sms порезанное на части function SplitSMS(sms_text: string; trans_on: boolean; var split_info: TSplitSMSInfo): TStringList; var n: integer; buf: string; head_str: string; sym_cnt, sms_cnt: word; max_sym: word; begin Result:= nil; //получаем макс. длину сообщени if trans_on then begin max_sym:= SMS_LENGTH_TRANSLIT; split_info.max_sms:= MAX_SMS_CNT_TRANS end else begin max_sym:= SMS_LENGTH_NOTRANSLIT; split_info.max_sms:= MAX_SMS_CNT_NOTRANS end; if Trim(sms_text) = '' then begin split_info.split_res:= SPLIT_SMS_IS_ZERO; //результат - пустое sms split_info.sym_cnt_more:= max_sym; exit end; //вычисляем длину сообщения c учетом транслитерации for n:= 1 to Length(sms_text) do inc(sym_cnt, VesSimvola(sms_text[n],trans_on)); if sym_cnt > max_sym then dec(max_sym,4); //при количестве sms больше 1 длина заголовка уменьш. на 4с //вычисляем количество sms sms_cnt:= (sym_cnt div max_sym); if (sym_cnt mod max_sym) <> 0 then begin inc(sms_cnt); split_info.sym_cnt_more:= max_sym - (sym_cnt mod max_sym) end else sym_cnt:= 0; split_info.sms_cnt:= sms_cnt; if sms_cnt > split_info.max_sms then begin split_info.split_res:= SPLIT_SMS_IS_BIG; //результат - слишком длинное sms exit end; Result:= TStringList.Create; if sms_cnt = 1 then begin Result.Add(sms_text); exit; end; n:= 1; while Length(sms_text) > 0 do begin head_str:= IntToStr(sms_cnt)+'.'+IntToStr(n)+' '; //типа 3.1 buf:= head_str + Copy(sms_text,1,max_sym); Result.Add(buf); delete(sms_text,1,max_sym); inc(n) end end; //возвращает префикс номера function GetPrefByNumber(var num: string; cut: boolean=false): string; begin Result:= 'error'; if not isValidNumber(num) then exit; Result:= Copy(num,1,4); if cut then num:= Copy(num,5,7); end; end.
unit uAlerts; interface uses SysUtils, Types, Graphics; procedure Alert(S: string); var AlertMessage: string = ''; AlertColor: TColor = clWhite; AMsgPos: Byte = 3; AMsgClr: Byte = 0; implementation uses uSCR, uGUI, uUtils, uResFont; procedure Alert(S: string); begin AMsgPos := StrToInt(Copy(S, 1, 1)); AMsgClr := StrToInt(Copy(S, 2, 1)); Delete(S, 1, 2); AlertMessage := S; case AMsgClr of 0: AlertColor := clBlack; 1: AlertColor := clGray; 2: AlertColor := clGreen; 3: AlertColor := clYellow; 4: AlertColor := clRed; 5: AlertColor := clMaroon; 6: AlertColor := clBlue; 7: AlertColor := clMoneyGreen; 8: AlertColor := clSkyBlue; 9: AlertColor := clCream; end; end; end.
unit browsermodules; {$mode delphi} interface uses Classes, SysUtils; type TBrowserModuleUIElement = (bmueEnabledDisableMenu, bmueCommandsSubmenu); TBrowserModuleUIElements = set of TBrowserModuleUIElement; { TBrowserModule } TBrowserModule = class public ShortDescription: string; Activated: Boolean; constructor Create; virtual; // function GetModuleUIElements(): TBrowserModuleUIElements; virtual; // For active/disabled modules function HandleOnPageLoad(AInput: string; out AOutput: string): Boolean; virtual; // For expansions function GetCommandCount: Integer; virtual; function GetCommandName(AID: Integer): string; virtual; procedure ExecuteCommand(AID: Integer); virtual; end; procedure RegisterBrowserModule(AModule: TBrowserModule); function GetBrowserModule(AIndex: Integer): TBrowserModule; function GetBrowserModuleCount(): Integer; implementation var gBrowserModules: TList; procedure RegisterBrowserModule(AModule: TBrowserModule); begin if AModule = nil then raise Exception.Create('[RegisterBrowserModule] Attempted to register a nil Module'); gBrowserModules.Add(AModule); end; function GetBrowserModule(AIndex: Integer): TBrowserModule; begin if AIndex < 0 then Exit(nil); Result := TBrowserModule(gBrowserModules.Items[AIndex]); end; function GetBrowserModuleCount: Integer; begin Result := gBrowserModules.Count; end; { TBrowserModule } constructor TBrowserModule.Create; begin end; function TBrowserModule.GetModuleUIElements: TBrowserModuleUIElements; begin Result := [bmueEnabledDisableMenu]; end; function TBrowserModule.HandleOnPageLoad(AInput: string; out AOutput: string): Boolean; begin AOutput := ''; Result := False; end; function TBrowserModule.GetCommandCount: Integer; begin Result := 0; end; function TBrowserModule.GetCommandName(AID: Integer): string; begin Result := ''; end; procedure TBrowserModule.ExecuteCommand(AID: Integer); begin end; initialization gBrowserModules := TList.Create; finalization gBrowserModules.Free; end.
unit MainFrm; 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.Edit, FMX.ScrollBox, FMX.Memo, DW.Firebase.InstanceId, DW.Firebase.Messaging; type TfrmMain = class(TForm) FirebaseCMLabel: TLabel; TokenLabel: TLabel; TokenMemo: TMemo; MessagesLabel: TLabel; MessagesMemo: TMemo; private FInstanceId: TFirebaseInstanceId; FMessaging: TFirebaseMessaging; FToken: string; procedure InstanceIdTokenRefreshHandler(Sender: TObject; const AToken: string); procedure MessagingMessageReceivedHandler(Sender: TObject; const APayload: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation {$R *.fmx} uses // DW DW.OSLog; constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FInstanceId := TFirebaseInstanceId.Create; FInstanceId.OnTokenRefresh := InstanceIdTokenRefreshHandler; FMessaging := TFirebaseMessaging.Create; FMessaging.OnMessageReceived := MessagingMessageReceivedHandler; // The first time the app is run, token will be blank at this point, however the OnTokenRefreshHandler will be called TokenMemo.Lines.Text := FInstanceId.Token; TOSLog.d('Token at startup: %s', [TokenMemo.Lines.Text]); FMessaging.Connect; end; destructor TfrmMain.Destroy; begin FInstanceId.Free; FMessaging.Free; inherited; end; procedure TfrmMain.InstanceIdTokenRefreshHandler(Sender: TObject; const AToken: string); begin TokenMemo.Lines.Text := AToken; TOSLog.d('Token in OnTokenRefresh: %s', [TokenMemo.Lines.Text]); end; procedure TfrmMain.MessagingMessageReceivedHandler(Sender: TObject; const APayload: TStrings); begin MessagesMemo.Lines.AddStrings(APayload); end; end.
unit Com_Streams; interface uses Windows, Classes, SyncObjs, Sysutils, sysconst, IdGlobal, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL; type TStreamState = (ssDisconnected, ssInitialize, ssConnecting, ssConnected, ssConnectFailed); TFileStream2 = class(TFileStream) protected FExceptions : Boolean; OverlapIOPending: Boolean; public property Exceptions : Boolean read FExceptions write FExceptions; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; procedure Flush; end; TTextStream = class(TFileStream2) protected FBuf : AnsiString; FBufPtr : PChar; FEof : Boolean; procedure ReadBlock; public constructor Create(const FileName: String; Mode: Word = fmOpenRead or fmShareDenyNone); class function Append(const FileName: String; Mode: Word = fmOpenReadWrite or fmShareDenyWrite) : TTextStream; overload; procedure Append; overload; function ReadCh : Char; function ReadLn : AnsiString; procedure WriteLn(S : String); procedure Write(const S : String); reintroduce; property Eof: boolean read FEof; end; function GetOSErrorMessage(ErrorCode : Integer) : String; overload; procedure RaiseOSError; overload; procedure RaiseOSError(err : Integer); overload; implementation uses Consts, Contnrs, Winsock, Com_Sync, Math, Variants, StrUtils; procedure RaiseOSError; begin RaiseOSError(GetLastError); end; procedure RaiseOSError(err : Integer); var Error: EOSError; begin if err = 0 then Exit; Error := EOSError.Create(GetOSErrorMessage(err)); Error.ErrorCode := err; SetLastError(err); raise Error; end; function GetOSErrorMessage(ErrorCode : Integer) : String; begin Result := TrimRight(SysErrorMessage(ErrorCode)); if Result = '' then Result := TrimRight(Format(SOSError,[ErrorCode,''])); end; { TFileStream2 } function TFileStream2.Read(var Buffer; Count: Longint): Longint; begin SetLastError(0); Result := inherited Read(Buffer,Count); if FExceptions and (Result = 0) and (GetLastError <> 0) then RaiseOSError; end; function TFileStream2.Write(const Buffer; Count: Longint): Longint; begin Result := inherited Write(Buffer,Count); if FExceptions and (Result < Count) then RaiseOSError; end; procedure TFileStream2.Flush; begin end; { TTextStream } constructor TTextStream.Create(const FileName: String; Mode: Word = fmOpenRead or fmShareDenyNone); begin inherited Create(FileName,Mode); SetLength(FBuf,8192); ReadBlock; end; class function TTextStream.Append(const FileName: String; Mode: Word = fmOpenReadWrite or fmShareDenyWrite) : TTextStream; var NeedToCreate : Boolean; begin NeedToCreate := not FileExists(FileName); if NeedToCreate then begin FileClose(FileCreate(FileName)); Sleep(0); end; Result := inherited Create(FileName,Mode); if not NeedToCreate then try SetLength(Result.FBuf,8192); Result.Append; except FreeAndNil(Result); raise; end; end; procedure TTextStream.Append; begin Seek(0,soFromEnd); ReadBlock; end; procedure TTextStream.ReadBlock; var r : Integer; begin r := Read(FBuf[1],Length(FBuf)); SetLength(FBuf,r); FEof := FBuf = ''; if not FEof then FBufPtr := @Fbuf[1] else FBufPtr := nil; end; function TTextStream.ReadLn : AnsiString; var P, Start: PChar; S: AnsiString; begin Result := ''; P := FBufPtr; while P <> nil do begin Start := P; while not CharInSet(P^,[#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); Result := Result + S; if P^ = #0 then begin ReadBlock; P := FBufPtr; if FEof then break; continue; end; if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); break; end; FBufPtr := P; end; function TTextStream.ReadCh : Char; procedure IncBufPtr; begin Inc(FBufPtr); if FBufPtr^ = #0 then ReadBlock; end; begin if FEof then RaiseOSError(ERROR_HANDLE_EOF); Result := FBufPtr^; IncBufPtr; if (Result = #13) and not FEof and (FBufPtr^ = #10) then IncBufPtr; end; procedure TTextStream.WriteLn(S : String); begin S := S + sLineBreak; WriteBuffer(S[1],Length(S)); end; procedure TTextStream.Write(const S : String); begin WriteBuffer(S[1],Length(S)); end; initialization finalization end.
{!DOCTOPIC}{ Type » TBoxArray } {!DOCREF} { @method: function TBoxArray.Len(): Int32; @desc: Returns the length of the array. Same as 'Length(arr)' } function TBoxArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TBoxArray.IsEmpty(): Boolean; @desc: Returns True if the array is empty. Same as 'Length(arr) = 0' } function TBoxArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure TBoxArray.Append(const B:TBox); @desc: Add another string to the array } procedure TBoxArray.Append(const B:TBox); var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := B; end; {!DOCREF} { @method: procedure TBoxArray.Insert(idx:Int32; Value:TBox); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure TBoxArray.Insert(idx:Int32; Value:TBox); var l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); MemMove(Self[idx], self[idx+1], (L-Idx)*SizeOf(TBox)); Self[idx] := value; end; {!DOCREF} { @method: procedure TBoxArray.Del(idx:Int32); @desc: Removes the element at the given index c'idx' } procedure TBoxArray.Del(idx:Int32); var i,l:Int32; begin l := Length(Self); if (l <= idx) or (idx < 0) then Exit(); if (L-1 <> idx) then MemMove(Self[idx+1], self[idx], (L-Idx)*SizeOf(TBox)); SetLength(Self, l-1); end; {!DOCREF} { @method: procedure TBoxArray.Remove(Value:TBox); @desc: Removes the first element from left which is equal to c'Value' } procedure TBoxArray.Remove(Value:TBox); begin Self.Del( Self.Find(Value) ); end; {!DOCREF} { @method: function TBoxArray.Pop(): TBox; @desc: Removes and returns the last item in the array } function TBoxArray.Pop(): TBox; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function TBoxArray.PopLeft(): TBox; @desc: Removes and returns the first item in the array } function TBoxArray.PopLeft(): TBox; begin Result := Self[0]; MemMove(Self[1], Self[0], SizeOf(Int32)*Length(Self)); SetLength(Self, High(self)); end; {!DOCREF} { @method: function TBoxArray.Slice(Start,Stop: Int32; Step:Int32=1): TBoxArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to c'step' past items. You can give it negative start, and stop, then it will wrap around based on length(..) If c'Start >= Stop', and c'Step <= -1' it will result in reversed output. [note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note] } function TBoxArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): TBoxArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure TBoxArray.Extend(Arr:TBoxArray); @desc: Extends the array with an array } procedure TBoxArray.Extend(Arr:TBoxArray); var L:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); MemMove(Arr[0],Self[L],Length(Arr)*SizeOf(TBox)); end; {!DOCREF} { @method: function TBoxArray.Find(Value:TBox): Int32; @desc: Searces for the given value and returns the first position from the left. } function TBoxArray.Find(Value:TBox): Int32; begin Result := exp_Find(Self,[Value]); end; {!DOCREF} { @method: function TBoxArray.Find(Sequence:TBoxArray): Int32; overload; @desc: Searces for the given sequence and returns the first position from the left. } function TBoxArray.Find(Sequence:TBoxArray): Int32; overload; begin Result := exp_Find(Self,Sequence); end; {!DOCREF} { @method: function TBoxArray.FindAll(Value:TBox): TIntArray; @desc: Searces for the given value and returns all the position where it was found. } function TBoxArray.FindAll(Value:TBox): TIntArray; begin Result := exp_FindAll(Self,[value]); end; {!DOCREF} { @method: function TBoxArray.FindAll(Sequence:TBoxArray): TIntArray; overload; @desc: Searces for the given sequence and returns all the position where it was found. } function TBoxArray.FindAll(Sequence:TBoxArray): TIntArray; overload; begin Result := exp_FindAll(Self,sequence); end; {!DOCREF} { @method: function TBoxArray.Contains(val:TBox): Boolean; @desc: Checks if the arr contains the given value c'val' } function TBoxArray.Contains(val:TBox): Boolean; begin Result := Self.Find(val) <> -1; end; {!DOCREF} { @method: function TBoxArray.Count(val:TBox): Int32; @desc: Counts all the occurances of the given value c'val' } function TBoxArray.Count(val:TBox): Int32; begin Result := Length(Self.FindAll(val)); end; {!DOCREF} { @method: procedure TBoxArray.Sort(key:TSortKey=sort_Default); @desc: Sorts the array [not supported] } procedure TBoxArray.Sort(key:TSortKey=sort_Default); begin //case key of // sort_default, sort_lex: se.SortTSA(Self,IgnoreCase); // sort_logical: se.SortTSANatural(Self); //else // WriteLn('TSortKey not supported'); //end; WriteLn('TBoxArray sorting is not supported yet'); end; {!DOCREF} { @method: function TStringArray.Sorted(key:TSortKey=sort_Default; IgnoreCase:Boolean=False): TStringArray; @desc: Sorts and returns a copy of the array [not supported] } function TBoxArray.Sorted(key:TSortKey=sort_Default): TStringArray; begin //Result := Self.Slice(); //case key of // sort_default, sort_lex: se.SortTSA(Result,IgnoreCase); // sort_logical: se.SortTSANatural(Result); //else // WriteLn('TSortKey not supported'); //end; WriteLn('TBoxArray sorting is not supported yet'); end; {!DOCREF} { @method: function TBoxArray.Reversed(): TBoxArray; @desc: Creates a reversed copy of the array } function TBoxArray.Reversed(): TBoxArray; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure TBoxArray.Reverse(); @desc: Reverses the array } procedure TBoxArray.Reverse(); begin Self := Self.Slice(,,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================}
unit LineNoMemo; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls; type TLineNoMemo = class(TMemo) private function GetColumNo: Integer; function GetLineNo: Integer; { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } property LineNo: Integer read GetLineNo; property ColumNo: Integer read GetColumNo; end; procedure Register; implementation uses Messages; procedure Register; begin RegisterComponents('componenteOW', [TLineNoMemo]); end; { TLineNoMemo } function TLineNoMemo.GetColumNo: Integer; begin Result := SelStart - Perform(EM_LINEINDEX, LineNo, 0); end; function TLineNoMemo.GetLineNo: Integer; begin Result := Perform(EM_LINEFROMCHAR, 0, 1); end; end.
unit ADC.DC; interface uses System.SysUtils, System.Classes, System.Types, System.Variants, System.StrUtils, System.AnsiStrings, Winapi.Windows, Winapi.ActiveX, Vcl.ComCtrls, ActiveDs_TLB, JwaLmAccess, JwaLmApiBuf, ADC.LDAP, JwaDSGetDc, JwaActiveDS, ADC.Types, ADC.Common, ADC.AD; type TDCInfo = class(TObject) private const ERROR_SUCCESS = $0; ERROR_INVALID_DOMAINNAME = $4BC; ERROR_INVALID_FLAGS = $3EC; ERROR_NOT_ENOUGH_MEMORY = $8; ERROR_NO_SUCH_DOMAIN = $54B; protected destructor Destroy; override; private FAdsApi: Byte; FName: string; FIPAddr: string; FAddr: string; FDomainDnsName: string; FDomainNetbiosName: string; FDomainGUID: TGUID; FDnsForestName: string; FSchemaAttributes: TStringList; procedure GetSchemaAttributes(AClass: array of string); overload; procedure GetSchemaAttributes(AConn: PLDAP; AClass: array of string); overload; function GetAttributeSyntax(AConn: PLDAP; AAttr: string): string; public class procedure EnumDomainControllers(const outDCList: TStrings; AdsApi: Byte); constructor Create(ADomain, ADCName: string; AAdsApi: Byte); reintroduce; function AttributeExists(AAttr: string): Boolean; procedure BuildTree(ATree: TTreeView); procedure RefreshData; published property AdsApi: Byte read FAdsApi write FAdsApi; property UserAttributes: TStringList read FSchemaAttributes; property DomainDnsName: string read FDomainDnsName; property Name: string read FName; property IPAddress: string read FIPAddr; property Address: string read FAddr; property DomainNetbiosName: string read FDomainNetbiosName; property DomainGUID: TGUID read FDomainGUID; property DnsForestName: string read FDnsForestName; end; function DsBind(DomainControllerName: LPCTSTR; DnsDomainName: LPCTSTR; var phDS: PHandle): DWORD; stdcall; function DsUnBind(var phDS: PHandle): DWORD; stdcall; implementation function DsBind; external 'ntdsapi.dll' name 'DsBindW'; function DsUnBind; external 'ntdsapi.dll' name 'DsUnBindW'; { TDCInfo } procedure TDCInfo.BuildTree(ATree: TTreeView); function GetNode(ParentNode: TTreeNode; NodeName: string): TTreeNode; var TmpNode: TTreeNode; begin if ParentNode = nil then TmpNode := ATree.Items.GetFirstNode else TmpNode := ParentNode.GetFirstChild; while (TmpNode <> nil) and (CompareText(TmpNode.Text, NodeName) <> 0) do TmpNode := TmpNode.GetNextSibling; Result := TmpNode; end; var ldapConn: PLDAP; RootDSE: IADs; TmpStr: string; i, j: Integer; CanonicalNames, NodeNames: TStringList; Node, ParentNode: TTreeNode; ContData: PADContainer; begin ATree.Items.BeginUpdate; ATree.Items.Clear; CanonicalNames := TStringList.Create; CanonicalNames.Sorted := True; NodeNames := TStringList.Create; NodeNames.StrictDelimiter := True; NodeNames.Delimiter := '/'; case FAdsApi of ADC_API_LDAP: begin ldapConn := nil; ServerBinding(FName, ldapConn, TExceptionProc(nil)); ADEnumContainers(ldapConn, CanonicalNames); ldap_unbind(ldapConn); end; ADC_API_ADSI: begin RootDSE := nil; ServerBinding(FName, @RootDSE, TExceptionProc(nil)); ADEnumContainers(RootDSE, CanonicalNames); RootDSE := nil; end; end; for i := 0 to CanonicalNames.Count - 1 do begin NodeNames.DelimitedText := CanonicalNames[i]; ParentNode := nil; for j := 0 to NodeNames.Count - 1 do begin Node := GetNode(ParentNode, NodeNames[j]); if Node = nil then begin TmpStr := ''; New(ContData); ContData^ := PADContainer(CanonicalNames.Objects[i])^; Node := ATree.Items.AddChildObject( ParentNode, NodeNames[j], ContData ); ContData^.Path := GetTreeNodePath(Node, TmpStr, '/'); if Node.Parent = nil then Node.ImageIndex := 0 else case ContData^.Category of AD_CONTCAT_CONTAINER: Node.ImageIndex := 1; AD_CONTCAT_ORGUNIT : Node.ImageIndex := 2; end; Node.SelectedIndex := Node.ImageIndex; end; ParentNode := Node; end; end; if ATree.Items.Count > 0 then ATree.TopItem.Expand(False); ATree.Items.EndUpdate; for i := CanonicalNames.Count - 1 downto 0 do if CanonicalNames.Objects[i] <> nil then begin Dispose(PADContainer(CanonicalNames.Objects[i])); CanonicalNames.Objects[i] := nil; end; CanonicalNames.Free; NodeNames.Free; end; constructor TDCInfo.Create(ADomain, ADCName: string; AAdsApi: Byte); begin FAdsApi := AAdsApi; FSchemaAttributes := TStringList.Create; FSchemaAttributes.Sorted := True; FDomainDnsName := ADomain; FName := ADCName; RefreshData; end; destructor TDCInfo.Destroy; begin FSchemaAttributes.Free; inherited; end; class procedure TDCInfo.EnumDomainControllers(const outDCList: TStrings; AdsApi: Byte); type PDomainsArray = ^TDomainsArray; TDomainsArray = array [1..100] of DS_DOMAIN_TRUSTS; var i: Integer; dwRet: DWORD; hGetDc: THandle; pszDnsHostName: LPTSTR; ulSocketCount: UINT; rgSocketAddresses: LPSOCKET_ADDRESS; Domains: PDomainsArray; DomainInfo: TDCInfo; begin for i := 0 to outDCList.Count - 1 do if outDCList.Objects[i] <> nil then outDCList.Objects[i].Free; outDCList.Clear; dwRet := DsEnumerateDomainTrusts( nil, DS_DOMAIN_PRIMARY {or DS_DOMAIN_IN_FOREST or DS_DOMAIN_DIRECT_OUTBOUND}, PDS_DOMAIN_TRUSTS(Domains), ulSocketCount ); if dwRet = ERROR_SUCCESS then for i := 1 to ulSocketCount do begin dwRet := DsGetDcOpen( PChar(Domains[i].DnsDomainName), DS_NOTIFY_AFTER_SITE_RECORDS, nil, nil, nil, DS_FORCE_REDISCOVERY, hGetDc ); if dwRet = ERROR_SUCCESS then begin while True do begin dwRet := DsGetDcNext( hGetDc, @ulSocketCount, @rgSocketAddresses, @pszDnsHostName ); case dwRet of ERROR_SUCCESS: begin DomainInfo := TDCInfo.Create(Domains[i].DnsDomainName, pszDnsHostName, AdsApi); outDCList.AddObject( DomainInfo.DomainDnsName + '|' + DomainInfo.Name, DomainInfo ); NetApiBufferFree(LPVOID(pszDnsHostName)); LocalFree(UInt64(rgSocketAddresses)); end; ERROR_NO_MORE_ITEMS: begin Break; end; ERROR_FILEMARK_DETECTED: begin { DS_NOTIFY_AFTER_SITE_RECORDS was specified in DsGetDcOpen and the end of the site-specific records was reached. } Continue; end; else begin Break; end; end; end; DsGetDcCloseW(hGetDc); end; end; NetApiBufferFree(Domains); end; procedure TDCInfo.GetSchemaAttributes(AConn: PLDAP; AClass: array of string); const AttrArray: array of AnsiString = [ 'subClassOf', 'systemAuxiliaryClass', 'mayContain', 'mustContain', 'systemMayContain', 'systemMustContain' ]; var returnCode: ULONG; errorCode: ULONG; morePages: Boolean; ldapBase: AnsiString; ldapFilter: AnsiString; ldapCookie: PLDAPBerVal; ldapPage: PLDAPControl; ldapControls: array[0..1] of PLDAPControl; ldapServerControls: PPLDAPControl; ldapCount: ULONG; ldapSearchResult: PLDAPMessage; ldapAttributes: array of PAnsiChar; ldapEntry: PLDAPMessage; ldapValues: PPAnsiChar; i: Integer; ldapClass: string; attr: AnsiString; begin if not Assigned(AConn) then Exit; ldapCookie := nil; ldapSearchResult := nil; ldapBase := 'CN=Schema,CN=Configuration,' + System.AnsiStrings.ReplaceText('DC=' + FDomainDnsName, '.', ',DC='); { Формируем набор атрибутов } SetLength(ldapAttributes, Length(AttrArray) + 1); for i := Low(AttrArray) to High(AttrArray) do ldapAttributes[i] := PAnsiChar(AttrArray[i]); for ldapClass in AClass do try { Формируем фильтр объектов AD } ldapFilter := '(&(objectCategory=classSchema)(lDAPDisplayName=' + ldapClass + '))'; ldapCookie := nil; { Постраничный поиск объектов AD } repeat returnCode := ldap_create_page_control( AConn, 1000, ldapCookie, 1, ldapPage ); if returnCode <> LDAP_SUCCESS then raise Exception.Create('Failure during ldap_create_page_control.'); ldapControls[0] := ldapPage; ldapControls[1] := nil; returnCode := ldap_search_ext_s( AConn, PAnsiChar(ldapBase), LDAP_SCOPE_ONELEVEL, PAnsiChar(ldapFilter), PAnsiChar(@ldapAttributes[0]), 0, nil,//@ldapControls, nil, nil, 0, ldapSearchResult ); if not (returnCode in [LDAP_SUCCESS, LDAP_PARTIAL_RESULTS]) then raise Exception.Create('Failure during ldap_search_ext_s.'); returnCode := ldap_parse_result( AConn^, ldapSearchResult, @errorCode, nil, nil, nil, ldapServerControls, False ); if ldapCookie <> nil then begin ber_bvfree(ldapCookie); ldapCookie := nil; end; returnCode := ldap_parse_page_control( AConn, ldapServerControls, ldapCount, ldapCookie ); if (ldapCookie <> nil) and (ldapCookie.bv_val <> nil) and (System.SysUtils.StrLen(ldapCookie.bv_val) > 0) then morePages := True else morePages := False; if ldapServerControls <> nil then begin ldap_controls_free(ldapServerControls); ldapServerControls := nil; end; ldapControls[0]:= nil; ldap_control_free(ldapPage); ldapPage := nil; { Обработка результатов. Присутствует рекурсия! } ldapEntry := ldap_first_entry(AConn, ldapSearchResult); while ldapEntry <> nil do begin for attr in AttrArray do begin i := 0; ldapValues := ldap_get_values(AConn, ldapEntry, PAnsiChar(attr)); if Assigned(ldapValues) then case IndexText(attr, ['subClassOf', 'systemAuxiliaryClass']) of 0: begin { Если текущий класс и его родитель не равны, то... } { Например класс "top" в поле "subClassOf" содержит } { себя же - "top", рекурсию в этом случае не выполняем } if CompareText(ldapClass, string(ldapValues^)) <> 0 then GetSchemaAttributes(AConn, [ldapValues^]) end; 1: begin while ldapValues^ <> nil do begin GetSchemaAttributes(AConn, [ldapValues^]); Inc(ldapValues); Inc(i); end; Dec(ldapValues, i); end; else begin while ldapValues^ <> nil do begin FSchemaAttributes.Add(ldapValues^ + '=' + GetAttributeSyntax(AConn, ldapValues^)); Inc(ldapValues); Inc(i); end; Dec(ldapValues, i); end; end; ldap_value_free(ldapValues); end; ldapEntry := ldap_next_entry(AConn, ldapEntry); end; ldap_msgfree(ldapSearchResult); ldapSearchResult := nil; until (morePages = False); ber_bvfree(ldapCookie); ldapCookie := nil; except; end; if ldapSearchResult <> nil then ldap_msgfree(ldapSearchResult); end; function TDCInfo.GetAttributeSyntax(AConn: PLDAP; AAttr: string): string; var returnCode: ULONG; ldapBase: AnsiString; ldapFilter: AnsiString; ldapSearchResult: PLDAPMessage; ldapAttributes: array of PAnsiChar; ldapEntry: PLDAPMessage; ldapValues: PPAnsiChar; syntax: string; begin if not Assigned(AConn) then Exit; ldapBase := 'CN=Schema,CN=Configuration,' + System.AnsiStrings.ReplaceText('DC=' + FDomainDnsName, '.', ',DC='); { Формируем фильтр объектов AD } ldapFilter := '(&(objectCategory=attributeSchema)(lDAPDisplayName=' + AAttr + '))'; { Формируем набор атрибутов } SetLength(ldapAttributes, 2); ldapAttributes[0] := PAnsiChar('attributeSyntax'); ldapAttributes[1] := nil; try returnCode := ldap_search_s( AConn, PAnsiChar(ldapBase), LDAP_SCOPE_ONELEVEL, PAnsiChar(ldapFilter), PAnsiChar(@ldapAttributes[0]), 0, ldapSearchResult ); if returnCode <> LDAP_SUCCESS then raise Exception.Create(ldap_err2string(returnCode)); { Обработка результатов } ldapEntry := ldap_first_entry(AConn, ldapSearchResult); while ldapEntry <> nil do begin ldapValues := ldap_get_values(AConn, ldapEntry, ldapAttributes[0]); if Assigned(ldapValues) then syntax := ldapValues^ else syntax := ''; case IndexText(syntax, [ '2.5.5.0', { Undefined } '2.5.5.1', { Object(DN-DN) } '2.5.5.2', { String(Object-Identifier) } '2.5.5.3', { Case-Sensitive String } '2.5.5.4', { CaseIgnoreString(Teletex) } '2.5.5.5', { String(IA5) } '2.5.5.6', { String(Numeric) } '2.5.5.7', { Object(DN-Binary) } '2.5.5.8', { Boolean } '2.5.5.9', { Integer } '2.5.5.10', { String(Octet) } '2.5.5.11', { String(UTC-Time) } '2.5.5.12', { String(Unicode) } '2.5.5.13', { Object(Presentation-Address) } '2.5.5.14', { Object(DN-String) } '2.5.5.15', { String(NT-Sec-Desc) } '2.5.5.16', { LargeInteger } '2.5.5.17' { String(Sid) } ] ) of 0: Result := ATTR_TYPE_UNDEFINED; 1: Result := ATTR_TYPE_DN_STRING; 2: Result := ATTR_TYPE_OID; 3: Result := ATTR_TYPE_CASE_EXACT_STRING; 4: Result := ATTR_TYPE_CASE_IGNORE_STRING; 5: Result := ATTR_TYPE_PRINTABLE_STRING; 6: Result := ATTR_TYPE_NUMERIC_STRING; 7: Result := ATTR_TYPE_DN_WITH_BINARY; 8: Result := ATTR_TYPE_BOOLEAN; 9: Result := ATTR_TYPE_INTEGER; 10: Result := ATTR_TYPE_OCTET_STRING; 11: Result := ATTR_TYPE_UTC_TIME; 12: Result := ATTR_TYPE_DIRECTORY_STRING; 13: Result := ATTR_TYPE_PRESENTATION_ADDRESS; 14: Result := ATTR_TYPE_DN_WITH_STRING; 15: Result := ATTR_TYPE_NT_SECURITY_DESCRIPTOR; 16: Result := ATTR_TYPE_LARGE_INTEGER; 17: Result := ATTR_TYPE_SID_STRING; else Result := syntax; end; ldap_value_free(ldapValues); ldapEntry := ldap_next_entry(AConn, ldapEntry); end; ldap_msgfree(ldapSearchResult); ldapSearchResult := nil; except end; if ldapSearchResult <> nil then ldap_msgfree(ldapSearchResult); ldapSearchResult := nil; end; procedure TDCInfo.GetSchemaAttributes(AClass: array of string); var i: Integer; hr: HRESULT; objClassName: string; objIADs: IADs; objSchema: IADsContainer; objClass: IADsClass; objProperty: IADsProperty; pathName: string; begin CoInitialize(nil); for objClassName in AClass do try pathName := Format('LDAP://%s/Schema/%s', [FName, objClassName]); hr := ADsOpenObject( PChar(pathName), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IADsClass, @objClass ); if hr <> S_OK then raise Exception.Create('TDCInfo.GetSchemaUserAttributes: ADsOpenObject'); hr := ADsOpenObject( PChar(objClass.Parent), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IADsContainer, @objSchema ); if SUCCEEDED(hr) then begin if VarIsArray(objClass.MandatoryProperties) then for i := VarArrayLowBound(objClass.MandatoryProperties, 1) to VarArrayHighBound(objClass.MandatoryProperties, 1) do begin objProperty := objSchema.GetObject('Property', objClass.MandatoryProperties[i]) as IADsProperty; FSchemaAttributes.Add( Format( '%s=%s', [objClass.MandatoryProperties[i], objProperty.Syntax] ) ); end; if VarIsArray(objClass.OptionalProperties) then for i := VarArrayLowBound(objClass.OptionalProperties, 1) to VarArrayHighBound(objClass.OptionalProperties, 1) do begin objProperty := objSchema.GetObject('Property', objClass.OptionalProperties[i]) as IADsProperty; FSchemaAttributes.Add( Format( '%s=%s', [objClass.OptionalProperties[i], objProperty.Syntax] ) ); end; end; except on e:Exception do begin OutputDebugString(PChar(e.Message)); Continue; end; end; CoUninitialize; end; procedure TDCInfo.RefreshData; var res: DWORD; pdcInfo: PDOMAIN_CONTROLLER_INFO; ldapConn: PLDAP; RootDSE: IADs; i: Integer; begin res := DsGetDcName( PChar(FName), PChar(FDomainDnsName), nil, nil, DS_IS_DNS_NAME or DS_RETURN_FLAT_NAME, pdcInfo ); case res of Self.ERROR_SUCCESS: begin Self.FDomainNetbiosName := pdcInfo.DomainName; case pdcInfo.DomainControllerAddressType of DS_NETBIOS_ADDRESS: Self.FAddr := StringReplace(pdcInfo.DomainControllerAddress, '\\', '', []); DS_INET_ADDRESS: Self.FIPAddr := StringReplace(pdcInfo.DomainControllerAddress, '\\', '', []); end; if Self.FAddr.IsEmpty then Self.FAddr := StringReplace(pdcInfo.DomainControllerName, '\\', '', []); end; Self.ERROR_INVALID_DOMAINNAME: ; Self.ERROR_INVALID_FLAGS: ; Self.ERROR_NOT_ENOUGH_MEMORY: ; Self.ERROR_NO_SUCH_DOMAIN: ; else ; end; NetApiBufferFree(pdcInfo); res := DsGetDcName( PChar(FName), PChar(FDomainDnsName), nil, nil, DS_IS_DNS_NAME or DS_RETURN_DNS_NAME or DS_IP_REQUIRED, pdcInfo ); case res of Self.ERROR_SUCCESS: begin Self.FDomainGUID := pdcInfo.DomainGuid; Self.FDnsForestName := pdcInfo.DnsForestName; case pdcInfo.DomainControllerAddressType of DS_NETBIOS_ADDRESS: Self.FAddr := StringReplace(pdcInfo.DomainControllerAddress, '\\', '', []); DS_INET_ADDRESS: Self.FIPAddr := StringReplace(pdcInfo.DomainControllerAddress, '\\', '', []); end; end; Self.ERROR_INVALID_DOMAINNAME: ; Self.ERROR_INVALID_FLAGS: ; Self.ERROR_NOT_ENOUGH_MEMORY: ; Self.ERROR_NO_SUCH_DOMAIN: ; else ; end; NetApiBufferFree(pdcInfo); FSchemaAttributes.Clear; case FAdsApi of ADC_API_LDAP: begin ldapConn := nil; ServerBinding(FName, ldapConn, TExceptionProc(nil)); GetSchemaAttributes(ldapConn, ['Computer', 'User', 'Group']); ldap_unbind(ldapConn); end; ADC_API_ADSI: begin GetSchemaAttributes(['Computer', 'User', 'Group']); end; end; end; function TDCInfo.AttributeExists(AAttr: string): Boolean; begin Result := FSchemaAttributes.IndexOfName(AAttr) > -1; end; end.
unit uTitulos; interface type TTitulos = class private Fstatusid: integer; Fvalor: double; Fdescricao: string; Fdatavencimento: Tdate; FID: integer; Fdatalancamento: Tdate; Fobservacoes: string; procedure setDatalancamento(const Value: Tdate); procedure setDatavencimento(const Value: Tdate); procedure setDescricao(const Value: string); procedure setID(const Value: integer); procedure SetObservacoes(const Value: string); procedure setStatusid(const Value: integer); procedure setValor(const Value: double); public property ID : integer read FID write setID; property descricao : string read Fdescricao write setDescricao; property valor : double read Fvalor write setValor; property statusid : integer read Fstatusid write setStatusid; property datalancamento : Tdate read Fdatalancamento write setDatalancamento; property datavencimento : Tdate read Fdatavencimento write setDatavencimento; property observacoes : string read Fobservacoes write SetObservacoes; end; implementation { TTitulos } procedure TTitulos.setDatalancamento(const Value: Tdate); begin Fdatalancamento := Value; end; procedure TTitulos.setDatavencimento(const Value: Tdate); begin Fdatavencimento := Value; end; procedure TTitulos.setDescricao(const Value: string); begin Fdescricao := Value; end; procedure TTitulos.setID(const Value: integer); begin FID := Value; end; procedure TTitulos.SetObservacoes(const Value: string); begin Fobservacoes := Value; end; procedure TTitulos.setStatusid(const Value: integer); begin Fstatusid := Value; end; procedure TTitulos.setValor(const Value: double); begin Fvalor := Value; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2017 * } { *********************************************************** } unit tfRC5; {$I TFL.inc} {$POINTERMATH ON} interface uses tfTypes; type PRC5Instance = ^TRC5Instance; TRC5Instance = record private const MAX_ROUNDS = 255; MAX_KEYLEN = 255; private type PRC5Block = ^TRC5Block; TRC5Block = record case Byte of 0: (Word16: array[0..1] of Word); 1: (Word32: array[0..1] of UInt32); 2: (Word64: array[0..1] of UInt64); end; TDummy = array[0..0] of UInt64; // to ensure 64-bit alignment private {$HINTS OFF} // -- inherited fields begin -- // from tfRecord FVTable: Pointer; FRefCount: Integer; // from tfBlockCipher FValidKey: Boolean; FAlgID: UInt32; // FDir: UInt32; // FMode: UInt32; // FPadding: UInt32; FIVector: TRC5Block; // -- inherited fields end -- {$HINTS ON} FBlockSize: Cardinal; // 4, 8, 16 FRounds: Cardinal; // 0..255 FSubKeys: TDummy; public class function Release(Inst: PRC5Instance): Integer; stdcall; static; class function ExpandKey32(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKey64(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKey128(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetBlockSize(Inst: PRC5Instance): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DuplicateKey(Inst: PRC5Instance; var Key: PRC5Instance): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure DestroyKey(Inst: PRC5Instance);{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptBlock32(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptBlock64(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptBlock128(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptBlock32(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptBlock64(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptBlock128(Inst: PRC5Instance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; function GetRC5Instance(var A: PRC5Instance; Flags: UInt32): TF_RESULT; function GetRC5InstanceEx(var A: PRC5Instance; Flags: UInt32; BlockSize, Rounds: Integer): TF_RESULT; implementation uses tfRecords, tfBaseCiphers; //const // MAX_BLOCK_SIZE = 16; // 16 bytes = 128 bits const RC5VTable32: array[0..18] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TRC5Instance.Release, @TRC5Instance.DestroyKey, @TRC5Instance.DuplicateKey, @TRC5Instance.ExpandKey32, @TBaseBlockCipher.SetKeyParam, @TBaseBlockCipher.GetKeyParam, @TRC5Instance.GetBlockSize, @TBaseBlockCipher.Encrypt, @TBaseBlockCipher.Decrypt, @TRC5Instance.EncryptBlock32, @TRC5Instance.DecryptBlock32, @TBaseBlockCipher.GetRand, @TBaseBlockCipher.RandBlock, @TBaseBlockCipher.RandCrypt, @TBaseBlockCipher.GetIsBlockCipher, @TBaseBlockCipher.ExpandKeyIV, @TBaseBlockCipher.ExpandKeyNonce ); RC5VTable64: array[0..18] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TRC5Instance.Release, @TRC5Instance.DestroyKey, @TRC5Instance.DuplicateKey, @TRC5Instance.ExpandKey64, @TBaseBlockCipher.SetKeyParam, @TBaseBlockCipher.GetKeyParam, @TRC5Instance.GetBlockSize, @TBaseBlockCipher.Encrypt, @TBaseBlockCipher.Decrypt, @TRC5Instance.EncryptBlock64, @TRC5Instance.DecryptBlock64, @TBaseBlockCipher.GetRand, @TBaseBlockCipher.RandBlock, @TBaseBlockCipher.RandCrypt, @TBaseBlockCipher.GetIsBlockCipher, @TBaseBlockCipher.ExpandKeyIV, @TBaseBlockCipher.ExpandKeyNonce ); RC5VTable128: array[0..18] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TRC5Instance.Release, @TRC5Instance.DestroyKey, @TRC5Instance.DuplicateKey, @TRC5Instance.ExpandKey128, @TBaseBlockCipher.SetKeyParam, @TBaseBlockCipher.GetKeyParam, @TRC5Instance.GetBlockSize, @TBaseBlockCipher.Encrypt, @TBaseBlockCipher.Decrypt, @TRC5Instance.EncryptBlock128, @TRC5Instance.DecryptBlock128, @TBaseBlockCipher.GetRand, @TBaseBlockCipher.RandBlock, @TBaseBlockCipher.RandCrypt, @TBaseBlockCipher.GetIsBlockCipher, @TBaseBlockCipher.ExpandKeyIV, @TBaseBlockCipher.ExpandKeyNonce ); procedure BurnKey(Inst: PRC5Instance); inline; var BurnSize: Integer; TmpBlockSize: Integer; TmpRounds: Integer; begin // if Inst.FSubKeys <> nil then begin // FillChar(Inst.FSubKeys^, (Inst.FRounds + 1) * Inst.FBlockSize, 0); // FreeMem(Inst.FSubKeys); // end; TmpBlockSize:= Inst.FBlockSize; TmpRounds:= Inst.FRounds; BurnSize:= SizeOf(TRC5Instance) - SizeOf(TRC5Instance.TDummy) + (TmpRounds + 1) * TmpBlockSize - Integer(@PRC5Instance(nil)^.FValidKey); // BurnSize:= Integer(@PRC5Algorithm(nil)^.FSubKeys) // - Integer(@PRC5Algorithm(nil)^.FValidKey); FillChar(Inst.FValidKey, BurnSize, 0); Inst.FBlockSize:= TmpBlockSize; Inst.FRounds:= TmpRounds; // if Inst.FSubKeys <> nil then begin // FillChar(Inst.FSubKeys.GetRawData^, Inst.FSubKeys.GetLen, 0); // end; end; class function TRC5Instance.Release(Inst: PRC5Instance): Integer; begin if Inst.FRefCount > 0 then begin Result:= tfDecrement(Inst.FRefCount); if Result = 0 then begin BurnKey(Inst); // if Inst.FSubKeys <> nil then Inst.FSubKeys._Release; FreeMem(Inst); end; end else Result:= Inst.FRefCount; end; function GetRC5Instance(var A: PRC5Instance; Flags: UInt32): TF_RESULT; begin Result:= GetRC5InstanceEx(A, Flags, // "standard" RC5: 8, // 64-bit block (8 bytes) 12 // 12 rounds ); end; function GetRC5InstanceEx(var A: PRC5Instance; Flags: UInt32; BlockSize, Rounds: Integer): TF_RESULT; var Tmp: PRC5Instance; begin if ((BlockSize <> 4) and (BlockSize <> 8) and (BlockSize <> 16)) or (Rounds < 1) or (Rounds > 255) then begin Result:= TF_E_INVALIDARG; Exit; end; // BlockSize:= BlockSize shr 3; try Tmp:= AllocMem(SizeOf(TRC5Instance) - SizeOf(TRC5Instance.TDummy) + (Rounds + 1) * BlockSize); case BlockSize of 4: Tmp^.FVTable:= @RC5VTable32; 8: Tmp^.FVTable:= @RC5VTable64; 16: Tmp^.FVTable:= @RC5VTable128; end; Tmp^.FRefCount:= 1; Result:= PBaseBlockCipher(Tmp).SetFlags(Flags); if Result <> TF_S_OK then begin FreeMem(Tmp); Exit; end; Tmp^.FBlockSize:= BlockSize; Tmp^.FRounds:= Rounds; if A <> nil then TRC5Instance.Release(A); A:= Tmp; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; class procedure TRC5Instance.DestroyKey(Inst: PRC5Instance); begin BurnKey(Inst); end; class function TRC5Instance.DuplicateKey(Inst: PRC5Instance; var Key: PRC5Instance): TF_RESULT; begin Result:= GetRC5InstanceEx(Key, PBaseBlockCipher(Inst).GetFlags, Inst.FBlockSize, Inst.FRounds); if Result = TF_S_OK then begin Key.FValidKey:= Inst.FValidKey; // Key.FDir:= Inst.FDir; // Key.FMode:= Inst.FMode; // Key.FPadding:= Inst.FPadding; Key.FIVector:= Inst.FIVector; Key.FRounds:= Inst.FRounds; Key.FBlockSize:= Inst.FBlockSize; // Result:= Key.FSubKeys.CopyBytes(Inst.FSubKeys); Move(Inst.FSubKeys, Key.FSubKeys, (Inst.FRounds + 1) * Inst.FBlockSize); end; end; function Rol16(Value: Word; Shift: Cardinal): Word; inline; begin Result:= (Value shl Shift) or (Value shr (16 - Shift)); end; function Rol32(Value: UInt32; Shift: Cardinal): UInt32; inline; begin Result:= (Value shl Shift) or (Value shr (32 - Shift)); end; function Rol64(Value: UInt64; Shift: Cardinal): UInt64; inline; begin Result:= (Value shl Shift) or (Value shr (64 - Shift)); end; function Ror16(Value: Word; Shift: Cardinal): Word; inline; begin Result:= (Value shr Shift) or (Value shl (16 - Shift)); end; function Ror32(Value: UInt32; Shift: Cardinal): UInt32; inline; begin Result:= (Value shr Shift) or (Value shl (32 - Shift)); end; function Ror64(Value: UInt64; Shift: Cardinal): UInt64; inline; begin Result:= (Value shr Shift) or (Value shl (64 - Shift)); end; class function TRC5Instance.EncryptBlock32(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = Word; var A, B: RC5Word; S: PRC5Word; I: Integer; begin S:= @Inst.FSubKeys; A:= PRC5Word(Data)[0] + S^; Inc(S); B:= PRC5Word(Data)[1] + S^; I:= Inst.FRounds; repeat Inc(S); A:= Rol16(A xor B, B) + S^; Inc(S); B:= Rol16(B xor A, A) + S^; Dec(I); until I = 0; PRC5Word(Data)[0]:= A; PRC5Word(Data)[1]:= B; Result:= TF_S_OK; end; class function TRC5Instance.EncryptBlock64(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = UInt32; var A, B: RC5Word; S: PRC5Word; I: Integer; begin S:= @Inst.FSubKeys; A:= PRC5Word(Data)[0] + S^; Inc(S); B:= PRC5Word(Data)[1] + S^; I:= Inst.FRounds; repeat Inc(S); A:= Rol32(A xor B, B) + S^; Inc(S); B:= Rol32(B xor A, A) + S^; Dec(I); until I = 0; PRC5Word(Data)[0]:= A; PRC5Word(Data)[1]:= B; Result:= TF_S_OK; end; class function TRC5Instance.EncryptBlock128(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = UInt64; var A, B: RC5Word; S: PRC5Word; I: Integer; begin S:= @Inst.FSubKeys; A:= PRC5Word(Data)[0] + S^; Inc(S); B:= PRC5Word(Data)[1] + S^; I:= Inst.FRounds; repeat Inc(S); A:= Rol64(A xor B, B) + S^; Inc(S); B:= Rol64(B xor A, A) + S^; Dec(I); until I = 0; PRC5Word(Data)[0]:= A; PRC5Word(Data)[1]:= B; Result:= TF_S_OK; end; class function TRC5Instance.DecryptBlock32(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = Word; var A, B: RC5Word; S: PRC5Word; I: Integer; begin A:= PRC5Word(Data)[0]; B:= PRC5Word(Data)[1]; I:= Inst.FRounds; S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1; repeat B:= Ror16(B - S^, A) xor A; Dec(S); A:= Ror16(A - S^, B) xor B; Dec(S); Dec(I); until I = 0; PRC5Word(Data)[1]:= B - S^; Dec(S); PRC5Word(Data)[0]:= A - S^; Result:= TF_S_OK; end; class function TRC5Instance.DecryptBlock64(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = UInt32; var A, B: RC5Word; S: PRC5Word; I: Integer; begin A:= PRC5Word(Data)[0]; B:= PRC5Word(Data)[1]; I:= Inst.FRounds; S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1; repeat B:= Ror32(B - S^, A) xor A; Dec(S); A:= Ror32(A - S^, B) xor B; Dec(S); Dec(I); until I = 0; PRC5Word(Data)[1]:= B - S^; Dec(S); PRC5Word(Data)[0]:= A - S^; Result:= TF_S_OK; end; class function TRC5Instance.DecryptBlock128(Inst: PRC5Instance; Data: PByte): TF_RESULT; type PRC5Word = ^RC5Word; RC5Word = UInt64; var A, B: RC5Word; S: PRC5Word; I: Integer; begin A:= PRC5Word(Data)[0]; B:= PRC5Word(Data)[1]; I:= Inst.FRounds; S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1; repeat B:= Ror64(B - S^, A) xor A; Dec(S); A:= Ror64(A - S^, B) xor B; Dec(S); Dec(I); until I = 0; PRC5Word(Data)[1]:= B - S^; Dec(S); PRC5Word(Data)[0]:= A - S^; Result:= TF_S_OK; end; class function TRC5Instance.ExpandKey32(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; type RC5Word = Word; // RC5 "word" size = 2 bytes PWArray = ^TWArray; TWArray = array[0..$FFFF] of RC5Word; const Pw = $B7E1; Qw = $9E37; kShift = 1; var L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word; S: PWArray; LLen: Integer; T: Integer; I, J, N: Integer; X, Y: RC5Word; NSteps: Integer; begin if (KeySize > 255) then begin Result:= TF_E_INVALIDARG; Exit; end; // Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1] LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift; FillChar(L, LLen * SizeOf(RC5Word), 0); Move(Key^, L, KeySize); S:= @Inst.FSubKeys; // Initialize the array of subkeys, FSubKeys[0..T-1] T:= 2 * (Inst.FRounds + 1); S^[0]:= Pw; for I:= 1 to T - 1 do S^[I]:= S^[I-1] + Qw; // Mix in the secret key if LLen > T then NSteps:= 3 * LLen else NSteps:= 3 * T; X:= 0; Y:= 0; I:= 0; J:= 0; for N:= 0 to NSteps - 1 do begin S^[I]:= Rol16((S^[I] + X + Y), 3); X:= S^[I]; L[J]:= Rol16((L[J] + X + Y), (X + Y) and $1F); Y:= L[J]; I:= (I + 1) mod T; J:= (J + 1) mod LLen; end; FillChar(L, LLen * SizeOf(RC5Word), 0); Inst.FValidKey:= True; Result:= TF_S_OK; end; class function TRC5Instance.ExpandKey64(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; type RC5Word = UInt32; // RC5 "word" size = 4 bytes PWArray = ^TWArray; TWArray = array[0..$FFFF] of RC5Word; const Pw = $B7E15163; Qw = $9E3779B9; kShift = 2; var L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word; S: PWArray; LLen: Integer; T: Integer; I, J, N: Integer; X, Y: RC5Word; NSteps: Integer; begin if (KeySize > 255) then begin Result:= TF_E_INVALIDARG; Exit; end; // Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1] LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift; FillChar(L, LLen * SizeOf(RC5Word), 0); Move(Key^, L, KeySize); S:= @Inst.FSubKeys; // Initialize the array of subkeys, FSubKeys[0..T-1] T:= 2 * (Inst.FRounds + 1); S^[0]:= Pw; for I:= 1 to T - 1 do S^[I]:= S^[I-1] + Qw; // Mix in the secret key if LLen > T then NSteps:= 3 * LLen else NSteps:= 3 * T; X:= 0; Y:= 0; I:= 0; J:= 0; for N:= 0 to NSteps - 1 do begin S^[I]:= Rol32((S^[I] + X + Y), 3); X:= S^[I]; L[J]:= Rol32((L[J] + X + Y), (X + Y) and $1F); Y:= L[J]; I:= (I + 1) mod T; J:= (J + 1) mod LLen; end; FillChar(L, LLen * SizeOf(RC5Word), 0); Inst.FValidKey:= True; Result:= TF_S_OK; end; class function TRC5Instance.ExpandKey128(Inst: PRC5Instance; Key: PByte; KeySize: Cardinal): TF_RESULT; type RC5Word = UInt64; // RC5 "word" size = 8 bytes PWArray = ^TWArray; TWArray = array[0..$FFFF] of RC5Word; const Pw = $B7E151628AED2A6B; Qw = $9E3779B97F4A7C15; kShift = 3; var L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word; S: PWArray; LLen: Integer; T: Integer; I, J, N: Integer; X, Y: RC5Word; NSteps: Integer; begin if (KeySize > 255) then begin Result:= TF_E_INVALIDARG; Exit; end; // Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1] LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift; FillChar(L, LLen * SizeOf(RC5Word), 0); Move(Key^, L, KeySize); S:= @Inst.FSubKeys; // Initialize the array of subkeys, FSubKeys[0..T-1] T:= 2 * (Inst.FRounds + 1); S^[0]:= Pw; for I:= 1 to T - 1 do S^[I]:= S^[I-1] + Qw; // Mix in the secret key if LLen > T then NSteps:= 3 * LLen else NSteps:= 3 * T; X:= 0; Y:= 0; I:= 0; J:= 0; for N:= 0 to NSteps - 1 do begin S^[I]:= Rol64((S^[I] + X + Y), 3); X:= S^[I]; L[J]:= Rol64((L[J] + X + Y), (X + Y) and $1F); Y:= L[J]; I:= (I + 1) mod T; J:= (J + 1) mod LLen; end; FillChar(L, LLen * SizeOf(RC5Word), 0); Inst.FValidKey:= True; Result:= TF_S_OK; end; class function TRC5Instance.GetBlockSize(Inst: PRC5Instance): Integer; begin Result:= Inst.FBlockSize; end; end.
unit CodingGif; interface uses Windows, SysUtils, Classes, MemUtils, Dibs, CodingAnim, ListUtils; type TGifDecoder = class( TAnimDecoder ) destructor Destroy; override; public//protected fFrameList : TObjectList; fDibHeader : PDib; function GetFrameDelay( FrameIndx : integer ) : longint; override; function GetFirstAnimFrame : integer; override; procedure SeekStart; override; public procedure LoadFromStream( aStream : TStream ); override; procedure SeekFrame( FrameIndx : integer ); override; procedure NextFrame; override; procedure ProcessFrame; override; end; implementation uses BitBlt, Gifs, ImageLoaders, GifLoader; // TGifFrame type TGifFrame = class fDibHeader : PDib; fDibPixels : pointer; fDelay : integer; constructor Create( aOwner : TGifDecoder; PrevFrame : TGifFrame; Data : TImageData ); destructor Destroy; override; end; constructor TGifFrame.Create( aOwner : TGifDecoder; PrevFrame : TGifFrame; Data : TImageData ); var wb : integer; begin inherited Create; fDelay := Data.Delay; if Data.LocalPalette then begin //fDibHeader := end; wb := DwordAlign( aOwner.Width ); getmem( fDibPixels, wb * aOwner.Height ); if Assigned( PrevFrame ) then BltCopyOpaque( PrevFrame.fDibPixels, fDibPixels, aOwner.Width, aOwner.Height, wb, wb ); Data.Decode( pchar(fDibPixels) + Data.Origin.y * wb + Data.Origin.x, wb ); end; destructor TGifFrame.Destroy; //.rag begin FreePtr(fDibPixels); inherited; end; // TGifDecoder procedure TGifDecoder.ProcessFrame; begin with fBufferRec do BltCopyOpaque( TGifFrame(fFrameList[CurrentFrameIndx-1]).fDibPixels, fBufferAddr, Width, Height, DwordAlign( Width ), fBufferWidth ); end; function TGifDecoder.GetFrameDelay( FrameIndx : integer ) : longint; begin Result := TGifFrame( fFrameList[FrameIndx-1] ).fDelay; end; function TGifDecoder.GetFirstAnimFrame : integer; begin Result := 1; end; procedure TGifDecoder.SeekFrame( FrameIndx : integer ); begin fCurrentFrameIndx := FrameIndx; end; procedure TGifDecoder.NextFrame; begin if CurrentFrameIndx >= EndingFrame then begin if Assigned( OnFinished ) then OnFinished( Self ); SeekFrame( StartingFrame ); end else begin inc( fCurrentFrameIndx ); //fCurrentFrame := Stream.RelockChunk( fCurrentFrame ); end; end; procedure TGifDecoder.SeekStart; begin fCurrentFrameIndx := FirstAnimFrame; end; procedure TGifDecoder.LoadFromStream( aStream : TStream ); var i : integer; GifFrame : TGifFrame; GifImages : TGifImages; begin GifImages := TGifImages.Create; GifImages.LoadFromStream( aStream ); fWidth := GifImages.Width; fHeight := GifImages.Height; fBitCount := 8; fSize := Point( Width, Height ); fDiskSize := -1; fFrameCount := GifImages.ImageCount; ResetFrameRange; fCurrentFrameIndx := 1; if fDibHeader<>nil then freemem(fDibHeader); fDibHeader := DibCopyHeader( GifImages.DibHeader ); fFrameList.free; fFrameList := TObjectList.Create; fFrameList.AssertCapacity( FrameCount ); GifFrame := nil; for i := 0 to FrameCount - 1 do begin GifFrame := TGifFrame.Create( Self, GifFrame, GifImages[i] ); fFrameList[i] := GifFrame; end; GifImages.Free; end; destructor TGifDecoder.destroy; begin fFrameList.Free; if fDibHeader<>nil then FreePtr( fDibHeader ); inherited; end; end.
unit BasicRankings; interface uses Classes, Rankings, Accounts, CacheAgent, Languages; type TAccountRanking = class( TRanking ) public constructor Create( anId, aSuperRanking : string; aName : TMultiString; Max : integer; AccountId : TAccountId ); private fAccountId : TAccountId; public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; override; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); override; function IsRankeable( const Obj : TObject ) : boolean; override; procedure Serialize( Prefix : string; List : TStringList ); override; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); override; end; TPrestigeRanking = class( TRanking ) public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; override; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); override; function IsRankeable( const Obj : TObject ) : boolean; override; procedure Serialize( Prefix : string; List : TStringList ); override; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); override; end; TWealthRanking = class( TRanking ) public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; override; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); override; function IsRankeable( const Obj : TObject ) : boolean; override; procedure Serialize( Prefix : string; List : TStringList ); override; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); override; end; TOverallRanking = class( TRanking ) public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; override; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); override; function IsRankeable( const Obj : TObject ) : boolean; override; procedure Serialize( Prefix : string; List : TStringList ); override; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); override; class function IsOverall : boolean; override; end; TContestRanking = class( TRanking ) private function CalcContestPoints(Obj : TObject) : integer; public function CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; override; procedure CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); override; function IsRankeable( const Obj : TObject ) : boolean; override; procedure Serialize( Prefix : string; List : TStringList ); override; procedure SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); override; class function IsOverall : boolean; override; class function Serializable : boolean; override; end; implementation uses Kernel, MathUtils, SysUtils, RankProtocol; // TAccountRanking constructor TAccountRanking.Create( anId, aSuperRanking : string; aName : TMultiString; Max : integer; AccountId : TAccountId ); begin inherited Create( anId, aSuperRanking, aName, Max ); fAccountId := AccountId; end; function TAccountRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; var Dealer1 : TMoneyDealer absolute Obj1; Dealer2 : TMoneyDealer absolute Obj2; acc1 : TMoney; acc2 : TMoney; begin try acc1 := Dealer1.Accounts.AccountArray[fAccountId].Value; acc2 := Dealer2.Accounts.AccountArray[fAccountId].Value; if acc1 > acc2 then result := -1 else if acc1 < acc2 then result := 1 else result := 0; except result := 0; end; end; procedure TAccountRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); var Tycoon : TTycoon absolute Obj; begin try Cache.WriteString( 'Name' + IntToStr(index), Tycoon.Name ); Cache.WriteString( 'Value' + IntToStr(index), FormatMoney(Tycoon.Accounts.AccountArray[fAccountId].Value) ); except end; end; function TAccountRanking.IsRankeable( const Obj : TObject ) : boolean; var Tycoon : TTycoon absolute Obj; begin result := Tycoon.Accounts.AccountArray[fAccountId].Value > 0; end; procedure TAccountRanking.Serialize( Prefix : string; List : TStringList ); begin inherited; List.Values[Prefix + tidRankings_RankType] := '1'; end; procedure TAccountRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); var Tycoon : TTycoon absolute Obj; begin inherited; try List.Values[Prefix + tidRankings_MemberName] := Tycoon.Name; List.Values[Prefix + tidRankings_MemberValue] := CurrToStr(Tycoon.Accounts.AccountArray[fAccountId].Value); except end; end; // TPrestigeRanking function TPrestigeRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; var Tycoon1 : TTycoon absolute Obj1; Tycoon2 : TTycoon absolute Obj2; begin if Tycoon1.Prestige > Tycoon2.Prestige then result := -1 else if Tycoon1.Prestige < Tycoon2.Prestige then result := 1 else result := 0; end; procedure TPrestigeRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); var Tycoon : TTycoon absolute Obj; begin try Cache.WriteString( 'Name' + IntToStr(index), Tycoon.Name ); Cache.WriteString( 'Value' + IntToStr(index), IntToStr(round(Tycoon.Prestige)) ); except end; end; function TPrestigeRanking.IsRankeable( const Obj : TObject ) : boolean; var Tycoon : TTycoon absolute Obj; begin result := Tycoon.Prestige > 0; end; procedure TPrestigeRanking.Serialize( Prefix : string; List : TStringList ); begin inherited; List.Values[Prefix + tidRankings_RankType] := '2'; end; procedure TPrestigeRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); var Tycoon : TTycoon absolute Obj; begin inherited; try List.Values[Prefix + tidRankings_MemberName] := Tycoon.Name; List.Values[Prefix + tidRankings_MemberValue] := IntToStr(round(Tycoon.Prestige)); except end; end; // TWealthRanking function TWealthRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; var Tycoon1 : TTycoon absolute Obj1; Tycoon2 : TTycoon absolute Obj2; begin if Tycoon1.Budget > Tycoon2.Budget then result := -1 else if Tycoon1.Budget < Tycoon2.Budget then result := 1 else result := 0; end; procedure TWealthRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); var Tycoon : TTycoon absolute Obj; begin try Cache.WriteString( 'Name' + IntToStr(index), Tycoon.Name ); Cache.WriteString( 'Value' + IntToStr(index), FormatMoney(Tycoon.Budget) ); except end; end; function TWealthRanking.IsRankeable( const Obj : TObject ) : boolean; var Tycoon : TTycoon absolute Obj; begin result := Tycoon.Budget > InitialBudget; end; procedure TWealthRanking.Serialize( Prefix : string; List : TStringList ); begin inherited; List.Values[Prefix + tidRankings_RankType] := '3'; end; procedure TWealthRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); var Tycoon : TTycoon absolute Obj; begin inherited; try List.Values[Prefix + tidRankings_MemberName] := Tycoon.Name; List.Values[Prefix + tidRankings_MemberValue] := CurrToStr(Tycoon.Budget); except end; end; // TOverallRanking function TOverallRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; var Tycoon1 : TTycoon absolute Obj1; Tycoon2 : TTycoon absolute Obj2; begin if Tycoon1.RankingAvg > Tycoon2.RankingAvg then result := -1 else if Tycoon1.RankingAvg < Tycoon2.RankingAvg then result := 1 else result := 0; end; procedure TOverallRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); var Tycoon : TTycoon absolute Obj; begin try Cache.WriteString( 'Name' + IntToStr(index), Tycoon.Name ); Cache.WriteString( 'Value' + IntToStr(index), IntToStr(round(Tycoon.RankingAvg)) ); except end; end; function TOverallRanking.IsRankeable( const Obj : TObject ) : boolean; var Tycoon : TTycoon absolute Obj; begin result := true; end; procedure TOverallRanking.Serialize( Prefix : string; List : TStringList ); begin inherited; List.Values[Prefix + tidRankings_RankType] := '0'; end; procedure TOverallRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); var Tycoon : TTycoon absolute Obj; begin inherited; try List.Values[Prefix + tidRankings_MemberName] := Tycoon.Name; List.Values[Prefix + tidRankings_MemberValue] := IntToStr(round(Tycoon.RankingAvg)); except end; end; class function TOverallRanking.IsOverall : boolean; begin result := true; end; // TContestRanking function TContestRanking.CalcContestPoints(Obj : TObject) : integer; var Tycoon : TTycoon absolute Obj; aux : string; begin result := 0; aux := Tycoon.Cookie['rkPts']; if aux <> '' then inc(result, StrToInt(aux)); aux := Tycoon.Cookie['lvPts']; if aux <> '' then inc(result, StrToInt(aux)); aux := Tycoon.Cookie['bnkPts']; if aux <> '' then inc(result, StrToInt(aux)); end; function TContestRanking.CompareObjects( const Obj1, Obj2 : TObject; const Context ) : integer; var Tycoon1 : TTycoon absolute Obj1; Tycoon2 : TTycoon absolute Obj2; pts1 : integer; pts2 : integer; begin pts1 := CalcContestPoints(Obj1); pts2 := CalcContestPoints(Obj2); if pts1 > pts2 then result := -1 else if pts1 < pts2 then result := 1 else result := 0; end; procedure TContestRanking.CacheItem( index : integer; const Obj : TObject; Cache : TObjectCache ); var Tycoon : TTycoon absolute Obj; begin try Cache.WriteString( 'Name' + IntToStr(index), Tycoon.Name ); Cache.WriteString( 'Value' + IntToStr(index), IntToStr(CalcContestPoints(Obj))); except end; end; function TContestRanking.IsRankeable( const Obj : TObject ) : boolean; var Tycoon : TTycoon absolute Obj; begin result := not Tycoon.IsRole and (Tycoon.Companies.Count > 0); //and (CalcContestPoints(Obj) > -1000); end; procedure TContestRanking.Serialize( Prefix : string; List : TStringList ); begin inherited; List.Values[Prefix + tidRankings_RankType] := '10'; end; procedure TContestRanking.SerializeItem( Prefix : string; index : integer; const Obj : TObject; List : TStringList ); var Tycoon : TTycoon absolute Obj; begin inherited; try List.Values[Prefix + tidRankings_MemberName] := Tycoon.Name; List.Values[Prefix + tidRankings_MemberValue] := IntToStr(CalcContestPoints(Obj)); except end; end; class function TContestRanking.IsOverall : boolean; begin result := true; end; class function TContestRanking.Serializable : boolean; begin result := false; end; end.
unit BubbleSort; interface uses StrategyInterface, ArraySubroutines; type TBubbleSort = class(TInterfacedObject, ISorter) procedure Sort(var A : Array of Integer); destructor Destroy; override; end; implementation procedure TBubbleSort.Sort(var A: array of Integer); var i, j : Integer; begin for i := Low(A) to High(A) do begin for j := Low(A) to High(A) do begin if A[j] > A[j+1] then Swap(A[j], A[j+1]); end; end; end; destructor TBubbleSort.Destroy; begin WriteLn('Bubble sort destr'); inherited; end; end.
unit uFMXListas; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, System.Rtti, FMX.Grid.Style, Data.Bind.EngExt, FMX.Bind.DBEngExt, FMX.Bind.Grid, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.Components, Data.Bind.Grid, Data.Bind.ObjectScope, FMX.ScrollBox, FMX.Grid, FMX.Edit; type TBaseClass = Class public Nome: string; End; TBaseClass2 = class(TBaseClass) end; TListaBase = class(TObjectList<TBaseClass2>) public function Add: TBaseClass2; overload; function Find(const AText: string): Integer; end; TForm41 = class(TForm) Button1: TButton; StringGrid1: TStringGrid; AdapterBindSource1: TAdapterBindSource; BindingsList1: TBindingsList; LinkGridToDataSourceAdapterBindSource1: TLinkGridToDataSource; Button2: TButton; Edit1: TEdit; Edit2: TEdit; Button3: TButton; Button4: TButton; Button5: TButton; procedure Button1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure AdapterBindSource1CreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private { Private declarations } FLista: TListaBase; public { Public declarations } end; var Form41: TForm41; implementation {$R *.fmx} procedure TForm41.AdapterBindSource1CreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); begin FLista := TListaBase.create(true); ABindSourceAdapter := TListBindSourceAdapter<TBaseClass2>.create(self, FLista, false); end; procedure TForm41.Button1Click(Sender: TObject); { var obj: TBaseClass; } begin { obj := TBaseClass.create; obj.Nome := 'List: ' + datetimeToStr(now); FLista.Add(obj); } with FLista.Add do begin // nome := 'Lista2: '+ datetimeToStr(now); Nome := Edit2.Text; end; AdapterBindSource1.InternalAdapter.Refresh; Edit1.Text := FLista.Count.ToString; end; procedure TForm41.Button2Click(Sender: TObject); begin if StringGrid1.Row >= 0 then FLista.Delete(StringGrid1.Row); AdapterBindSource1.InternalAdapter.Refresh; Edit1.Text := FLista.Count.ToString; end; procedure TForm41.Button3Click(Sender: TObject); var it: TBaseClass; i: Integer; begin i := FLista.Find(Edit2.Text); if i >= 0 then StringGrid1.Row := i; { i :=-1; for it in FLista do begin inc(i); if it.Nome = edit2.text then begin StringGrid1.Row := i; edit1.Text := i.ToString; exit; end; end; } end; procedure TForm41.Button4Click(Sender: TObject); begin FLista.Clear; AdapterBindSource1.InternalAdapter.Refresh; end; procedure TForm41.Button5Click(Sender: TObject); var obj:TBaseClass2; begin obj:=TBaseClass2.create; obj.Nome := dateTimeToStr(now); fLista.Insert( StringGrid1.Row, obj ); AdapterBindSource1.InternalAdapter.Refresh; end; procedure TForm41.FormDestroy(Sender: TObject); begin FLista.Free; end; { TListaBase } function TListaBase.Add: TBaseClass2; begin result := TBaseClass2.create; inherited Add(result); end; function TListaBase.Find(const AText: string): Integer; var i: Integer; begin result := -1; for i := 0 to Count - 1 do if items[i].Nome = AText then begin result := i; exit; end; end; end.
unit MainMenuUnit; {* Основное меню } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\MainMenuUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "MainMenu" MUID: (4DD24BD40021) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit , BaseTypesUnit , DynamicTreeUnit , BannerUnit ; type TSectionType = ( {* Тип секции ОМ } ST_FINANCE {* Налоги и финансы } , ST_HR {* Раздел для кадровиков } , ST_LEGAL {* Раздел для юристов } , ST_BUDGET_ORGS {* Бюджетные организаций } , ST_GOS_ZAKUPKI {* Госзакупки } , ST_LAW_FOR_ALL {* Право для всех } , ST_BUSINESS_REFERENCES {* Бизнес-справки } , ST_CHANGES_IN_LEGISLATION {* Изменения в законодательстве } );//TSectionType ISectionItem = interface {* Элемент раздела ОМ } ['{257ACC4A-9B2A-4AD1-B238-0CDCE6A5406E}'] procedure GetCaption; stdcall; procedure Open(out aRet {* IUnknown }); stdcall; {* Получить сущность элемента (может быть IQuery, IDocument, INodeBase, IString, IBookmark) } property Caption: read GetCaption; {* Имя } end;//ISectionItem ISectionItemList = array of ISectionItem; ISection = interface ['{BBB2D3C6-226C-4A9F-AAC6-32775E30B7C7}'] procedure GetCaption; stdcall; procedure GetItems(out aRet {* ISectionItemList }); stdcall; {* Получить элементы раздела ОМ } property Caption: read GetCaption; {* имя } end;//ISection IMainMenuSection = interface ['{9B596AAB-BF7B-41A0-978D-3FAD93DC180C}'] procedure GetCaption; stdcall; procedure GetItems(out aRet {* ISectionItemList }); stdcall; {* Получить элементы раздела ОМ } function GetNewsSectionIndex: Integer; stdcall; {* получить для проф. секции индекс в новостной секции } procedure GetBanner(out aRet {* IBanner }); stdcall; property Caption: read GetCaption; {* имя } end;//IMainMenuSection IMainMenuSectionList = array of IMainMenuSection; IMainMenu = interface {* Основное меню } ['{7EAB7EE0-39FB-42FD-BE38-AF667AE0466E}'] procedure GetBaseSearchPanes(out aRet {* INodeBase }); stdcall; {* Получить дерево вкладок Бзового поиска } procedure GetSection(type: TSectionType; out aRet {* ISection }); stdcall; {* Получить дерево секции ОМ по типу } procedure GetProfessionSectionList(out aRet {* IMainMenuSectionList }); stdcall; {* список секций проф. меню } procedure GetNewsSectionList(out aRet {* IMainMenuSectionList }); stdcall; {* список новостных секций ОМ } procedure GetBusinessReferenceSection(out aRet {* IMainMenuSection }); stdcall; {* раздел бизнес-справки } procedure GetChangesInLegislationSection(out aRet {* IMainMenuSection }); stdcall; {* раздел изменения в законодательстве } end;//IMainMenu implementation uses l3ImplUses ; end.
(* * 计算 MD5(代码来自网络,有修改、优化,支持大文件) *) unit iocp_md5; interface {$I in_iocp.inc} uses {$IFDEF DELPHI_XE7UP} Winapi.Windows, System.SysUtils, {$ELSE} Windows, SysUtils, {$ENDIF} iocp_utils; type MD5Count = array[0..01] of DWORD; MD5State = array[0..03] of DWORD; MD5Block = array[0..15] of DWORD; MD5CBits = array[0..07] of byte; MD5Digest = array[0..15] of byte; MD5Buff = array[0..63] of byte; TMD5Digest = MD5Digest; PMD5Digest = ^TMD5Digest; MD5Context = record State: MD5State; Count: MD5Count; Buffer: MD5Buff; end; // 增加 IOCP 应用结构 PIOCPHashCode = ^TIOCPHashCode; TIOCPHashCode = record case Integer of 0: (MurmurHash, Tail: UInt64); // = TMurmurHash 1: (MD5Code: TMD5Digest); // MD5 = 128 Bits end; {$IF CompilerVersion < 18.5} FILE_SIZE = Cardinal; {$ELSE} FILE_SIZE = Int64; {$IFEND} function MD5Buffer(Buffer: PAnsiChar; Len: Integer): MD5Digest; function MD5String(const S: AnsiString): MD5Digest; function MD5File(const FileName: String): MD5Digest; overload; function MD5File(Handle: THandle): MD5Digest; overload; function MD5Part(Handle: THandle; Offset: FILE_SIZE; PartSize: Cardinal): MD5Digest; function MD5Match(const D1, D2: MD5Digest): Boolean; function MD5MatchEx(D1: PMD5Digest; const D2: MD5Digest): Boolean; function MD5Print(D: MD5Digest): AnsiString; implementation var PADDING: MD5Buff = ( $80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ); function F(x, y, z: DWORD): DWORD; begin Result := (x and y) or ((not x) and z); end; function G(x, y, z: DWORD): DWORD; begin Result := (x and z) or (y and (not z)); end; function H(x, y, z: DWORD): DWORD; begin Result := x xor y xor z; end; function I(x, y, z: DWORD): DWORD; begin Result := y xor (x or (not z)); end; procedure rot(var x: DWORD; n: BYTE); begin x := (x shl n) or (x shr (32 - n)); end; procedure FF(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin inc(a, F(b, c, d) + x + ac); rot(a, s); inc(a, b); end; procedure GG(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin inc(a, G(b, c, d) + x + ac); rot(a, s); inc(a, b); end; procedure HH(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin inc(a, H(b, c, d) + x + ac); rot(a, s); inc(a, b); end; procedure II(var a: DWORD; b, c, d, x: DWORD; s: BYTE; ac: DWORD); begin inc(a, I(b, c, d) + x + ac); rot(a, s); inc(a, b); end; procedure Encode(Source, Target: pointer; Count: longword); var S: PByte; T: PDWORD; I: longword; begin S := Source; T := Target; for I := 1 to Count div 4 do begin T^ := S^; inc(S); T^ := T^ or (S^ shl 8); inc(S); T^ := T^ or (S^ shl 16); inc(S); T^ := T^ or (S^ shl 24); inc(S); inc(T); end; end; procedure Decode(Source, Target: pointer; Count: longword); var S: PDWORD; T: PByte; I: longword; begin S := Source; T := Target; for I := 1 to Count do begin T^ := S^ and $ff; inc(T); T^ := (S^ shr 8) and $ff; inc(T); T^ := (S^ shr 16) and $ff; inc(T); T^ := (S^ shr 24) and $ff; inc(T); inc(S); end; end; procedure Transform(Buffer: pointer; var State: MD5State); {$IFDEF USE_INLINE} inline; {$ENDIF} var a, b, c, d: DWORD; Block: MD5Block; begin Encode(Buffer, @Block, 64); a := State[0]; b := State[1]; c := State[2]; d := State[3]; FF(a, b, c, d, Block[ 0], 7, $d76aa478); FF(d, a, b, c, Block[ 1], 12, $e8c7b756); FF(c, d, a, b, Block[ 2], 17, $242070db); FF(b, c, d, a, Block[ 3], 22, $c1bdceee); FF(a, b, c, d, Block[ 4], 7, $f57c0faf); FF(d, a, b, c, Block[ 5], 12, $4787c62a); FF(c, d, a, b, Block[ 6], 17, $a8304613); FF(b, c, d, a, Block[ 7], 22, $fd469501); FF(a, b, c, d, Block[ 8], 7, $698098d8); FF(d, a, b, c, Block[ 9], 12, $8b44f7af); FF(c, d, a, b, Block[10], 17, $ffff5bb1); FF(b, c, d, a, Block[11], 22, $895cd7be); FF(a, b, c, d, Block[12], 7, $6b901122); FF(d, a, b, c, Block[13], 12, $fd987193); FF(c, d, a, b, Block[14], 17, $a679438e); FF(b, c, d, a, Block[15], 22, $49b40821); GG(a, b, c, d, Block[ 1], 5, $f61e2562); GG(d, a, b, c, Block[ 6], 9, $c040b340); GG(c, d, a, b, Block[11], 14, $265e5a51); GG(b, c, d, a, Block[ 0], 20, $e9b6c7aa); GG(a, b, c, d, Block[ 5], 5, $d62f105d); GG(d, a, b, c, Block[10], 9, $2441453); GG(c, d, a, b, Block[15], 14, $d8a1e681); GG(b, c, d, a, Block[ 4], 20, $e7d3fbc8); GG(a, b, c, d, Block[ 9], 5, $21e1cde6); GG(d, a, b, c, Block[14], 9, $c33707d6); GG(c, d, a, b, Block[ 3], 14, $f4d50d87); GG(b, c, d, a, Block[ 8], 20, $455a14ed); GG(a, b, c, d, Block[13], 5, $a9e3e905); GG(d, a, b, c, Block[ 2], 9, $fcefa3f8); GG(c, d, a, b, Block[ 7], 14, $676f02d9); GG(b, c, d, a, Block[12], 20, $8d2a4c8a); HH(a, b, c, d, Block[ 5], 4, $fffa3942); HH(d, a, b, c, Block[ 8], 11, $8771f681); HH(c, d, a, b, Block[11], 16, $6d9d6122); HH(b, c, d, a, Block[14], 23, $fde5380c); HH(a, b, c, d, Block[ 1], 4, $a4beea44); HH(d, a, b, c, Block[ 4], 11, $4bdecfa9); HH(c, d, a, b, Block[ 7], 16, $f6bb4b60); HH(b, c, d, a, Block[10], 23, $bebfbc70); HH(a, b, c, d, Block[13], 4, $289b7ec6); HH(d, a, b, c, Block[ 0], 11, $eaa127fa); HH(c, d, a, b, Block[ 3], 16, $d4ef3085); HH(b, c, d, a, Block[ 6], 23, $4881d05); HH(a, b, c, d, Block[ 9], 4, $d9d4d039); HH(d, a, b, c, Block[12], 11, $e6db99e5); HH(c, d, a, b, Block[15], 16, $1fa27cf8); HH(b, c, d, a, Block[ 2], 23, $c4ac5665); II(a, b, c, d, Block[ 0], 6, $f4292244); II(d, a, b, c, Block[ 7], 10, $432aff97); II(c, d, a, b, Block[14], 15, $ab9423a7); II(b, c, d, a, Block[ 5], 21, $fc93a039); II(a, b, c, d, Block[12], 6, $655b59c3); II(d, a, b, c, Block[ 3], 10, $8f0ccc92); II(c, d, a, b, Block[10], 15, $ffeff47d); II(b, c, d, a, Block[ 1], 21, $85845dd1); II(a, b, c, d, Block[ 8], 6, $6fa87e4f); II(d, a, b, c, Block[15], 10, $fe2ce6e0); II(c, d, a, b, Block[ 6], 15, $a3014314); II(b, c, d, a, Block[13], 21, $4e0811a1); II(a, b, c, d, Block[ 4], 6, $f7537e82); II(d, a, b, c, Block[11], 10, $bd3af235); II(c, d, a, b, Block[ 2], 15, $2ad7d2bb); II(b, c, d, a, Block[ 9], 21, $eb86d391); inc(State[0], a); inc(State[1], b); inc(State[2], c); inc(State[3], d); end; procedure MD5Init(var Context: MD5Context); begin with Context do begin State[0] := $67452301; State[1] := $efcdab89; State[2] := $98badcfe; State[3] := $10325476; Count[0] := 0; Count[1] := 0; ZeroMemory(@Buffer, SizeOf(MD5Buff)); end; end; procedure MD5Update(var Context: MD5Context; Input: PAnsiChar; Length: longword); var Index: longword; PartLen: longword; I: longword; begin with Context do begin Index := (Count[0] shr 3) and $3f; inc(Count[0], Length shl 3); if Count[0] < (Length shl 3) then inc(Count[1]); inc(Count[1], Length shr 29); end; PartLen := 64 - Index; if Length >= PartLen then begin CopyMemory(@Context.Buffer[Index], Input, PartLen); Transform(@Context.Buffer, Context.State); I := PartLen; while I + 63 < Length do begin Transform(@Input[I], Context.State); inc(I, 64); end; Index := 0; end else I := 0; CopyMemory(@Context.Buffer[Index], @Input[I], Length - I); end; procedure MD5Final(var Context: MD5Context; var Digest: MD5Digest); var Bits: MD5CBits; Index: longword; PadLen: longword; begin Decode(@Context.Count, @Bits, 2); Index := (Context.Count[0] shr 3) and $3f; if Index < 56 then PadLen := 56 - Index else PadLen := 120 - Index; MD5Update(Context, @PADDING, PadLen); MD5Update(Context, @Bits, 8); Decode(@Context.State, @Digest, 4); ZeroMemory(@Context, SizeOf(MD5Context)); end; function MD5Buffer(Buffer: PAnsiChar; Len: Integer): MD5Digest; var Context: MD5Context; begin // 计算内存块的 MD5 MD5Init(Context); MD5Update(Context, Buffer, Len); MD5Final(Context, Result); end; function MD5String(const S: AnsiString): MD5Digest; var Context: MD5Context; begin // 计算字符串的 MD5 MD5Init(Context); MD5Update(Context, PAnsiChar(S), Length(S)); MD5Final(Context, Result); end; function MD5File(const FileName: string): MD5Digest; var Handle: THandle; begin // 计算文件的 MD5(支持大文件) Handle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); try Result := MD5File(Handle); finally if (Handle <> INVALID_HANDLE_VALUE) then CloseHandle(Handle); end; end; function MD5File(Handle: THandle): MD5Digest; var Inf: SYSTEM_INFO; MapHandle: THandle; FileSize, Offset: FILE_SIZE; Granularity, PartSize: Cardinal; MapOffset: LARGE_INTEGER; ViewPointer: Pointer; Context: MD5Context; begin // 计算文件的 MurmurHash(支持大文件) // https://blog.csdn.net/chenxing888/article/details/5912183 MD5Init(Context); if (Handle > 0) and (Handle <> INVALID_HANDLE_VALUE) then begin MapHandle := CreateFileMapping(Handle, nil, PAGE_READONLY, 0, 0, nil); if (MapHandle <> 0) then try {$IFDEF DELPHI_7} GetSystemInfo(Inf); // 取内存分配精度 {$ELSE} GetSystemInfo(&Inf); // 取内存分配精度 {$ENDIF} FileSize := GetFileSize64(Handle); Granularity := Inf.dwAllocationGranularity * 100; Offset := 0; while (FileSize > 0) do begin if (FileSize > Granularity) then PartSize := Granularity else PartSize := FileSize; // 映射: 位移=Offset, 长度=MapSize MapOffset.QuadPart := Offset; ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, MapOffset.HighPart, MapOffset.LowPart, PartSize); Inc(Offset, PartSize); Dec(FileSize, PartSize); if (ViewPointer <> nil) then try MD5Update(Context, ViewPointer, PartSize); finally UnmapViewOfFile(ViewPointer); end; end; finally CloseHandle(MapHandle); end; end; MD5Final(Context, Result); end; function MD5Part(Handle: THandle; Offset: FILE_SIZE; PartSize: Cardinal): MD5Digest; var MapHandle: THandle; MapOffset: LARGE_INTEGER; ViewPointer: Pointer; Context: MD5Context; begin // 计算文件范围的 MD5(支持大文件) MD5Init(Context); if (Handle = 0) or (Handle = INVALID_HANDLE_VALUE) or (PartSize = 0) then begin MD5Final(Context, Result); Exit; end; MapHandle := CreateFileMapping(Handle, nil, PAGE_READONLY, 0, 0, nil); if (MapHandle <> 0) then try // 映射范围: 位移=Offset, 长度=PartSize MapOffset.QuadPart := Offset; ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, MapOffset.HighPart, MapOffset.LowPart, PartSize); if (ViewPointer <> nil) then try MD5Update(Context, ViewPointer, PartSize); finally UnmapViewOfFile(ViewPointer); end; finally CloseHandle(MapHandle); end; MD5Final(Context, Result); end; function MD5Match(const D1, D2: MD5Digest): boolean; var i: byte; begin // 比较 MD5 for i := 0 to 15 do if D1[i] <> D2[i] then begin Result := False; Exit; end; Result := True; end; function MD5MatchEx(D1: PMD5Digest; const D2: MD5Digest): Boolean; // 比较 MD5 var PD2: PIOCPHashCode; begin // 比较 MD5 PD2 := PIOCPHashCode(@D2); Result := (PIOCPHashCode(D1)^.MurmurHash = PD2^.MurmurHash) and (PIOCPHashCode(D1)^.Tail = PD2^.Tail); end; function MD5Print(D: MD5Digest): AnsiString; const Digits: array[0..15] of AnsiChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); var i, k: byte; begin // 转换 MD5 到字符串 Result := '012345678901234567890123456789AB'; for i := 0 to 15 do begin k := i * 2 + 1; Result[k] := Digits[(D[I] shr 4) and $0f]; Result[k + 1] := Digits[D[I] and $0f]; end; end; end.
unit PDTabControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const noTab = -1; type TTabAlign = (taLeft, taCenter, taRight); type TPDTabControl = //class(TGraphicControl) class(TCustomControl) public constructor Create(AOwner : TComponent); override; destructor Destroy; override; protected fTopMargin : word; fBottomColor : TColor; fTopColor : TColor; fLineColor : TColor; fTabColor : TColor; fSelTabColor : TColor; fHilTextColor : TColor; fSelTextColor : TColor; fTabNames : TStrings; fCurrentTab : integer; fTextAlign : TTabAlign; fTextMargin : integer; fTopTextMargin : integer; fOnTabChange : TNotifyEvent; private fBitmap : TBitmap; fTabSize : integer; fTabMargin : integer; fLightedTab : integer; fFitSpace : boolean; fDrawOffset : integer; fUpdating : boolean; private procedure AdjustBitmap; function GetTextFlags : integer; //procedure DrawText(const text : string; aCanvas : TCanvas; origin : integer; color : TColor; render, jump : boolean); procedure DrawText(index : integer; aCanvas : TCanvas; origin : integer; color : TColor; render : boolean); procedure RedrawTabText(tab : integer; color : TColor; toBmp : boolean); procedure DrawTabs; procedure RenderToBmp; procedure ReDrawAll; procedure MessureTabs; protected procedure Paint; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure Loaded; override; private function PointInTab(aX, aY : integer; var tab : integer) : boolean; function TabOrigin(tab : integer) : integer; protected procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; 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 procedure AddObject(tabName : string; Obj : TObject); procedure BeginUpdate; procedure EndUpdate; private procedure SetTopMargin(aMargin : word); procedure SetBottomColor(aColor : TColor); procedure SetTopColor(aColor : TColor); procedure SetLineColor(aColor : TColor); procedure SetTabColor(aColor : TColor); procedure SetSelTabColor(aColor : TColor); procedure SetHilTextColor(aColor : TColor); procedure SetSelTextColor(aColor : TColor); procedure SetTabNames(aList : TStrings); procedure SetCurrentTab(aIndex : integer); procedure SetTextAlign(anAlign : TTabAlign); procedure SetTextMargin(aMargin : integer); procedure SetTopTextMargin(aMargin : integer); published property TopMargin : word read fTopMargin write SetTopMargin; property BottomColor : TColor read fBottomColor write SetBottomColor; property TopColor : TColor read fTopColor write SetTopColor; property LineColor : TColor read fLineColor write SetLineColor; property TabColor : TColor read fTabColor write SetTabColor; property SelTabColor : TColor read fSelTabColor write SetSelTabColor; property HilTextColor : TColor read fHilTextColor write SetHilTextColor; property SelTextColor : TColor read fSelTextColor write SetSelTextColor; property TabNames : TStrings read fTabNames write SetTabNames; property CurrentTab : integer read fCurrentTab write SetCurrentTab; property TextAlign : TTabAlign read fTextAlign write SetTextAlign; property TextMargin : integer read fTextMargin write SetTextMargin; property TopTextMargin : integer read fTopTextMargin write SetTopTextMargin; property OnTabChange : TNotifyEvent read fOnTabChange write fOnTabChange; property Align; property DragCursor; property DragMode; property Enabled; property Font; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses GradientUtils; function max(a, b : integer) : integer; begin if a > b then result := a else result := b; end; function min(a, b : integer) : integer; begin if a > b then result := b else result := a; end; // TPDTabControl constructor TPDTabControl.Create(AOwner : TComponent); begin inherited; fTabNames := TStringList.Create; fBitmap := TBitmap.Create; fLightedTab := noTab; Width := 250; Height := 20; fTopMargin := 4; fTopColor := clBlack; fBottomColor := $00487195; fLineColor := $00487195; fTabColor := clBlack; fSelTabColor := $00444F35; fHilTextColor := $003FFCF8; fSelTextColor := $0095FBF3; fCurrentTab := noTab; fTextAlign := taCenter; fTextMargin := 0; fUpdating := false; end; destructor TPDTabControl.Destroy; begin fBitmap.Free; inherited; end; procedure TPDTabControl.AdjustBitmap; begin fBitmap.Width := max(Width, fTabNames.Count*(fTabSize + fTabMargin) + fTabMargin); fFitSpace := fBitmap.Width = Width; end; function TPDTabControl.GetTextFlags : integer; begin result := DT_SINGLELINE or DT_VCENTER; case fTextAlign of taLeft : result := result or DT_LEFT; taCenter : result := result or DT_CENTER; taRight : result := result or DT_RIGHT; end; end; procedure TPDTabControl.DrawText(index : integer; aCanvas : TCanvas; origin : integer; color : TColor; render : boolean); var len : integer; R : TRect; CR : TRect; text : string; begin text := fTabNames[index]; R.Bottom := pred(Height); if index = fCurrentTab then R.Top := fTopMargin + max(1, fTopTextMargin - 2) else R.Top := fTopMargin + fTopTextMargin; case fTextAlign of taLeft : begin R.Left := origin + fTabMargin; R.Right := R.Left + fTabSize; end; taRight : begin R.Left := origin + fTabMargin + fTextMargin; R.Right := R.Left + fTabSize; end; taCenter : begin R.Left := origin + fTabMargin; R.Right := R.Left + fTabSize + fTextMargin; end end; len := length(text); aCanvas.Font.Color := color; aCanvas.Brush.Style := bsClear; Windows.DrawText(aCanvas.Handle, pchar(text), len, R, GetTextFlags); if render then begin CR := R; OffsetRect(CR, -fDrawOffset, 0); Canvas.CopyRect(CR, fBitmap.Canvas, R); end; end; procedure TPDTabControl.RedrawTabText(tab : integer; color : TColor; toBmp : boolean); begin if tab <> noTab then DrawText(tab, fBitmap.Canvas, TabOrigin(tab), color, not toBmp); end; procedure TPDTabControl.DrawTabs; var i : integer; x : integer; curx : integer; Points : array[0..3] of TPoint; procedure SetPoints(origin : integer); begin Points[0].x := origin; Points[0].y := pred(fBitmap.Height); Points[1].x := origin + fTabMargin - 1; Points[1].y := fTopMargin; Points[2].x := origin + fTabMargin + fTabSize; Points[2].y := fTopMargin; Points[3].x := origin + 2*fTabMargin + fTabSize - 1; Points[3].y := pred(fBitmap.Height); end; begin x := pred(fTabNames.Count)*(fTabSize + fTabMargin); curx := noTab; fBitmap.Canvas.Pen.Color := fLineColor; for i := pred(fTabNames.Count) downto 0 do begin if i <> fCurrentTab then begin // Tab polygon fBitmap.Canvas.Brush.Color := fTabColor; fBitmap.Canvas.Brush.Style := bsSolid; SetPoints(x); fBitmap.Canvas.Polygon(Points); // Tab text DrawText(i, fBitmap.Canvas, x, Font.Color, false); end else curx := x; dec(x, fTabMargin + fTabSize); end; if curx >= 0 then begin fBitmap.Canvas.Pen.Color := fLineColor; fBitmap.Canvas.MoveTo(0, pred(fBitmap.Height)); fBitmap.Canvas.LineTo(pred(fBitmap.Width), pred(fBitmap.Height)); SetPoints(curx); fBitmap.Canvas.Brush.Style := bsSolid; fBitmap.Canvas.Pen.Color := fSelTabColor; fBitmap.Canvas.Brush.Color := fSelTabColor; fBitmap.Canvas.Polygon(Points); fBitmap.Canvas.Pen.Color := fLineColor; inc(Points[3].x); inc(Points[3].y); fBitmap.Canvas.Polyline(Points); // Tab text DrawText(fCurrentTab, fBitmap.Canvas, curx, fSelTextColor, false); end; end; procedure TPDTabControl.RenderToBmp; begin GradientUtils.Gradient(fBitmap.Canvas, fTopColor, fBottomColor, false, ClientRect); fBitmap.Canvas.Font := Font; DrawTabs; end; procedure TPDTabControl.ReDrawAll; begin if not fUpdating then begin MessureTabs; RenderToBmp; Refresh; end; end; procedure TPDTabControl.MessureTabs; var i : integer; begin fTabSize := 0; fBitmap.Canvas.Font := Font; for i := 0 to pred(fTabNames.Count) do fTabSize := max(fTabSize, fTextMargin + Canvas.TextWidth(fTabNames[i])); AdjustBitmap; end; procedure TPDTabControl.Paint; var R : TRect; begin R := ClientRect; OffsetRect(R, fDrawOffset, 0); Canvas.CopyRect(ClientRect, fBitmap.Canvas, R); end; procedure TPDTabControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; if Parent <> nil then begin fBitmap.Width := Width; fBitmap.Height := Height; fTabMargin := Height - fTopMargin; RenderToBmp; end; end; procedure TPDTabControl.Loaded; begin inherited; if Parent <> nil then begin MessureTabs; RenderToBmp; end; end; function TPDTabControl.PointInTab(aX, aY : integer; var tab : integer) : boolean; var tabOffs : integer; begin inc(aX, fDrawOffset); tab := aX div (fTabSize + fTabMargin); if tab > fTabNames.Count then tab := noTab; tabOffs := aX mod (fTabSize + fTabMargin); result := (tab < fTabNames.Count) and (tabOffs > fTabMargin) and (aY > fTopMargin); end; function TPDTabControl.TabOrigin(tab : integer) : integer; begin result := tab*(fTabsize + fTabMargin); end; procedure TPDTabControl.CMMouseEnter(var Message: TMessage); begin end; procedure TPDTabControl.CMMouseLeave(var Message: TMessage); begin if fLightedTab <> noTab then DrawText(fLightedTab, fBitmap.Canvas, TabOrigin(fLightedTab), Font.Color, true); fLightedTab := noTab; Cursor := crDefault; end; procedure TPDTabControl.CMFontChanged(var Message: TMessage); begin inherited; ReDrawAll; end; procedure TPDTabControl.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TPDTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var tab : integer; begin inherited; if PointInTab(X, Y, tab) then begin fLightedTab := noTab; MouseCapture := true; CurrentTab := tab; Cursor := crDefault; if Assigned(fOnTabChange) then fOnTabChange(self); end; end; procedure TPDTabControl.MouseMove(Shift: TShiftState; X, Y: Integer); var tab : integer; offchg : boolean; oldoff : integer; begin inherited; oldoff := fDrawOffset; if not fFitSpace then begin if Width - X < fTabMargin then fDrawOffset := min(fDrawOffset + fTabSize, fBitmap.Width - Width) else if X < fTabMargin then fDrawOffset := max(0, fDrawOffset - fTabSize); end; offchg := oldoff <> fDrawOffset; if PointInTab(X, Y, tab) and (Shift = []) then begin Cursor := crHandPoint; if fLightedTab <> tab then begin RedrawTabText(fLightedTab, Font.Color, offchg); if tab <> fCurrentTab then begin fLightedTab := tab; RedrawTabText(tab, fHilTextColor, offchg); end else begin fLightedTab := noTab; Cursor := crDefault; end; end end else begin Cursor := crDefault; if fLightedTab < fTabNames.Count then RedrawTabText(fLightedTab, Font.Color, offchg); fLightedTab := noTab; end; if offchg then Refresh; end; procedure TPDTabControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; MouseCapture := false; end; procedure TPDTabControl.AddObject(tabName : string; Obj : TObject); begin fTabNames.AddObject(tabName, Obj); end; procedure TPDTabControl.BeginUpdate; begin fUpdating := true; end; procedure TPDTabControl.EndUpdate; begin fUpdating := false; ReDrawAll; end; procedure TPDTabControl.SetTopMargin(aMargin : word); begin if fTopMargin <> aMargin then begin fTopMargin := min(Height div 2, aMargin); fTabMargin := Height - fTopMargin; ReDrawAll; end; end; procedure TPDTabControl.SetBottomColor(aColor : TColor); begin if fBottomColor <> aColor then begin fBottomColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetTopColor(aColor : TColor); begin if fTopColor <> aColor then begin fTopColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetLineColor(aColor : TColor); begin if fLineColor <> aColor then begin fLineColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetTabColor(aColor : TColor); begin if fTabColor <> aColor then begin fTabColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetSelTabColor(aColor : TColor); begin if fSelTabColor <> aColor then begin fSelTabColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetHilTextColor(aColor : TColor); begin if fHilTextColor <> aColor then begin fHilTextColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetSelTextColor(aColor : TColor); begin if fSelTextColor <> aColor then begin fSelTextColor := aColor; ReDrawAll; end; end; procedure TPDTabControl.SetTabNames(aList : TStrings); begin fTabNames.Clear; fTabNames.AddStrings(aList); MessureTabs; fCurrentTab := 0; ReDrawAll; end; procedure TPDTabControl.SetCurrentTab(aIndex : integer); begin if aIndex <> fCurrentTab then begin fCurrentTab := min(aIndex, pred(fTabNames.Count)); ReDrawAll; if Assigned(fOnTabChange) then fOnTabChange(self); end; end; procedure TPDTabControl.SetTextAlign(anAlign : TTabAlign); begin if fTextAlign <> anAlign then begin fTextAlign := anAlign; ReDrawAll; end; end; procedure TPDTabControl.SetTextMargin(aMargin : integer); begin if fTextMargin <> aMargin then begin fTextMargin := max(0, aMargin); ReDrawAll; end; end; procedure TPDTabControl.SetTopTextMargin(aMargin : integer); begin if fTopTextMargin <> aMargin then begin fTopTextMargin := max(0, aMargin); ReDrawAll; end; end; procedure Register; begin RegisterComponents('Five', [TPDTabControl]); end; end.
{ Subroutine SST_R_SYO_INIT * * Init the SST front end for reading SYN files. } module sst_r_syo_init; define sst_r_syo_init; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_init; {init front end state for reading .syn files} var gnam: string_leafname_t; {generic name of input file} fnam_synstart: string_treename_t; {pathname to SYO_SYN.INS.PAS file} sym_p: sst_symbol_p_t; {pointer to module name symbol} stat: sys_err_t; {completion status code} { ********************************************** * * Local function LOOKUP_SYMBOL (NAME) * * Look up symbol in symbol table. The function returns the pointer to the * symbol descriptor with the name NAME. It is an error if the symbol does not * exist. } function lookup_symbol ( in name: string) {name of symbol to look up} :sst_symbol_p_t; {returned pointer to symbol descriptor} var vname: string_var80_t; {var string symbol name} sym_p: sst_symbol_p_t; {pointer to symbol descriptor} stat: sys_err_t; {completion status code} begin vname.max := sizeof(vname.str); {init local var string} string_vstring (vname, name, sizeof(name)); {make var string symbol name} sst_symbol_lookup_name (vname, sym_p, stat); {try to look up name in symbol table} sys_error_abort (stat, 'sst_syo_read', 'symbol_predef_not_found', nil, 0); lookup_symbol := sym_p; {return pointer to symbol descriptor} end; { ********************************************** * * Start of main routine. } begin gnam.max := sizeof(gnam.str); {init local var strings} fnam_synstart.max := sizeof(fnam_synstart.str); prefix.max := sizeof(prefix.str); {init var string in common block} sys_cognivis_dir ('lib', fnam_synstart); {make pathname of SYO_SYN.INS.PAS} string_appends (fnam_synstart, '/syo_syn.ins.pas'); sst_r_pas_init; {init for reading Pascal syntax} sst_r.doit^ ( {run Pascal front end} fnam_synstart, {name of Pascal file to read} gnam, {returned generic name of input file} stat); {returned completion status code} if sys_stat_match (sst_subsys_k, sst_stat_err_handled_k, stat) then begin sys_exit_error; {exit quietly with error condition} end; sys_error_abort (stat, 'sst', 'readin', nil, 0); { * The symbol table has been seeded with all the general utility symbols * we might want to use. Now switch setup for reading SYN files. } syo_preproc_set (nil); {de-install Pascal front end preprocessor} sst_r.doit := addr(sst_r_syo_doit); {set up front end call table} { * Save pointers to all the pre-defined symbols we might need later. } sym_start_routine_p := lookup_symbol ('syo_p_start_routine'); sym_end_routine_p := lookup_symbol ('syo_p_end_routine'); sym_cpos_push_p := lookup_symbol ('syo_p_cpos_push'); sym_cpos_pop_p := lookup_symbol ('syo_p_cpos_pop'); sym_tag_start_p := lookup_symbol ('syo_p_tag_start'); sym_tag_end_p := lookup_symbol ('syo_p_tag_end'); sym_charcase_p := lookup_symbol ('syo_p_charcase'); sym_get_ichar_p := lookup_symbol ('syo_p_get_ichar'); sym_test_eod_p := lookup_symbol ('syo_p_test_eod'); sym_test_eof_p := lookup_symbol ('syo_p_test_eof'); sym_test_string_p := lookup_symbol ('syo_p_test_string'); sym_int_machine_t_p := lookup_symbol ('sys_int_machine_t'); sym_mflag_t_p := lookup_symbol ('syo_mflag_k_t'); sym_charcase_t_p := lookup_symbol ('syo_charcase_k_t'); sym_mflag_yes_p := lookup_symbol ('syo_mflag_yes_k'); sym_mflag_no_p := lookup_symbol ('syo_mflag_no_k'); sym_charcase_down_p := lookup_symbol ('syo_charcase_down_k'); sym_charcase_up_p := lookup_symbol ('syo_charcase_up_k'); sym_charcase_asis_p := lookup_symbol ('syo_charcase_asis_k'); sym_ichar_eol_p := lookup_symbol ('syo_ichar_eol_k'); sym_ichar_eof_p := lookup_symbol ('syo_ichar_eof_k'); sym_ichar_eod_p := lookup_symbol ('syo_ichar_eod_k'); sym_error_p := lookup_symbol ('error'); { * Create special "constants" in common block. } lab_fall_k := univ_ptr(addr(lab_fall_k)); lab_same_k := univ_ptr(addr(lab_same_k)); { * Create "module" for all the routines generated from the SYN file. } sst_symbol_new_name ( {create module name symbol} string_v('module_syn'(0)), sym_p, stat); sys_error_abort (stat, 'sst_syo_read', 'module_symbol_create', nil, 0); sst_scope_new; {create new subordinate scope for module} sst_scope_p^.symbol_p := sym_p; sym_p^.symtype := sst_symtype_module_k; {fill in module symbol descriptor} sym_p^.flags := [sst_symflag_def_k, sst_symflag_used_k]; sym_p^.module_scope_p := sst_scope_p; sst_opcode_new; {create MODULE opcode} sst_opc_p^.opcode := sst_opc_module_k; sst_opc_p^.module_sym_p := sym_p; sst_opcode_pos_push (sst_opc_p^.module_p); {switch to defining module contents} end;
unit UCountryFlag; interface uses Windows, Graphics; type // diese Klasse zeichnet verschiedene skalierbare Landesflaggen TCountryFlag = class(TObject) private FNationality: Integer; FCanvas: TCanvas; procedure PaintRect(r:TRect; color : TColor); procedure PaintVerticalFlag(rect:TRect; c1,c2,c3:TColor); procedure PaintHorizontalFlag(rect:TRect; c1,c2,c3:TColor); procedure GermanFlag(rect:TRect); procedure FrenchFlag(rect:TRect); procedure BelgianFlag(rect:TRect); procedure ItalianFlag(rect:TRect); procedure SpanishFlag(rect:TRect); procedure IrishFlag(rect:TRect); public procedure Paint(rect:TRect); property Nationality: Integer read FNationality write FNationality; property Canvas:TCanvas read FCanvas write FCanvas; end; implementation { TCountryFlag } // Rechteck mit Farbe "color" zeichnen procedure TCountryFlag.PaintRect(r: TRect; color: TColor); begin canvas.Brush.Color := color; canvas.FillRect(r); end; procedure TCountryFlag.PaintVerticalFlag(rect: TRect; c1, c2, c3: TColor); var h : Integer; r : TRect; begin h := (rect.Bottom - rect.Top) div 3; r := rect; r.Bottom := r.Top + h; PaintRect(r, c1); r.Top := rect.Top + h; r.Bottom := r.Top + h; PaintRect(r, c2); r.Top := rect.Top + h * 2; r.Bottom := r.Top + h; PaintRect(r, c3); end; procedure TCountryFlag.PaintHorizontalFlag(rect: TRect; c1, c2, c3: TColor); var w : Integer; r : TRect; begin w := (rect.Right - rect. Left) div 3; r := rect; r.Right := r.Left + w; PaintRect(r, c1); r.Left := rect.Left + w; r.Right := r.Left + w; PaintRect(r, c2); r.Left := rect.Left + w * 2; r.Right := r.Left + w; PaintRect(r, c3); end; procedure TCountryFlag.FrenchFlag(rect: TRect); const BLAU = $A45500; WEISS = $FFFFFF; ROT = $3145EF; begin PaintHorizontalFlag(rect, BLAU, WEISS, ROT); end; procedure TCountryFlag.GermanFlag(rect: TRect); const SCHWARZ = $000000; ROT = $0000FF; GOLD = $00CCFF; begin PaintVerticalFlag(rect, SCHWARZ, ROT, GOLD); end; procedure TCountryFlag.BelgianFlag(rect: TRect); const SCHWARZ = $000000; GELB = $00D4FF; ROT = $2A31E0; begin PaintHorizontalFlag(rect, SCHWARZ, GELB, ROT); end; procedure TCountryFlag.ItalianFlag(rect: TRect); const // TODO: richtige Farben suchen GRUEN = $00A000; WEISS = $FFFFFF; ROT = $2A31E0; begin PaintHorizontalFlag(rect, GRUEN, WEISS, ROT); end; procedure TCountryFlag.SpanishFlag(rect: TRect); const // TODO: richtige Farben suchen ROT = $2A31E0; GELB = $00D4FF; var h : Integer; r : TRect; begin h := (rect.Bottom - rect.Top) div 4; r := rect; r.Bottom := r.Top + h; PaintRect(r, ROT); r.Top := rect.Top + h; r.Bottom := r.Top + h * 2; PaintRect(r, GELB); r.Top := rect.Top + h * 3; r.Bottom := r.Top + h; PaintRect(r, ROT); end; procedure TCountryFlag.IrishFlag(rect: TRect); const // TODO: richtige Farben suchen GRUEN = $439500; WEISS = $FFFFFF; ORANGE = $0073FF; begin PaintHorizontalFlag(rect, GRUEN, WEISS, ORANGE); end; procedure TCountryFlag.Paint(rect: TRect); begin Assert(Assigned(Canvas)); case Nationality of 0 : GermanFlag(rect); 1 : FrenchFlag(rect); 2 : BelgianFlag(rect); 3 : ItalianFlag(rect); 4 : SpanishFlag(rect); 5 : IrishFlag(rect); end; end; end.
unit DealItemsTreeView; interface uses Controls, Sysutils, VirtualTrees, VirtualTree_Editor, define_dealitem, define_stock_quotes_instant, db_dealitem; type PDealItemNode = ^TDealItemNode; TDealItemNode = record Caption: string; DBType: integer; DealItem: PRT_DealItem; InstantQuote: PRT_InstantQuote; end; TDealItemColumns_BaseInfo = record Col_Index: TVirtualTreeColumn; Col_Code: TVirtualTreeColumn; Col_Name: TVirtualTreeColumn; Col_FirstDealDate: TVirtualTreeColumn; Col_LastDealDate: TVirtualTreeColumn; Col_EndDealDate: TVirtualTreeColumn; end; TDealItemColumns_BaseInfoEx = record Col_VolumeTotal : TVirtualTreeColumn; // 当前总股本 Col_VolumeDeal : TVirtualTreeColumn; // 当前流通股本 Col_VolumeDate : TVirtualTreeColumn; // 当前股本结构开始时间 Col_Industry : TVirtualTreeColumn; // 行业 Col_Area : TVirtualTreeColumn; // 地区 Col_PERatio : TVirtualTreeColumn; // 市盈率 end; TDealItemColumns_Quote = record Col_PrePriceClose: TVirtualTreeColumn; Col_PreDealVolume: TVirtualTreeColumn; Col_PreDealAmount: TVirtualTreeColumn; Col_PriceOpen: TVirtualTreeColumn; // 开盘价 Col_PriceHigh: TVirtualTreeColumn; // 最高价 Col_PriceLow: TVirtualTreeColumn; // 最低价 Col_PriceClose: TVirtualTreeColumn; // 收盘价 Col_DealVolume: TVirtualTreeColumn; // 成交量 Col_DealAmount: TVirtualTreeColumn; // 成交金额 (总金额) Col_DealVolumeRate: TVirtualTreeColumn; // 换手率 end; TDealItemTreeData = record TreeView: TBaseVirtualTree; IndexRootNode: PVirtualNode; ItemRootNode: PVirtualNode; Columns_BaseInfo: TDealItemColumns_BaseInfo; Columns_BaseInfoEx: TDealItemColumns_BaseInfoEx; Columns_InstantQuote: TDealItemColumns_Quote; ParentControl: TWinControl; IsOwnedTreeView: Boolean; end; TDealItemTreeCtrl = class protected fDealItemTreeData: TDealItemTreeData; procedure vtDealItemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); function TreeCtrlGetEditDataType(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): TEditorValueType; procedure TreeCtrlCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); procedure TreeCtrlEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); function TreeCtrlGetEditText(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): WideString; procedure TreeCtrlEditUpdateData(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex; AData: WideString); public constructor Create(AParent: TWinControl); destructor Destroy; override; procedure BuildDealItemsTreeNodes(ADBItem: TDBDealItem; AIsExcludeEnd: Boolean = true); procedure InitializeDealItemsTree(ATreeView: TBaseVirtualTree); procedure Clear; function AddDealItemsTreeColumn_Index: TVirtualTreeColumn; function AddDealItemsTreeColumn_Code: TVirtualTreeColumn; function AddDealItemsTreeColumn_Name: TVirtualTreeColumn; function AddDealItemsTreeColumn_FirstDeal: TVirtualTreeColumn; function AddDealItemsTreeColumn_LastDeal: TVirtualTreeColumn; function AddDealItemsTreeColumn_EndDeal: TVirtualTreeColumn; function AddDealItemsTreeColumn_PriceOpen: TVirtualTreeColumn; function AddDealItemsTreeColumn_PriceClose: TVirtualTreeColumn; function AddDealItemsTreeColumn_PriceHigh: TVirtualTreeColumn; function AddDealItemsTreeColumn_PriceLow: TVirtualTreeColumn; function AddDealItemsTreeColumn_PrePriceClose: TVirtualTreeColumn; function AddDealItemsTreeColumn_PreVolume: TVirtualTreeColumn; function AddDealItemsTreeColumn_PreAmount: TVirtualTreeColumn; function AddDealItemsTreeColumn_Volume: TVirtualTreeColumn; function AddDealItemsTreeColumn_Amount: TVirtualTreeColumn; function AddDealItemsTreeColumn_VolumeChangeRate: TVirtualTreeColumn; property TreeView: TBaseVirtualTree read fDealItemTreeData.TreeView; end; implementation uses UtilsDateTime; constructor TDealItemTreeCtrl.Create(AParent: TWinControl); begin FillChar(fDealItemTreeData, SizeOf(fDealItemTreeData), 0); fDealItemTreeData.ParentControl := AParent; end; destructor TDealItemTreeCtrl.Destroy; begin inherited; end; procedure TDealItemTreeCtrl.InitializeDealItemsTree(ATreeView: TBaseVirtualTree); begin fDealItemTreeData.TreeView := ATreeView; if nil = fDealItemTreeData.TreeView then begin fDealItemTreeData.TreeView := TVirtualStringTree.Create(fDealItemTreeData.ParentControl); fDealItemTreeData.IsOwnedTreeView := True; end; if nil <> fDealItemTreeData.ParentControl then begin fDealItemTreeData.TreeView.Parent := fDealItemTreeData.ParentControl; fDealItemTreeData.TreeView.Align := alClient; end; if fDealItemTreeData.TreeView is TVirtualStringTree then begin TVirtualStringTree(fDealItemTreeData.TreeView).NodeDataSize := SizeOf(TDealItemNode); TVirtualStringTree(fDealItemTreeData.TreeView).OnGetText := vtDealItemGetText; // ----------------------------------- TVirtualStringTree(fDealItemTreeData.TreeView).Header.Options := [hoVisible, hoColumnResize]; TVirtualStringTree(fDealItemTreeData.TreeView).OnCreateEditor := TreeCtrlCreateEditor; TVirtualStringTree(fDealItemTreeData.TreeView).OnEditing := TreeCtrlEditing; end; // ----------------------------------- AddDealItemsTreeColumn_Index; AddDealItemsTreeColumn_Code; AddDealItemsTreeColumn_Name; //AddDealItemsTreeColumn_FirstDeal; //AddDealItemsTreeColumn_EndDeal; // ----------------------------------- if fDealItemTreeData.TreeView is TVirtualStringTree then begin TVirtualStringTree(fDealItemTreeData.TreeView).Indent := 4; TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.AnimationOptions := []; TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.SelectionOptions := [toExtendedFocus,toFullRowSelect]; TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.AutoOptions := [ {toAutoDropExpand, toAutoScrollOnExpand, toAutoSort, toAutoTristateTracking, toAutoDeleteMovedNodes, toAutoChangeScale}]; end; end; procedure TDealItemTreeCtrl.TreeCtrlCreateEditor(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink); begin EditLink := TPropertyEditLink.Create(TreeCtrlGetEditDataType, TreeCtrlGetEditText, TreeCtrlEditUpdateData); end; function TDealItemTreeCtrl.TreeCtrlGetEditText(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): WideString; begin vtDealItemGetText(ATree, ANode, AColumn, ttNormal, Result); end; procedure TDealItemTreeCtrl.TreeCtrlEditUpdateData(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex; AData: WideString); var tmpVData: PDealItemNode; tmpDate: Integer; begin tmpVData := ATree.GetNodeData(ANode); if nil <> tmpVData then begin // Col_Index: TVirtualTreeColumn; // Col_Code: TVirtualTreeColumn; // Col_Name: TVirtualTreeColumn; // Col_LastDealDate if nil <> fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate then begin if AColumn = fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Index then begin if nil <> tmpVData.DealItem then begin try tmpDate := Trunc(ParseDateTime(AData)); tmpVData.DealItem.FirstDealDate := tmpDate; except end; end; end; end; if nil <> fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate then begin if AColumn = fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Index then begin if nil <> tmpVData.DealItem then begin try tmpDate := Trunc(ParseDateTime(AData)); tmpVData.DealItem.EndDealDate := tmpDate; except end; end; end; end; end; end; procedure TDealItemTreeCtrl.TreeCtrlEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean); begin Allowed := true; end; function TDealItemTreeCtrl.TreeCtrlGetEditDataType(ATree: TBaseVirtualTree; ANode: PVirtualNode; AColumn: TColumnIndex): TEditorValueType; begin Result := editString; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_Index: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_Index then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_Index := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; //fDealItemTreeData.Columns_BaseInfo.Col_Index.Width := 50; fDealItemTreeData.Columns_BaseInfo.Col_Index.Text := 'ID'; fDealItemTreeData.Columns_BaseInfo.Col_Index.Width := TVirtualStringTree(fDealItemTreeData.TreeView).Canvas.TextWidth('2000'); fDealItemTreeData.Columns_BaseInfo.Col_Index.Width := fDealItemTreeData.Columns_BaseInfo.Col_Index.Width + TVirtualStringTree(fDealItemTreeData.TreeView).TextMargin + TVirtualStringTree(fDealItemTreeData.TreeView).Indent; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_Index; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_Code: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_Code then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_Code := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_BaseInfo.Col_Code.Width := TVirtualStringTree(fDealItemTreeData.TreeView).Canvas.TextWidth('600000'); fDealItemTreeData.Columns_BaseInfo.Col_Code.Width := fDealItemTreeData.Columns_BaseInfo.Col_Code.Width + TVirtualStringTree(fDealItemTreeData.TreeView).TextMargin * 2 + fDealItemTreeData.Columns_BaseInfo.Col_Code.Margin + fDealItemTreeData.Columns_BaseInfo.Col_Code.Spacing; fDealItemTreeData.Columns_BaseInfo.Col_Code.Text := 'Code'; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_Code; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_Name: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_Name then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_Name := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_BaseInfo.Col_Name.Width := 80; fDealItemTreeData.Columns_BaseInfo.Col_Name.Text := 'Name'; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_Name; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_FirstDeal: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Width := 80; fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Text := 'FirstDate'; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_LastDeal: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate.Width := 80; fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate.Text := 'LastDate'; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_EndDeal: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Width := 80; fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Text := 'EndDate'; end; end; Result := fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PriceOpen: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen.Text := 'Open'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PriceClose: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PriceClose then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PriceClose := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PriceClose.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PriceClose.Text := 'Close'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PriceClose; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PriceHigh: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh.Text := 'High'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PriceLow: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PriceLow then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PriceLow := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PriceLow.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PriceLow.Text := 'High'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PriceLow; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PrePriceClose: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PrePriceClose then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PrePriceClose := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PrePriceClose.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PrePriceClose.Text := 'PreClose'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PrePriceClose; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PreVolume: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PreDealVolume then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PreDealVolume := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PreDealVolume.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PreDealVolume.Text := 'PreVolume'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PreDealVolume; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_PreAmount: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_PreDealAmount then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_PreDealAmount := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_PreDealAmount.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_PreDealAmount.Text := 'PreAmount'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_PreDealAmount; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_Volume: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_DealVolume then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_DealVolume := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_DealVolume.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_DealVolume.Text := 'Volume'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_DealVolume; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_Amount: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_DealAmount then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_DealAmount := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_DealAmount.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_DealAmount.Text := 'Amount'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_DealAmount; end; function TDealItemTreeCtrl.AddDealItemsTreeColumn_VolumeChangeRate: TVirtualTreeColumn; begin if nil = fDealItemTreeData.Columns_InstantQuote.Col_DealVolumeRate then begin if fDealItemTreeData.TreeView is TVirtualStringTree then begin fDealItemTreeData.Columns_InstantQuote.Col_DealVolumeRate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add; fDealItemTreeData.Columns_InstantQuote.Col_DealVolumeRate.Width := 80; fDealItemTreeData.Columns_InstantQuote.Col_DealVolumeRate.Text := 'VChangeRate'; end; end; Result := fDealItemTreeData.Columns_InstantQuote.Col_DealVolumeRate; end; procedure TDealItemTreeCtrl.Clear; begin if nil <> fDealItemTreeData.TreeView then begin fDealItemTreeData.TreeView.Clear; end; end; procedure TDealItemTreeCtrl.BuildDealItemsTreeNodes(ADBItem: TDBDealItem; AIsExcludeEnd: Boolean = true); var i: integer; tmpParent: PVirtualNode; tmpVNode: PVirtualNode; tmpVData: PDealItemNode; begin if nil = ADBItem then exit; tmpParent := nil; fDealItemTreeData.ItemRootNode := nil; fDealItemTreeData.IndexRootNode := nil; fDealItemTreeData.TreeView.BeginUpdate; try if 0 < ADBItem.RecordCount then begin if DBType_Item_China = ADBItem.DBType then begin if nil = fDealItemTreeData.ItemRootNode then begin fDealItemTreeData.ItemRootNode := fDealItemTreeData.TreeView.AddChild(nil); tmpVData := fDealItemTreeData.TreeView.GetNodeData(fDealItemTreeData.ItemRootNode); if nil <> tmpVData then begin tmpVData.Caption := '沪深'; end; end; tmpParent := fDealItemTreeData.ItemRootNode; end; if DBType_Index_China = ADBItem.DBType then begin if nil = fDealItemTreeData.IndexRootNode then begin fDealItemTreeData.IndexRootNode := fDealItemTreeData.TreeView.AddChild(nil); tmpVData := fDealItemTreeData.TreeView.GetNodeData(fDealItemTreeData.IndexRootNode); if nil <> tmpVData then begin tmpVData.Caption := '股指'; end; end; tmpParent := fDealItemTreeData.IndexRootNode; end; end; for i := 0 to ADBItem.RecordCount - 1 do begin if 0 = ADBItem.Items[i].EndDealDate then begin tmpVNode := fDealItemTreeData.TreeView.AddChild(tmpParent); if nil <> tmpVNode then begin tmpVData := fDealItemTreeData.TreeView.GetNodeData(tmpVNode); if nil <> tmpVData then tmpVData.DealItem := ADBItem.Items[i]; end; end; end; if nil <> fDealItemTreeData.ItemRootNode then fDealItemTreeData.TreeView.Expanded[fDealItemTreeData.ItemRootNode] := True; finally fDealItemTreeData.TreeView.EndUpdate; end; end; procedure TDealItemTreeCtrl.vtDealItemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); function IsCell(AColumn: TVirtualTreeColumn): Boolean; begin Result := false; if nil = AColumn then exit; Result := AColumn.Index = Column; end; var tmpVData: PDealItemNode; begin CellText := ''; tmpVData := Sender.GetNodeData(Node); if nil <> tmpVData then begin if nil = tmpVData.DealItem then begin if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_Index) then begin CellText := tmpVData.Caption; exit; end; end else begin if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_Index) then begin CellText := IntToStr(Node.Index); exit; end; if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_Code) then begin CellText := tmpVData.DealItem.sCode; exit; end; if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_Name) then begin CellText := tmpVData.DealItem.Name; exit; end; if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate) then begin if 0 < tmpVData.DealItem.FirstDealDate then CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.FirstDealDate); exit; end; if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate) then begin if 0 < tmpVData.DealItem.EndDealDate then CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.EndDealDate); exit; end; if IsCell(fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate) then begin if 0 < tmpVData.DealItem.LastDealDate then CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.LastDealDate); exit; end; // ================================ if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_PriceOpen) then begin if nil <> tmpVData.InstantQuote then CellText := FormatFloat('0.00', tmpVData.InstantQuote.PriceRange.PriceOpen.Value / 1000); exit; end; if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_PriceClose) then begin if nil <> tmpVData.InstantQuote then CellText := FormatFloat('0.00', tmpVData.InstantQuote.PriceRange.PriceClose.Value / 1000); exit; end; if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_PriceHigh) then begin if nil <> tmpVData.InstantQuote then CellText := FormatFloat('0.00', tmpVData.InstantQuote.PriceRange.PriceHigh.Value / 1000); exit; end; if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_PriceLow) then begin if nil <> tmpVData.InstantQuote then CellText := FormatFloat('0.00', tmpVData.InstantQuote.PriceRange.PriceLow.Value / 1000); exit; end; if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_DealVolume) then begin if nil <> tmpVData.InstantQuote then CellText := IntToStr(tmpVData.InstantQuote.Volume); exit; end; if IsCell(fDealItemTreeData.Columns_InstantQuote.Col_DealAmount) then begin if nil <> tmpVData.InstantQuote then CellText := IntToStr(tmpVData.InstantQuote.Amount); exit; end; end; end; end; end.
unit MFichas.Model.Pagamento.Formas.Dinheiro.Estornar; interface uses System.SysUtils, MFichas.Model.Pagamento.Interfaces, MFichas.Model.Entidade.VENDAPAGAMENTOS, MFichas.Controller.Types; type TModelPagamentoFormasDinheiroEstornar = class(TInterfacedObject, iModelPagamentoMetodosEstornar) private [weak] FParent: iModelPagamento; FValor : Currency; FEntidade: TVENDAPAGAMENTOS; constructor Create(AParent: iModelPagamento); procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelPagamento): iModelPagamentoMetodosEstornar; function SetValor(AValue: Currency): iModelPagamentoMetodosEstornar; function &End : iModelPagamentoMetodos; end; implementation { TModelPagamentoFormasDinheiroEstornar } function TModelPagamentoFormasDinheiroEstornar.&End: iModelPagamentoMetodos; begin //TODO: IMPLEMENTAR METODO DE ESTORNO EM DINHEIRO Result := FParent.Dinheiro; Gravar; end; procedure TModelPagamentoFormasDinheiroEstornar.Gravar; begin FEntidade.VENDA := FParent.EntidadeDeVenda.GUUID; FEntidade.TIPO := Integer(tpDinheiro); FEntidade.VALOR := FValor; FEntidade.STATUS := Integer(spEstornado); FParent.DAO.Insert(FEntidade); end; constructor TModelPagamentoFormasDinheiroEstornar.Create(AParent: iModelPagamento); begin FParent := AParent; FEntidade := TVENDAPAGAMENTOS.Create; end; destructor TModelPagamentoFormasDinheiroEstornar.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; {$ENDIF} inherited; end; class function TModelPagamentoFormasDinheiroEstornar.New(AParent: iModelPagamento): iModelPagamentoMetodosEstornar; begin Result := Self.Create(AParent); end; function TModelPagamentoFormasDinheiroEstornar.SetValor( AValue: Currency): iModelPagamentoMetodosEstornar; begin Result := Self; FValor := AValue; end; end.
unit DcefB_Events; interface uses Windows, Classes, Controls, Dcef3_ceflib; type TBrowserDataChangeKind = (BrowserDataChange_StatusMessage, BrowserDataChange_Address, BrowserDataChange_Title); { TBrowserDownloadUpdatedKind = (BrowserDownloadUpdated_Start, BrowserDownloadUpdated_Progress, BrowserDownloadUpdated_End, BrowserDownloadUpdated_Canceled); } TOnPageChanging = procedure(Sender: TObject; var Allow: Boolean) of object; TOnPageChanged = TNotifyEvent; TOnPageLoadingStateChange = procedure(const PageID: Integer; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean) of object; TOnPageStateChange = procedure(const PageID: Integer; const Kind: TBrowserDataChangeKind; const Value: string; const PageActived: Boolean) of object; TOnPageAdd = procedure(const PageID: Integer; Const AddAtLast: Boolean) of object; TOnPageClose = procedure(const ClosePageIDArr: Array of Integer; Const ShowPageID: Integer) of object; TOnLoadStart = procedure(const PageIndex: Integer; const browser: ICefBrowser; const frame: ICefFrame) of object; TOnLoadEnd = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer) of object; TOnLoadError = procedure(const PageIndex: Integer; const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring) of object; TOnBeforeBrowse = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; var Cancel: Boolean) of object; TOnPreKeyEvent = procedure(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var isKeyboardShortcut: Boolean; var Cancel: Boolean) of object; TOnKeyEvent = procedure(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var Cancel: Boolean) of object; TOnBeforeResourceLoad = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var CancelLoad: Boolean) of object; TOnGetResourceHandler = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var ResourceHandler: ICefResourceHandler) of object; TOnResourceRedirect = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring) of object; TOnGotFocus = procedure(const PageID: Integer; const browser: ICefBrowser; var CancelEventBuiltIn: Boolean) of object; TOnSetFocus = procedure(const PageID: Integer; const browser: ICefBrowser; source: TCefFocusSource; var CancelFocus: Boolean) of object; TOnTakeFocus = procedure(const PageID: Integer; const browser: ICefBrowser; next: Boolean) of object; TOnBeforeContextMenu = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel) of object; TOnContextMenuCommand = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; var CancelEventBuiltIn: Boolean) of object; TOnContextMenuDismissed = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame) of object; TOnJsdialog = procedure(const PageID: Integer; const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean) of object; TOnBeforeUnloadDialog = procedure(const PageID: Integer; const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean) of object; TOnDialogClosed = procedure(const PageID: Integer; const browser: ICefBrowser) of object; { TOnDownloadUpdated = procedure(Const DcefItemIndex: Integer; Const Kind: TBrowserDownloadUpdatedKind) of object; } TOnBeforeDownload = procedure(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback; var CancelBuiltinPro: Boolean) of object; TOnDownloadUpdated = procedure(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback) of object; TOnGetAuthCredentials = procedure(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; var CancelEventBuiltIn: Boolean) of object; TOnConsoleMessage = procedure(const PageID: Integer; const browser: ICefBrowser; const message, source: ustring; line: Integer; var CancelEventBuiltIn: Boolean) of object; TOnProtocolExecution = procedure(const PageID: Integer; browser: ICefBrowser; const url: ustring; var allowOsExecution: Boolean) of object; TOnFileDialog = procedure(const PageID: Integer; const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback; out Result: Boolean) of object; TOnPluginCrashed = procedure(const PageID: Integer; const browser: ICefBrowser; const pluginPath: ustring) of object; TOnBeforePluginLoad = procedure(const PageID: Integer; const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo; var CancelLoad: Boolean) of object; TOnRequestGeolocationPermission = procedure(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean) of object; TOnCancelGeolocationPermission = procedure(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer) of object; TOnQuotaRequest = procedure(const PageID: Integer; const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback; out Result: Boolean) of object; TOnDragEnter = procedure(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean) of object; TOnStartDragging = procedure(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean) of object; TOnUpdateDragCursor = procedure(const PageID: Integer; const browser: ICefBrowser; operation: TCefDragOperation) of object; TOnCertificateError = procedure(const PageID: Integer; certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback; out Result: Boolean) of object; TOnCursorChange = procedure(const PageID: Integer; const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo) of object; IDcefBrowserEvents = interface procedure doOnPageChanging(Sender: TObject; var Allow: Boolean); procedure doOnPageChanged(Sender: TObject); procedure doOnPageLoadingStateChange(const PageID: Integer; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); procedure doOnPageStateChange(const PageID: Integer; const Kind: TBrowserDataChangeKind; const Value: string; const PageActived: Boolean); procedure doOnPageAdd(const PageID: Integer; Const AddAtLast: Boolean); procedure doOnPageClose(const ClosePageIDArr: Array of Integer; Const ShowPageID: Integer); procedure doOnLoadStart(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); procedure doOnLoadEnd(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); procedure doOnLoadError(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring); procedure doOnBeforeBrowse(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; var Cancel: Boolean); procedure doOnPreKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var isKeyboardShortcut: Boolean; var Cancel: Boolean); procedure doOnKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var Cancel: Boolean); procedure doOnBeforeResourceLoad(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var CancelLoad: Boolean); procedure doOnGetResourceHandler(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var ResourceHandler: ICefResourceHandler); procedure doOnResourceRedirect(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring); procedure doOnGotFocus(const PageID: Integer; const browser: ICefBrowser; var CancelEventBuiltIn: Boolean); procedure doOnSetFocus(const PageID: Integer; const browser: ICefBrowser; source: TCefFocusSource; var CancelFocus: Boolean); procedure doOnTakeFocus(const PageID: Integer; const browser: ICefBrowser; next: Boolean); procedure doOnBeforeContextMenu(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); procedure doOnContextMenuCommand(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; var CancelEventBuiltIn: Boolean); procedure doOnContextMenuDismissed(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); procedure doOnJsdialog(const PageID: Integer; const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); procedure doOnBeforeUnloadDialog(const PageID: Integer; const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); procedure doOnDialogClosed(const PageID: Integer; const browser: ICefBrowser); procedure doOnPluginCrashed(const PageID: Integer; const browser: ICefBrowser; const pluginPath: ustring); procedure doOnBeforePluginLoad(const PageID: Integer; const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo; var CancelLoad: Boolean); { procedure doOnDownloadUpdated(Const DcefItemIndex: Integer; Const Kind: TBrowserDownloadUpdatedKind); } procedure doOnBeforeDownload(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback; var CancelBuiltinPro: Boolean); procedure doOnDownloadUpdated(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); procedure doOnGetAuthCredentials(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; var CancelEventBuiltIn: Boolean); procedure doOnConsoleMessage(const PageID: Integer; const browser: ICefBrowser; const message, source: ustring; line: Integer; var CancelEventBuiltIn: Boolean); procedure doOnProtocolExecution(const PageID: Integer; browser: ICefBrowser; const url: ustring; var allowOsExecution: Boolean); procedure doOnFileDialog(const PageID: Integer; const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback; out Result: Boolean); procedure doOnRequestGeolocationPermission(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean); procedure doOnCancelGeolocationPermission(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer); procedure doOnQuotaRequest(const PageID: Integer; const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback; out Result: Boolean); procedure doOnDragEnter(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean); procedure doOnStartDragging(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean); procedure doOnUpdateDragCursor(const PageID: Integer; const browser: ICefBrowser; operation: TCefDragOperation); procedure doOnCertificateError(const PageID: Integer; certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback; out Result: Boolean); procedure doOnCursorChange(const PageID: Integer; const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); end; TDcefBrowserEvents = class(TInterfacedObject, IDcefBrowserEvents) private FOnPageChanging: TOnPageChanging; FOnPageChanged: TOnPageChanged; FOnPageLoadingStateChange: TOnPageLoadingStateChange; FOnPageStateChange: TOnPageStateChange; FOnPageAdd: TOnPageAdd; FOnPageClose: TOnPageClose; FOnLoadStart: TOnLoadStart; FOnLoadEnd: TOnLoadEnd; FOnLoadError: TOnLoadError; FOnBeforeBrowse: TOnBeforeBrowse; FOnPreKeyEvent: TOnPreKeyEvent; FOnKeyEvent: TOnKeyEvent; FOnBeforeResourceLoad: TOnBeforeResourceLoad; FOnGetResourceHandler: TOnGetResourceHandler; FOnResourceRedirect: TOnResourceRedirect; FOnGotFocus: TOnGotFocus; FOnSetFocus: TOnSetFocus; FOnTakeFocus: TOnTakeFocus; FOnBeforeContextMenu: TOnBeforeContextMenu; FOnContextMenuCommand: TOnContextMenuCommand; FOnContextMenuDismissed: TOnContextMenuDismissed; FOnJsdialog: TOnJsdialog; FOnBeforeUnloadDialog: TOnBeforeUnloadDialog; FOnDialogClosed: TOnDialogClosed; FOnPluginCrashed: TOnPluginCrashed; FOnBeforePluginLoad: TOnBeforePluginLoad; FOnBeforeDownload: TOnBeforeDownload; FOnDownloadUpdated: TOnDownloadUpdated; FOnGetAuthCredentials: TOnGetAuthCredentials; FOnConsoleMessage: TOnConsoleMessage; FOnProtocolExecution: TOnProtocolExecution; FOnFileDialog: TOnFileDialog; FOnRequestGeolocationPermission: TOnRequestGeolocationPermission; FOnCancelGeolocationPermission: TOnCancelGeolocationPermission; FOnQuotaRequest: TOnQuotaRequest; FOnCertificateError: TOnCertificateError; FOnDragEnter: TOnDragEnter; FOnStartDragging: TOnStartDragging; FOnUpdateDragCursor: TOnUpdateDragCursor; FOnCursorChange: TOnCursorChange; protected procedure doOnPageChanging(Sender: TObject; var Allow: Boolean); procedure doOnPageChanged(Sender: TObject); procedure doOnPageLoadingStateChange(const PageID: Integer; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); virtual; procedure doOnPageStateChange(const PageID: Integer; const Kind: TBrowserDataChangeKind; const Value: string; const PageActived: Boolean); virtual; procedure doOnPageAdd(const PageID: Integer; Const AddAtLast: Boolean); virtual; procedure doOnPageClose(const ClosePageIDArr: Array of Integer; Const ShowPageID: Integer); virtual; procedure doOnLoadStart(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); virtual; procedure doOnLoadEnd(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); virtual; procedure doOnLoadError(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring); virtual; procedure doOnBeforeBrowse(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; var Cancel: Boolean); virtual; procedure doOnPreKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var isKeyboardShortcut: Boolean; var Cancel: Boolean); virtual; procedure doOnKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var Cancel: Boolean); virtual; procedure doOnBeforeResourceLoad(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var CancelLoad: Boolean); virtual; procedure doOnGetResourceHandler(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var ResourceHandler: ICefResourceHandler); virtual; procedure doOnResourceRedirect(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring); virtual; procedure doOnGotFocus(const PageID: Integer; const browser: ICefBrowser; var CancelEventBuiltIn: Boolean); virtual; procedure doOnSetFocus(const PageID: Integer; const browser: ICefBrowser; source: TCefFocusSource; var CancelFocus: Boolean); virtual; procedure doOnTakeFocus(const PageID: Integer; const browser: ICefBrowser; next: Boolean); virtual; procedure doOnBeforeContextMenu(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); virtual; procedure doOnContextMenuCommand(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; var CancelEventBuiltIn: Boolean); virtual; procedure doOnContextMenuDismissed(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); virtual; procedure doOnJsdialog(const PageID: Integer; const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); virtual; procedure doOnBeforeUnloadDialog(const PageID: Integer; const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); virtual; procedure doOnDialogClosed(const PageID: Integer; const browser: ICefBrowser); virtual; procedure doOnPluginCrashed(const PageID: Integer; const browser: ICefBrowser; const pluginPath: ustring); virtual; procedure doOnBeforePluginLoad(const PageID: Integer; const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo; var CancelLoad: Boolean); virtual; { procedure doOnDownloadUpdated(Const DcefItemIndex: Integer; Const Kind: TBrowserDownloadUpdatedKind); virtual; } procedure doOnBeforeDownload(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback; var CancelBuiltinPro: Boolean); virtual; procedure doOnDownloadUpdated(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); virtual; procedure doOnGetAuthCredentials(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; var CancelEventBuiltIn: Boolean); virtual; procedure doOnConsoleMessage(const PageID: Integer; const browser: ICefBrowser; const message, source: ustring; line: Integer; var CancelEventBuiltIn: Boolean); virtual; procedure doOnProtocolExecution(const PageID: Integer; browser: ICefBrowser; const url: ustring; var allowOsExecution: Boolean); virtual; procedure doOnFileDialog(const PageID: Integer; const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback; out Result: Boolean); virtual; procedure doOnRequestGeolocationPermission(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean); virtual; procedure doOnCancelGeolocationPermission(const PageID: Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer); virtual; procedure doOnQuotaRequest(const PageID: Integer; const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback; out Result: Boolean); virtual; procedure doOnCertificateError(const PageID: Integer; certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback; out Result: Boolean); virtual; procedure doOnDragEnter(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean); virtual; procedure doOnStartDragging(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean); virtual; procedure doOnUpdateDragCursor(const PageID: Integer; const browser: ICefBrowser; operation: TCefDragOperation); virtual; procedure doOnCursorChange(const PageID: Integer; const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); virtual; public destructor Destroy; override; property OnPageChanging: TOnPageChanging read FOnPageChanging write FOnPageChanging; property OnPageChanged: TOnPageChanged read FOnPageChanged write FOnPageChanged; property OnPageLoadingStateChange: TOnPageLoadingStateChange read FOnPageLoadingStateChange write FOnPageLoadingStateChange; property OnPageStateChange: TOnPageStateChange read FOnPageStateChange write FOnPageStateChange; property OnPageAdd: TOnPageAdd read FOnPageAdd write FOnPageAdd; property OnPageClose: TOnPageClose read FOnPageClose write FOnPageClose; property OnLoadStart: TOnLoadStart read FOnLoadStart write FOnLoadStart; property OnLoadEnd: TOnLoadEnd read FOnLoadEnd write FOnLoadEnd; property OnLoadError: TOnLoadError read FOnLoadError write FOnLoadError; property OnBeforeBrowse: TOnBeforeBrowse read FOnBeforeBrowse write FOnBeforeBrowse; property OnPreKeyEvent: TOnPreKeyEvent read FOnPreKeyEvent write FOnPreKeyEvent; property OnKeyEvent: TOnKeyEvent read FOnKeyEvent write FOnKeyEvent; property OnBeforeResourceLoad: TOnBeforeResourceLoad read FOnBeforeResourceLoad write FOnBeforeResourceLoad; property OnGetResourceHandler: TOnGetResourceHandler read FOnGetResourceHandler write FOnGetResourceHandler; property OnResourceRedirect: TOnResourceRedirect read FOnResourceRedirect write FOnResourceRedirect; property OnGotFocus: TOnGotFocus read FOnGotFocus write FOnGotFocus; property OnSetFocus: TOnSetFocus read FOnSetFocus write FOnSetFocus; property OnTakeFocus: TOnTakeFocus read FOnTakeFocus write FOnTakeFocus; property OnBeforeContextMenu: TOnBeforeContextMenu read FOnBeforeContextMenu write FOnBeforeContextMenu; property OnContextMenuCommand: TOnContextMenuCommand read FOnContextMenuCommand write FOnContextMenuCommand; property OnContextMenuDismissed: TOnContextMenuDismissed read FOnContextMenuDismissed write FOnContextMenuDismissed; property OnJsdialog: TOnJsdialog read FOnJsdialog write FOnJsdialog; property OnBeforeUnloadDialog: TOnBeforeUnloadDialog read FOnBeforeUnloadDialog write FOnBeforeUnloadDialog; property OnDialogClosed: TOnDialogClosed read FOnDialogClosed write FOnDialogClosed; property OnPluginCrashed: TOnPluginCrashed read FOnPluginCrashed write FOnPluginCrashed; property OnBeforePluginLoad: TOnBeforePluginLoad read FOnBeforePluginLoad write FOnBeforePluginLoad; property OnBeforeDownload: TOnBeforeDownload read FOnBeforeDownload write FOnBeforeDownload; property OnDownloadUpdated: TOnDownloadUpdated read FOnDownloadUpdated write FOnDownloadUpdated; property OnGetAuthCredentials: TOnGetAuthCredentials read FOnGetAuthCredentials write FOnGetAuthCredentials; property OnConsoleMessage: TOnConsoleMessage read FOnConsoleMessage write FOnConsoleMessage; property OnProtocolExecution: TOnProtocolExecution read FOnProtocolExecution write FOnProtocolExecution; property OnFileDialog: TOnFileDialog read FOnFileDialog write FOnFileDialog; property OnRequestGeolocationPermission: TOnRequestGeolocationPermission read FOnRequestGeolocationPermission write FOnRequestGeolocationPermission; property OnCancelGeolocationPermission: TOnCancelGeolocationPermission read FOnCancelGeolocationPermission write FOnCancelGeolocationPermission; property OnQuotaRequest: TOnQuotaRequest read FOnQuotaRequest write FOnQuotaRequest; property OnCertificateError: TOnCertificateError read FOnCertificateError write FOnCertificateError; property OnDragEnter: TOnDragEnter read FOnDragEnter write FOnDragEnter; property OnStartDragging: TOnStartDragging read FOnStartDragging write FOnStartDragging; property OnUpdateDragCursor: TOnUpdateDragCursor read FOnUpdateDragCursor write FOnUpdateDragCursor; property OnCursorChange: TOnCursorChange read FOnCursorChange write FOnCursorChange; end; implementation { TDcefBrowserEvents } destructor TDcefBrowserEvents.Destroy; begin inherited; end; procedure TDcefBrowserEvents.doOnPageStateChange(const PageID: Integer; const Kind: TBrowserDataChangeKind; const Value: string; const PageActived: Boolean); begin if Assigned(FOnPageStateChange) then FOnPageStateChange(PageID, Kind, Value, PageActived); end; procedure TDcefBrowserEvents.doOnPluginCrashed(const PageID: Integer; const browser: ICefBrowser; const pluginPath: ustring); begin if Assigned(FOnPluginCrashed) then FOnPluginCrashed(PageID, browser, pluginPath); end; procedure TDcefBrowserEvents.doOnDialogClosed(const PageID: Integer; const browser: ICefBrowser); begin if Assigned(FOnDialogClosed) then FOnDialogClosed(PageID, browser); end; procedure TDcefBrowserEvents.doOnDownloadUpdated(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const callback: ICefDownloadItemCallback); begin if Assigned(FOnDownloadUpdated) then FOnDownloadUpdated(PageID, browser, downloadItem, callback); end; { procedure TDcefBrowserEvents.doOnDownloadUpdated(const DcefItemIndex: Integer; const Kind: TBrowserDownloadUpdatedKind); begin if Assigned(FOnDownloadUpdated) then FOnDownloadUpdated(DcefItemIndex, Kind); end; } procedure TDcefBrowserEvents.doOnDragEnter(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; mask: TCefDragOperations; out Result: Boolean); begin if Assigned(FOnDragEnter) then FOnDragEnter(PageID, browser, dragData, mask, Result); end; procedure TDcefBrowserEvents.doOnFileDialog(const PageID: Integer; const browser: ICefBrowser; mode: TCefFileDialogMode; const title, defaultFileName: ustring; acceptTypes: TStrings; const callback: ICefFileDialogCallback; out Result: Boolean); begin if Assigned(FOnFileDialog) then FOnFileDialog(PageID, browser, mode, title, defaultFileName, acceptTypes, callback, Result); end; procedure TDcefBrowserEvents.doOnPageAdd(const PageID: Integer; Const AddAtLast: Boolean); begin if Assigned(FOnPageAdd) then FOnPageAdd(PageID, AddAtLast); end; procedure TDcefBrowserEvents.doOnBeforeBrowse(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; isRedirect: Boolean; var Cancel: Boolean); begin if Assigned(FOnBeforeBrowse) then FOnBeforeBrowse(PageID, browser, frame, request, isRedirect, Cancel); end; procedure TDcefBrowserEvents.doOnBeforeContextMenu(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; const model: ICefMenuModel); begin if Assigned(FOnBeforeContextMenu) then FOnBeforeContextMenu(PageID, browser, frame, params, model); end; procedure TDcefBrowserEvents.doOnBeforeDownload(const PageID: Integer; const browser: ICefBrowser; const downloadItem: ICefDownloadItem; const suggestedName: ustring; const callback: ICefBeforeDownloadCallback; var CancelBuiltinPro: Boolean); begin if Assigned(FOnBeforeDownload) then FOnBeforeDownload(PageID, browser, downloadItem, suggestedName, callback, CancelBuiltinPro); end; procedure TDcefBrowserEvents.doOnBeforePluginLoad(const PageID: Integer; const browser: ICefBrowser; const url, policyUrl: ustring; const info: ICefWebPluginInfo; var CancelLoad: Boolean); begin if Assigned(FOnBeforePluginLoad) then FOnBeforePluginLoad(PageID, browser, url, policyUrl, info, CancelLoad); end; procedure TDcefBrowserEvents.doOnBeforeResourceLoad(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var CancelLoad: Boolean); begin if Assigned(FOnBeforeResourceLoad) then FOnBeforeResourceLoad(PageID, browser, frame, request, CancelLoad); end; procedure TDcefBrowserEvents.doOnBeforeUnloadDialog(const PageID: Integer; const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnBeforeUnloadDialog) then FOnBeforeUnloadDialog(PageID, browser, messageText, isReload, callback, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnCancelGeolocationPermission(const PageID : Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer); begin if Assigned(FOnCancelGeolocationPermission) then FOnCancelGeolocationPermission(PageID, browser, requestingUrl, requestId); end; procedure TDcefBrowserEvents.doOnCertificateError(const PageID: Integer; certError: TCefErrorCode; const requestUrl: ustring; const callback: ICefAllowCertificateErrorCallback; out Result: Boolean); begin if Assigned(FOnCertificateError) then FOnCertificateError(PageID, certError, requestUrl, callback, Result); end; procedure TDcefBrowserEvents.doOnConsoleMessage(const PageID: Integer; const browser: ICefBrowser; const message, source: ustring; line: Integer; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnConsoleMessage) then FOnConsoleMessage(PageID, browser, message, source, line, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnContextMenuCommand(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const params: ICefContextMenuParams; commandId: Integer; eventFlags: TCefEventFlags; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnContextMenuCommand) then FOnContextMenuCommand(PageID, browser, frame, params, commandId, eventFlags, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnContextMenuDismissed(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); begin if Assigned(FOnContextMenuDismissed) then FOnContextMenuDismissed(PageID, browser, frame); end; procedure TDcefBrowserEvents.doOnCursorChange(const PageID: Integer; const browser: ICefBrowser; cursor: TCefCursorHandle; cursorType: TCefCursorType; const customCursorInfo: PCefCursorInfo); begin if Assigned(FOnCursorChange) then FOnCursorChange(PageID, browser, cursor, cursorType, customCursorInfo); end; procedure TDcefBrowserEvents.doOnPageChanged(Sender: TObject); begin if Assigned(FOnPageChanged) then FOnPageChanged(Sender); end; procedure TDcefBrowserEvents.doOnPageChanging(Sender: TObject; var Allow: Boolean); begin if Assigned(FOnPageChanging) then FOnPageChanging(Sender, Allow); end; procedure TDcefBrowserEvents.doOnPageClose(const ClosePageIDArr : Array of System.Integer; Const ShowPageID: Integer); begin if Assigned(FOnPageClose) then FOnPageClose(ClosePageIDArr, ShowPageID); end; procedure TDcefBrowserEvents.doOnPageLoadingStateChange(const PageID: Integer; const browser: ICefBrowser; isLoading, canGoBack, canGoForward: Boolean); begin if Assigned(FOnPageLoadingStateChange) then FOnPageLoadingStateChange(PageID, browser, isLoading, canGoBack, canGoForward); end; procedure TDcefBrowserEvents.doOnGetAuthCredentials(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; isProxy: Boolean; const host: ustring; port: Integer; const realm, scheme: ustring; const callback: ICefAuthCallback; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnGetAuthCredentials) then FOnGetAuthCredentials(PageID, browser, frame, isProxy, host, port, realm, scheme, callback, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnGetResourceHandler(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; var ResourceHandler: ICefResourceHandler); begin if Assigned(FOnGetResourceHandler) then FOnGetResourceHandler(PageID, browser, frame, request, ResourceHandler); end; procedure TDcefBrowserEvents.doOnGotFocus(const PageID: Integer; const browser: ICefBrowser; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnGotFocus) then FOnGotFocus(PageID, browser, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnJsdialog(const PageID: Integer; const browser: ICefBrowser; const originUrl, acceptLang: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; var CancelEventBuiltIn: Boolean); begin if Assigned(FOnJsdialog) then FOnJsdialog(PageID, browser, originUrl, acceptLang, dialogType, messageText, defaultPromptText, callback, CancelEventBuiltIn); end; procedure TDcefBrowserEvents.doOnKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var Cancel: Boolean); begin if Assigned(FOnKeyEvent) then FOnKeyEvent(PageID, browser, event, osEvent, Cancel); end; procedure TDcefBrowserEvents.doOnLoadEnd(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer); begin if Assigned(FOnLoadEnd) then FOnLoadEnd(PageID, browser, frame, httpStatusCode); end; procedure TDcefBrowserEvents.doOnLoadError(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; errorCode: Integer; const errorText, failedUrl: ustring); begin if Assigned(FOnLoadError) then FOnLoadError(PageID, browser, frame, errorCode, errorText, failedUrl); end; procedure TDcefBrowserEvents.doOnLoadStart(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame); begin if Assigned(FOnLoadStart) then FOnLoadStart(PageID, browser, frame); end; procedure TDcefBrowserEvents.doOnPreKeyEvent(const PageID: Integer; const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: TCefEventHandle; var isKeyboardShortcut: Boolean; var Cancel: Boolean); begin if Assigned(FOnPreKeyEvent) then FOnPreKeyEvent(PageID, browser, event, osEvent, isKeyboardShortcut, Cancel); end; procedure TDcefBrowserEvents.doOnProtocolExecution(const PageID: Integer; browser: ICefBrowser; const url: ustring; var allowOsExecution: Boolean); begin if Assigned(FOnProtocolExecution) then FOnProtocolExecution(PageID, browser, url, allowOsExecution); end; procedure TDcefBrowserEvents.doOnQuotaRequest(const PageID: Integer; const browser: ICefBrowser; const originUrl: ustring; newSize: Int64; const callback: ICefQuotaCallback; out Result: Boolean); begin if Assigned(FOnQuotaRequest) then FOnQuotaRequest(PageID, browser, originUrl, newSize, callback, Result); end; procedure TDcefBrowserEvents.doOnRequestGeolocationPermission(const PageID : Integer; const browser: ICefBrowser; const requestingUrl: ustring; requestId: Integer; const callback: ICefGeolocationCallback; out Result: Boolean); begin if Assigned(FOnRequestGeolocationPermission) then FOnRequestGeolocationPermission(PageID, browser, requestingUrl, requestId, callback, Result); end; procedure TDcefBrowserEvents.doOnResourceRedirect(const PageID: Integer; const browser: ICefBrowser; const frame: ICefFrame; const oldUrl: ustring; var newUrl: ustring); begin if Assigned(FOnResourceRedirect) then FOnResourceRedirect(PageID, browser, frame, oldUrl, newUrl); end; procedure TDcefBrowserEvents.doOnSetFocus(const PageID: Integer; const browser: ICefBrowser; source: TCefFocusSource; var CancelFocus: Boolean); begin if Assigned(FOnSetFocus) then FOnSetFocus(PageID, browser, source, CancelFocus); end; procedure TDcefBrowserEvents.doOnStartDragging(const PageID: Integer; const browser: ICefBrowser; const dragData: ICefDragData; allowedOps: TCefDragOperations; x, y: Integer; out Result: Boolean); begin if Assigned(FOnStartDragging) then FOnStartDragging(PageID, browser, dragData, allowedOps, x, y, Result); end; procedure TDcefBrowserEvents.doOnTakeFocus(const PageID: Integer; const browser: ICefBrowser; next: Boolean); begin if Assigned(FOnTakeFocus) then FOnTakeFocus(PageID, browser, next); end; procedure TDcefBrowserEvents.doOnUpdateDragCursor(const PageID: Integer; const browser: ICefBrowser; operation: TCefDragOperation); begin if Assigned(FOnUpdateDragCursor) then FOnUpdateDragCursor(PageID, browser, operation); end; end.
unit MFichas.Model.Configuracao.Metodos.Editar.View; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Configuracao.Interfaces, MFichas.Model.Entidade.CONFIGURACOES, ORMBR.Types.Blob; type TModelConfiguracaoMetodosEditarView = class(TInterfacedObject, iModelConfiguracaoMetodosEditarView) private [weak] FParent : iModelConfiguracao; FEntidade : TCONFIGURACOES; FImpressora : String; FListaConfiguracao: TObjectList<TCONFIGURACOES>; constructor Create(AParent: iModelConfiguracao); procedure RecuperarObjectoNoBancoDeDados; procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosEditarView; function Impressora(AImpressora: String): iModelConfiguracaoMetodosEditarView; function &End : iModelConfiguracaoMetodos; end; implementation { TModelConfiguracaoMetodosEditarView } function TModelConfiguracaoMetodosEditarView.&End: iModelConfiguracaoMetodos; begin Result := FParent.Metodos; RecuperarObjectoNoBancoDeDados; Gravar; end; procedure TModelConfiguracaoMetodosEditarView.Gravar; begin FParent.DAO.Modify(FEntidade); FEntidade.IMPRESSORA := FImpressora; FParent.DAO.Update(FEntidade); end; function TModelConfiguracaoMetodosEditarView.Impressora( AImpressora: String): iModelConfiguracaoMetodosEditarView; begin Result := Self; FImpressora := AImpressora; end; constructor TModelConfiguracaoMetodosEditarView.Create(AParent: iModelConfiguracao); begin FParent := AParent; FEntidade := TCONFIGURACOES.Create; end; destructor TModelConfiguracaoMetodosEditarView.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); if Assigned(FListaConfiguracao) then FreeAndNil(FListaConfiguracao); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; if Assigned(FListaConfiguracao) then begin FListaConfiguracao.Free; FListaConfiguracao.DisposeOf; end; {$ENDIF} inherited; end; class function TModelConfiguracaoMetodosEditarView.New(AParent: iModelConfiguracao): iModelConfiguracaoMetodosEditarView; begin Result := Self.Create(AParent); end; procedure TModelConfiguracaoMetodosEditarView.RecuperarObjectoNoBancoDeDados; begin FListaConfiguracao := FParent.DAO.Find; FEntidade.GUUID := FListaConfiguracao[0].GUUID; FEntidade.IMPRESSORA := FListaConfiguracao[0].IMPRESSORA; FEntidade.NOMEDISPOSITIVO := FListaConfiguracao[0].NOMEDISPOSITIVO; FEntidade.GUUIDDISPOSITIVO := FListaConfiguracao[0].GUUIDDISPOSITIVO; FEntidade.DATACADASTRO := FListaConfiguracao[0].DATACADASTRO; FEntidade.DATAALTERACAO := FListaConfiguracao[0].DATAALTERACAO; FEntidade.DATALIBERACAO := FListaConfiguracao[0].DATALIBERACAO; end; end.
{*******************************************************} { } { Turbo Pascal Version 7.0 } { Turbo Vision Unit } { } { Copyright (c) 1992 Borland International } { } {*******************************************************} unit HistList; {$H-} {$X+,R-,I-,Q-,V-} {$S-} {**************************************************************************** History buffer structure: Byte Byte String Byte Byte String +-------------------------+-------------------------+--...--+ | 0 | Id | History string | 0 | Id | History string | | +-------------------------+-------------------------+--...--+ ***************************************************************************} interface uses Use32, Objects; const HistoryBlock: Pointer = nil; HistorySize: Sw_Word = 1024; HistoryUsed: Sw_Word = 0; procedure HistoryAdd(Id: Byte; const Str: String); function HistoryCount(Id: Byte): Sw_Word; function HistoryStr(Id: Byte; Index: Sw_Integer): String; procedure ClearHistory; procedure InitHistory; procedure DoneHistory; procedure StoreHistory(var S: TStream); procedure LoadHistory(var S: TStream); implementation type pbyte=^byte; thistrec=packed record Zero : byte; Id : byte; Str : String; end; phistrec=^thistrec; var CurId: Byte; CurString: PString; { Advance CurString to next string with an ID of CurId } procedure AdvanceStringPointer; var p : phistrec; begin while (CurString<>nil) do begin inc(pchar(CurString),pbyte(CurString)^+1); if pchar(CurString)-pchar(HistoryBlock)>=HistoryUsed then begin CurString:=nil; exit; end; p:=phistrec(CurString); inc(pchar(CurString),2); if (p^.Id=CurId) then exit; end; end; procedure DeleteString; var len : Sw_integer; p,p2 : pchar; begin p:=pchar(CurString); p2:=pchar(CurString); len:=pbyte(p2)^+3; dec(p,2); inc(p2,pbyte(p2)^+1); Move(p2^,p^,HistoryUsed-(p2-pchar(HistoryBlock))); dec(HistoryUsed,len); end; procedure InsertString(Id: Byte; const Str: String); var p1,p2 : pchar; begin while (HistoryUsed+Length(Str)>HistorySize) do begin runerror(199); end; p1:=pchar(HistoryBlock)+1; p2:=p1+Length(Str)+3; Move(p1^,p2^,HistoryUsed-1); PHistRec(p1)^.Zero:=0; PHistRec(p1)^.Id:=Id; Move(Str[0],PHistRec(p1)^.Str,Length(Str)+1); inc(HistoryUsed,Length(Str)+3); end; procedure StartId(Id: Byte); begin CurId := Id; CurString := HistoryBlock; end; function HistoryCount(Id: Byte): Sw_Word; var Count: Sw_Word; begin StartId(Id); Count := 0; AdvanceStringPointer; while CurString <> nil do begin Inc(Count); AdvanceStringPointer; end; HistoryCount := Count; end; procedure HistoryAdd(Id: Byte; const Str: String); begin if Str = '' then Exit; StartId(Id); { Delete duplicates } AdvanceStringPointer; while CurString <> nil do begin if Str = CurString^ then DeleteString; AdvanceStringPointer; end; InsertString(Id, Str); end; function HistoryStr(Id: Byte; Index: Sw_Integer): String; var I: Sw_Integer; begin StartId(Id); for I := 0 to Index do AdvanceStringPointer; if CurString <> nil then HistoryStr := CurString^ else HistoryStr := ''; end; procedure ClearHistory; begin PChar(HistoryBlock)^ := #0; HistoryUsed := 1; end; procedure StoreHistory(var S: TStream); var Size: Sw_Word; begin Size := HistoryUsed; S.Write(Size, SizeOf(Sw_Word)); S.Write(HistoryBlock^, Size); end; procedure LoadHistory(var S: TStream); var Size: Sw_Word; begin S.Read(Size, SizeOf(Sw_Word)); S.Read(HistoryBlock^, Size); HistoryUsed := Size; end; procedure InitHistory; begin GetMem(HistoryBlock, HistorySize); ClearHistory; end; procedure DoneHistory; begin FreeMem(HistoryBlock, HistorySize); end; end.